Newer
Older
package oidc
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
func TestKnownBrokenAuthHeaderProvider(t *testing.T) {
tests := []struct {
issuerURL string
expect bool
}{
{"https://dev.oktapreview.com", true},
{"https://dev.okta.com", true},
{"https://okta.com", true},
{"https://dev.oktaaccounts.com", false},
{"https://accounts.google.com", false},
}
for _, tc := range tests {
got := knownBrokenAuthHeaderProvider(tc.issuerURL)
if got != tc.expect {
t.Errorf("knownBrokenAuthHeaderProvider(%q), want=%t, got=%t", tc.issuerURL, tc.expect, got)
}
}
}
func TestHandleCallback(t *testing.T) {
t.Helper()
tests := []struct {
Stephan Renatus
committed
name string
userIDKey string
preferredUsernameKey string
emailKey string
groupsKey string
Stephan Renatus
committed
insecureSkipEmailVerified bool
Stephan Renatus
committed
expectUserID string
expectGroups []string
Stephan Renatus
committed
token map[string]interface{}
Stephan Renatus
committed
{
name: "simpleCase",
userIDKey: "", // not configured
userNameKey: "", // not configured
expectUserID: "subvalue",
expectUserName: "namevalue",
expectGroups: []string{"group1", "group2"},
Stephan Renatus
committed
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"groups": []string{"group1", "group2"},
Stephan Renatus
committed
"email": "emailvalue",
"email_verified": true,
},
},
name: "customEmailClaim",
userIDKey: "", // not configured
userNameKey: "", // not configured
emailKey: "mail",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"mail": "emailvalue",
"email_verified": true,
},
},
name: "overrideWithCustomEmailClaim",
userIDKey: "", // not configured
userNameKey: "", // not configured
overrideClaimMapping: true,
emailKey: "custommail",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "customemailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"custommail": "customemailvalue",
"email_verified": true,
},
},
Stephan Renatus
committed
{
name: "email_verified not in claims, configured to be skipped",
insecureSkipEmailVerified: true,
expectUserID: "subvalue",
Stephan Renatus
committed
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"email": "emailvalue",
},
},
{
name: "withUserIDKey",
userIDKey: "name",
expectUserID: "namevalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
Stephan Renatus
committed
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"email": "emailvalue",
"email_verified": true,
Stephan Renatus
committed
},
},
name: "withUserNameKey",
userNameKey: "user_name",
expectUserID: "subvalue",
expectUserName: "username",
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"user_name": "username",
"email": "emailvalue",
"email_verified": true,
},
},
name: "withPreferredUsernameKey",
preferredUsernameKey: "username_key",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectPreferredUsername: "username_value",
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"username_key": "username_value",
"email": "emailvalue",
"email_verified": true,
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
{
name: "withoutPreferredUsernameKeyAndBackendReturns",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectPreferredUsername: "preferredusernamevalue",
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"preferred_username": "preferredusernamevalue",
"email": "emailvalue",
"email_verified": true,
},
},
{
name: "withoutPreferredUsernameKeyAndBackendNotReturn",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectPreferredUsername: "",
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"email": "emailvalue",
"email_verified": true,
},
},
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
{
name: "emptyEmailScope",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "",
scopes: []string{"groups"},
insecureSkipEmailVerified: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"user_name": "username",
},
},
{
name: "emptyEmailScopeButEmailProvided",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
scopes: []string{"groups"},
insecureSkipEmailVerified: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"user_name": "username",
"email": "emailvalue",
},
},
name: "customGroupsKey",
groupsKey: "cognito:groups",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
expectGroups: []string{"group3", "group4"},
scopes: []string{"groups"},
insecureSkipEmailVerified: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"user_name": "username",
"email": "emailvalue",
"cognito:groups": []string{"group3", "group4"},
},
},
{
name: "customGroupsKeyButGroupsProvided",
groupsKey: "cognito:groups",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
expectGroups: []string{"group1", "group2"},
scopes: []string{"groups"},
insecureSkipEmailVerified: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"user_name": "username",
"email": "emailvalue",
"groups": []string{"group1", "group2"},
"cognito:groups": []string{"group3", "group4"},
},
},
name: "customGroupsKeyDespiteGroupsProvidedButOverride",
overrideClaimMapping: true,
groupsKey: "cognito:groups",
expectUserID: "subvalue",
expectUserName: "namevalue",
expectedEmailField: "emailvalue",
expectGroups: []string{"group3", "group4"},
scopes: []string{"groups"},
insecureSkipEmailVerified: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"user_name": "username",
"email": "emailvalue",
"groups": []string{"group1", "group2"},
"cognito:groups": []string{"group3", "group4"},
},
},
Joost Buskermolen
committed
{
name: "singularGroupResponseAsString",
userIDKey: "", // not configured
userNameKey: "", // not configured
expectUserID: "subvalue",
expectUserName: "namevalue",
expectGroups: []string{"group1"},
expectedEmailField: "emailvalue",
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"groups": "group1",
"email": "emailvalue",
"email_verified": true,
},
},
userIDKey: "", // not configured
userNameKey: "", // not configured
expectUserID: "subvalue",
expectUserName: "namevalue",
expectGroups: []string{"group1", "gh::acme::pipeline-one", "clr_delim-acme-foobar", "keep_delim-acme-foo-bar", "bk-emailvalue"},
expectedEmailField: "emailvalue",
newGroupFromClaims: []NewGroupFromClaims{
{ // The basic functionality, should create "gh::acme::pipeline-one".
"organization",
"pipeline",
},
Delimiter: "::",
Prefix: "gh",
},
{ // Non existing claims, should not generate any any new group claim.
"non-existing1",
"non-existing2",
},
Delimiter: "::",
Prefix: "tfe",
},
{ // In this case the delimiter character("-") should be removed removed from "claim-with-delimiter" claim to ensure the resulting
// claim structure is in full control of the Dex operator and not the person creating a new pipeline.
// Should create "clr_delim-acme-foobar" and not "tfe-acme-foo-bar".
"organization",
"claim-with-delimiter",
},
Delimiter: "-",
ClearDelimiter: true,
Prefix: "clr_delim",
},
{ // In this case the delimiter character("-") should be NOT removed from "claim-with-delimiter" claim.
// Should create "keep_delim-acme-foo-bar".
"organization",
"claim-with-delimiter",
},
Delimiter: "-",
// ClearDelimiter: false,
Prefix: "keep_delim",
{ // Ignore non string claims (like arrays), this should result in "bk-emailvalue".
"non-string-claim",
"non-string-claim2",
"email",
},
Delimiter: "-",
Prefix: "bk",
},
},
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
"groups": "group1",
"organization": "acme",
"pipeline": "pipeline-one",
"email": "emailvalue",
"email_verified": true,
"claim-with-delimiter": "foo-bar",
"non-string-claim": []string{
"element1",
"element2",
},
"non-string-claim2": 666,
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
Anthony Brandelli
committed
idTokenDesired := true
testServer, err := setupServer(tc.token, idTokenDesired)
if err != nil {
t.Fatal("failed to setup test server", err)
}
defer testServer.Close()
var scopes []string
if len(tc.scopes) > 0 {
scopes = tc.scopes
} else {
scopes = []string{"email", "groups"}
}
Lars Lehtonen
committed
basicAuth := true
Stephan Renatus
committed
Issuer: serverURL,
ClientID: "clientID",
ClientSecret: "clientSecret",
Stephan Renatus
committed
RedirectURI: fmt.Sprintf("%s/callback", serverURL),
UserIDKey: tc.userIDKey,
UserNameKey: tc.userNameKey,
Stephan Renatus
committed
InsecureSkipEmailVerified: tc.insecureSkipEmailVerified,
InsecureEnableGroups: true,
Lars Lehtonen
committed
BasicAuthUnsupported: &basicAuth,
OverrideClaimMapping: tc.overrideClaimMapping,
config.ClaimMapping.PreferredUsernameKey = tc.preferredUsernameKey
config.ClaimMapping.EmailKey = tc.emailKey
config.ClaimMapping.GroupsKey = tc.groupsKey
config.ClaimMutations.NewGroupFromClaims = tc.newGroupFromClaims
conn, err := newConnector(config)
if err != nil {
t.Fatal("failed to create new connector", err)
}
req, err := newRequestWithAuthCode(testServer.URL, "someCode")
if err != nil {
t.Fatal("failed to create request", err)
}
identity, err := conn.HandleCallback(connector.Scopes{Groups: true}, req)
if err != nil {
t.Fatal("handle callback failed", err)
}
expectEquals(t, identity.UserID, tc.expectUserID)
expectEquals(t, identity.Username, tc.expectUserName)
expectEquals(t, identity.PreferredUsername, tc.expectPreferredUsername)
expectEquals(t, identity.Email, tc.expectedEmailField)
expectEquals(t, identity.Groups, tc.expectGroups)
Anthony Brandelli
committed
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
func TestRefresh(t *testing.T) {
t.Helper()
tests := []struct {
name string
expectUserID string
expectUserName string
idTokenDesired bool
token map[string]interface{}
}{
{
name: "IDTokenOnRefresh",
expectUserID: "subvalue",
expectUserName: "namevalue",
idTokenDesired: true,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
},
},
{
name: "NoIDTokenOnRefresh",
expectUserID: "subvalue",
expectUserName: "namevalue",
idTokenDesired: false,
token: map[string]interface{}{
"sub": "subvalue",
"name": "namevalue",
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
testServer, err := setupServer(tc.token, tc.idTokenDesired)
if err != nil {
t.Fatal("failed to setup test server", err)
}
defer testServer.Close()
scopes := []string{"openid", "offline_access"}
serverURL := testServer.URL
config := Config{
Issuer: serverURL,
ClientID: "clientID",
ClientSecret: "clientSecret",
Scopes: scopes,
RedirectURI: fmt.Sprintf("%s/callback", serverURL),
GetUserInfo: true,
}
conn, err := newConnector(config)
if err != nil {
t.Fatal("failed to create new connector", err)
}
req, err := newRequestWithAuthCode(testServer.URL, "someCode")
if err != nil {
t.Fatal("failed to create request", err)
}
refreshTokenStr := "{\"RefreshToken\":\"asdf\"}"
refreshToken := []byte(refreshTokenStr)
identity := connector.Identity{
UserID: tc.expectUserID,
Username: tc.expectUserName,
ConnectorData: refreshToken,
}
refreshIdentity, err := conn.Refresh(req.Context(), connector.Scopes{OfflineAccess: true}, identity)
if err != nil {
t.Fatal("Refresh failed", err)
}
expectEquals(t, refreshIdentity.UserID, tc.expectUserID)
expectEquals(t, refreshIdentity.Username, tc.expectUserName)
})
}
}
func TestTokenIdentity(t *testing.T) {
tokenTypeAccess := "urn:ietf:params:oauth:token-type:access_token"
tokenTypeID := "urn:ietf:params:oauth:token-type:id_token"
long2short := map[string]string{
tokenTypeAccess: "access_token",
tokenTypeID: "id_token",
}
tests := []struct {
name string
subjectType string
userInfo bool
expectError bool
}{
{
name: "id_token",
subjectType: tokenTypeID,
}, {
name: "access_token",
subjectType: tokenTypeAccess,
expectError: true,
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
}, {
name: "id_token with user info",
subjectType: tokenTypeID,
userInfo: true,
}, {
name: "access_token with user info",
subjectType: tokenTypeAccess,
userInfo: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
testServer, err := setupServer(map[string]any{
"sub": "subvalue",
"name": "namevalue",
}, true)
if err != nil {
t.Fatal("failed to setup test server", err)
}
conn, err := newConnector(Config{
Issuer: testServer.URL,
Scopes: []string{"openid", "groups"},
GetUserInfo: tc.userInfo,
})
if err != nil {
t.Fatal("failed to create new connector", err)
}
res, err := http.Get(testServer.URL + "/token")
if err != nil {
t.Fatal("failed to get initial token", err)
}
defer res.Body.Close()
var tokenResponse map[string]any
err = json.NewDecoder(res.Body).Decode(&tokenResponse)
if err != nil {
t.Fatal("failed to decode initial token", err)
}
origToken := tokenResponse[long2short[tc.subjectType]].(string)
identity, err := conn.TokenIdentity(ctx, tc.subjectType, origToken)
if err != nil {
if tc.expectError {
return
}
t.Fatal("failed to get token identity", err)
}
// assert identity
expectEquals(t, identity.UserID, "subvalue")
expectEquals(t, identity.Username, "namevalue")
})
}
}
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
func TestProviderOverride(t *testing.T) {
testServer, err := setupServer(map[string]any{
"sub": "subvalue",
"name": "namevalue",
}, true)
if err != nil {
t.Fatal("failed to setup test server", err)
}
t.Run("No override", func(t *testing.T) {
conn, err := newConnector(Config{
Issuer: testServer.URL,
Scopes: []string{"openid", "groups"},
})
if err != nil {
t.Fatal("failed to create new connector", err)
}
expAuth := fmt.Sprintf("%s/authorize", testServer.URL)
if conn.provider.Endpoint().AuthURL != expAuth {
t.Fatalf("unexpected auth URL: %s, expected: %s\n", conn.provider.Endpoint().AuthURL, expAuth)
}
expToken := fmt.Sprintf("%s/token", testServer.URL)
if conn.provider.Endpoint().TokenURL != expToken {
t.Fatalf("unexpected token URL: %s, expected: %s\n", conn.provider.Endpoint().TokenURL, expToken)
}
})
t.Run("Override", func(t *testing.T) {
conn, err := newConnector(Config{
Issuer: testServer.URL,
Scopes: []string{"openid", "groups"},
ProviderDiscoveryOverrides: ProviderDiscoveryOverrides{TokenURL: "/test1", AuthURL: "/test2"},
})
if err != nil {
t.Fatal("failed to create new connector", err)
}
expAuth := "/test2"
if conn.provider.Endpoint().AuthURL != expAuth {
t.Fatalf("unexpected auth URL: %s, expected: %s\n", conn.provider.Endpoint().AuthURL, expAuth)
}
expToken := "/test1"
if conn.provider.Endpoint().TokenURL != expToken {
t.Fatalf("unexpected token URL: %s, expected: %s\n", conn.provider.Endpoint().TokenURL, expToken)
}
})
}
Anthony Brandelli
committed
func setupServer(tok map[string]interface{}, idTokenDesired bool) (*httptest.Server, error) {
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
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, fmt.Errorf("failed to generate rsa key: %v", err)
}
jwk := jose.JSONWebKey{
Key: key,
KeyID: "keyId",
Algorithm: "RSA",
}
mux := http.NewServeMux()
mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&map[string]interface{}{
"keys": []map[string]interface{}{{
"alg": jwk.Algorithm,
"kty": jwk.Algorithm,
"kid": jwk.KeyID,
"n": n(&key.PublicKey),
"e": e(&key.PublicKey),
}},
})
})
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
url := fmt.Sprintf("http://%s", r.Host)
Stephan Renatus
committed
tok["iss"] = url
tok["exp"] = time.Now().Add(time.Hour).Unix()
tok["aud"] = "clientID"
token, err := newToken(&jwk, tok)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Add("Content-Type", "application/json")
Anthony Brandelli
committed
if idTokenDesired {
json.NewEncoder(w).Encode(&map[string]string{
"access_token": token,
"id_token": token,
Anthony Brandelli
committed
} else {
json.NewEncoder(w).Encode(&map[string]string{
"access_token": token,
Anthony Brandelli
committed
}
})
mux.HandleFunc("/userinfo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
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
})
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
url := fmt.Sprintf("http://%s", r.Host)
json.NewEncoder(w).Encode(&map[string]string{
"issuer": url,
"token_endpoint": fmt.Sprintf("%s/token", url),
"authorization_endpoint": fmt.Sprintf("%s/authorize", url),
"userinfo_endpoint": fmt.Sprintf("%s/userinfo", url),
"jwks_uri": fmt.Sprintf("%s/keys", url),
})
})
return httptest.NewServer(mux), nil
}
func newToken(key *jose.JSONWebKey, claims map[string]interface{}) (string, error) {
signingKey := jose.SigningKey{
Key: key,
Algorithm: jose.RS256,
}
signer, err := jose.NewSigner(signingKey, &jose.SignerOptions{})
if err != nil {
return "", fmt.Errorf("failed to create new signer: %v", err)
}
payload, err := json.Marshal(claims)
if err != nil {
return "", fmt.Errorf("failed to marshal claims: %v", err)
}
signature, err := signer.Sign(payload)
if err != nil {
return "", fmt.Errorf("failed to sign: %v", err)
}
return signature.CompactSerialize()
}
func newConnector(config Config) (*oidcConnector, error) {
logger := logrus.New()
conn, err := config.Open("id", logger)
if err != nil {
return nil, fmt.Errorf("unable to open: %v", err)
}
oidcConn, ok := conn.(*oidcConnector)
if !ok {
return nil, errors.New("failed to convert to oidcConnector")
}
return oidcConn, nil
}
func newRequestWithAuthCode(serverURL string, code string) (*http.Request, error) {
req, err := http.NewRequest("GET", serverURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %v", err)
}
values := req.URL.Query()
values.Add("code", code)
req.URL.RawQuery = values.Encode()
return req, nil
}
func n(pub *rsa.PublicKey) string {
return encode(pub.N.Bytes())
}
func e(pub *rsa.PublicKey) string {
data := make([]byte, 8)
binary.BigEndian.PutUint64(data, uint64(pub.E))
return encode(bytes.TrimLeft(data, "\x00"))
}
func encode(payload []byte) string {
result := base64.URLEncoding.EncodeToString(payload)
return strings.TrimRight(result, "=")
}
func expectEquals(t *testing.T, a interface{}, b interface{}) {
if !reflect.DeepEqual(a, b) {
t.Errorf("Expected %+v to equal %+v", a, b)
}
}