/
oidc.go
858 lines (757 loc) · 22.9 KB
/
oidc.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
package auth
import (
"bytes"
"compress/flate"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/secrets"
"golang.org/x/oauth2"
)
const (
OidcUserInfoName = "oauthOidcUserInfo"
OidcAnyClaimsName = "oauthOidcAnyClaims"
OidcAllClaimsName = "oauthOidcAllClaims"
oauthOidcCookieName = "skipperOauthOidc"
stateValidity = 1 * time.Minute
oidcInfoHeader = "Skipper-Oidc-Info"
cookieMaxSize = 4093 // common cookie size limit http://browsercookielimits.squawky.net/
)
// Filter parameter:
//
// oauthOidc...("https://oidc-provider.example.com", "client_id", "client_secret",
// "http://target.example.com/subpath/callback", "email profile", "name email picture",
// "parameter=value", "X-Auth-Authorization:claims.email")
const (
paramIdpURL int = iota
paramClientID
paramClientSecret
paramCallbackURL
paramScopes
paramClaims
paramAuthCodeOpts
paramUpstrHeaders
)
type (
tokenOidcSpec struct {
typ roleCheckType
SecretsFile string
secretsRegistry secrets.EncrypterCreator
}
tokenOidcFilter struct {
typ roleCheckType
config *oauth2.Config
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
claims []string
validity time.Duration
cookiename string
redirectPath string
encrypter secrets.Encryption
authCodeOptions []oauth2.AuthCodeOption
compressor cookieCompression
upstreamHeaders map[string]string
}
tokenContainer struct {
OAuth2Token *oauth2.Token `json:"oauth2token"`
OIDCIDToken string `json:"oidctoken"`
UserInfo *oidc.UserInfo `json:"userInfo,omitempty"`
Subject string `json:"subject"`
Claims map[string]interface{} `json:"claims"`
}
cookieCompression interface {
compress([]byte) ([]byte, error)
decompress([]byte) ([]byte, error)
}
deflatePoolCompressor struct {
poolWriter *sync.Pool
}
)
// NewOAuthOidcUserInfos creates filter spec which tests user info.
func NewOAuthOidcUserInfos(secretsFile string, secretsRegistry *secrets.Registry) filters.Spec {
return &tokenOidcSpec{typ: checkOIDCUserInfo, SecretsFile: secretsFile, secretsRegistry: secretsRegistry}
}
// NewOAuthOidcAnyClaims creates a filter spec which verifies that the token
// has one of the claims specified
func NewOAuthOidcAnyClaims(secretsFile string, secretsRegistry *secrets.Registry) filters.Spec {
return &tokenOidcSpec{typ: checkOIDCAnyClaims, SecretsFile: secretsFile, secretsRegistry: secretsRegistry}
}
// NewOAuthOidcAllClaims creates a filter spec which verifies that the token
// has all the claims specified
func NewOAuthOidcAllClaims(secretsFile string, secretsRegistry *secrets.Registry) filters.Spec {
return &tokenOidcSpec{typ: checkOIDCAllClaims, SecretsFile: secretsFile, secretsRegistry: secretsRegistry}
}
// CreateFilter creates an OpenID Connect authorization filter.
//
// first arg: a provider, for example "https://accounts.google.com",
// which has the path /.well-known/openid-configuration
//
// Example:
//
// oauthOidcAllClaims("https://accounts.identity-provider.com", "some-client-id", "some-client-secret",
// "http://callback.com/auth/provider/callback", "scope1 scope2", "claim1 claim2", "<optional>", "<optional>") -> "https://internal.example.org";
func (s *tokenOidcSpec) CreateFilter(args []interface{}) (filters.Filter, error) {
sargs, err := getStrings(args)
if err != nil {
return nil, err
}
if len(sargs) < paramClaims {
return nil, filters.ErrInvalidFilterParameters
}
issuerURL, err := url.Parse(sargs[paramIdpURL])
if err != nil {
log.Errorf("Failed to parse url %s: %v.", sargs[paramIdpURL], err)
return nil, filters.ErrInvalidFilterParameters
}
provider, err := oidc.NewProvider(context.Background(), issuerURL.String())
if err != nil {
log.Errorf("Failed to create new provider %s: %v.", issuerURL, err)
return nil, filters.ErrInvalidFilterParameters
}
h := sha256.New()
for i, s := range sargs {
// CallbackURL not taken into account for cookie hashing for additional sub path ingresses
if i == paramCallbackURL {
continue
}
h.Write([]byte(s))
}
byteSlice := h.Sum(nil)
sargsHash := fmt.Sprintf("%x", byteSlice)[:8]
generatedCookieName := oauthOidcCookieName + sargsHash + "-"
log.Debugf("Generated Cookie Name: %s", generatedCookieName)
redirectURL, err := url.Parse(sargs[paramCallbackURL])
if err != nil || sargs[paramCallbackURL] == "" {
return nil, fmt.Errorf("invalid redirect url '%s': %v", sargs[paramCallbackURL], err)
}
encrypter, err := s.secretsRegistry.GetEncrypter(1*time.Minute, s.SecretsFile)
if err != nil {
return nil, err
}
f := &tokenOidcFilter{
typ: s.typ,
redirectPath: redirectURL.Path,
config: &oauth2.Config{
ClientID: sargs[paramClientID],
ClientSecret: sargs[paramClientSecret],
RedirectURL: sargs[paramCallbackURL], // self endpoint
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID}, // mandatory scope by spec
},
provider: provider,
verifier: provider.Verifier(&oidc.Config{
ClientID: sargs[paramClientID],
}),
validity: 1 * time.Hour,
cookiename: generatedCookieName,
encrypter: encrypter,
compressor: newDeflatePoolCompressor(flate.BestCompression),
}
// user defined scopes
scopes := strings.Split(sargs[paramScopes], " ")
if len(sargs[paramScopes]) == 0 {
scopes = []string{}
}
// scopes are only used to request claims to be in the IDtoken requested from auth server
// https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
f.config.Scopes = append(f.config.Scopes, scopes...)
// user defined claims to check for authnz
if len(sargs[paramClaims]) > 0 {
f.claims = strings.Split(sargs[paramClaims], " ")
}
f.authCodeOptions = make([]oauth2.AuthCodeOption, 0)
if len(sargs) > paramAuthCodeOpts && sargs[paramAuthCodeOpts] != "" {
extraParameters := strings.Split(sargs[paramAuthCodeOpts], " ")
for _, p := range extraParameters {
splitP := strings.Split(p, "=")
log.Debug(splitP)
if len(splitP) != 2 {
return nil, filters.ErrInvalidFilterParameters
}
f.authCodeOptions = append(f.authCodeOptions, oauth2.SetAuthURLParam(splitP[0], splitP[1]))
}
}
log.Debugf("Auth Code Options: %v", f.authCodeOptions)
// inject additional headers from the access token for upstream applications
if len(sargs) > paramUpstrHeaders && sargs[paramUpstrHeaders] != "" {
f.upstreamHeaders = make(map[string]string)
for _, header := range strings.Split(sargs[paramUpstrHeaders], " ") {
sl := strings.SplitN(header, ":", 2)
if len(sl) != 2 || sl[0] == "" || sl[1] == "" {
return nil, fmt.Errorf("%w: malformatted filter for upstream headers %s", filters.ErrInvalidFilterParameters, sl)
}
f.upstreamHeaders[sl[0]] = sl[1]
}
log.Debugf("Upstream Headers: %v", f.upstreamHeaders)
}
return f, nil
}
func (s *tokenOidcSpec) Name() string {
switch s.typ {
case checkOIDCUserInfo:
return OidcUserInfoName
case checkOIDCAnyClaims:
return OidcAnyClaimsName
case checkOIDCAllClaims:
return OidcAllClaimsName
}
return AuthUnknown
}
func (f *tokenOidcFilter) validateAnyClaims(h map[string]interface{}) bool {
if len(f.claims) == 0 {
return true
}
if len(h) == 0 {
return false
}
keys := make([]string, 0, len(h))
for k := range h {
keys = append(keys, k)
}
return intersect(f.claims, keys)
}
func (f *tokenOidcFilter) validateAllClaims(h map[string]interface{}) bool {
l := len(f.claims)
if l == 0 {
return true
}
if len(h) < l {
return false
}
keys := make([]string, 0, len(h))
for k := range h {
keys = append(keys, k)
}
return all(f.claims, keys)
}
type OauthState struct {
Validity int64 `json:"validity"`
Nonce string `json:"nonce"`
RedirectUrl string `json:"redirectUrl"`
}
func createState(nonce []byte, redirectUrl string) ([]byte, error) {
state := &OauthState{
Validity: time.Now().Add(stateValidity).Unix(),
Nonce: fmt.Sprintf("%x", nonce),
RedirectUrl: redirectUrl,
}
return json.Marshal(state)
}
func extractState(encState []byte) (*OauthState, error) {
var state OauthState
err := json.Unmarshal(encState, &state)
if err != nil {
return nil, err
}
return &state, nil
}
func (f *tokenOidcFilter) internalServerError(ctx filters.FilterContext) {
rsp := &http.Response{
StatusCode: http.StatusInternalServerError,
}
ctx.Serve(rsp)
}
// https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps
// 1. Client prepares an Authentication Request containing the desired request parameters.
// 2. Client sends the request to the Authorization Server.
func (f *tokenOidcFilter) doOauthRedirect(ctx filters.FilterContext) {
nonce, err := f.encrypter.CreateNonce()
if err != nil {
log.Errorf("Failed to create nonce: %v.", err)
f.internalServerError(ctx)
return
}
redirectUrl := ctx.Request().URL.String()
statePlain, err := createState(nonce, redirectUrl)
if err != nil {
log.Errorf("Failed to create oauth2 state: %v.", err)
f.internalServerError(ctx)
return
}
stateEnc, err := f.encrypter.Encrypt(statePlain)
if err != nil {
log.Errorf("Failed to encrypt data block: %v.", err)
f.internalServerError(ctx)
return
}
oauth2URL := f.config.AuthCodeURL(fmt.Sprintf("%x", stateEnc), f.authCodeOptions...)
rsp := &http.Response{
Header: http.Header{
"Location": []string{oauth2URL},
},
StatusCode: http.StatusTemporaryRedirect,
Status: "Moved Temporarily",
}
log.Debugf("serve redirect: plaintextState:%s to Location: %s", statePlain, rsp.Header.Get("Location"))
ctx.Serve(rsp)
}
func (f *tokenOidcFilter) Response(filters.FilterContext) {}
func extractDomainFromHost(host string) string {
h, _, err := net.SplitHostPort(host)
if err != nil {
h = host
}
ip := net.ParseIP(h)
if ip != nil {
return ip.String()
}
if strings.Count(h, ".") < 2 {
return h
}
return strings.Join(strings.Split(h, ".")[1:], ".")
}
func getHost(request *http.Request) string {
if h := request.Header.Get("host"); h != "" {
return h
} else {
return request.Host
}
}
func chunkCookie(cookie http.Cookie) (cookies []http.Cookie) {
for index := 'a'; index <= 'z'; index++ {
cookieSize := len(cookie.String())
if cookieSize < cookieMaxSize {
cookie.Name += string(index)
return append(cookies, cookie)
}
newCookie := cookie
newCookie.Name += string(index)
// non-deterministic approach support signature changes
cut := len(cookie.Value) - (cookieSize - cookieMaxSize) - 1
newCookie.Value, cookie.Value = cookie.Value[:cut], cookie.Value[cut:]
cookies = append(cookies, newCookie)
}
log.Error("unsupported amount of chunked cookies")
return
}
func mergerCookies(cookies []http.Cookie) (cookie http.Cookie) {
if len(cookies) == 0 {
return
}
cookie = cookies[0]
cookie.Name = cookie.Name[:len(cookie.Name)-1]
cookie.Value = ""
// potentially shuffeled
sort.Slice(cookies, func(i, j int) bool {
return cookies[i].Name < cookies[j].Name
})
for _, ck := range cookies {
cookie.Value += ck.Value
}
return
}
func (f *tokenOidcFilter) doDownstreamRedirect(ctx filters.FilterContext, oidcState []byte, redirectUrl string) {
log.Debugf("Doing Downstream Redirect to :%s", redirectUrl)
r := &http.Response{
StatusCode: http.StatusTemporaryRedirect,
Header: http.Header{
"Location": {redirectUrl},
},
}
oidcCookies := chunkCookie(http.Cookie{
Name: f.cookiename,
Value: base64.StdEncoding.EncodeToString(oidcState),
Path: "/",
Secure: true,
HttpOnly: true,
MaxAge: int(f.validity.Seconds()),
Domain: extractDomainFromHost(getHost(ctx.Request())),
})
for _, cookie := range oidcCookies {
r.Header.Add("Set-Cookie", cookie.String())
}
ctx.Serve(r)
}
func (f *tokenOidcFilter) validateCookie(cookie *http.Cookie) ([]byte, bool) {
if cookie == nil {
log.Debugf("Cookie is nil")
return nil, false
}
log.Debugf("validate cookie name: %s", f.cookiename)
decodedCookie, err := base64.StdEncoding.DecodeString(cookie.Value)
if err != nil {
log.Debugf("Base64 decoding the cookie failed: %v", err)
return nil, false
}
decryptedCookie, err := f.encrypter.Decrypt(decodedCookie)
if err != nil {
log.Debugf("Decrypting the cookie failed: %v", err)
return nil, false
}
decompressedCookie, err := f.compressor.decompress(decryptedCookie)
if err != nil {
log.Error(err)
return nil, false
}
return decompressedCookie, true
}
// https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps
// 5. Authorization Server sends the End-User back to the Client with an Authorization Code.
func (f *tokenOidcFilter) callbackEndpoint(ctx filters.FilterContext) {
var (
claimsMap map[string]interface{}
oauth2Token *oauth2.Token
data []byte
resp tokenContainer
sub string
userInfo *oidc.UserInfo
oidcIDToken string
)
r := ctx.Request()
oauthState, err := f.getCallbackState(ctx)
if err != nil {
if _, ok := err.(*requestError); !ok {
log.Errorf("Error while retrieving callback state: %v.", err)
}
unauthorized(
ctx,
"",
invalidToken,
r.Host,
fmt.Sprintf("Failed to get state from callback: %v.", err),
)
return
}
oauth2Token, err = f.getTokenWithExchange(oauthState, ctx)
if err != nil {
if _, ok := err.(*requestError); !ok {
log.Errorf("Error while getting token in callback: %v.", err)
}
unauthorized(
ctx,
"",
invalidClaim,
r.Host,
fmt.Sprintf("Failed to get token in callback: %v.", err),
)
return
}
switch f.typ {
case checkOIDCUserInfo:
userInfo, err = f.provider.UserInfo(r.Context(), oauth2.StaticTokenSource(oauth2Token))
if err != nil {
// error coming from an external library and the possible error reasons are
// not documented explicitly, so we assume that the cause is always rooted
// in the incoming request, and only log it with a debug flag, via calling
// unauthorized().
unauthorized(
ctx,
"",
invalidToken,
r.Host,
fmt.Sprintf("Failed to get userinfo: %v.", err),
)
return
}
oidcIDToken, err = f.getidtoken(ctx, oauth2Token)
if err != nil {
if _, ok := err.(*requestError); !ok {
log.Errorf("Error while getting id token: %v", err)
}
unauthorized(
ctx,
"",
invalidClaim,
r.Host,
fmt.Sprintf("Failed to get id token: %v", err),
)
return
}
sub = userInfo.Subject
claimsMap, _, err = f.tokenClaims(ctx, oauth2Token)
if err != nil {
unauthorized(
ctx,
"",
invalidToken,
r.Host,
fmt.Sprintf("Failed to get claims: %v.", err),
)
return
}
case checkOIDCAnyClaims, checkOIDCAllClaims:
oidcIDToken, err = f.getidtoken(ctx, oauth2Token)
if err != nil {
if _, ok := err.(*requestError); !ok {
log.Errorf("Error while getting id token: %v", err)
}
unauthorized(
ctx,
"",
invalidClaim,
r.Host,
fmt.Sprintf("Failed to get id token: %v", err),
)
return
}
claimsMap, sub, err = f.tokenClaims(ctx, oauth2Token)
if err != nil {
if _, ok := err.(*requestError); !ok {
log.Errorf("Failed to get claims with error: %v", err)
}
unauthorized(
ctx,
"",
invalidToken,
r.Host,
fmt.Sprintf(
"Failed to get claims: %s, %v",
f.claims,
err,
),
)
return
}
}
resp = tokenContainer{
OAuth2Token: oauth2Token,
OIDCIDToken: oidcIDToken,
UserInfo: userInfo,
Subject: sub,
Claims: claimsMap,
}
data, err = json.Marshal(resp)
if err != nil {
log.Errorf("Failed to serialize claims: %v.", err)
unauthorized(
ctx,
"",
invalidSub,
r.Host,
"Failed to serialize claims.",
)
return
}
compressedData, err := f.compressor.compress(data)
if err != nil {
log.Error(err)
}
encryptedData, err := f.encrypter.Encrypt(compressedData)
if err != nil {
log.Errorf("Failed to encrypt the returned oidc data: %v.", err)
unauthorized(
ctx,
"",
invalidSub,
r.Host,
"Failed to encrypt the returned oidc data.",
)
return
}
f.doDownstreamRedirect(ctx, encryptedData, oauthState.RedirectUrl)
}
func (f *tokenOidcFilter) Request(ctx filters.FilterContext) {
var (
allowed bool
cookies []http.Cookie
container tokenContainer
)
r := ctx.Request()
for _, cookie := range r.Cookies() {
if strings.HasPrefix(cookie.Name, f.cookiename) {
cookies = append(cookies, *cookie)
}
}
sessionCookie := mergerCookies(cookies)
log.Debugf("Request: Cookie merged, %d chunks, len: %d", len(cookies), len(sessionCookie.String()))
cookie, ok := f.validateCookie(&sessionCookie)
log.Debugf("Request: Cookie Validation: %v", ok)
if !ok {
// 5. Authorization Server sends the End-User back to the Client with an Authorization Code.
if strings.Contains(r.URL.Path, f.redirectPath) {
f.callbackEndpoint(ctx)
return
}
// 1. Client prepares an Authentication Request containing the desired request parameters.
f.doOauthRedirect(ctx)
return
}
err := json.Unmarshal([]byte(cookie), &container)
if err != nil {
unauthorized(
ctx,
"",
invalidToken,
r.Host,
fmt.Sprintf("Failed to deserialize cookie: %v.", err),
)
return
}
// filter specific checks
switch f.typ {
case checkOIDCUserInfo:
if container.OAuth2Token.Valid() && container.UserInfo != nil {
allowed = f.validateAllClaims(container.Claims)
}
case checkOIDCAnyClaims:
allowed = f.validateAnyClaims(container.Claims)
case checkOIDCAllClaims:
allowed = f.validateAllClaims(container.Claims)
default:
unauthorized(ctx, "unknown", invalidFilter, r.Host, "")
return
}
if !allowed {
unauthorized(ctx, container.Subject, invalidClaim, r.Host, "")
return
}
// saving token info for chained filter
ctx.StateBag()[oidcClaimsCacheKey] = container
// adding upstream headers
err = f.setHeaders(ctx, container)
if err != nil {
log.Error(err)
f.internalServerError(ctx)
return
}
}
func (f *tokenOidcFilter) setHeaders(ctx filters.FilterContext, container tokenContainer) (err error) {
oidcInfoJson, err := json.Marshal(container)
if err != nil || !gjson.ValidBytes(oidcInfoJson) {
return fmt.Errorf("failed to serialize OIDC token info: %w", err)
}
// backwards compatible
if len(f.upstreamHeaders) == 0 {
ctx.Request().Header.Set(oidcInfoHeader, string(oidcInfoJson))
return
}
parsed := gjson.ParseBytes(oidcInfoJson)
for key, query := range f.upstreamHeaders {
match := parsed.Get(query)
log.Debugf("header: %s results: %s", query, match.String())
if !match.Exists() {
log.Errorf("Lookup failed for upstream header '%s'", query)
continue
}
ctx.Request().Header.Set(key, match.String())
}
return
}
func (f *tokenOidcFilter) tokenClaims(ctx filters.FilterContext, oauth2Token *oauth2.Token) (map[string]interface{}, string, error) {
r := ctx.Request()
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
return nil, "", requestErrorf("invalid token, no id_token field in oauth2 token")
}
var idToken *oidc.IDToken
idToken, err := f.verifier.Verify(r.Context(), rawIDToken)
if err != nil {
return nil, "", requestErrorf("failed to verify id token: %v", err)
}
tokenMap := make(map[string]interface{})
if err = idToken.Claims(&tokenMap); err != nil {
return nil, "", requestErrorf("failed to deserialize id token: %v", err)
}
sub, ok := tokenMap["sub"].(string)
if !ok {
return nil, "", requestErrorf("claims do not contain sub")
}
return tokenMap, sub, nil
}
func (f *tokenOidcFilter) getidtoken(ctx filters.FilterContext, oauth2Token *oauth2.Token) (string, error) {
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
return "", requestErrorf("invalid token, no id_token field in oauth2 token")
}
return rawIDToken, nil
}
func (f *tokenOidcFilter) getCallbackState(ctx filters.FilterContext) (*OauthState, error) {
// CSRF protection using similar to
// https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Encrypted_Token_Pattern,
// because of https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
r := ctx.Request()
stateQueryEncHex := r.URL.Query().Get("state")
if stateQueryEncHex == "" {
return nil, requestErrorf("no state parameter")
}
stateQueryEnc := make([]byte, len(stateQueryEncHex))
if _, err := fmt.Sscanf(stateQueryEncHex, "%x", &stateQueryEnc); err != nil && err != io.EOF {
return nil, requestErrorf("failed to read hex string: %v", err)
}
stateQueryPlain, err := f.encrypter.Decrypt(stateQueryEnc)
if err != nil {
// TODO: Implement metrics counter for number of incorrect tokens
return nil, requestErrorf("token from state query is invalid: %v", err)
}
log.Debugf("len(stateQueryPlain): %d, stateQueryEnc: %d, stateQueryEncHex: %d", len(stateQueryPlain), len(stateQueryEnc), len(stateQueryEncHex))
state, err := extractState(stateQueryPlain)
if err != nil {
return nil, requestErrorf("failed to deserialize state: %v", err)
}
return state, nil
}
func (f *tokenOidcFilter) getTokenWithExchange(state *OauthState, ctx filters.FilterContext) (*oauth2.Token, error) {
r := ctx.Request()
if state.Validity < time.Now().Unix() {
return nil, requestErrorf("state is no longer valid. %v", state.Validity)
}
// authcode flow
code := r.URL.Query().Get("code")
// https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps
// 6. Client requests a response using the Authorization Code at the Token Endpoint.
// 7. Client receives a response that contains an ID Token and Access Token in the response body.
oauth2Token, err := f.config.Exchange(r.Context(), code, f.authCodeOptions...)
if err != nil {
// error coming from an external library and the possible error reasons are
// not documented explicitly, so we assume that the cause is always rooted
// in the incoming request.
err = requestErrorf("oauth2 exchange: %v", err)
}
return oauth2Token, err
}
func (f *tokenOidcFilter) Close() error {
f.encrypter.Close()
return nil
}
func newDeflatePoolCompressor(level int) *deflatePoolCompressor {
return &deflatePoolCompressor{
poolWriter: &sync.Pool{
New: func() interface{} {
w, err := flate.NewWriter(ioutil.Discard, level)
if err != nil {
log.Errorf("failed to generate new deflate writer: %v", err)
}
return w
},
},
}
}
func (dc *deflatePoolCompressor) compress(rawData []byte) ([]byte, error) {
pw, ok := dc.poolWriter.Get().(*flate.Writer)
if !ok || pw == nil {
return nil, fmt.Errorf("could not get a flate.Writer from the pool")
}
defer dc.poolWriter.Put(pw)
var buf bytes.Buffer
pw.Reset(&buf)
if _, err := pw.Write(rawData); err != nil {
return nil, err
}
if err := pw.Close(); err != nil {
return nil, err
}
log.Debugf("cookie compressed: %d to %d", len(rawData), buf.Len())
return buf.Bytes(), nil
}
func (dc *deflatePoolCompressor) decompress(compData []byte) ([]byte, error) {
zr := flate.NewReader(bytes.NewReader(compData))
if err := zr.Close(); err != nil {
return nil, err
}
return ioutil.ReadAll(zr)
}