-
-
Notifications
You must be signed in to change notification settings - Fork 414
/
server.go
265 lines (225 loc) · 7.04 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package tfa
import (
"net/http"
"net/url"
"github.com/sirupsen/logrus"
"github.com/thomseddon/traefik-forward-auth/internal/provider"
muxhttp "github.com/traefik/traefik/v2/pkg/muxer/http"
)
// Server contains muxer and handler methods
type Server struct {
muxer *muxhttp.Muxer
}
// NewServer creates a new server object and builds muxer
func NewServer() *Server {
s := &Server{}
s.buildRoutes()
return s
}
func (s *Server) buildRoutes() {
var err error
s.muxer, err = muxhttp.NewMuxer()
if err != nil {
log.Fatal(err)
}
// Let's build a muxer
for name, rule := range config.Rules {
matchRule := rule.formattedRule()
if rule.Action == "allow" {
_ = s.muxer.AddRoute(matchRule, 1, s.AllowHandler(name))
} else {
_ = s.muxer.AddRoute(matchRule, 1, s.AuthHandler(rule.Provider, name))
}
}
// Add callback handler
s.muxer.Handle(config.Path, s.AuthCallbackHandler())
// Add logout handler
s.muxer.Handle(config.Path+"/logout", s.LogoutHandler())
// Add a default handler
if config.DefaultAction == "allow" {
s.muxer.NewRoute().Handler(s.AllowHandler("default"))
} else {
s.muxer.NewRoute().Handler(s.AuthHandler(config.DefaultProvider, "default"))
}
}
// RootHandler Overwrites the request method, host and URL with those from the
// forwarded request so it's correctly routed by mux
func (s *Server) RootHandler(w http.ResponseWriter, r *http.Request) {
// Modify request
r.Method = r.Header.Get("X-Forwarded-Method")
r.Host = r.Header.Get("X-Forwarded-Host")
// Read URI from header if we're acting as forward auth middleware
if _, ok := r.Header["X-Forwarded-Uri"]; ok {
r.URL, _ = url.Parse(r.Header.Get("X-Forwarded-Uri"))
}
// Pass to mux
s.muxer.ServeHTTP(w, r)
}
// AllowHandler Allows requests
func (s *Server) AllowHandler(rule string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.logger(r, "Allow", rule, "Allowing request")
w.WriteHeader(200)
}
}
// AuthHandler Authenticates requests
func (s *Server) AuthHandler(providerName, rule string) http.HandlerFunc {
p, _ := config.GetConfiguredProvider(providerName)
return func(w http.ResponseWriter, r *http.Request) {
// Logging setup
logger := s.logger(r, "Auth", rule, "Authenticating request")
// Get auth cookie
c, err := r.Cookie(config.CookieName)
if err != nil {
s.authRedirect(logger, w, r, p)
return
}
// Validate cookie
email, err := ValidateCookie(r, c)
if err != nil {
if err.Error() == "Cookie has expired" {
logger.Info("Cookie has expired")
s.authRedirect(logger, w, r, p)
} else {
logger.WithField("error", err).Warn("Invalid cookie")
http.Error(w, "Not authorized", 401)
}
return
}
// Validate user
valid := ValidateEmail(email, rule)
if !valid {
logger.WithField("email", email).Warn("Invalid email")
http.Error(w, "Not authorized", 401)
return
}
// Valid request
logger.Debug("Allowing valid request")
w.Header().Set("X-Forwarded-User", email)
w.WriteHeader(200)
}
}
// AuthCallbackHandler Handles auth callback request
func (s *Server) AuthCallbackHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Logging setup
logger := s.logger(r, "AuthCallback", "default", "Handling callback")
// Check state
state := r.URL.Query().Get("state")
if err := ValidateState(state); err != nil {
logger.WithFields(logrus.Fields{
"error": err,
}).Warn("Error validating state")
http.Error(w, "Not authorized", 401)
return
}
// Check for CSRF cookie
c, err := FindCSRFCookie(r, state)
if err != nil {
logger.Info("Missing csrf cookie")
http.Error(w, "Not authorized", 401)
return
}
// Validate CSRF cookie against state
valid, providerName, redirect, err := ValidateCSRFCookie(c, state)
if !valid {
logger.WithFields(logrus.Fields{
"error": err,
"csrf_cookie": c,
}).Warn("Error validating csrf cookie")
http.Error(w, "Not authorized", 401)
return
}
// Get provider
p, err := config.GetConfiguredProvider(providerName)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err,
"csrf_cookie": c,
"provider": providerName,
}).Warn("Invalid provider in csrf cookie")
http.Error(w, "Not authorized", 401)
return
}
// Clear CSRF cookie
http.SetCookie(w, ClearCSRFCookie(r, c))
// Exchange code for token
token, err := p.ExchangeCode(redirectUri(r), r.URL.Query().Get("code"))
if err != nil {
logger.WithField("error", err).Error("Code exchange failed with provider")
http.Error(w, "Service unavailable", 503)
return
}
// Get user
user, err := p.GetUser(token)
if err != nil {
logger.WithField("error", err).Error("Error getting user")
http.Error(w, "Service unavailable", 503)
return
}
// Generate cookie
http.SetCookie(w, MakeCookie(r, user.Email))
logger.WithFields(logrus.Fields{
"provider": providerName,
"redirect": redirect,
"user": user.Email,
}).Info("Successfully generated auth cookie, redirecting user.")
// Redirect
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
}
}
// LogoutHandler logs a user out
func (s *Server) LogoutHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Clear cookie
http.SetCookie(w, ClearCookie(r))
logger := s.logger(r, "Logout", "default", "Handling logout")
logger.Info("Logged out user")
if config.LogoutRedirect != "" {
http.Redirect(w, r, config.LogoutRedirect, http.StatusTemporaryRedirect)
} else {
http.Error(w, "You have been logged out", 401)
}
}
}
func (s *Server) authRedirect(logger *logrus.Entry, w http.ResponseWriter, r *http.Request, p provider.Provider) {
// Error indicates no cookie, generate nonce
err, nonce := Nonce()
if err != nil {
logger.WithField("error", err).Error("Error generating nonce")
http.Error(w, "Service unavailable", 503)
return
}
// Set the CSRF cookie
csrf := MakeCSRFCookie(r, nonce)
http.SetCookie(w, csrf)
if !config.InsecureCookie && r.Header.Get("X-Forwarded-Proto") != "https" {
logger.Warn("You are using \"secure\" cookies for a request that was not " +
"received via https. You should either redirect to https or pass the " +
"\"insecure-cookie\" config option to permit cookies via http.")
}
// Forward them on
loginURL := p.GetLoginURL(redirectUri(r), MakeState(r, p, nonce))
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
logger.WithFields(logrus.Fields{
"csrf_cookie": csrf,
"login_url": loginURL,
}).Debug("Set CSRF cookie and redirected to provider login url")
}
func (s *Server) logger(r *http.Request, handler, rule, msg string) *logrus.Entry {
// Create logger
logger := log.WithFields(logrus.Fields{
"handler": handler,
"rule": rule,
"method": r.Header.Get("X-Forwarded-Method"),
"proto": r.Header.Get("X-Forwarded-Proto"),
"host": r.Header.Get("X-Forwarded-Host"),
"uri": r.Header.Get("X-Forwarded-Uri"),
"source_ip": r.Header.Get("X-Forwarded-For"),
})
// Log request
logger.WithFields(logrus.Fields{
"cookies": r.Cookies(),
}).Debug(msg)
return logger
}