forked from ooraini/oidc-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
439 lines (374 loc) · 10.5 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package main
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/jmespath/go-jmespath"
"golang.org/x/oauth2"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
prefix = "/auth"
SessionCookieName = "oidc_auth"
headerPrefix = "HEADER_"
)
var (
provider *oidc.Provider
config oauth2.Config
verifier *oidc.IDTokenVerifier
sameSite http.SameSite
jmespathHeaders map[string]*jmespath.JMESPath
defaultHeaders string
)
func getEnvOrDie(key string) string {
val := os.Getenv(key)
if val == "" {
log.Fatalf("missing environemnt variable '%s'", key)
}
return val
}
func getEnvOrDefault(key, fallback string) string {
val := os.Getenv(key)
if val == "" {
return fallback
}
return val
}
func main() {
var err error
issuer := getEnvOrDie("ISSUER")
if getEnvOrDefault("INSECURE_SKIP_VERIFY", "false") == "true" {
t := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
http.DefaultClient = &http.Client{Transport: t}
}
ss := getEnvOrDefault("SAMESITE", "lax")
if strings.EqualFold(ss, "lax") {
sameSite = http.SameSiteLaxMode
} else if strings.EqualFold(ss, "strict") {
sameSite = http.SameSiteStrictMode
} else if strings.EqualFold(ss, "none") {
sameSite = http.SameSiteNoneMode
} else {
log.Fatalf("SAMESITE '%s' not supported\n", ss)
}
defaultHeaders = getEnvOrDefault("DEFAULT_HEADERS", "")
jmespathHeaders, err = loadHeaderExprs()
if err != nil {
log.Fatalln("unable to load JMESPATH expressions", err)
}
scopes := getEnvOrDefault("SCOPES", "openid profile email groups")
provider, err = oidc.NewProvider(context.Background(), issuer)
if err != nil {
log.Fatalln("unable to create OIDC provider", err)
}
config = oauth2.Config{
ClientID: getEnvOrDie("CLIENT_ID"),
ClientSecret: getEnvOrDie("CLIENT_SECRET"),
Endpoint: provider.Endpoint(),
Scopes: strings.Split(scopes, " "),
}
verifier = provider.Verifier(&oidc.Config{ClientID: config.ClientID})
http.HandleFunc(prefix+"/login", login)
http.HandleFunc(prefix+"/logout", logout)
http.HandleFunc(prefix+"/callback", callback)
http.HandleFunc(prefix+"/decisions", decide)
http.HandleFunc("/", http.NotFound)
err = http.ListenAndServe(":"+getEnvOrDefault("PORT", "80"), nil)
if err != nil {
log.Fatalln("unable to listen", err)
}
}
func loadHeaderExprs() (map[string]*jmespath.JMESPath, error) {
result := map[string]*jmespath.JMESPath{}
for _, pair := range os.Environ() {
prefixedName, value, _ := strings.Cut(pair, "=")
if strings.HasPrefix(prefixedName, headerPrefix) {
name := prefixedName[len(headerPrefix):]
compiled, err := jmespath.Compile(value)
if err != nil {
log.Printf("unable to parse JMESTPATH expression '%s'\n", value)
return nil, err
} else {
result[name] = compiled
log.Printf("header '%s' is avalible\n", name)
}
}
}
return result, nil
}
func logout(rw http.ResponseWriter, req *http.Request) {
clearCookie(rw, SessionCookieName)
infoS(req, "clearing session", http.StatusFound)
http.Redirect(rw, req, "/", http.StatusFound)
}
func infoS(req *http.Request, message string, status int) {
log.Printf("%s - %s %s %s - %s\n", req.Host, req.Method, req.URL.Path, message, http.StatusText(status))
}
func decide(rw http.ResponseWriter, req *http.Request) {
sessionCookie, err := req.Cookie(SessionCookieName)
if err != nil {
infoS(req, "no session cookie", http.StatusUnauthorized)
rw.WriteHeader(http.StatusUnauthorized)
return
}
rawIdToken := sessionCookie.Value
idToken, err := verifier.Verify(req.Context(), rawIdToken)
if err != nil {
infoS(req, "verify failed : "+err.Error(), http.StatusUnauthorized)
clearCookie(rw, SessionCookieName)
rw.WriteHeader(http.StatusUnauthorized)
return
}
var claims map[string]interface{}
if err = idToken.Claims(&claims); err != nil {
infoS(req, "no claims in token", http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
emailClaim := claims["email"]
groupsClaim := claims["groups"]
userEmail := ""
if email, ok := emailClaim.(string); ok {
userEmail = email
}
var userGroups []string
if groups, ok := groupsClaim.([]interface{}); ok {
for _, group := range groups {
if g, ok := group.(string); ok {
userGroups = append(userGroups, g)
}
}
}
queryParams := req.URL.Query()
headers := queryParams.Get("headers")
allowedGroups := queryParams.Get("allowed_groups")
allowedEmails := queryParams.Get("allowed_emails")
if headers == "" {
headers = defaultHeaders
}
if allowedGroups != "" {
allowed := false
for _, group := range strings.Split(allowedGroups, ",") {
if contains(group, userGroups) {
allowed = true
break
}
}
if !allowed {
infoS(req, fmt.Sprintf("user '%s' not in allowed groups", userEmail), http.StatusForbidden)
rw.WriteHeader(http.StatusForbidden)
return
}
}
if allowedEmails != "" {
if !contains(userEmail, strings.Split(allowedEmails, ",")) {
infoS(req, fmt.Sprintf("user '%s' not in allowed emails", userEmail), http.StatusForbidden)
rw.WriteHeader(http.StatusForbidden)
return
}
}
idTokenJson, err := base64.RawURLEncoding.DecodeString(strings.Split(rawIdToken, ".")[1])
if err != nil {
infoS(req, "token payload", http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
var data map[string]interface{}
if json.Unmarshal(idTokenJson, &data) != nil {
infoS(req, "unmarshal", http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
data["raw"] = rawIdToken
for _, header := range strings.Split(headers, ",") {
expr := jmespathHeaders[header]
if expr == nil {
continue
}
search, err := expr.Search(data)
if err != nil {
continue
}
if result, ok := search.(string); ok {
rw.Header().Set(header, result)
}
}
rw.WriteHeader(http.StatusOK)
infoS(req, userEmail, http.StatusOK)
}
func callback(rw http.ResponseWriter, req *http.Request) {
state, err := req.Cookie("state")
if err != nil {
infoS(req, "no state cookie", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
rd, err := req.Cookie("rd")
if err != nil {
infoS(req, "no rd cookie", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
clearCookie(rw, "state")
clearCookie(rw, "rd")
queryParams := req.URL.Query()
if state.Value != queryParams.Get("state") {
infoS(req, "state mismatch", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
code := queryParams.Get("code")
if code == "" {
infoS(req, "no code", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
rdUrl, err := url.Parse(rd.Value)
if err != nil {
infoS(req, "invalid rd url : "+err.Error(), http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
redirectUrl := fmt.Sprintf("%s://%s%s/callback", rdUrl.Scheme, rdUrl.Host, prefix)
token, err := config.Exchange(req.Context(), code, oauth2.SetAuthURLParam("redirect_uri", redirectUrl))
if err != nil {
infoS(req, "code exchange error : "+err.Error(), http.StatusUnauthorized)
rw.WriteHeader(http.StatusUnauthorized)
return
}
rawIdToken, ok := token.Extra("id_token").(string)
if !ok {
infoS(req, "no id_token", http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
_, err = verifier.Verify(req.Context(), rawIdToken)
if err != nil {
infoS(req, "invalid token : "+err.Error(), http.StatusUnauthorized)
rw.WriteHeader(http.StatusUnauthorized)
return
}
http.SetCookie(rw, &http.Cookie{
Name: SessionCookieName,
Value: rawIdToken,
Expires: time.Now().Add(time.Hour * 24),
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: sameSite,
})
infoS(req, "redirecting to '"+rd.Value+"'", http.StatusFound)
http.Redirect(rw, req, rd.Value, http.StatusFound)
}
func login(rw http.ResponseWriter, req *http.Request) {
queryParams := req.URL.Query()
rd := queryParams.Get("rd")
if rd == "" {
host := req.Header.Get("X-Forwarded-Host")
proto := req.Header.Get("X-Forwarded-Proto")
port := req.Header.Get("X-Forwarded-Port")
if host != "" {
builder := strings.Builder{}
if proto == "https" || proto == "http" {
builder.WriteString(proto)
} else {
builder.WriteString("https")
}
builder.WriteString("://")
builder.WriteString(host)
if p, err := strconv.Atoi(port); err != nil && p > 1 && p < 65535 {
builder.WriteString(":")
builder.WriteString(port)
}
rd = builder.String()
} else {
host = req.Host
if host == "" {
infoS(req, "could not determine the redirect URL", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
rd = "https://" + host
}
}
stateCookie, err := req.Cookie("state")
if err != nil && stateCookie != nil {
left := stateCookie.Expires.Sub(time.Now())
if left > (time.Minute*9)+time.Second*50 {
infoS(req, "consecutive logins too soon", http.StatusBadRequest)
rw.WriteHeader(http.StatusBadGateway)
return
}
}
state, err := generateRandomState()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rdUrl, err := url.Parse(rd)
if err != nil {
infoS(req, "invalid rd url : "+err.Error(), http.StatusBadRequest)
rw.WriteHeader(http.StatusBadRequest)
return
}
redirectUrl := fmt.Sprintf("%s://%s%s/callback", rdUrl.Scheme, rdUrl.Host, prefix)
http.SetCookie(rw, &http.Cookie{
Name: "state",
Value: state,
Path: "/",
Expires: time.Now().Add(time.Minute * 10),
Secure: true,
HttpOnly: true,
SameSite: sameSite,
})
http.SetCookie(rw, &http.Cookie{
Name: "rd",
Value: rd,
Path: "/",
Expires: time.Now().Add(time.Minute * 10),
Secure: true,
HttpOnly: true,
SameSite: sameSite,
})
clearCookie(rw, SessionCookieName)
infoS(req, "redirecting to authorization server", http.StatusFound)
http.Redirect(rw, req, config.AuthCodeURL(state, oauth2.SetAuthURLParam("redirect_uri", redirectUrl)), http.StatusFound)
}
func clearCookie(rw http.ResponseWriter, name string) {
http.SetCookie(rw, &http.Cookie{
Name: name,
Path: "/",
Value: "",
Expires: time.Unix(0, 0),
HttpOnly: true,
})
}
func generateRandomState() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
state := base64.URLEncoding.EncodeToString(b)
return state, nil
}
func contains(s string, slice []string) bool {
for _, item := range slice {
if s == item {
return true
}
}
return false
}