From c97d41b854c34b8affd8094a8b7c88cefdf10a0d Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 15 Nov 2026 10:17:14 +0530 Subject: [PATCH] fix(authn): stop trusting keys that are removed from the JWKS KeySet only ever added keys, so a kid rotated out of /jwks stayed trusted for the life of the process. Rotating a leaked signing key did not take effect until every server restarted. Each successful fetch now replaces the cached key set, and a set older than five minutes is re-fetched in the background (requests keep being served from the cache, and a failed refresh keeps the cached keys and retries after 30s), so a removed key stops verifying within that window. --- authn/jwks.go | 58 ++++++++++++++++++++---- authn/jwks_test.go | 107 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 9 deletions(-) diff --git a/authn/jwks.go b/authn/jwks.go index a999bc1..ed7c469 100644 --- a/authn/jwks.go +++ b/authn/jwks.go @@ -63,15 +63,21 @@ type KeySet struct { url string client *http.Client - mu sync.Mutex - keys map[string]ed25519.PublicKey // kid -> key - fetched time.Time + mu sync.Mutex + keys map[string]ed25519.PublicKey // kid -> key; exactly the last fetched set + fetched time.Time + refreshing bool // a background refresh is in flight } // refreshInterval is the minimum time between JWKS re-fetches, so a flood of // bad-kid tokens cannot hammer the auth service. const refreshInterval = 30 * time.Second +// maxKeyAge bounds how long a cached key set is trusted without re-checking the +// JWKS. Rotating a key out (the response to a leak) takes effect on every +// server within this window instead of at its next restart. +const maxKeyAge = 5 * time.Minute + // NewKeySet points at a priompt-auth /jwks URL. The first fetch happens lazily // on first use (and retries on unknown kid), so the server starts fine even if // the auth service is briefly down. @@ -90,17 +96,53 @@ type jwks struct { } // key returns the public key for kid, re-fetching the JWKS (rate-limited) when -// the kid is unknown — the rotation path. +// the kid is unknown — the rotation path. A key set older than maxKeyAge is +// refreshed in the background so a key removed from the JWKS stops verifying. func (k *KeySet) key(kid string) (ed25519.PublicKey, error) { k.mu.Lock() defer k.mu.Unlock() if pub, ok := k.keys[kid]; ok { + // Serve this request from the cache and refresh off the request path: + // an auth-service outage must not stall verification of known keys. + if time.Since(k.fetched) > maxKeyAge && !k.refreshing { + k.refreshing = true + go k.refresh() + } return pub, nil } if time.Since(k.fetched) < refreshInterval { return nil, fmt.Errorf("unknown key id %q", kid) } k.fetched = time.Now() + keys, err := k.fetch() + if err != nil { + return nil, err + } + k.keys = keys + if pub, ok := k.keys[kid]; ok { + return pub, nil + } + return nil, fmt.Errorf("unknown key id %q", kid) +} + +// refresh re-fetches the JWKS in the background. On failure the cached keys +// stay in use and the next attempt waits refreshInterval, not maxKeyAge. +func (k *KeySet) refresh() { + keys, err := k.fetch() + k.mu.Lock() + defer k.mu.Unlock() + k.refreshing = false + if err != nil { + k.fetched = time.Now().Add(refreshInterval - maxKeyAge) + return + } + k.keys, k.fetched = keys, time.Now() +} + +// fetch downloads the JWKS and returns its Ed25519 keys. The result replaces +// the cached set wholesale: a kid that is no longer served is no longer +// trusted, which is what makes rotating a leaked key out effective. +func (k *KeySet) fetch() (map[string]ed25519.PublicKey, error) { resp, err := k.client.Get(k.url) if err != nil { return nil, err @@ -113,6 +155,7 @@ func (k *KeySet) key(kid string) (ed25519.PublicKey, error) { if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil { return nil, err } + keys := map[string]ed25519.PublicKey{} for _, jk := range doc.Keys { if jk.Kty != "OKP" || jk.Crv != "Ed25519" { continue @@ -121,12 +164,9 @@ func (k *KeySet) key(kid string) (ed25519.PublicKey, error) { if err != nil || len(raw) != ed25519.PublicKeySize { continue } - k.keys[jk.Kid] = ed25519.PublicKey(raw) + keys[jk.Kid] = ed25519.PublicKey(raw) } - if pub, ok := k.keys[kid]; ok { - return pub, nil - } - return nil, fmt.Errorf("unknown key id %q", kid) + return keys, nil } // Verify checks an EdDSA compact JWT and returns its claims. It enforces the diff --git a/authn/jwks_test.go b/authn/jwks_test.go index c3c15e2..5ec93af 100644 --- a/authn/jwks_test.go +++ b/authn/jwks_test.go @@ -7,6 +7,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "sync" "testing" "time" ) @@ -128,3 +129,109 @@ func TestIdentityExpires(t *testing.T) { t.Fatalf("jwt: Expires = %v err=%v, want %v", id.Expires, err, exp) } } + +// rotatingJWKS serves whatever key is current; swap it to simulate rotation. +type rotatingJWKS struct { + mu sync.Mutex + kid string + pub ed25519.PublicKey +} + +func (r *rotatingJWKS) set(kid string, pub ed25519.PublicKey) { + r.mu.Lock() + r.kid, r.pub = kid, pub + r.mu.Unlock() +} + +func (r *rotatingJWKS) ServeHTTP(w http.ResponseWriter, _ *http.Request) { + r.mu.Lock() + defer r.mu.Unlock() + w.Write(JWKSJSON(r.pub, r.kid)) +} + +// A key rotated out of the JWKS must stop verifying without a restart — the +// response to a leaked signing key. +func TestRotatedOutKeyStopsVerifying(t *testing.T) { + oldPub, oldPriv, _ := ed25519.GenerateKey(nil) + newPub, newPriv, _ := ed25519.GenerateKey(nil) + jw := &rotatingJWKS{} + jw.set("old", oldPub) + srv := httptest.NewServer(jw) + t.Cleanup(srv.Close) + ks := NewKeySet(srv.URL) + exp := time.Now().Add(time.Hour).Unix() + oldTok := MintJWT(oldPriv, "old", Claims{Sub: "x", Exp: exp}) + newTok := MintJWT(newPriv, "new", Claims{Sub: "x", Exp: exp}) + + if _, err := ks.Verify(oldTok); err != nil { + t.Fatalf("old key before rotation: %v", err) + } + jw.set("new", newPub) + + // Path 1: an unknown kid triggers a fetch, which must replace the set. + ks.mu.Lock() + ks.fetched = time.Time{} // past the rate limit + ks.mu.Unlock() + if _, err := ks.Verify(newTok); err != nil { + t.Fatalf("new key after rotation: %v", err) + } + if _, err := ks.Verify(oldTok); err == nil { + t.Fatal("old key still verifies after a fetch that no longer serves it") + } + + // Path 2: with no unknown kid ever presented, a stale cache is refreshed. + ks2 := NewKeySet(srv.URL) + jw.set("old", oldPub) + if _, err := ks2.Verify(oldTok); err != nil { + t.Fatal(err) + } + jw.set("new", newPub) + ks2.mu.Lock() + ks2.fetched = time.Now().Add(-maxKeyAge - time.Second) + ks2.mu.Unlock() + ks2.Verify(oldTok) // served from cache; starts the background refresh + deadline := time.Now().Add(5 * time.Second) + for { + if _, err := ks2.Verify(oldTok); err != nil { + break + } + if time.Now().After(deadline) { + t.Fatal("old key still verifies after the key set went stale") + } + time.Sleep(10 * time.Millisecond) + } +} + +// A failed background refresh keeps serving the cached keys. +func TestStaleRefreshFailureKeepsCachedKeys(t *testing.T) { + pub, priv, _ := ed25519.GenerateKey(nil) + up := true + var mu sync.Mutex + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + mu.Lock() + defer mu.Unlock() + if !up { + http.Error(w, "down", http.StatusServiceUnavailable) + return + } + w.Write(JWKSJSON(pub, "k")) + })) + t.Cleanup(srv.Close) + ks := NewKeySet(srv.URL) + tok := MintJWT(priv, "k", Claims{Sub: "x", Exp: time.Now().Add(time.Hour).Unix()}) + if _, err := ks.Verify(tok); err != nil { + t.Fatal(err) + } + mu.Lock() + up = false + mu.Unlock() + ks.mu.Lock() + ks.fetched = time.Now().Add(-maxKeyAge - time.Second) + ks.mu.Unlock() + for i := 0; i < 20; i++ { + if _, err := ks.Verify(tok); err != nil { + t.Fatalf("auth service down: cached key must keep verifying, got %v", err) + } + time.Sleep(10 * time.Millisecond) + } +}