From 4cb3e70ec069c675ef12a857c117359fbe3ab64a Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 02:17:27 +0800 Subject: [PATCH 1/3] fix(federation): refuse a trust chain that expires while it resolves Resolver.Resolve read the clock once, when it started, and verified every statement it fetched at that time. A resolution whose fetches outlasted the chain's earliest exp therefore returned a chain that had already expired, and AutomaticClientRepository handed the requests waiting on that resolution a client, and its keys, registered from it. The cache itself was not extended past the chain's expiry: its entry expired with the chain, so only the requests sharing that resolution were answered from the expired chain. Resolve now checks ResolvedEntity.ExpiresAt against the clock again when it finishes, with the MaxClockSkew tolerance each statement's exp was checked with, and refuses a chain that has expired by then. Automatic registration repeats the check after building the registration, since fetching the RP's jwks_uri can take the chain past its expiry after Resolve returned. Such a registration fails like any other: invalid_client for the client, reported to OnResolutionFailure and remembered for FailureCacheAge. Co-Authored-By: Claude Opus 5.5 --- UPGRADING.md | 32 ++++ federation/automatic_registration.go | 10 +- federation/automatic_registration_test.go | 6 +- federation/resolution_expiry_test.go | 208 ++++++++++++++++++++++ federation/resolver.go | 31 ++++ 5 files changed, 285 insertions(+), 2 deletions(-) create mode 100644 federation/resolution_expiry_test.go diff --git a/UPGRADING.md b/UPGRADING.md index f71678a9..44daeecd 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,38 @@ Most production-assurance changes only affect `Config.Assurance = AssuranceProduction`. A development-assurance setup built on `memstore` and `keys/ephemeral` needs only the steps not marked *production only*. +## v0.85.1 + +### A Trust Chain that expires while it resolves is refused (federation) + +**Affects:** a server using automatic registration +(`Config.AutomaticRegistration`), or code calling +`federation.Resolver.Resolve`, whose Relying Parties' Trust Chains can +expire while they are being resolved: a chain with little lifetime +left, fetched over slow federation endpoints. + +**Why:** `Resolve` verified every statement at the time it started, +so a resolution whose fetches outlasted the chain's earliest `exp` +returned a chain that had already expired, and automatic registration +handed the requests waiting on it a client registered from that chain. +`Resolve` now checks the chain's expiry (`ResolvedEntity.ExpiresAt`, +with `Limits.MaxClockSkew`'s tolerance) again when it finishes, and +automatic registration checks it once more after building the +registration (which can fetch the RP's `jwks_uri`). + +**What fails:** such a resolution returns an error ("the trust chain +for ... expired at ..., before its resolution finished"); for automatic +registration the client gets `invalid_client`, the failure is reported +to `OnResolutionFailure` and remembered for `FailureCacheAge`, as any +other registration failure. A resolution started after the chain +expired was already refused, so the only new refusals are of chains +that expire mid-resolution. + +**What to change:** nothing in code. If it shows up in +`OnResolutionFailure`, the federation's statements are issued with too +little lifetime for how long its endpoints take to answer: ask the +superior or RP to issue them for longer. + ## v0.85.0 ### Codes, refresh tokens and `auth_req_id`s are stored under digests covering the issuer (server, storage) diff --git a/federation/automatic_registration.go b/federation/automatic_registration.go index f4fce8b1..95dd8072 100644 --- a/federation/automatic_registration.go +++ b/federation/automatic_registration.go @@ -962,8 +962,16 @@ func (a *AutomaticClientRepository) register(ctx context.Context, id fapi.Client return cachedClient{}, fmt.Errorf("federation: %q: %w", id, err) } + // Building the registration can fetch (its jwks_uri), so the chain + // can expire after Resolve has checked it: a registration whose + // chain has expired by now is never handed out, not even to the + // requests waiting on this resolution. + now := a.clock.Now() + if err := a.resolver.checkChainUnexpired(string(id), resolved.ExpiresAt, now); err != nil { + return cachedClient{}, err + } expiresAt := resolved.ExpiresAt - if maxAge := a.clock.Now().Add(a.cfg.MaxCacheAge); maxAge.Before(expiresAt) { + if maxAge := now.Add(a.cfg.MaxCacheAge); maxAge.Before(expiresAt) { expiresAt = maxAge } superior, branch := chainPosition(resolved.Chain) diff --git a/federation/automatic_registration_test.go b/federation/automatic_registration_test.go index bde85c1c..015aaf04 100644 --- a/federation/automatic_registration_test.go +++ b/federation/automatic_registration_test.go @@ -44,6 +44,10 @@ type automaticRegistrationFixture struct { rpConfigCalls *int32 rpMux *http.ServeMux + // pool trusts both servers' certificates, for a test building a + // fetcher of its own over them. + pool *x509.CertPool + // setTAPolicy, set by setupAutomaticRegistrationFixtureUnderIntermediate // only, has the Trust Anchor sign and serve its Subordinate Statement // about the Intermediate with another metadata policy from then on. @@ -140,7 +144,7 @@ func setupAutomaticRegistrationFixtureWithPolicy(t *testing.T, metadataFn func(r taID: taID, rpID: rpID, taKey: taKey, taJWKS: taJWKS, rpFedKey: rpFedKey, rpOIDCKey: rpOIDCKey, fetcher: fetcher, now: now, rpConfigCalls: &calls, - rpMux: rpMux, + rpMux: rpMux, pool: pool, } } diff --git a/federation/resolution_expiry_test.go b/federation/resolution_expiry_test.go new file mode 100644 index 00000000..d1e7a31e --- /dev/null +++ b/federation/resolution_expiry_test.go @@ -0,0 +1,208 @@ +package federation_test + +import ( + "context" + "crypto/tls" + "net/http" + "sync" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/fapihttp" + "github.com/idfoundry/fapigo/federation" + "github.com/idfoundry/fapigo/keys" +) + +// expiryTestSkew is the MaxClockSkew the resolvers in this file allow. +const expiryTestSkew = 5 * time.Second + +// settableClock is a federation.Clock a fetch can move while a +// resolution runs. +type settableClock struct { + mu sync.Mutex + now time.Time +} + +func (c *settableClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *settableClock) set(now time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = now +} + +// onFetchTransport calls on with every request's path before sending it +// on: the time a fetch takes, as a test chooses it. +type onFetchTransport struct { + base http.RoundTripper + on func(path string) +} + +func (t onFetchTransport) RoundTrip(r *http.Request) (*http.Response, error) { + t.on(r.URL.Path) + return t.base.RoundTrip(r) +} + +// slowResolution is the fixture f's federation with a clock that moves +// to at, if at isn't zero, when path is fetched. +type slowResolution struct { + f *automaticRegistrationFixture + clock *settableClock + fetcher *fapihttp.Client + resolver *federation.Resolver +} + +func newSlowResolution(t *testing.T, f *automaticRegistrationFixture, path string, at *time.Time) *slowResolution { + t.Helper() + clock := &settableClock{now: f.now} + transport := onFetchTransport{ + base: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: f.pool}}, + on: func(p string) { + if p == path && !at.IsZero() { + clock.set(*at) + } + }, + } + fetcher, err := fapihttp.New(&http.Client{Transport: transport}, fapihttp.Config{ + MaxResponseBytes: 1 << 16, RequestTimeout: 5 * time.Second, MaxRedirects: 1, + AllowLoopbackHTTP: true, + }) + if err != nil { + t.Fatalf("fapihttp.New: %v", err) + } + resolver, err := federation.NewResolver(federation.Config{ + TrustAnchors: []federation.TrustAnchor{{EntityID: f.taID, JWKS: f.taJWKS}}, + Limits: federation.Limits{MaxPathLength: 5, MaxAuthorityHints: 5, MaxStatementLifetime: 2 * time.Hour, MaxClockSkew: expiryTestSkew}, + }, federation.Dependencies{HTTP: fetcher, Clock: clock}) + if err != nil { + t.Fatalf("NewResolver: %v", err) + } + return &slowResolution{f: f, clock: clock, fetcher: fetcher, resolver: resolver} +} + +// chainExpiry resolves f's RP once, with no time passing, for its Trust +// Chain's expiry. +func chainExpiry(t *testing.T, f *automaticRegistrationFixture) time.Time { + t.Helper() + var never time.Time + resolved, err := newSlowResolution(t, f, "", &never).resolver.Resolve(context.Background(), f.rpID) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + return resolved.ExpiresAt +} + +// TestResolveRefusesChainExpiredWhileResolving: Resolve verifies each +// statement at the time it started, so one whose last fetch (the Trust +// Anchor's Subordinate Statement about the RP) ends after the chain's +// exp has expired by the time it would return. It is refused, as +// starting the resolution then would have refused it; a chain still +// within MaxClockSkew of its exp then is not. +func TestResolveRefusesChainExpiredWhileResolving(t *testing.T) { + f := setupAutomaticRegistrationFixture(t, rpMetadataBuilder(t)) + exp := chainExpiry(t, f) + for name, tc := range map[string]struct { + at time.Time + refused bool + }{ + "long past exp": {at: exp.Add(time.Hour), refused: true}, + "just past skew": {at: exp.Add(expiryTestSkew + time.Second), refused: true}, + "within skew": {at: exp.Add(expiryTestSkew), refused: false}, + "before exp": {at: exp.Add(-time.Second), refused: false}, + "no time passes": {refused: false}, + } { + t.Run(name, func(t *testing.T) { + at := tc.at + slow := newSlowResolution(t, f, "/fetch", &at) + resolved, err := slow.resolver.Resolve(context.Background(), f.rpID) + if tc.refused { + if err == nil { + t.Fatalf("Resolve finishing at %v = chain expiring at %v, nil error; want the expired chain refused", slow.clock.Now(), resolved.ExpiresAt) + } + return + } + if err != nil { + t.Fatalf("Resolve finishing at %v: %v, want the chain (exp %v, skew %v)", slow.clock.Now(), err, exp, expiryTestSkew) + } + }) + } +} + +// TestAutomaticRegistrationRefusesChainExpiredWhileRegistering: a +// registration whose Trust Chain expires while it is built (here, while +// the RP's jwks_uri is fetched, after the chain has resolved) isn't +// handed to the request waiting on it: neither ResolveClient nor the key +// source answers with it, and nothing is cached. +func TestAutomaticRegistrationRefusesChainExpiredWhileRegistering(t *testing.T) { + f := setupAutomaticRegistrationFixture(t, rpMetadataBuilderWithJWKSURI(t)) + f.rpMux.HandleFunc("/jwks.json", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(jwksFor(t, "rp-oidc", f.rpOIDCKey)) + }) + exp := chainExpiry(t, f) + for name, tc := range map[string]struct { + at time.Time + refused bool + }{ + "long past exp": {at: exp.Add(time.Hour), refused: true}, + "just past skew": {at: exp.Add(expiryTestSkew + time.Second), refused: true}, + "within skew": {at: exp.Add(expiryTestSkew), refused: false}, + } { + t.Run(name, func(t *testing.T) { + at := tc.at + checkSlowRegistration(t, newSlowResolution(t, f, "/jwks.json", &at), tc.refused) + }) + } +} + +// TestAutomaticRegistrationRefusesChainExpiredWhileResolving is +// TestAutomaticRegistrationRefusesChainExpiredWhileRegistering with the +// chain expiring during the resolution itself. +func TestAutomaticRegistrationRefusesChainExpiredWhileResolving(t *testing.T) { + f := setupAutomaticRegistrationFixture(t, rpMetadataBuilder(t)) + at := chainExpiry(t, f).Add(time.Hour) + checkSlowRegistration(t, newSlowResolution(t, f, "/fetch", &at), true) +} + +// checkSlowRegistration registers slow's RP through a fresh +// repository's ResolveClient and through its key source, and checks +// each is refused, with nothing cached, or answered, as refused says. +func checkSlowRegistration(t *testing.T, slow *slowResolution, refused bool) { + t.Helper() + id := fapi.ClientID(slow.f.rpID) + newRepo := func() *federation.AutomaticClientRepository { + slow.clock.set(slow.f.now) + repo, err := federation.NewAutomaticClientRepository(alwaysFailsRepository{}, slow.resolver, slow.fetcher, validAutomaticRegistrationConfig(), slow.clock) + if err != nil { + t.Fatalf("NewAutomaticClientRepository: %v", err) + } + return repo + } + + repo := newRepo() + client, err := repo.ResolveClient(context.Background(), id) + _, _, cached := federation.CachedChainPosition(repo, id) + if refused && (err == nil || cached) { + t.Fatalf("ResolveClient finishing at %v = (%q, %v), cached %v; want the expired chain's registration refused and not cached", slow.clock.Now(), client.ID(), err, cached) + } + if !refused && err != nil { + t.Fatalf("ResolveClient finishing at %v: %v, want the client registered", slow.clock.Now(), err) + } + + src, err := federation.NewAutomaticClientKeySource(alwaysFailsKeySource{}, newRepo()) + if err != nil { + t.Fatalf("NewAutomaticClientKeySource: %v", err) + } + set, err := src.ResolveVerificationKeys(context.Background(), keys.ClientKeyRequest{ClientID: id, Algorithm: fapi.ES256}) + if refused && (err == nil || len(set.Keys) != 0) { + t.Fatalf("ResolveVerificationKeys finishing at %v = %d keys, %v; want the expired chain's keys refused", slow.clock.Now(), len(set.Keys), err) + } + if !refused && (err != nil || len(set.Keys) == 0) { + t.Fatalf("ResolveVerificationKeys finishing at %v = %d keys, %v; want the RP's key", slow.clock.Now(), len(set.Keys), err) + } +} diff --git a/federation/resolver.go b/federation/resolver.go index 5374c6da..ef019876 100644 --- a/federation/resolver.go +++ b/federation/resolver.go @@ -436,7 +436,38 @@ func newChainWalkState(subjectID string, leafStmt intfed.Statement, leafToken st // (see Dependencies.HTTP), and a caller that resolves an Entity // Identifier an unauthenticated party names (as automatic registration // does with a client_id) lets that party send them. +// +// Every statement is verified at the time Resolve started, and a Trust +// Chain that has expired by the time it finishes (Dependencies.Clock +// past ResolvedEntity.ExpiresAt by more than Limits.MaxClockSkew, as a +// slow fetch can make it) is refused, as starting the resolution then +// would have refused it. func (r *Resolver) Resolve(ctx context.Context, subjectID string) (ResolvedEntity, error) { + resolved, err := r.resolveFrom(ctx, subjectID) + if err != nil { + return ResolvedEntity{}, err + } + if err := r.checkChainUnexpired(subjectID, resolved.ExpiresAt, r.deps.Clock.Now()); err != nil { + return ResolvedEntity{}, err + } + return resolved, nil +} + +// checkChainUnexpired refuses subjectID's Trust Chain, expiring at +// expiresAt, if it has expired at now: by more than +// Limits.MaxClockSkew, the tolerance each of its statements' exp was +// checked with. +func (r *Resolver) checkChainUnexpired(subjectID string, expiresAt, now time.Time) error { + if now.After(expiresAt.Add(r.cfg.Limits.MaxClockSkew)) { + return fmt.Errorf("federation: the trust chain for %q expired at %s, before its resolution finished at %s", + subjectID, expiresAt.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339)) + } + return nil +} + +// resolveFrom is Resolve, verifying every statement at the time it +// starts, without checking the chain at the time it finishes. +func (r *Resolver) resolveFrom(ctx context.Context, subjectID string) (ResolvedEntity, error) { if subjectID == "" { return ResolvedEntity{}, fmt.Errorf("federation: subject entity ID is empty") } From 49587781b5c42c74fe95d83e6bc904486123c553 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 02:17:27 +0800 Subject: [PATCH 2/3] fix(federation): answer a resolution-failure hook resolving its own client_id OnResolutionFailure runs on the resolution's goroutine before the resolution finishes. A hook calling ResolveClient for the same client_id relied on the failure having been remembered just before it ran; when it had not been (the memory of failures full, which any caller can bring about by naming enough failing client_ids, or the hook outlasting FailureCacheAge) the call joined the in-flight resolution and waited on the hook that was waiting on it. With no deadline on the call that wait never ended: the hook, the requests sharing the resolution and its place under MaxConcurrentResolutions were held for good, so enough of them refused every new resolution with ErrTooManyResolutions. The failure is now also recorded on the in-flight resolution before the hook is called, bounded as a remembered failure is, and a request for that client_id that finds it there gets it at once instead of waiting. That covers the hook's own calls, whatever context they carry, and makes the documented promise that a request arriving while the hook runs is answered without joining the resolution hold even when the failure could not be remembered. The hook's documentation now says a hook may resolve the same client_id and what it gets. Co-Authored-By: Claude Opus 5.5 --- docs/guides/openid-federation.md | 3 +- federation/automatic_registration.go | 52 +++++++--- federation/export_test.go | 4 + federation/resolution_reentrant_test.go | 130 ++++++++++++++++++++++++ server/config.go | 8 +- 5 files changed, 180 insertions(+), 17 deletions(-) create mode 100644 federation/resolution_reentrant_test.go diff --git a/docs/guides/openid-federation.md b/docs/guides/openid-federation.md index 3469e277..4fd2c2b8 100644 --- a/docs/guides/openid-federation.md +++ b/docs/guides/openid-federation.md @@ -119,7 +119,8 @@ your operator why a client was refused, once per resolution attempted; the client itself only sees `invalid_client`. The hook runs on a goroutine of the library's own, shared by the requests for that client_id made while it resolves, and can run after the request that triggered the resolution has -returned. It must not block, panic, or resolve the same client_id. A panic +returned. It must not block or panic; resolving the same client_id from it +gets the failure it reports at once, rather than waiting on itself. A panic in it is recovered rather than ending the process: the requests waiting on that resolution get `server_error`, and the failure is remembered as if the hook had returned. diff --git a/federation/automatic_registration.go b/federation/automatic_registration.go index 95dd8072..1594c06b 100644 --- a/federation/automatic_registration.go +++ b/federation/automatic_registration.go @@ -259,13 +259,18 @@ type AutomaticRegistrationConfig struct { // that started the resolution has returned, while another still // waits. ctx keeps that first request's values but not its // cancellation, and is cancelled once no request waits on the - // resolution any more. So it must not block, must not panic, and - // must not call ResolveClient for the same client_id, which could - // wait on the very resolution calling it. The failure is remembered, - // as FailureCacheAge sets out, before it is called, so a request - // arriving while it runs is answered from that memory instead of - // joining the resolution. A panic in it is recovered rather than - // ending the process: every request waiting on the resolution gets + // resolution any more. So it must not block and must not panic. The + // failure is remembered, as FailureCacheAge sets out, before it is + // called, and a request for that client_id arriving while it runs + // gets that failure at once instead of joining the resolution, even + // once FailureCacheAge has passed or when the failure couldn't be + // remembered. That includes a ResolveClient (or + // AutomaticClientKeySource lookup) for the same client_id made from + // the hook itself, which so never waits on the very resolution + // calling it; resolving another client_id from it needs a place + // under MaxConcurrentResolutions of its own while this resolution + // still holds one. A panic in it is recovered rather than ending + // the process: every request waiting on the resolution gets // an error wrapping storage.ErrStoreUnavailable (the server answers // 500 server_error), and the failure it was called for is remembered // as if it had returned. A failure is remembered for FailureCacheAge, @@ -486,7 +491,10 @@ type AutomaticClientRepository struct { // inflightResolution is one in-progress resolution that concurrent // callers for the same client_id wait on; done is closed once entry and // err are set. waiters counts the callers waiting on it, and cancel -// stops it once the last of them has gone. Both are guarded by +// stops it once the last of them has gone. failure, once set, is the +// failure the resolution has ended in, while OnResolutionFailure is +// called with it: a caller for its client_id gets that at once instead +// of waiting (see resolveUncached). waiters and failure are guarded by // AutomaticClientRepository.mu. type inflightResolution struct { done chan struct{} @@ -494,6 +502,7 @@ type inflightResolution struct { err error waiters int cancel context.CancelFunc + failure error } // NewAutomaticClientRepository validates cfg and returns an @@ -693,6 +702,10 @@ func (a *AutomaticClientRepository) resolve(ctx context.Context, id fapi.ClientI return cachedClient{}, err } call, ok := a.inflight[id] + if ok && call.failure != nil { + a.mu.Unlock() + return cachedClient{}, call.failure + } if !ok { if a.running >= a.maxConcurrentResolutions() { a.mu.Unlock() @@ -793,7 +806,7 @@ func (a *AutomaticClientRepository) startResolution(ctx context.Context, id fapi func (a *AutomaticClientRepository) runResolution(ctx context.Context, id fapi.ClientID, call *inflightResolution) { entry, err := cachedClient{}, errResolutionUnfinished defer func() { a.finishResolution(id, call, entry, err, recover()) }() - entry, err = a.resolveUncached(ctx, id) + entry, err = a.resolveUncached(ctx, id, call) } // finishResolution records call's outcome for every caller waiting on @@ -872,8 +885,8 @@ func (a *AutomaticClientRepository) leaveResolution(id fapi.ClientID, call *infl // resolveUncached resolves id's Trust Chain and builds its registration, // caching a success and reporting a failure to // AutomaticRegistrationConfig.OnResolutionFailure. resolve runs at most -// one at a time per client_id. -func (a *AutomaticClientRepository) resolveUncached(ctx context.Context, id fapi.ClientID) (cachedClient, error) { +// one at a time per client_id, as call. +func (a *AutomaticClientRepository) resolveUncached(ctx context.Context, id fapi.ClientID, call *inflightResolution) (cachedClient, error) { if err := ValidEntityID(string(id)); err != nil { // Not a federation client_id at all — an ordinary unknown // client, so nothing for OnResolutionFailure to report. @@ -891,8 +904,14 @@ func (a *AutomaticClientRepository) resolveUncached(ctx context.Context, id fapi return cachedClient{}, err } // Remembered before the hook runs, so a hook that panics (see - // runResolution) still leaves the failure remembered. + // runResolution) still leaves the failure remembered. And + // published on call, so a request for id while the hook runs, + // the hook's own included, gets it at once rather than waiting + // on call, which the hook would keep from finishing: memory + // alone doesn't do that when it is full or the hook outlasts + // FailureCacheAge. a.rememberFailure(id, err, a.clock.Now()) + a.publishFailure(call, err) if a.cfg.OnResolutionFailure != nil { a.cfg.OnResolutionFailure(ctx, id, err) } @@ -920,6 +939,15 @@ func (a *AutomaticClientRepository) rememberRegistration(id fapi.ClientID, entry delete(a.failures, id) } +// publishFailure records err, bounded as rememberFailure bounds it, as +// the failure call has ended in, for the callers resolve answers from +// it while OnResolutionFailure runs. +func (a *AutomaticClientRepository) publishFailure(call *inflightResolution, err error) { + a.mu.Lock() + defer a.mu.Unlock() + call.failure = newRememberedFailure(err) +} + // rememberFailure records err as id's registration failure until // FailureCacheAge after now, within maxFailedResolutions, keeping only // its bounded message (see rememberedFailure) and its own copy of id diff --git a/federation/export_test.go b/federation/export_test.go index 6bdf0a7e..6e445d18 100644 --- a/federation/export_test.go +++ b/federation/export_test.go @@ -14,6 +14,10 @@ func CachedChainPosition(r *AutomaticClientRepository, id fapi.ClientID) (superi return slot.entry.superior, slot.entry.branch, true } +// MaxFailedResolutions is maxFailedResolutions, for tests in package +// federation_test. +const MaxFailedResolutions = maxFailedResolutions + // MaxEntityIDBytes is maxEntityIDBytes, for tests in package // federation_test. const MaxEntityIDBytes = maxEntityIDBytes diff --git a/federation/resolution_reentrant_test.go b/federation/resolution_reentrant_test.go new file mode 100644 index 00000000..9de52bae --- /dev/null +++ b/federation/resolution_reentrant_test.go @@ -0,0 +1,130 @@ +package federation_test + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/federation" +) + +// reentrantGuard is how long a test in this file waits for a +// ResolveClient whose OnResolutionFailure calls ResolveClient again +// before calling it stuck. +const reentrantGuard = 5 * time.Second + +// TestReentrantResolutionFailureHookReturns: an OnResolutionFailure +// hook that calls ResolveClient, with no deadline, for the client_id +// whose failure it reports gets that failure at once rather than +// waiting on the resolution calling it, so neither call is stuck and +// the resolution's place under MaxConcurrentResolutions frees. That +// holds when the failure is remembered as the hook runs and also when +// it isn't (here, remembered for less time than the hook takes). +func TestReentrantResolutionFailureHookReturns(t *testing.T) { + for name, tc := range map[string]struct { + hookTakes time.Duration + hookCtx bool + }{ + "remembered, no context": {}, + "remembered, hook's context": {hookCtx: true}, + "forgotten, no context": {hookTakes: time.Minute}, + "forgotten, hook's context": {hookTakes: time.Minute, hookCtx: true}, + } { + t.Run(name, func(t *testing.T) { + checkReentrantHook(t, tc.hookTakes, tc.hookCtx) + }) + } +} + +// checkReentrantHook resolves an RP that fails registration (it has no +// openid_relying_party metadata) through a repository allowing one +// resolution at a time, whose hook moves the clock on by hookTakes and +// then calls ResolveClient for the same client_id, with its own ctx if +// hookCtx is set or with none. +func checkReentrantHook(t *testing.T, hookTakes time.Duration, hookCtx bool) { + f := setupAutomaticRegistrationFixture(t, nil) + clock := &settableClock{now: f.now} + inner := make(chan error, 1) + cfg := validAutomaticRegistrationConfig() + cfg.FailureCacheAge = time.Second + cfg.MaxConcurrentResolutions = 1 + var repo *federation.AutomaticClientRepository + cfg.OnResolutionFailure = func(ctx context.Context, id fapi.ClientID, _ error) { + clock.set(clock.Now().Add(hookTakes)) + if !hookCtx { + ctx = context.Background() + } + _, err := repo.ResolveClient(ctx, id) + inner <- err + } + var err error + repo, err = federation.NewAutomaticClientRepository(alwaysFailsRepository{}, f.newResolver(t), f.fetcher, cfg, clock) + if err != nil { + t.Fatalf("NewAutomaticClientRepository: %v", err) + } + + awaitReentrantHook(t, repo, fapi.ClientID(f.rpID), inner) +} + +// TestReentrantResolutionFailureHookReturnsWhenMemoryFull is +// TestReentrantResolutionFailureHookReturns with the failure not +// remembered because maxFailedResolutions others, which any caller +// can have resolved, fill the memory. +func TestReentrantResolutionFailureHookReturnsWhenMemoryFull(t *testing.T) { + ts := httptest.NewTLSServer(http.NotFoundHandler()) + t.Cleanup(ts.Close) + target := fapi.ClientID(ts.URL + "/target") + inner := make(chan error, 1) + cfg := validAutomaticRegistrationConfig() + cfg.MaxConcurrentResolutions = 1 + var repo *federation.AutomaticClientRepository + cfg.OnResolutionFailure = func(_ context.Context, id fapi.ClientID, _ error) { + if id == target { + _, err := repo.ResolveClient(context.Background(), id) + inner <- err + } + } + repo = stallingRepository(t, ts, cfg) + for i := range federation.MaxFailedResolutions { + if _, err := repo.ResolveClient(context.Background(), fapi.ClientID(fmt.Sprintf("%s/rp%d", ts.URL, i))); err == nil { + t.Fatalf("ResolveClient(rp%d) = nil error, want the fetch failure", i) + } + } + awaitReentrantHook(t, repo, target, inner) + if _, _, _, remembered := federation.ResolutionState(repo, target); remembered { + t.Fatal("the target's failure is remembered, want the memory full") + } +} + +// awaitReentrantHook resolves id, whose resolution fails and whose +// OnResolutionFailure calls ResolveClient for id and sends what that +// returns on inner, and checks both return the failure, within +// reentrantGuard, leaving no resolution running. +func awaitReentrantHook(t *testing.T, repo *federation.AutomaticClientRepository, id fapi.ClientID, inner <-chan error) { + t.Helper() + outer := make(chan error, 1) + go func() { + _, err := repo.ResolveClient(context.Background(), id) + outer <- err + }() + select { + case err := <-outer: + if err == nil || errors.Is(err, federation.ErrTooManyResolutions) { + t.Fatalf("ResolveClient = %v, want the registration failure", err) + } + case <-time.After(reentrantGuard): + _, otherErr := repo.ResolveClient(context.Background(), "https://other.example.invalid") + t.Fatalf("ResolveClient whose hook calls ResolveClient for the same client_id still waiting after %v; an unrelated resolution meanwhile = %v", reentrantGuard, otherErr) + } + if err := <-inner; err == nil || errors.Is(err, federation.ErrTooManyResolutions) { + t.Fatalf("the hook's own ResolveClient = %v, want the registration failure", err) + } + if running, inflight, _, _ := federation.ResolutionState(repo, id); running != 0 || inflight != 0 { + t.Fatalf("after the resolution: %d running, %d in flight; want 0 and 0", running, inflight) + } +} diff --git a/server/config.go b/server/config.go index a8e4f97f..a5c2552c 100644 --- a/server/config.go +++ b/server/config.go @@ -871,10 +871,10 @@ type AutomaticRegistrationConfig struct { // federation.AutomaticRegistrationConfig.OnResolutionFailure: it // runs on a goroutine of the library's own, not the request's, and // can run after the request that triggered the resolution has - // returned. Log err, never return it to the client, and don't block, - // panic, or resolve the same client_id from it. A panic is recovered, - // and the requests waiting on that resolution get server_error. - // Optional. + // returned. Log err, never return it to the client, and don't block + // or panic in it; resolving the same client_id from it gets this + // failure at once. A panic is recovered, and the requests waiting on + // that resolution get server_error. Optional. OnResolutionFailure func(ctx context.Context, clientID fapi.ClientID, err error) } From 74d08bd5deff2b8a45002e08f62bf26cfcdc14c7 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 02:17:56 +0800 Subject: [PATCH 3/3] test: add mutants for chain expiry during resolution and re-entrant hooks Cover the chain expiry check at the end of Resolve and after building an automatic registration, its clock-skew tolerance, and the failure published on an in-flight resolution for OnResolutionFailure. The remembered-before-hook mutant moves past the new publishFailure call. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 64 +++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 87a7e20e..61a44b86 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -2646,8 +2646,8 @@ { "id": "fed-resolution-failure-remembered-before-hook", "file": "federation/automatic_registration.go", - "old": "a.rememberFailure(id, err, a.clock.Now())\n\t\tif a.cfg.OnResolutionFailure != nil {\n\t\t\ta.cfg.OnResolutionFailure(ctx, id, err)\n\t\t}", - "new": "if a.cfg.OnResolutionFailure != nil {\n\t\t\ta.cfg.OnResolutionFailure(ctx, id, err)\n\t\t}\n\t\ta.rememberFailure(id, err, a.clock.Now())", + "old": "a.rememberFailure(id, err, a.clock.Now())\n\t\ta.publishFailure(call, err)\n\t\tif a.cfg.OnResolutionFailure != nil {\n\t\t\ta.cfg.OnResolutionFailure(ctx, id, err)\n\t\t}", + "new": "a.publishFailure(call, err)\n\t\tif a.cfg.OnResolutionFailure != nil {\n\t\t\ta.cfg.OnResolutionFailure(ctx, id, err)\n\t\t}\n\t\ta.rememberFailure(id, err, a.clock.Now())", "module": "root", "packages": [ "./federation" @@ -5598,5 +5598,65 @@ ], "run": "^TestIssuersPrintNoKey$", "why": "log/slog logs a TrustMarkIssuer's redacted shadow" + }, + { + "id": "fed-chain-expiry-skew", + "file": "federation/resolver.go", + "old": "if now.After(expiresAt.Add(r.cfg.Limits.MaxClockSkew)) {", + "new": "if now.After(expiresAt) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestResolveRefusesChainExpiredWhileResolving|TestAutomaticRegistrationRefusesChainExpiredWhileRegistering|TestAutomaticRegistrationRefusesChainExpiredWhileResolving)$", + "why": "a chain still within MaxClockSkew of its exp when its resolution finishes is accepted, as each statement's exp check accepts it" + }, + { + "id": "fed-resolve-end-expiry-check", + "file": "federation/resolver.go", + "old": "if err := r.checkChainUnexpired(subjectID, resolved.ExpiresAt, r.deps.Clock.Now()); err != nil {", + "new": "if err := r.checkChainUnexpired(subjectID, resolved.ExpiresAt, r.deps.Clock.Now()); err != nil && false {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestResolveRefusesChainExpiredWhileResolving|TestAutomaticRegistrationRefusesChainExpiredWhileRegistering|TestAutomaticRegistrationRefusesChainExpiredWhileResolving)$", + "why": "Resolve refuses a Trust Chain that expired before its resolution finished" + }, + { + "id": "fed-register-expiry-check", + "file": "federation/automatic_registration.go", + "old": "if err := a.resolver.checkChainUnexpired(string(id), resolved.ExpiresAt, now); err != nil {", + "new": "if err := a.resolver.checkChainUnexpired(string(id), resolved.ExpiresAt, now); err != nil && false {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestResolveRefusesChainExpiredWhileResolving|TestAutomaticRegistrationRefusesChainExpiredWhileRegistering|TestAutomaticRegistrationRefusesChainExpiredWhileResolving)$", + "why": "automatic registration refuses a chain that expired while the registration was built (jwks_uri fetch)" + }, + { + "id": "fed-reentrant-hook-published-failure", + "file": "federation/automatic_registration.go", + "old": "if ok && call.failure != nil {", + "new": "if ok && call.failure != nil && false {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestReentrantResolutionFailureHookReturns|TestReentrantResolutionFailureHookReturnsWhenMemoryFull)$", + "why": "a request for a client_id whose resolution is reporting its failure gets it at once instead of waiting on the hook" + }, + { + "id": "fed-reentrant-hook-publish", + "file": "federation/automatic_registration.go", + "old": "\t\ta.publishFailure(call, err)\n", + "new": "\t\t_ = call\n", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestReentrantResolutionFailureHookReturns|TestReentrantResolutionFailureHookReturnsWhenMemoryFull)$", + "why": "the failure is published on the in-flight resolution before OnResolutionFailure runs" } ]