Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions authn/jwks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
107 changes: 107 additions & 0 deletions authn/jwks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
Expand Down Expand Up @@ -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)
}
}
Loading