From 9a2c0ce93622814b9a4c730232dbace453f467be Mon Sep 17 00:00:00 2001 From: Yusufhan Sacak Date: Thu, 26 Nov 2026 18:27:17 +0000 Subject: [PATCH 1/3] perf(auth/github-oidc): cache GitHub's JWKS between token exchanges The GitHub OIDC exchange fetched the JWKS on every request, inside the JWT keyfunc and before the signature, issuer or audience were checked, using http.DefaultClient with no timeout. Cache the parsed keys by kid for one hour, matching the max-age GitHub sends on the JWKS document. An unknown kid or an expired cache starts a refetch, at most once every 30 seconds, and concurrent callers share the fetch in progress. A failed fetch keeps the cached keys until they expire; after that the exchange fails closed. A response with no usable RSA keys counts as a failed fetch, so it cannot evict good keys. As before, only the first entry for a kid is used. The fetch has its own 10 second timeout and is not cancelled when the triggering caller goes away, so a client cannot keep the cache empty by hanging up. go-oidc's RemoteKeySet was not used because it refetches on every unknown kid with no rate limit. --- internal/api/handlers/v0/auth/github_oidc.go | 151 +++++- .../v0/auth/github_oidc_internal_test.go | 506 ++++++++++++++++++ 2 files changed, 643 insertions(+), 14 deletions(-) create mode 100644 internal/api/handlers/v0/auth/github_oidc_internal_test.go diff --git a/internal/api/handlers/v0/auth/github_oidc.go b/internal/api/handlers/v0/auth/github_oidc.go index de95c6755..1d7bcff7b 100644 --- a/internal/api/handlers/v0/auth/github_oidc.go +++ b/internal/api/handlers/v0/auth/github_oidc.go @@ -9,6 +9,8 @@ import ( "math/big" "net/http" "strings" + "sync" + "time" "github.com/danielgtaylor/huma/v2" "github.com/golang-jwt/jwt/v5" @@ -49,25 +51,63 @@ type OIDCValidator interface { ValidateToken(ctx context.Context, token string, audience string) (*GitHubOIDCClaims, error) } -// GitHubOIDCValidator validates GitHub OIDC tokens +// GitHubOIDCValidator validates GitHub OIDC tokens. It caches GitHub's +// signing keys, so it is safe for concurrent use and should be shared. type GitHubOIDCValidator struct { jwksURL string issuer string + client *http.Client + now func() time.Time + + mu sync.Mutex + keys map[string]*rsa.PublicKey + expiresAt time.Time + // lastFetch is when the last fetch started, successful or not. + lastFetch time.Time + inflight *jwksFetch } +// jwksFetch is a JWKS fetch in progress. Callers that need the result wait +// for done; err is set before done is closed. +type jwksFetch struct { + done chan struct{} + err error +} + +// githubJWKSCacheTTL is how long fetched keys are trusted. It matches the +// "Cache-Control: max-age=3600" GitHub sends with the JWKS document. After it +// passes the keys are not used until a fetch succeeds, so a long GitHub outage +// fails closed rather than serving old keys forever. +const githubJWKSCacheTTL = time.Hour + +// githubJWKSMinRefreshInterval is the minimum gap between fetch attempts. The +// fetch happens before the token's signature is checked, so without this +// limit any token with an unknown kid would cost one request to GitHub. It +// also bounds the delay before a newly rotated key is picked up. +const githubJWKSMinRefreshInterval = 30 * time.Second + +// githubJWKSFetchTimeout bounds a single JWKS fetch. +const githubJWKSFetchTimeout = 10 * time.Second + // NewGitHubOIDCValidator creates a new GitHub OIDC validator func NewGitHubOIDCValidator() *GitHubOIDCValidator { - return &GitHubOIDCValidator{ - jwksURL: "https://token.actions.githubusercontent.com/.well-known/jwks", - issuer: "https://token.actions.githubusercontent.com", - } + return newGitHubOIDCValidator( + "https://token.actions.githubusercontent.com/.well-known/jwks", + "https://token.actions.githubusercontent.com", + ) } // NewMockOIDCValidator creates a mock validator for testing func NewMockOIDCValidator(jwksURL, issuer string) *GitHubOIDCValidator { + return newGitHubOIDCValidator(jwksURL, issuer) +} + +func newGitHubOIDCValidator(jwksURL, issuer string) *GitHubOIDCValidator { return &GitHubOIDCValidator{ jwksURL: jwksURL, issuer: issuer, + client: &http.Client{Timeout: githubJWKSFetchTimeout}, + now: time.Now, } } @@ -141,7 +181,7 @@ func (v *GitHubOIDCValidator) fetchJWKS(ctx context.Context) (*JWKS, error) { return nil, fmt.Errorf("failed to create request: %w", err) } - resp, err := http.DefaultClient.Do(req) + resp, err := v.client.Do(req) if err != nil { return nil, fmt.Errorf("failed to fetch JWKS: %w", err) } @@ -159,22 +199,105 @@ func (v *GitHubOIDCValidator) fetchJWKS(ctx context.Context) (*JWKS, error) { return &jwks, nil } -// getPublicKey extracts the RSA public key for the given key ID +// getPublicKey returns the RSA public key for the given key ID. Keys come from +// the cache while it is fresh. An unknown kid or an expired cache starts a +// fetch, at most once per githubJWKSMinRefreshInterval; concurrent callers +// share the fetch in progress. func (v *GitHubOIDCValidator) getPublicKey(ctx context.Context, kid string) (*rsa.PublicKey, error) { - // Fetch JWKS from GitHub - jwks, err := v.fetchJWKS(ctx) - if err != nil { - return nil, fmt.Errorf("failed to fetch JWKS: %w", err) + v.mu.Lock() + now := v.now() + fresh := now.Before(v.expiresAt) + if key, ok := v.keys[kid]; ok && fresh { + v.mu.Unlock() + return key, nil } - for _, key := range jwks.Keys { - if key.KID == kid { - return v.parseRSAPublicKey(key) + call := v.inflight + if call == nil { + if !v.lastFetch.IsZero() && now.Sub(v.lastFetch) < githubJWKSMinRefreshInterval { + v.mu.Unlock() + if fresh { + return nil, fmt.Errorf("key with ID %s not found", kid) + } + return nil, fmt.Errorf("JWKS unavailable: last fetch failed less than %s ago", githubJWKSMinRefreshInterval) } + v.lastFetch = now + call = &jwksFetch{done: make(chan struct{})} + v.inflight = call + // The fetch must not be cut short by this caller hanging up, or a + // client could cancel every fetch and keep the cache empty while the + // refresh limit blocks everyone else. It runs detached, bounded by + // its own timeout, and this caller stops waiting if ctx ends. + fetchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), githubJWKSFetchTimeout) + go func() { + defer cancel() + v.refreshKeys(fetchCtx, call) + }() + } + v.mu.Unlock() + + select { + case <-call.done: + case <-ctx.Done(): + return nil, ctx.Err() + } + if call.err != nil { + return nil, fmt.Errorf("failed to fetch JWKS: %w", call.err) + } + + v.mu.Lock() + defer v.mu.Unlock() + if key, ok := v.keys[kid]; ok && v.now().Before(v.expiresAt) { + return key, nil } return nil, fmt.Errorf("key with ID %s not found", kid) } +// refreshKeys fetches the JWKS and, on success, replaces the cached keys. On +// failure the cached keys are kept and stay usable until they expire. +func (v *GitHubOIDCValidator) refreshKeys(ctx context.Context, call *jwksFetch) { + var keys map[string]*rsa.PublicKey + jwks, err := v.fetchJWKS(ctx) + if err == nil { + keys = v.usableKeys(jwks) + if len(keys) == 0 { + // Don't let an empty or broken document evict good keys. + err = fmt.Errorf("JWKS contains no usable RSA keys") + } + } + + v.mu.Lock() + if err == nil { + v.keys = keys + v.expiresAt = v.now().Add(githubJWKSCacheTTL) + } + call.err = err + v.inflight = nil + v.mu.Unlock() + close(call.done) +} + +// usableKeys returns the RSA keys in jwks by kid. Only the first entry for a +// kid counts, as it did before keys were cached: if that entry is not a +// usable RSA key, the kid is left out even when a later entry would parse. +// Entries without a kid are skipped. +func (v *GitHubOIDCValidator) usableKeys(jwks *JWKS) map[string]*rsa.PublicKey { + keys := make(map[string]*rsa.PublicKey, len(jwks.Keys)) + seen := make(map[string]bool, len(jwks.Keys)) + for _, jwk := range jwks.Keys { + if jwk.KID == "" || seen[jwk.KID] { + continue + } + seen[jwk.KID] = true + key, err := v.parseRSAPublicKey(jwk) + if err != nil { + continue + } + keys[jwk.KID] = key + } + return keys +} + // parseRSAPublicKey converts JWK to RSA public key func (v *GitHubOIDCValidator) parseRSAPublicKey(jwk JWK) (*rsa.PublicKey, error) { if jwk.KTY != "RSA" { diff --git a/internal/api/handlers/v0/auth/github_oidc_internal_test.go b/internal/api/handlers/v0/auth/github_oidc_internal_test.go new file mode 100644 index 000000000..b0d283f03 --- /dev/null +++ b/internal/api/handlers/v0/auth/github_oidc_internal_test.go @@ -0,0 +1,506 @@ +package auth + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/json" + "math/big" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testOIDCIssuer = "https://token.actions.example" + testOIDCAudience = "https://registry.test" +) + +// fakeClock is a manually advanced clock for cache expiry tests. +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func newFakeClock() *fakeClock { + return &fakeClock{t: time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)} +} + +func (c *fakeClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +type testSigningKey struct { + kid string + key *rsa.PrivateKey +} + +func newTestSigningKey(t *testing.T, kid string) testSigningKey { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + return testSigningKey{kid: kid, key: key} +} + +func (k testSigningKey) jwk() JWK { + return JWK{ + KTY: "RSA", + KID: k.kid, + Use: "sig", + N: base64.RawURLEncoding.EncodeToString(k.key.N.Bytes()), + E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(k.key.E)).Bytes()), + } +} + +// token signs a valid GitHub-shaped OIDC token with this key. The jwt +// expiry check uses the real clock, so the expiry is relative to time.Now. +func (k testSigningKey) token(t *testing.T) string { + t.Helper() + claims := GitHubOIDCClaims{ + RegisteredClaims: jwt.RegisteredClaims{ + Issuer: testOIDCIssuer, + Subject: "repo:octo-org/octo-repo:ref:refs/heads/main", + Audience: jwt.ClaimStrings{testOIDCAudience}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)), + }, + RepositoryOwner: "octo-org", + } + tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) + tok.Header["kid"] = k.kid + signed, err := tok.SignedString(k.key) + require.NoError(t, err) + return signed +} + +// jwksServer serves a JWKS document that tests can change, and counts fetches. +type jwksServer struct { + *httptest.Server + fetches atomic.Int64 + + mu sync.Mutex + keys []JWK + fail bool + block chan struct{} +} + +func newJWKSServer(t *testing.T, keys ...testSigningKey) *jwksServer { + t.Helper() + s := &jwksServer{} + s.setKeys(keys...) + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.fetches.Add(1) + s.mu.Lock() + keys, fail, block := s.keys, s.fail, s.block + s.mu.Unlock() + if block != nil { + select { + case <-block: + case <-r.Context().Done(): + return + } + } + if fail { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(JWKS{Keys: keys}) + })) + t.Cleanup(s.Close) + return s +} + +func (s *jwksServer) setKeys(keys ...testSigningKey) { + jwks := make([]JWK, 0, len(keys)) + for _, k := range keys { + jwks = append(jwks, k.jwk()) + } + s.setRawKeys(jwks) +} + +// setRawKeys serves exactly these entries, which may be malformed. nil is +// served as {"keys":null}. +func (s *jwksServer) setRawKeys(keys []JWK) { + s.mu.Lock() + defer s.mu.Unlock() + s.keys = keys +} + +func (s *jwksServer) setFail(fail bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.fail = fail +} + +// hold makes requests wait until the returned release func is called. Release +// is idempotent and also runs at cleanup, before the server is closed, so a +// failed assertion cannot leave a handler blocked. +func (s *jwksServer) hold(t *testing.T) (release func()) { + t.Helper() + ch := make(chan struct{}) + var once sync.Once + release = func() { + once.Do(func() { + s.mu.Lock() + s.block = nil + s.mu.Unlock() + close(ch) + }) + } + s.mu.Lock() + s.block = ch + s.mu.Unlock() + t.Cleanup(release) + return release +} + +func newTestValidator(s *jwksServer, clock *fakeClock) *GitHubOIDCValidator { + v := NewMockOIDCValidator(s.URL, testOIDCIssuer) + v.now = clock.Now + return v +} + +func validate(v *GitHubOIDCValidator, token string) error { + _, err := v.ValidateToken(context.Background(), token, testOIDCAudience) + return err +} + +func TestGitHubOIDCValidator_CachesJWKSAcrossExchanges(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + v := newTestValidator(srv, newFakeClock()) + + for range 5 { + require.NoError(t, validate(v, key.token(t))) + } + assert.Equal(t, int64(1), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_UnknownKidRefetchIsRateLimited(t *testing.T) { + key := newTestSigningKey(t, "key-1") + unknown := newTestSigningKey(t, "not-published") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + require.Equal(t, int64(1), srv.fetches.Load()) + + // Within the refresh interval an unknown kid must not cause a fetch. + for range 10 { + err := validate(v, unknown.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "not found") + } + assert.Equal(t, int64(1), srv.fetches.Load()) + + // Once the interval has passed, one unknown kid may trigger one refetch... + clock.Advance(githubJWKSMinRefreshInterval) + require.Error(t, validate(v, unknown.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + // ...and the tokens after it are answered from the cache. + for range 10 { + require.Error(t, validate(v, unknown.token(t))) + } + assert.Equal(t, int64(2), srv.fetches.Load()) + + // The known key still validates without a fetch. + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_PicksUpRotatedKey(t *testing.T) { + oldKey := newTestSigningKey(t, "key-old") + newKey := newTestSigningKey(t, "key-new") + srv := newJWKSServer(t, oldKey) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, oldKey.token(t))) + + srv.setKeys(newKey) + clock.Advance(githubJWKSMinRefreshInterval) + + require.NoError(t, validate(v, newKey.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + // The new key is now cached, and the retired one is gone. + require.NoError(t, validate(v, newKey.token(t))) + require.Error(t, validate(v, oldKey.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_RefetchesAfterTTL(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + clock.Advance(githubJWKSCacheTTL - time.Second) + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(1), srv.fetches.Load()) + + clock.Advance(2 * time.Second) + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_FetchFailureWithWarmCache(t *testing.T) { + key := newTestSigningKey(t, "key-1") + unknown := newTestSigningKey(t, "not-published") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + srv.setFail(true) + clock.Advance(githubJWKSCacheTTL / 2) + + // Cached keys keep working while GitHub is unreachable. + require.NoError(t, validate(v, key.token(t))) + + // A failed refetch for an unknown kid does not drop the cached keys. + require.Error(t, validate(v, unknown.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_FetchFailureFailsClosed(t *testing.T) { + t.Run("cold cache", func(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + srv.setFail(true) + v := newTestValidator(srv, newFakeClock()) + + err := validate(v, key.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "503") + }) + + t.Run("expired cache", func(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + srv.setFail(true) + clock.Advance(githubJWKSCacheTTL + time.Second) + + require.Error(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + // Failed attempts are rate limited too, so an outage does not turn + // every exchange into an outbound request. + require.Error(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + // Once GitHub answers again the next attempt after the interval succeeds. + srv.setFail(false) + clock.Advance(githubJWKSMinRefreshInterval) + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(3), srv.fetches.Load()) + }) +} + +func TestGitHubOIDCValidator_ConcurrentExchangesShareOneFetch(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + release := srv.hold(t) + v := newTestValidator(srv, newFakeClock()) + + const n = 20 + tokens := make([]string, n) + for i := range tokens { + tokens[i] = key.token(t) + } + + var wg sync.WaitGroup + errs := make(chan error, n) + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + errs <- validate(v, tokens[i]) + }() + } + // Give the goroutines time to pile up behind the first fetch. + time.Sleep(50 * time.Millisecond) + release() + wg.Wait() + close(errs) + + for err := range errs { + require.NoError(t, err) + } + assert.Equal(t, int64(1), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_CancelledCallerDoesNotAbortFetch(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t, key) + release := srv.hold(t) + v := newTestValidator(srv, newFakeClock()) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := v.ValidateToken(ctx, key.token(t), testOIDCAudience) + done <- err + }() + + require.Eventually(t, func() bool { return srv.fetches.Load() == 1 }, time.Second, 5*time.Millisecond) + cancel() + err := <-done + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) + + // The fetch the cancelled caller started still fills the cache, so a + // client that hangs up cannot leave the next caller throttled. + release() + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(1), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_SkipsUnusableKeys(t *testing.T) { + good := newTestSigningKey(t, "good") + ecKid := newTestSigningKey(t, "ec-key") + badN := newTestSigningKey(t, "bad-n") + noKid := newTestSigningKey(t, "") + + badNJWK := badN.jwk() + badNJWK.N = "!!not-base64!!" + srv := newJWKSServer(t) + srv.setRawKeys([]JWK{ + good.jwk(), + {KTY: "EC", KID: "ec-key", Use: "sig"}, + badNJWK, + noKid.jwk(), + }) + v := newTestValidator(srv, newFakeClock()) + + require.NoError(t, validate(v, good.token(t))) + for _, k := range []testSigningKey{ecKid, badN, noKid} { + err := validate(v, k.token(t)) + require.Error(t, err, "kid %q", k.kid) + assert.Contains(t, err.Error(), "not found", "kid %q", k.kid) + } + assert.Equal(t, int64(1), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_DuplicateKidFirstEntryWins(t *testing.T) { + a := newTestSigningKey(t, "dup") + b := newTestSigningKey(t, "dup") + broken := a.jwk() + broken.N = "!!not-base64!!" + + tests := []struct { + name string + keys []JWK + accepted []testSigningKey + rejected []testSigningKey + }{ + {name: "a then b", keys: []JWK{a.jwk(), b.jwk()}, accepted: []testSigningKey{a}, rejected: []testSigningKey{b}}, + {name: "b then a", keys: []JWK{b.jwk(), a.jwk()}, accepted: []testSigningKey{b}, rejected: []testSigningKey{a}}, + {name: "unusable first entry is not replaced", keys: []JWK{broken, b.jwk()}, rejected: []testSigningKey{a, b}}, + {name: "unusable later entry is ignored", keys: []JWK{a.jwk(), broken}, accepted: []testSigningKey{a}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // The good key keeps the document from being empty. + other := newTestSigningKey(t, "other") + srv := newJWKSServer(t) + srv.setRawKeys(append(tt.keys, other.jwk())) + v := newTestValidator(srv, newFakeClock()) + + for _, k := range tt.accepted { + require.NoError(t, validate(v, k.token(t))) + } + for _, k := range tt.rejected { + require.Error(t, validate(v, k.token(t))) + } + assert.Equal(t, int64(1), srv.fetches.Load()) + }) + } +} + +func TestGitHubOIDCValidator_NoUsableKeysIsAFailedFetch(t *testing.T) { + emptyDocs := map[string][]JWK{ + "null keys": nil, + "empty keys": {}, + "only unusable keys": { + {KTY: "EC", KID: "ec-key", Use: "sig"}, + {KTY: "RSA", KID: "bad-n", N: "!!not-base64!!", E: "AQAB"}, + }, + } + + for name, doc := range emptyDocs { + t.Run(name+" with warm cache", func(t *testing.T) { + key := newTestSigningKey(t, "key-1") + unknown := newTestSigningKey(t, "not-published") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + srv.setRawKeys(doc) + clock.Advance(githubJWKSMinRefreshInterval) + + err := validate(v, unknown.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "no usable RSA keys") + assert.Equal(t, int64(2), srv.fetches.Load()) + + // The cached key survives until its TTL, and the failed fetch + // still counts towards the refresh limit. + require.NoError(t, validate(v, key.token(t))) + require.Error(t, validate(v, unknown.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + clock.Advance(githubJWKSCacheTTL - githubJWKSMinRefreshInterval - time.Second) + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) + + clock.Advance(2 * time.Second) + require.Error(t, validate(v, key.token(t))) + assert.Equal(t, int64(3), srv.fetches.Load()) + }) + + t.Run(name+" with cold cache", func(t *testing.T) { + key := newTestSigningKey(t, "key-1") + srv := newJWKSServer(t) + srv.setRawKeys(doc) + v := newTestValidator(srv, newFakeClock()) + + err := validate(v, key.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "no usable RSA keys") + }) + } +} + +func TestNewGitHubOIDCValidator_ClientHasTimeout(t *testing.T) { + v := NewGitHubOIDCValidator() + require.NotNil(t, v.client) + assert.Equal(t, githubJWKSFetchTimeout, v.client.Timeout) + assert.Positive(t, v.client.Timeout) +} From 58fb45ab2c3e8ad296e4ec7ec7fd0bbf7f48ffd4 Mon Sep 17 00:00:00 2001 From: Yusufhan Sacak Date: Sat, 28 Nov 2026 09:49:33 +0000 Subject: [PATCH 2/3] fix(auth/github-oidc): don't cache JWKS entries with an unusable n or e A JWKS entry with a missing or malformed modulus or exponent parsed into a key that can never verify a signature. If it was the only entry in a refresh, it replaced keys that still worked. Refuse such keys in parseRSAPublicKey, using the same bounds rsa.VerifyPKCS1v15 enforces, so the refresh counts as failed and the cached keys stay. --- internal/api/handlers/v0/auth/github_oidc.go | 10 ++++++++++ .../api/handlers/v0/auth/github_oidc_internal_test.go | 7 +++++++ 2 files changed, 17 insertions(+) diff --git a/internal/api/handlers/v0/auth/github_oidc.go b/internal/api/handlers/v0/auth/github_oidc.go index 1d7bcff7b..d773e7ddf 100644 --- a/internal/api/handlers/v0/auth/github_oidc.go +++ b/internal/api/handlers/v0/auth/github_oidc.go @@ -320,6 +320,16 @@ func (v *GitHubOIDCValidator) parseRSAPublicKey(jwk JWK) (*rsa.PublicKey, error) n := new(big.Int).SetBytes(nBytes) e := new(big.Int).SetBytes(eBytes) + // Reject keys that rsa.VerifyPKCS1v15 would refuse, so a missing or + // broken n or e cannot be cached in place of keys that still work. + // The 31-bit limit also keeps the int conversion below from truncating. + if n.BitLen() < 1024 || n.Bit(0) == 0 { + return nil, fmt.Errorf("invalid modulus") + } + if e.BitLen() > 31 || e.Int64() < 3 || e.Bit(0) == 0 { + return nil, fmt.Errorf("invalid exponent") + } + return &rsa.PublicKey{ N: n, E: int(e.Int64()), diff --git a/internal/api/handlers/v0/auth/github_oidc_internal_test.go b/internal/api/handlers/v0/auth/github_oidc_internal_test.go index b0d283f03..7d6b0e7e1 100644 --- a/internal/api/handlers/v0/auth/github_oidc_internal_test.go +++ b/internal/api/handlers/v0/auth/github_oidc_internal_test.go @@ -444,6 +444,7 @@ func TestGitHubOIDCValidator_DuplicateKidFirstEntryWins(t *testing.T) { } func TestGitHubOIDCValidator_NoUsableKeysIsAFailedFetch(t *testing.T) { + realN := newTestSigningKey(t, "n-source").jwk().N emptyDocs := map[string][]JWK{ "null keys": nil, "empty keys": {}, @@ -451,6 +452,12 @@ func TestGitHubOIDCValidator_NoUsableKeysIsAFailedFetch(t *testing.T) { {KTY: "EC", KID: "ec-key", Use: "sig"}, {KTY: "RSA", KID: "bad-n", N: "!!not-base64!!", E: "AQAB"}, }, + "only key missing n": {{KTY: "RSA", KID: "no-n", E: "AQAB"}}, + "only key missing e": {{KTY: "RSA", KID: "no-e", N: realN}}, + "only key with tiny n": {{KTY: "RSA", KID: "tiny-n", N: "Aw", E: "AQAB"}}, + "only key with even e": {{KTY: "RSA", KID: "even-e", N: realN, E: "Ag"}}, + // 2^64 + 65537, which would truncate to 65537 in an int. + "only key with oversized e": {{KTY: "RSA", KID: "big-e", N: realN, E: "AQAAAAAAAQAB"}}, } for name, doc := range emptyDocs { From 21ee15f96df7958c27995e32201c2bd1171429dd Mon Sep 17 00:00:00 2001 From: Yusufhan Sacak Date: Sat, 28 Nov 2026 09:55:58 +0000 Subject: [PATCH 3/3] fix(auth/github-oidc): reject empty kid and bound the JWKS body read A token with "kid": "" can never match a cached key, but it still started a JWKS refresh and used up the 30 second window. Treat it like a missing kid. Read at most 1 MiB of a 200 JWKS response, as error bodies are already bounded. A larger document fails to decode, so the fetch counts as failed and the cached keys stay. --- internal/api/handlers/v0/auth/github_oidc.go | 9 +++- .../v0/auth/github_oidc_internal_test.go | 49 ++++++++++++++++++- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/internal/api/handlers/v0/auth/github_oidc.go b/internal/api/handlers/v0/auth/github_oidc.go index d773e7ddf..13bee751f 100644 --- a/internal/api/handlers/v0/auth/github_oidc.go +++ b/internal/api/handlers/v0/auth/github_oidc.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/json" "fmt" + "io" "math/big" "net/http" "strings" @@ -89,6 +90,10 @@ const githubJWKSMinRefreshInterval = 30 * time.Second // githubJWKSFetchTimeout bounds a single JWKS fetch. const githubJWKSFetchTimeout = 10 * time.Second +// githubJWKSMaxBodySize bounds how much of a JWKS response is read. GitHub's +// document is a few KiB; a larger one fails to decode and the fetch fails. +const githubJWKSMaxBodySize = 1 << 20 + // NewGitHubOIDCValidator creates a new GitHub OIDC validator func NewGitHubOIDCValidator() *GitHubOIDCValidator { return newGitHubOIDCValidator( @@ -120,7 +125,7 @@ func (v *GitHubOIDCValidator) ValidateToken(ctx context.Context, tokenString str func(token *jwt.Token) (any, error) { // Get key ID from header kid, ok := token.Header["kid"].(string) - if !ok { + if !ok || kid == "" { return nil, fmt.Errorf("missing kid in token header") } @@ -192,7 +197,7 @@ func (v *GitHubOIDCValidator) fetchJWKS(ctx context.Context) (*JWKS, error) { } var jwks JWKS - if err := json.NewDecoder(resp.Body).Decode(&jwks); err != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, githubJWKSMaxBodySize)).Decode(&jwks); err != nil { return nil, fmt.Errorf("failed to decode JWKS: %w", err) } diff --git a/internal/api/handlers/v0/auth/github_oidc_internal_test.go b/internal/api/handlers/v0/auth/github_oidc_internal_test.go index 7d6b0e7e1..a82b19931 100644 --- a/internal/api/handlers/v0/auth/github_oidc_internal_test.go +++ b/internal/api/handlers/v0/auth/github_oidc_internal_test.go @@ -9,6 +9,7 @@ import ( "math/big" "net/http" "net/http/httptest" + "strings" "sync" "sync/atomic" "testing" @@ -399,7 +400,9 @@ func TestGitHubOIDCValidator_SkipsUnusableKeys(t *testing.T) { v := newTestValidator(srv, newFakeClock()) require.NoError(t, validate(v, good.token(t))) - for _, k := range []testSigningKey{ecKid, badN, noKid} { + // A token with an empty kid is refused before the key lookup; see + // TestGitHubOIDCValidator_EmptyKidDoesNotFetch. + for _, k := range []testSigningKey{ecKid, badN} { err := validate(v, k.token(t)) require.Error(t, err, "kid %q", k.kid) assert.Contains(t, err.Error(), "not found", "kid %q", k.kid) @@ -407,6 +410,50 @@ func TestGitHubOIDCValidator_SkipsUnusableKeys(t *testing.T) { assert.Equal(t, int64(1), srv.fetches.Load()) } +func TestGitHubOIDCValidator_EmptyKidDoesNotFetch(t *testing.T) { + key := newTestSigningKey(t, "key-1") + noKid := newTestSigningKey(t, "") + rotated := newTestSigningKey(t, "key-2") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + clock.Advance(githubJWKSMinRefreshInterval) + + err := validate(v, noKid.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing kid") + assert.Equal(t, int64(1), srv.fetches.Load()) + + // The refresh window is still open for a kid that is really new. + srv.setKeys(key, rotated) + require.NoError(t, validate(v, rotated.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + +func TestGitHubOIDCValidator_OversizedJWKSIsAFailedFetch(t *testing.T) { + key := newTestSigningKey(t, "key-1") + unknown := newTestSigningKey(t, "not-published") + srv := newJWKSServer(t, key) + clock := newFakeClock() + v := newTestValidator(srv, clock) + + require.NoError(t, validate(v, key.token(t))) + // A valid document, just over the size limit. + srv.setRawKeys([]JWK{key.jwk(), {KTY: "RSA", KID: "padding", Use: strings.Repeat("x", githubJWKSMaxBodySize)}}) + clock.Advance(githubJWKSMinRefreshInterval) + + err := validate(v, unknown.token(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to decode JWKS") + assert.Equal(t, int64(2), srv.fetches.Load()) + + // The cached key is kept. + require.NoError(t, validate(v, key.token(t))) + assert.Equal(t, int64(2), srv.fetches.Load()) +} + func TestGitHubOIDCValidator_DuplicateKidFirstEntryWins(t *testing.T) { a := newTestSigningKey(t, "dup") b := newTestSigningKey(t, "dup")