|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/rsa" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/json" |
| 9 | + "math/big" |
| 10 | + "net/http" |
| 11 | + "net/http/httptest" |
| 12 | + "sync" |
| 13 | + "sync/atomic" |
| 14 | + "testing" |
| 15 | + "time" |
| 16 | + |
| 17 | + "github.com/golang-jwt/jwt/v5" |
| 18 | + "github.com/wso2/openfgc/portal/backend/internal/system/config" |
| 19 | +) |
| 20 | + |
| 21 | +type testJWKS struct { |
| 22 | + mu sync.RWMutex |
| 23 | + key *rsa.PrivateKey |
| 24 | + kid string |
| 25 | + fail bool |
| 26 | + hits atomic.Int64 |
| 27 | +} |
| 28 | + |
| 29 | +func newTestValidator(t *testing.T) (*Validator, *testJWKS, func(jwt.MapClaims, string) string) { |
| 30 | + t.Helper() |
| 31 | + state := &testJWKS{kid: "key-1"} |
| 32 | + var err error |
| 33 | + state.key, err = rsa.GenerateKey(rand.Reader, 2048) |
| 34 | + if err != nil { |
| 35 | + t.Fatal(err) |
| 36 | + } |
| 37 | + var server *httptest.Server |
| 38 | + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 39 | + state.hits.Add(1) |
| 40 | + state.mu.RLock() |
| 41 | + defer state.mu.RUnlock() |
| 42 | + if state.fail { |
| 43 | + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 44 | + return |
| 45 | + } |
| 46 | + if r.URL.Path == "/.well-known/openid-configuration" { |
| 47 | + _ = json.NewEncoder(w).Encode(discovery{JWKSURI: server.URL + "/keys"}) |
| 48 | + return |
| 49 | + } |
| 50 | + if r.URL.Path == "/keys" { |
| 51 | + n := base64.RawURLEncoding.EncodeToString(state.key.PublicKey.N.Bytes()) |
| 52 | + e := base64.RawURLEncoding.EncodeToString(big.NewInt(int64(state.key.PublicKey.E)).Bytes()) |
| 53 | + _ = json.NewEncoder(w).Encode(jwks{Keys: []jwk{{KID: state.kid, KTY: "RSA", N: n, E: e}}}) |
| 54 | + return |
| 55 | + } |
| 56 | + http.NotFound(w, r) |
| 57 | + })) |
| 58 | + cfg := config.AuthConfig{IssuerURL: server.URL, ResourceAudience: "consent-api", AllowedAlgorithms: []string{"RS256"}, JWKSTTL: time.Hour, JWKSRefreshTimeout: time.Second, ClockSkew: 0} |
| 59 | + sign := func(claims jwt.MapClaims, kid string) string { |
| 60 | + state.mu.RLock() |
| 61 | + key := state.key |
| 62 | + state.mu.RUnlock() |
| 63 | + token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) |
| 64 | + token.Header["kid"] = kid |
| 65 | + raw, signErr := token.SignedString(key) |
| 66 | + if signErr != nil { |
| 67 | + t.Fatal(signErr) |
| 68 | + } |
| 69 | + return raw |
| 70 | + } |
| 71 | + return NewValidator(cfg), state, sign |
| 72 | +} |
| 73 | + |
| 74 | +func validClaims(issuer string) jwt.MapClaims { |
| 75 | + now := time.Now() |
| 76 | + return jwt.MapClaims{"iss": issuer, "aud": "consent-api", "sub": "user-1", "org_id": "org-1", "scope": "portal:consents:read:self", "iat": now.Unix(), "nbf": now.Unix(), "exp": now.Add(time.Hour).Unix()} |
| 77 | +} |
| 78 | + |
| 79 | +func TestValidatorRejectsInvalidClaims(t *testing.T) { |
| 80 | + v, _, sign := newTestValidator(t) |
| 81 | + base := validClaims(v.cfg.IssuerURL) |
| 82 | + tests := []struct { |
| 83 | + name string |
| 84 | + mutate func(jwt.MapClaims) |
| 85 | + alg string |
| 86 | + }{ |
| 87 | + {"wrong issuer", func(c jwt.MapClaims) { c["iss"] = "https://other" }, "RS256"}, |
| 88 | + {"wrong audience", func(c jwt.MapClaims) { c["aud"] = "other" }, "RS256"}, |
| 89 | + {"expired", func(c jwt.MapClaims) { c["exp"] = time.Now().Add(-time.Minute).Unix() }, "RS256"}, |
| 90 | + {"not yet valid", func(c jwt.MapClaims) { c["nbf"] = time.Now().Add(time.Minute).Unix() }, "RS256"}, |
| 91 | + {"missing sub", func(c jwt.MapClaims) { delete(c, "sub") }, "RS256"}, |
| 92 | + {"missing org", func(c jwt.MapClaims) { delete(c, "org_id") }, "RS256"}, |
| 93 | + } |
| 94 | + for _, tt := range tests { |
| 95 | + t.Run(tt.name, func(t *testing.T) { |
| 96 | + c := jwt.MapClaims{} |
| 97 | + for k, v := range base { |
| 98 | + c[k] = v |
| 99 | + } |
| 100 | + tt.mutate(c) |
| 101 | + if _, err := v.Validate(context.Background(), sign(c, "key-1")); err == nil { |
| 102 | + t.Fatal("expected validation failure") |
| 103 | + } |
| 104 | + }) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +func TestValidatorRejectsInvalidSignatureAndTokenType(t *testing.T) { |
| 109 | + v, _, sign := newTestValidator(t) |
| 110 | + other, err := rsa.GenerateKey(rand.Reader, 2048) |
| 111 | + if err != nil { |
| 112 | + t.Fatal(err) |
| 113 | + } |
| 114 | + token := jwt.NewWithClaims(jwt.SigningMethodRS256, validClaims(v.cfg.IssuerURL)) |
| 115 | + token.Header["kid"] = "key-1" |
| 116 | + raw, err := token.SignedString(other) |
| 117 | + if err != nil { |
| 118 | + t.Fatal(err) |
| 119 | + } |
| 120 | + if _, err := v.Validate(context.Background(), raw); err == nil { |
| 121 | + t.Fatal("expected invalid signature") |
| 122 | + } |
| 123 | + v.cfg.RequireAccessTokenType = true |
| 124 | + v.cfg.TokenTypeClaim, v.cfg.AccessTokenType = "token_type", "access_token" |
| 125 | + claims := validClaims(v.cfg.IssuerURL) |
| 126 | + claims["token_type"] = "id_token" |
| 127 | + if _, err := v.Validate(context.Background(), sign(claims, "key-1")); err == nil { |
| 128 | + t.Fatal("expected token type rejection") |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +func TestValidatorUsesCachedJWKS(t *testing.T) { |
| 133 | + v, state, sign := newTestValidator(t) |
| 134 | + raw := sign(validClaims(v.cfg.IssuerURL), "key-1") |
| 135 | + if _, err := v.Validate(context.Background(), raw); err != nil { |
| 136 | + t.Fatal(err) |
| 137 | + } |
| 138 | + first := state.hits.Load() |
| 139 | + if _, err := v.Validate(context.Background(), raw); err != nil { |
| 140 | + t.Fatal(err) |
| 141 | + } |
| 142 | + second := state.hits.Load() |
| 143 | + if second != first { |
| 144 | + t.Fatalf("expected cache hit without network refresh: %d -> %d", first, second) |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +func TestValidatorParsesScopesAndRejectsUnknownAlgorithm(t *testing.T) { |
| 149 | + v, state, sign := newTestValidator(t) |
| 150 | + p, err := v.Validate(context.Background(), sign(validClaims(v.cfg.IssuerURL), "key-1")) |
| 151 | + if err != nil || len(p.Scopes) != 1 { |
| 152 | + t.Fatalf("expected valid scoped principal, got %#v, %v", p, err) |
| 153 | + } |
| 154 | + token := jwt.NewWithClaims(jwt.SigningMethodHS256, validClaims(v.cfg.IssuerURL)) |
| 155 | + token.Header["kid"] = "key-1" |
| 156 | + raw, _ := token.SignedString([]byte("secret")) |
| 157 | + if _, err := v.Validate(context.Background(), raw); err == nil { |
| 158 | + t.Fatal("expected algorithm rejection") |
| 159 | + } |
| 160 | + _ = state |
| 161 | +} |
| 162 | + |
| 163 | +func TestValidatorRefreshesUnknownKIDAndKeepsLastKnownGoodKey(t *testing.T) { |
| 164 | + v, state, sign := newTestValidator(t) |
| 165 | + if _, err := v.Validate(context.Background(), sign(validClaims(v.cfg.IssuerURL), "key-1")); err != nil { |
| 166 | + t.Fatal(err) |
| 167 | + } |
| 168 | + state.mu.Lock() |
| 169 | + next, _ := rsa.GenerateKey(rand.Reader, 2048) |
| 170 | + state.key, state.kid = next, "key-2" |
| 171 | + state.mu.Unlock() |
| 172 | + if _, err := v.Validate(context.Background(), sign(validClaims(v.cfg.IssuerURL), "key-2")); err != nil { |
| 173 | + t.Fatalf("expected rotation refresh: %v", err) |
| 174 | + } |
| 175 | + state.mu.Lock() |
| 176 | + state.fail = true |
| 177 | + state.mu.Unlock() |
| 178 | + if _, err := v.Validate(context.Background(), sign(validClaims(v.cfg.IssuerURL), "key-2")); err != nil { |
| 179 | + t.Fatalf("expected cached key during refresh failure: %v", err) |
| 180 | + } |
| 181 | +} |
0 commit comments