Repository navigation
Closed
Labels
Description
Context
Part of #4978 (Phase 2 of the DCR story, #4976). This sub-issue implements the in-memory credential store and the DCR resolver that performs discovery and registration at startup.
Depends on: #5037 (Sub-issue A — DCRUpstreamConfig, FetchAuthorizationServerMetadata, and OAuth2Config.Validate() must land first).
Followed by: Sub-issue C (wiring + observability + integration tests).
Scope
Step 2f — DCRCredentialStore (pkg/authserver/runner/dcr_store.go)
New file:
DCRCredentialStoreinterface withGet(ctx context.Context, key DCRKey) (*DCRResolution, bool, error)andPut(ctx context.Context, key DCRKey, resolution *DCRResolution) error.DCRKeystruct:Issuer,RedirectURI,ScopesHash(SHA-256 hex of sorted scope list for canonical form shared by future Redis backend).- In-memory implementation: plain
map[DCRKey]*DCRResolutionguarded bysync.RWMutex. No TTL, no cleanup goroutine — entries are long-lived. Reference shape:pkg/authserver/storage/memory.go. NewInMemoryDCRCredentialStore() DCRCredentialStoreconstructor.dcrStaleAgeThreshold = 90 * 24 * time.Hourconstant (referenced by Step 2g logs).
New file pkg/authserver/runner/dcr_store_test.go:
- Put/Get round-trip; distinct DCRKey values don't collide;
ScopesHashis stable across permuted scope order.
Step 2c — resolveDCRCredentials (pkg/authserver/runner/dcr.go)
New file:
DCRResolutionstruct:ClientID,ClientSecret,AuthorizationEndpoint,TokenEndpoint,RegistrationAccessToken,RegistrationClientURI,TokenEndpointAuthMethod,CreatedAt time.Time.needsDCR(rc *authserver.OAuth2UpstreamRunConfig) bool— returnsrc.ClientID == "" && rc.DCRConfig != nil.applyResolution(rc *authserver.OAuth2UpstreamRunConfig, res *DCRResolution)— copies resolved fields into the caller's run-config COPY (per.claude/rules/go-style.mdcopy-before-mutate rule).scopesHash(scopes []string) string— SHA-256 hex of sorted scope list.- Auth-method intersection helper: preference order
private_key_jwt > client_secret_basic > client_secret_post > none; empty intersection returns a clear error. resolveDCRCredentials(ctx, rc, issuer, cache)full flow:- Defensive re-check of
ClientIDXORDCRConfig. - Cache lookup via
DCRCredentialStore.Get— hit short-circuits immediately. - Endpoint resolution: call
FetchAuthorizationServerMetadatawhenDiscoveryURLset; useRegistrationEndpointdirectly when set; synthesize{origin}/registerwhen metadata omitsregistration_endpoint(nanobot/Hydra convention). - Explicit
rc.AuthorizationEndpoint/rc.TokenEndpointoverride discovered values. - Redirect URI: use
rc.RedirectURIwhen set; elseurl.Parse(issuer)+ResolveReference("/oauth/callback"). Require HTTPS unless host is loopback. - Auth-method selection via intersection helper.
- Scopes:
rc.Scopeswhen set; elsemetadata.ScopesSupported; else empty +slog.Warn. - Initial access token: read via
resolveSecret(file, envVar)atpkg/authserver/runner/embeddedauthserver.go:409; attach asAuthorization: Bearer {token}. - Call
oauthproto.RegisterClientDynamically()exactly once — no retry loop. - Capture full RFC 7591 + RFC 7592 response into
DCRResolution(includingRegistrationAccessToken,RegistrationClientURI). - Store via
DCRCredentialStore.Putbefore returning.
- Defensive re-check of
New file pkg/authserver/runner/dcr_test.go:
- Resolver flow via a single
httptest.NewServermounting AS metadata + DCR endpoint. - Cache-hit short-circuits: pre-populate store via
Put, assert zero HTTP requests to mock server. - Explicit
AuthorizationEndpointoverrides discovered value. - Initial access token sent as
Authorization: Bearer …. client_secret_basicchosen overnonewhen both advertised.- Missing
registration_endpointexercises synthesized/registerpath. - Teardown via
t.Cleanup(server.Close)(notdeferwhent.Parallel()used).
Acceptance Criteria
Step 2f
-
pkg/authserver/runner/dcr_store.godefinesDCRCredentialStoreinterface withGet(ctx, DCRKey) (*DCRResolution, bool, error)andPut(ctx, DCRKey, *DCRResolution) error. -
DCRKeystruct hasIssuer,RedirectURI,ScopesHashfields;ScopesHashis SHA-256 hex of sorted scope list. - In-memory implementation:
map[DCRKey]*DCRResolutionguarded bysync.RWMutex, no cleanup goroutine. -
dcrStaleAgeThreshold = 90 * 24 * time.Hourconstant defined in runner package. -
NewInMemoryDCRCredentialStore() DCRCredentialStoreconstructor exported. - Unit test:
PutthenGetreturns the stored resolution. - Unit test: two distinct
DCRKeyvalues do not collide. - Unit test:
ScopesHashis identical for["openid", "profile"]and["profile", "openid"].
Step 2c
-
DCRResolutionstruct has:ClientID,ClientSecret,AuthorizationEndpoint,TokenEndpoint,RegistrationAccessToken,RegistrationClientURI,TokenEndpointAuthMethod,CreatedAt. -
needsDCR(rc) boolreturns true iffrc.ClientID == ""andrc.DCRConfig != nil. -
applyResolution(rc, res)copies resolved credentials and endpoints into the caller's run-config copy. - Cache hit short-circuits before any network I/O.
- On cache miss: calls
FetchAuthorizationServerMetadatawhenDiscoveryURLset; usesRegistrationEndpointdirectly when set; synthesizes{origin}/registerwhen metadata omitsregistration_endpoint. - Explicit
rc.AuthorizationEndpoint/rc.TokenEndpointwin over discovered values. - Redirect URI: uses
rc.RedirectURIwhen set; otherwise derives from issuer +/oauth/callback. HTTPS required unless host is loopback. -
TokenEndpointAuthMethod: defaults toclient_secret_basic; intersectstoken_endpoint_auth_methods_supportedagainst preference orderprivate_key_jwt > client_secret_basic > client_secret_post > none; empty intersection returns an error. - Initial access token (from file or env, via
resolveSecret) sent asAuthorization: Bearer {token}. -
oauthproto.RegisterClientDynamically()called exactly once per resolution. - RFC 7592 fields (
RegistrationAccessToken,RegistrationClientURI) captured inDCRResolution. - Resolution stored via
DCRCredentialStore.Putbefore returning. - Unit test: pre-populated store →
resolveDCRCredentials→ zero HTTP requests to mock server. - Unit test: explicit
AuthorizationEndpointoverrides discovered value. - Unit test: initial access token forwarded as
Authorization: Bearer …. - Unit test:
client_secret_basicchosen overnonewhen both advertised. - Unit test: metadata missing
registration_endpointtriggers synthesized/registerpath. - Secret grep:
grep -nE '(client_secret|registration_access_token|initial_access_token|refresh_token)' pkg/authserver/runner/dcr.goreturns only struct-field / JSON-tag hits, neverslog.*call arguments.
Cross-cutting
-
task build,task test,task lint-fix,task license-checkall pass. - All new
.gofiles have SPDX 2-line header.
Patterns & References
resolveSecret(file, envVar)atpkg/authserver/runner/embeddedauthserver.go:409— reuse for initial access token, do not duplicate secret-loading logic.pkg/authserver/storage/memory.go— reference shape forsync.RWMutex+ map in-memory store.pkg/authserver/storage/redis_keys.go:72-80— reference for future Redis DCR key scheme; theDCRKey.Issuer/RedirectURI/ScopesHashtuple is designed to compose the<id>segment in Phase 3 without redefining the canonical form.- Plain
testing+testify(not Ginkgo).require.NoErrorovert.Fatal. Table-driven tests.t.Cleanup(server.Close)— neverdeferwhent.Parallel()is used. - Write to durable storage before updating in-memory state (
.claude/rules/go-style.md) —Putbefore returning to caller. - SPDX header required on all new files (
task license-fixcatches omissions).
Activity
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver
Add authserver DCR credential store and resolver (#5042)