-
Notifications
You must be signed in to change notification settings - Fork 1
/
federated.go
953 lines (765 loc) · 28.4 KB
/
federated.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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
/*
Copyright 2022-2024 EscherCloud.
Copyright 2024 the Unikorn Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package oauth2
import (
"bytes"
"context"
"crypto/md5" //nolint:gosec
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
_ "embed"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"text/template"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-jose/go-jose/v3/jwt"
"github.com/spf13/pflag"
"golang.org/x/oauth2"
"github.com/unikorn-cloud/core/pkg/server/errors"
unikornv1 "github.com/unikorn-cloud/identity/pkg/apis/unikorn/v1alpha1"
"github.com/unikorn-cloud/identity/pkg/generated"
"github.com/unikorn-cloud/identity/pkg/jose"
"github.com/unikorn-cloud/identity/pkg/oauth2/providers"
"github.com/unikorn-cloud/identity/pkg/rbac"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)
type Options struct {
}
func (o *Options) AddFlags(f *pflag.FlagSet) {
}
// Authenticator provides Keystone authentication functionality.
type Authenticator struct {
options *Options
namespace string
client client.Client
// issuer allows creation and validation of JWT bearer tokens.
issuer *jose.JWTIssuer
rbac *rbac.RBAC
}
// New returns a new authenticator with required fields populated.
// You must call AddFlags after this.
func New(options *Options, namespace string, client client.Client, issuer *jose.JWTIssuer, rbac *rbac.RBAC) *Authenticator {
return &Authenticator{
options: options,
namespace: namespace,
client: client,
issuer: issuer,
rbac: rbac,
}
}
func (a *Authenticator) GetRBAC() *rbac.RBAC {
return a.rbac
}
type Error string
const (
ErrorInvalidRequest Error = "invalid_request"
ErrorUnauthorizedClient Error = "unauthorized_client"
ErrorAccessDenied Error = "access_denied"
ErrorUnsupportedResponseType Error = "unsupported_response_type"
ErrorInvalidScope Error = "invalid_scope"
ErrorServerError Error = "server_error"
)
const (
ProviderCookie = "provider"
)
// State records state across the call to the authorization server.
// This must be encrypted with JWE.
type State struct {
// Nonce is the one time nonce used to create the token.
Nonce string `json:"n"`
// Code verfier is required to prove our identity when
// exchanging the code with the token endpoint.
CodeVerfier string `json:"cv"`
// OAuth2Provider is the name of the provider configuration in
// use, this will reference the issuer and allow discovery.
OAuth2Provider string `json:"oap"`
// ClientID is the client identifier.
ClientID string `json:"cid"`
// ClientRedirectURI is the redirect URL requested by the client.
ClientRedirectURI string `json:"cri"`
// Client state records the client's OAuth state while we interact
// with the OIDC authorization server.
ClientState string `json:"cst,omitempty"`
// ClientCodeChallenge records the client code challenge so we can
// authenticate we are handing the authorization token back to the
// correct client.
ClientCodeChallenge string `json:"ccc"`
// ClientScope records the requested client scope.
ClientScope Scope `json:"csc,omitempty"`
// ClientNonce is injected into a OIDC id_token.
ClientNonce string `json:"cno,omitempty"`
}
// Code is an authorization code to return to the client that can be
// exchanged for an access token. Much like how we client things in the oauth2
// state during the OIDC exchange, to mitigate problems with horizonal scaling
// and sharing stuff, we do the same here.
// WARNING: Don't make this too big, the ingress controller will barf if the
// headers are too hefty.
type Code struct {
// ClientID is the client identifier.
ClientID string `json:"cid"`
// ClientRedirectURI is the redirect URL requested by the client.
ClientRedirectURI string `json:"cri"`
// ClientCodeChallenge records the client code challenge so we can
// authenticate we are handing the authorization token back to the
// correct client.
ClientCodeChallenge string `json:"ccc"`
// ClientScope records the requested client scope.
ClientScope Scope `json:"csc,omitempty"`
// ClientNonce is injected into a OIDC id_token.
ClientNonce string `json:"cno,omitempty"`
// Subject is the canonical subject name (not an alias).
Subject string `json:"sub"`
// Groups is the set of groups the user has with the IdP.
Groups []string `json:"grp,omitempty"`
}
var (
// errorTemplate defines the HTML used to raise an error to the client.
//go:embed error.tmpl
errorTemplate string
// loginTemplate defines the HTML used to acquire an email address from
// the end user.
//go:embed login.tmpl
loginTemplate string
)
// htmlError is used in dire situations when we cannot return an error via
// the usual oauth2 flow.
func htmlError(w http.ResponseWriter, r *http.Request, status int, description string) {
log := log.FromContext(r.Context())
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(status)
tmpl, err := template.New("error").Parse(errorTemplate)
if err != nil {
log.Info("oauth2: failed to parse template", "error", err)
return
}
templateContext := map[string]interface{}{
"description": description,
}
var buffer bytes.Buffer
if err := tmpl.Execute(&buffer, templateContext); err != nil {
log.Info("oauth2: failed to render template", "error", err)
return
}
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Info("oauth2: failed to write HTML response")
}
}
// authorizationError redirects to the client's callback URI with an error
// code in the query.
func authorizationError(w http.ResponseWriter, r *http.Request, redirectURI string, kind Error, description string) {
values := &url.Values{}
values.Set("error", string(kind))
values.Set("error_description", description)
http.Redirect(w, r, redirectURI+"?"+values.Encode(), http.StatusFound)
}
func (a *Authenticator) lookupClient(w http.ResponseWriter, r *http.Request, clientID string) (*unikornv1.OAuth2Client, bool) {
var clients unikornv1.OAuth2ClientList
if err := a.client.List(r.Context(), &clients, &client.ListOptions{Namespace: a.namespace}); err != nil {
htmlError(w, r, http.StatusInternalServerError, err.Error())
return nil, false
}
for i := range clients.Items {
if clients.Items[i].Spec.ID == clientID {
return &clients.Items[i], true
}
}
htmlError(w, r, http.StatusBadRequest, "client_id is invalid")
return nil, false
}
// OAuth2AuthorizationValidateNonRedirecting checks authorization request parameters
// are valid that directly control the ability to redirect, and returns some helpful
// debug in HTML.
func (a *Authenticator) authorizationValidateNonRedirecting(w http.ResponseWriter, r *http.Request) bool {
query := r.URL.Query()
if !query.Has("client_id") {
htmlError(w, r, http.StatusBadRequest, "client_id is not specified")
return false
}
if !query.Has("redirect_uri") {
htmlError(w, r, http.StatusBadRequest, "redirect_uri is not specified")
return false
}
client, ok := a.lookupClient(w, r, query.Get("client_id"))
if !ok {
return false
}
if client.Spec.RedirectURI != query.Get("redirect_uri") {
htmlError(w, r, http.StatusBadRequest, "redirect_uri is invalid")
return false
}
return true
}
// OAuth2AuthorizationValidateRedirecting checks autohorization request parameters after
// the redirect URI has been validated. If any of these fail, we redirect but with an
// error query rather than a code for the client to pick up and run with.
func (a *Authenticator) authorizationValidateRedirecting(w http.ResponseWriter, r *http.Request) bool {
query := r.URL.Query()
var kind Error
var description string
switch {
case query.Get("response_type") != "code":
kind = ErrorUnsupportedResponseType
description = "response_type must be 'code'"
case query.Get("code_challenge_method") != "S256":
kind = ErrorInvalidRequest
description = "code_challenge_method must be 'S256'"
case query.Get("code_challenge") == "":
kind = ErrorInvalidRequest
description = "code_challenge must be specified"
default:
return true
}
authorizationError(w, r, query.Get("redirect_uri"), kind, description)
return false
}
// oidcConfig returns a oauth2 configuration for the OIDC backend.
func (a *Authenticator) oidcConfig(r *http.Request, provider *unikornv1.OAuth2Provider, endpoint oauth2.Endpoint, scopes []string) *oauth2.Config {
s := []string{
oidc.ScopeOpenID,
// For the user's name.
"profile",
// For the user's real email address i.e. not an alias.
"email",
}
s = append(s, scopes...)
return &oauth2.Config{
ClientID: provider.Spec.ClientID,
Endpoint: endpoint,
// TODO: the ingress converts this all into a relative URL
// and adds an X-Forwardered-Host, X-Forwarded-Proto. You should
// never use HTTP anyway to be fair...
RedirectURL: "https://" + r.Host + "/oidc/callback",
Scopes: s,
}
}
// encodeCodeChallengeS256 performs code verifier to code challenge translation
// for the SHA256 method.
func encodeCodeChallengeS256(codeVerifier string) string {
hash := sha256.Sum256([]byte(codeVerifier))
return base64.RawURLEncoding.EncodeToString(hash[:])
}
// randomString creates size bytes of high entropy randomness and base64 URL
// encodes it into a string. Bear in mind base64 expands the size by 33%, so for example
// an oauth2 code verifier needs to be at least 43 bytes, so youd nee'd a size of 32,
// 32 * 1.33 = 42.66.
func randomString(size int) (string, error) {
buf := make([]byte, size)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
type providerGetter func(*http.Request, string) (*unikornv1.OAuth2Provider, error)
func (a *Authenticator) cookieProviderGetter(r *http.Request, _ string) (*unikornv1.OAuth2Provider, error) {
providerCookie, err := r.Cookie(ProviderCookie)
if err != nil {
return nil, err
}
return a.lookupProviderByType(r.Context(), unikornv1.IdentityProviderType(providerCookie.Value))
}
func (a *Authenticator) organizationProviderGetter(r *http.Request, email string) (*unikornv1.OAuth2Provider, error) {
organization, err := a.lookupOrganization(r.Context(), email)
if err != nil {
return nil, err
}
return a.lookupProviderByName(r.Context(), *organization.Spec.ProviderName)
}
func (a *Authenticator) providerGetters() []providerGetter {
return []providerGetter{
a.cookieProviderGetter,
a.organizationProviderGetter,
}
}
// Authorization redirects the client to the OIDC autorization endpoint
// to get an authorization code. Note that this function is responsible for
// either returning an authorization grant or error via a HTTP 302 redirect,
// or returning a HTML fragment for errors that cannot follow the provided
// redirect URI.
//
//nolint:cyclop
func (a *Authenticator) Authorization(w http.ResponseWriter, r *http.Request) {
log := log.FromContext(r.Context())
query := r.URL.Query()
if !a.authorizationValidateNonRedirecting(w, r) {
return
}
if !a.authorizationValidateRedirecting(w, r) {
return
}
// If the login_hint is provided, we can short cut the user interaction and
// directly do the request to the backend provider. This makes token expiry
// alomost seamless in that a client can catch a 401, and just redirect back
// here with the cached email address in the id_token. For users who have
// clicked "login in X", we need to have remembered this provider with a
// cookie also.
if email := query.Get("login_hint"); email != "" {
for _, getter := range a.providerGetters() {
provider, err := getter(r, email)
if err == nil {
a.providerAuthenticationRequest(w, r, email, provider, query)
return
}
}
}
loginQuery := url.Values{}
loginQuery.Set("state", query.Encode())
loginQuery.Set("callback", "https://"+r.Host+"/oauth2/v2/login")
// TODO: this needs to be driven by the available oauth2providers
loginQuery.Set("providers", "google microsoft")
client, ok := a.lookupClient(w, r, query.Get("client_id"))
if !ok {
htmlError(w, r, http.StatusBadRequest, "client_id is not specified")
return
}
// Redirect to an external login handler, if you have chosen to.
if client.Spec.LoginURI != nil {
http.Redirect(w, r, fmt.Sprintf("%s?%s", *client.Spec.LoginURI, loginQuery.Encode()), http.StatusFound)
return
}
// Otherwise use the internal version.
tmpl, err := template.New("login").Parse(loginTemplate)
if err != nil {
log.Info("oauth2: failed to parse template", "error", err)
return
}
templateContext := map[string]interface{}{
"state": query.Encode(),
}
var buffer bytes.Buffer
if err := tmpl.Execute(&buffer, templateContext); err != nil {
log.Info("oauth2: failed to render template", "error", err)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Info("oauth2: failed to write HTML response")
}
}
// lookupOrganization maps from an email address to an organization, this handles
// corporate mandates that say your entire domain have to use a single sign on
// provider across the entire enterprise.
func (a *Authenticator) lookupOrganization(ctx context.Context, email string) (*unikornv1.Organization, error) {
if email == "" {
//nolint:goerr113
return nil, fmt.Errorf("no email address provided")
}
// TODO: error checking.
parts := strings.Split(email, "@")
// TODO: error checking.
domain := parts[1]
var organizations unikornv1.OrganizationList
if err := a.client.List(ctx, &organizations, &client.ListOptions{Namespace: a.namespace}); err != nil {
return nil, err
}
for i := range organizations.Items {
if organizations.Items[i].Spec.Domain == nil {
continue
}
if *organizations.Items[i].Spec.Domain == domain {
return &organizations.Items[i], nil
}
}
// TODO: error type!
//nolint:goerr113
return nil, fmt.Errorf("unsupported domain")
}
func (a *Authenticator) lookupProviderByType(ctx context.Context, t unikornv1.IdentityProviderType) (*unikornv1.OAuth2Provider, error) {
var resources unikornv1.OAuth2ProviderList
if err := a.client.List(ctx, &resources, &client.ListOptions{Namespace: a.namespace}); err != nil {
return nil, err
}
for i := range resources.Items {
if resources.Items[i].Spec.Type == t {
return &resources.Items[i], nil
}
}
// TODO: error type!
//nolint:goerr113
return nil, fmt.Errorf("unsupported provider type")
}
func (a *Authenticator) lookupProviderByName(ctx context.Context, name string) (*unikornv1.OAuth2Provider, error) {
var providerResource unikornv1.OAuth2Provider
if err := a.client.Get(ctx, client.ObjectKey{Namespace: a.namespace, Name: name}, &providerResource); err != nil {
return nil, err
}
return &providerResource, nil
}
// newOIDCProvider abstracts away any hacks for specific providers.
func newOIDCProvider(ctx context.Context, p *unikornv1.OAuth2Provider) (*oidc.Provider, error) {
if p.Spec.Type == unikornv1.MicrosoftEntra {
ctx = oidc.InsecureIssuerURLContext(ctx, "https://login.microsoftonline.com/{tenantid}/v2.0")
}
return oidc.NewProvider(ctx, p.Spec.Issuer)
}
// providerAuthenticationRequest takes a client provided email address and routes it
// to the correct identity provider, if we can.
func (a *Authenticator) providerAuthenticationRequest(w http.ResponseWriter, r *http.Request, email string, providerResource *unikornv1.OAuth2Provider, query url.Values) {
log := log.FromContext(r.Context())
driver := providers.New(providerResource.Spec.Type)
provider, err := newOIDCProvider(r.Context(), providerResource)
if err != nil {
log.Error(err, "failed to do OIDC discovery")
return
}
endpoint := provider.Endpoint()
clientRedirectURI := query.Get("redirect_uri")
// OIDC requires a nonce, just some random data base64 URL encoded will suffice.
nonce, err := randomString(16)
if err != nil {
authorizationError(w, r, clientRedirectURI, ErrorServerError, "unable to create oidc nonce: "+err.Error())
return
}
// We pass a hashed code challenge to the OIDC authorization endpoint when
// requesting an authentication code. When we exchange that for a token we
// send the initial code challenge verifier so the token endpoint can validate
// it's talking to the same client.
codeVerifier, err := randomString(32)
if err != nil {
authorizationError(w, r, clientRedirectURI, ErrorServerError, "unable to create oauth2 code verifier: "+err.Error())
return
}
codeChallenge := encodeCodeChallengeS256(codeVerifier)
// Rather than cache any state we require after the oauth rediretion dance, which
// requires persistent state at the minimum, and a database in the case of multi-head
// deployments, just encrypt it and send with the authoriation request.
oidcState := &State{
OAuth2Provider: providerResource.Name,
Nonce: nonce,
CodeVerfier: codeVerifier,
ClientID: query.Get("client_id"),
ClientRedirectURI: query.Get("redirect_uri"),
ClientState: query.Get("state"),
ClientCodeChallenge: query.Get("code_challenge"),
}
// To implement OIDC we need a copy of the scopes.
if query.Has("scope") {
oidcState.ClientScope = NewScope(query.Get("scope"))
}
if query.Has("nonce") {
oidcState.ClientNonce = query.Get("nonce")
}
state, err := a.issuer.EncodeJWEToken(oidcState)
if err != nil {
authorizationError(w, r, clientRedirectURI, ErrorServerError, "failed to encode oidc state: "+err.Error())
return
}
// Finally generate the redirection URL and send back to the client.
authURLParams := []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
oauth2.SetAuthURLParam("login_hint", email),
oidc.Nonce(nonce),
}
http.Redirect(w, r, a.oidcConfig(r, providerResource, endpoint, driver.Scopes()).AuthCodeURL(state, authURLParams...), http.StatusFound)
}
// Login handles the response from the user login prompt.
func (a *Authenticator) Login(w http.ResponseWriter, r *http.Request) {
log := log.FromContext(r.Context())
if err := r.ParseForm(); err != nil {
log.Error(err, "form parse failed")
return
}
if !r.Form.Has("state") {
log.Info("state doesn't exist in form")
return
}
query, err := url.ParseQuery(r.Form.Get("state"))
if err != nil {
log.Error(err, "failed to parse query")
return
}
if providerType := r.Form.Get("provider"); providerType != "" {
provider, err := a.lookupProviderByType(r.Context(), unikornv1.IdentityProviderType(providerType))
if err != nil {
authorizationError(w, r, query.Get("redirect_uri"), ErrorServerError, err.Error())
return
}
// Remember the choice for steam-lining login when a login_hint is provided.
cookie := &http.Cookie{
Name: ProviderCookie,
Value: providerType,
Secure: true,
HttpOnly: true,
}
w.Header().Add("Set-Cookie", cookie.String())
a.providerAuthenticationRequest(w, r, r.Form.Get("email"), provider, query)
return
}
// Remove the cookie otherwise.
cookie := &http.Cookie{
Name: ProviderCookie,
Value: "undefined",
MaxAge: -1,
}
w.Header().Add("Set-Cookie", cookie.String())
if !r.Form.Has("email") {
log.Info("email doesn't exist in form")
return
}
organization, err := a.lookupOrganization(r.Context(), r.Form.Get("email"))
if err != nil {
authorizationError(w, r, query.Get("redirect_uri"), ErrorServerError, err.Error())
return
}
provider, err := a.lookupProviderByName(r.Context(), *organization.Spec.ProviderName)
if err != nil {
authorizationError(w, r, query.Get("redirect_uri"), ErrorServerError, err.Error())
return
}
a.providerAuthenticationRequest(w, r, r.Form.Get("email"), provider, query)
}
// oidcExtractIDToken wraps up token verification against the JWKS service and conversion
// to a concrete type.
func (a *Authenticator) oidcExtractIDToken(ctx context.Context, provider *oidc.Provider, providerResource *unikornv1.OAuth2Provider, token string) (*oidc.IDToken, error) {
config := &oidc.Config{
ClientID: providerResource.Spec.ClientID,
// TODO: this is a Entra-ism
SkipIssuerCheck: true,
}
idTokenVerifier := provider.Verifier(config)
idToken, err := idTokenVerifier.Verify(ctx, token)
if err != nil {
return nil, err
}
return idToken, nil
}
// OIDCCallback is called by the authorization endpoint in order to return an
// authorization back to us. We then exchange the code for an ID token, and
// refresh token. Remember, as far as the client is concerned we're still doing
// the code grant, so return errors in the redirect query.
//
//nolint:cyclop
func (a *Authenticator) OIDCCallback(w http.ResponseWriter, r *http.Request) {
log := log.FromContext(r.Context())
query := r.URL.Query()
// This should always be present, if not then we are boned and cannot
// send an error back to the redirectURI, cos that's in the state!
if !query.Has("state") {
htmlError(w, r, http.StatusBadRequest, "oidc state is required")
return
}
// Extract our state for the next part...
state := &State{}
if err := a.issuer.DecodeJWEToken(query.Get("state"), state); err != nil {
htmlError(w, r, http.StatusBadRequest, "oidc state failed to decode")
return
}
if query.Has("error") {
authorizationError(w, r, state.ClientRedirectURI, Error(query.Get("error")), query.Get("description"))
return
}
if !query.Has("code") {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "oidc callback does not contain an authorization code")
return
}
var providerResource unikornv1.OAuth2Provider
if err := a.client.Get(r.Context(), client.ObjectKey{Namespace: a.namespace, Name: state.OAuth2Provider}, &providerResource); err != nil {
log.Error(err, "failed to get provider")
return
}
provider, err := newOIDCProvider(r.Context(), &providerResource)
if err != nil {
log.Error(err, "failed to do OIDC discovery")
return
}
endpoint := provider.Endpoint()
// Exchange the code for an id_token, access_token and refresh_token with
// the extracted code verifier.
authURLParams := []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("client_id", state.ClientID),
oauth2.SetAuthURLParam("code_verifier", state.CodeVerfier),
}
if providerResource.Spec.ClientSecret != nil {
authURLParams = append(authURLParams, oauth2.SetAuthURLParam("client_secret", *providerResource.Spec.ClientSecret))
}
tokens, err := a.oidcConfig(r, &providerResource, endpoint, nil).Exchange(r.Context(), query.Get("code"), authURLParams...)
if err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "oidc code exchange failed: "+err.Error())
return
}
idTokenRaw, ok := tokens.Extra("id_token").(string)
if !ok {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "oidc response missing id_token")
return
}
idToken, err := a.oidcExtractIDToken(r.Context(), provider, &providerResource, idTokenRaw)
if err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "id_token verification failed: "+err.Error())
return
}
var claims OIDCClaimsEmail
if err := idToken.Claims(&claims); err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "failed to extract id_token email claims: "+err.Error())
return
}
userExists, err := a.rbac.UserExists(r.Context(), claims.Email)
if err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "failed to perform RBAC user lookup: "+err.Error())
return
}
if !userExists {
authorizationError(w, r, state.ClientRedirectURI, ErrorAccessDenied, "user not found")
return
}
// Grab user RBAC information while we have the access token.
organization, _ := a.lookupOrganization(r.Context(), claims.Email)
driver := providers.New(providerResource.Spec.Type)
groups, err := driver.Groups(r.Context(), organization, idToken, tokens.AccessToken)
if err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "failed to lookup user groups: "+err.Error())
return
}
// NOTE: the email is the canonical one returned by the IdP, which removes
// aliases from the equation.
oauth2Code := &Code{
ClientID: state.ClientID,
ClientRedirectURI: state.ClientRedirectURI,
ClientCodeChallenge: state.ClientCodeChallenge,
ClientScope: state.ClientScope,
ClientNonce: state.ClientNonce,
Subject: claims.Email,
Groups: groups,
}
code, err := a.issuer.EncodeJWEToken(oauth2Code)
if err != nil {
authorizationError(w, r, state.ClientRedirectURI, ErrorServerError, "failed to encode authorization code: "+err.Error())
return
}
q := &url.Values{}
q.Set("code", code)
if state.ClientState != "" {
q.Set("state", state.ClientState)
}
http.Redirect(w, r, state.ClientRedirectURI+"?"+q.Encode(), http.StatusFound)
}
// tokenValidate does any request validation when issuing a token.
func tokenValidate(r *http.Request) error {
if r.Form.Get("grant_type") != "authorization_code" {
return errors.OAuth2UnsupportedGrantType("grant_type must be 'authorization_code'")
}
required := []string{
"client_id",
"redirect_uri",
"code",
"code_verifier",
}
for _, parameter := range required {
if !r.Form.Has(parameter) {
return errors.OAuth2InvalidRequest(parameter + " must be specified")
}
}
return nil
}
// tokenValidateCode validates the request against the parsed code.
func tokenValidateCode(code *Code, r *http.Request) error {
if code.ClientID != r.Form.Get("client_id") {
return errors.OAuth2InvalidGrant("client_id mismatch")
}
if code.ClientRedirectURI != r.Form.Get("redirect_uri") {
return errors.OAuth2InvalidGrant("redirect_uri mismatch")
}
if code.ClientCodeChallenge != encodeCodeChallengeS256(r.Form.Get("code_verifier")) {
return errors.OAuth2InvalidClient("code_verfier invalid")
}
return nil
}
// oidcHash is used to create at_hash and c_hash values.
// TODO: this is very much tied to the algorithm defined (hard coded) in
// the JOSE package.
func oidcHash(value string) string {
sum := sha512.Sum512([]byte(value))
return base64.RawURLEncoding.EncodeToString(sum[:sha512.Size>>1])
}
// oidcPicture returns a URL to a picture for the user.
func oidcPicture(email string) string {
//nolint:gosec
return fmt.Sprintf("https://www.gravatar.com/avatar/%x", md5.Sum([]byte(email)))
}
// oidcIDToken builds an OIDC ID token.
func (a *Authenticator) oidcIDToken(r *http.Request, scope Scope, expiry time.Time, atHash string, code *Code) (*string, error) {
//nolint:nilnil
if !slices.Contains(scope, "openid") {
return nil, nil
}
claims := &IDToken{
Claims: jwt.Claims{
Issuer: "https://" + r.Host,
Subject: code.Subject,
Audience: []string{
code.ClientID,
},
Expiry: jwt.NewNumericDate(expiry),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
OIDCClaims: OIDCClaims{
Nonce: code.ClientNonce,
ATHash: atHash,
},
}
// TODO: we should just pass through the federated id_token in the code...
if slices.Contains(scope, "email") {
claims.OIDCClaimsEmail.Email = code.Subject
}
if slices.Contains(scope, "profile") {
claims.OIDCClaimsProfile.Picture = oidcPicture(code.Subject)
}
idToken, err := a.issuer.EncodeJWT(claims)
if err != nil {
return nil, err
}
return &idToken, nil
}
// Token issues an OAuth2 access token from the provided autorization code.
func (a *Authenticator) Token(w http.ResponseWriter, r *http.Request) (*generated.Token, error) {
if err := r.ParseForm(); err != nil {
return nil, errors.OAuth2InvalidRequest("failed to parse form data: " + err.Error())
}
if err := tokenValidate(r); err != nil {
return nil, err
}
code := &Code{}
if err := a.issuer.DecodeJWEToken(r.Form.Get("code"), code); err != nil {
return nil, errors.OAuth2InvalidRequest("failed to parse code: " + err.Error())
}
if err := tokenValidateCode(code, r); err != nil {
return nil, err
}
expiry := time.Now().Add(24 * time.Hour)
// TODO: add some scopes, these hould probably be derived from the organization.
accessToken, err := a.Issue(r, code, expiry)
if err != nil {
return nil, err
}
// Handle OIDC.
idToken, err := a.oidcIDToken(r, code.ClientScope, expiry, oidcHash(accessToken), code)
if err != nil {
return nil, err
}
result := &generated.Token{
TokenType: "Bearer",
AccessToken: accessToken,
IdToken: idToken,
ExpiresIn: int(time.Until(expiry).Seconds()),
}
return result, nil
}