forked from thomseddon/traefik-forward-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
278 lines (239 loc) · 6.71 KB
/
main.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
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/namsral/flag"
"github.com/op/go-logging"
)
// Vars
var fw *ForwardAuth
var log = logging.MustGetLogger("traefik-forward-auth")
// Primary handler
func handler(w http.ResponseWriter, r *http.Request) {
// Get uri
req := r.Header.Get("X-Forwarded-Uri")
if req == "" {
req = r.RequestURI
}
// Parse uri
uri, err := url.Parse(req)
if err != nil {
log.Error("Error parsing url")
http.Error(w, "Service unavailable", 503)
return
}
// Ignore for "favicon.ico"
if uri.Path == "/favicon.ico" {
w.WriteHeader(200)
return
}
// ACME challenge check
if fw.SkipACME && strings.HasPrefix(uri.Path, "/.well-known/acme-challenge/") {
w.WriteHeader(200)
return
}
// Handle callback
if uri.Path == fw.Path {
handleCallback(w, r, uri.Query())
return
}
// Get auth cookie
c, err := r.Cookie(fw.CookieName)
if err != nil {
// Error indicates no cookie, generate nonce
err, nonce := fw.Nonce()
if err != nil {
log.Error("Error generating nonce")
http.Error(w, "Service unavailable", 503)
return
}
// Set the CSRF cookie
http.SetCookie(w, fw.MakeCSRFCookie(r, nonce))
log.Debug("Set CSRF cookie and redirecting to github login")
// Forward them on
http.Redirect(w, r, fw.GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
return
}
// Validate cookie
valid, email, err := fw.ValidateCookie(r, c)
if !valid {
log.Debugf("Invlaid cookie: %s", err)
http.Error(w, "Not authorized", 401)
return
}
// Validate user
valid = fw.ValidateEmail(email)
if !valid {
log.Debugf("Invalid email: %s", email)
http.Error(w, "Not authorized", 401)
return
}
// Set authorized user
w.Header().Set("X-Auth-User", email)
// Valid request
w.WriteHeader(200)
}
// Authenticate user after they have come back from github
func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
// Check for CSRF cookie
csrfCookie, err := r.Cookie(fw.CSRFCookieName)
if err != nil {
log.Debug("Missing csrf cookie")
http.Error(w, "Not authorized", 401)
return
}
// Validate state
state := qs.Get("state")
valid, redirect, err := fw.ValidateCSRFCookie(csrfCookie, state)
if !valid {
log.Debugf("Invalid oauth state, expected '%s', got '%s'\n", csrfCookie.Value, state)
http.Error(w, "Not authorized", 401)
return
}
// Clear CSRF cookie
http.SetCookie(w, fw.ClearCSRFCookie(r))
// Exchange code for token
token, err := fw.ExchangeCode(r, qs.Get("code"))
if err != nil {
log.Debugf("Code exchange failed with: %s\n", err)
http.Error(w, "Service unavailable", 503)
return
}
// Get user
user, err := fw.GetUser(token)
if err != nil {
log.Debugf("Error getting user: %s\n", err)
http.Error(w, "Service unavailable", 503)
return
}
log.Debugf("User has been authorized: %s<%s>", user.Name, user.Email)
// Get orgs
if fw.GithubOrg != "" {
orgs, err := fw.GetOrgs(token)
if err != nil {
log.Debugf("Error getting orgs: %s\n", err)
http.Error(w, "Service unavailable", 503)
return
}
for _, org := range orgs {
if org.Name == fw.GithubOrg {
goto PASSED
}
}
log.Debugf("User organizations not matched: %s\n", fw.GithubOrg)
http.Error(w, "Access Denied", 403)
return
PASSED:
}
// Generate cookie
http.SetCookie(w, fw.MakeCookie(r, user.Name))
log.Debugf("Generated auth cookie for %s\n", user.Name)
// Redirect
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
}
// Main
func main() {
// Parse options
flag.String(flag.DefaultConfigFlagname, "", "Path to config file")
path := flag.String("url-path", "_oauth", "Callback URL")
lifetime := flag.Int("lifetime", 43200, "Session length in seconds")
secret := flag.String("secret", "", "*Secret used for signing (required)")
authHost := flag.String("auth-host", "", "Central auth login")
clientId := flag.String("client-id", "", "*Github Client ID (required)")
clientSecret := flag.String("client-secret", "", "*Github Client Secret (required)")
cookieName := flag.String("cookie-name", "_forward_auth", "Cookie Name")
cSRFCookieName := flag.String("csrf-cookie-name", "_forward_auth_csrf", "CSRF Cookie Name")
cookieDomainList := flag.String("cookie-domains", "", "Comma separated list of cookie domains") //todo
cookieSecret := flag.String("cookie-secret", "", "depreciated")
cookieSecure := flag.Bool("cookie-secure", true, "Use secure cookies")
domainList := flag.String("domain", "", "Comma separated list of email domains to allow")
emailWhitelist := flag.String("whitelist", "", "Comma separated list of emails to allow")
githubOrg := flag.String("github-org", "", "Restrict logins to members of this organisation")
prompt := flag.String("prompt", "", "Space separated list of OpenID prompt options")
skipACME := flag.Bool("skip-acme", true, "Skip ACME challenge request")
flag.Parse()
// Backwards compatability
if *secret == "" && *cookieSecret != "" {
*secret = *cookieSecret
}
// Check for show stopper errors
stop := false
if *clientId == "" {
stop = true
log.Critical("client-id must be set")
}
if *clientSecret == "" {
stop = true
log.Critical("client-secret must be set")
}
if *secret == "" {
stop = true
log.Critical("secret must be set")
}
if stop {
return
}
// Parse lists
var cookieDomains []CookieDomain
if *cookieDomainList != "" {
for _, d := range strings.Split(*cookieDomainList, ",") {
cookieDomain := NewCookieDomain(d)
cookieDomains = append(cookieDomains, *cookieDomain)
}
}
var domain []string
if *domainList != "" {
domain = strings.Split(*domainList, ",")
}
var whitelist []string
if *emailWhitelist != "" {
whitelist = strings.Split(*emailWhitelist, ",")
}
// Setup
fw = &ForwardAuth{
Path: fmt.Sprintf("/%s", *path),
Lifetime: time.Second * time.Duration(*lifetime),
Secret: []byte(*secret),
AuthHost: *authHost,
ClientId: *clientId,
ClientSecret: *clientSecret,
Scope: "user:email read:org",
LoginURL: &url.URL{
Scheme: "https",
Host: "github.com",
Path: "/login/oauth/authorize",
},
TokenURL: &url.URL{
Scheme: "https",
Host: "github.com",
Path: "/login/oauth/access_token",
},
UserURL: &url.URL{
Scheme: "https",
Host: "api.github.com",
Path: "/user",
},
OrgsURL: &url.URL{
Scheme: "https",
Host: "api.github.com",
Path: "/user/orgs",
},
CookieName: *cookieName,
CSRFCookieName: *cSRFCookieName,
CookieDomains: cookieDomains,
CookieSecure: *cookieSecure,
Domain: domain,
Whitelist: whitelist,
GithubOrg: *githubOrg,
Prompt: *prompt,
SkipACME: *skipACME,
}
// Attach handler
http.HandleFunc("/", handler)
log.Debugf("Staring with options: %#v", fw)
log.Notice("Litening on :4181")
log.Notice(http.ListenAndServe(":4181", nil))
}