Repository navigation
Description
Description
Phase 3 of the DCR story (#4976). Ship persistent DCRCredentialStore backends (in-process memory + Redis) that drop in behind the interface defined by #4978, and wire the persistent store into pkg/authserver/runner/embeddedauthserver.go in place of the Phase 2 in-memory stub. This is the last missing piece for the Datadog-style upstream demo to survive authserver restarts and scale across replicas: restarting (or scaling out to) an authserver backed by Redis reuses already-registered DCR credentials instead of re-registering at the upstream.
This umbrella tracks three sub-issues:
- Persistent DCRCredentialStore: types, interface, and in-memory backend #5183 — types,
DCRCredentialStoreinterface, and in-memory implementation - Persistent DCRCredentialStore: Redis backend #5184 — Redis backend
- Persistent DCRCredentialStore: wire into EmbeddedAuthServer #5185 — wire the persistent store into
EmbeddedAuthServer
Context
#4978 (Phase 2) defines the narrow DCRCredentialStore interface — Get(ctx, DCRKey) (*DCRResolution, bool, error) and Put(ctx, DCRKey, *DCRResolution) error — together with the DCRKey{Issuer, RedirectURI, ScopesHash} canonical cache key, and ships an in-process in-memory stub keyed on (issuer, redirect_uri, scopes_hash). Full RFC 7592 fields (RegistrationAccessToken, RegistrationClientURI) are already captured by Phase 2 so Phase 3 has everything it needs to round-trip a credential through durable storage.
The persistent backends must:
- Match the existing
pkg/authserver/storage/shape — one in-memory implementation, one Redis Sentinel implementation — and follow the prior-art Redis key schemethv:auth:{ns:name}:<type>:<id>(seepkg/authserver/storage/redis_keys.go:63-83) so DCR keys share the{ns:name}Redis Cluster hash tag with the rest of a server's state. - Honor
client_secret_expires_at(RFC 7591 §3.2.1, unix seconds;0means "never") as the Redis TTL when the authorization server provides it. When absent or0, no TTL is applied and entries are long-lived. - Obey
.claude/rules/go-style.md§"Write to Durable Storage Before Updating In-Memory State" on every write path — durable first, in-memory after. - Copy-before-mutate when returning
DCRCredentials(per.claude/rules/go-style.md§"Copy Before Mutating Caller Input"): return a defensive copy or document immutability, matching the existingUpstreamTokens/PendingAuthorizationpattern inpkg/authserver/storage/memory.go.
Wiring site: createStorage(ctx, cfg.Storage) at pkg/authserver/runner/embeddedauthserver.go:455 selects memory vs. Redis for the main Storage backend; the DCRCredentialStore reuses that same branch so a single storage_type: redis config toggles both.
This task introduces no new protocol behavior beyond #4978. It is a drop-in persistence layer behind an already-defined interface.
Dependencies: ##4978
Blocks: (none — terminal task in the DAG)
Acceptance Criteria
DCRCredentials value type — pkg/authserver/storage/types.go
- New exported type
DCRCredentialsis added with the following fields (order may follow the local file convention, but all fields must be present):Key DCRKey— canonical cache key (mirrors theDCRKeytype frompkg/authserver/runner/dcr_store.godefined in Authserver DCR integration (Phase 2, Steps 2a-2g) #4978; Phase 3 consumes the same canonical form — do NOT redefine the hashing).ProviderName string— debug / audit only (the upstreamUpstreamRunConfig.Namethat triggered the registration; never used as a primary key).ClientID stringClientSecret string—//nolint:gosec // G117comment consistent withUpstreamTokens.AccessToken.TokenEndpointAuthMethod stringRegistrationAccessToken string(RFC 7592 —//nolint:gosecas above)RegistrationClientURI string(RFC 7592)AuthorizationEndpoint stringTokenEndpoint stringCreatedAt time.Time
- Doc comment on
DCRCredentialsstates that consumers receive a defensive copy (the type is effectively immutable from the caller's perspective). - The existing
DCRKeytype is re-exported from (or imported into)pkg/authserver/storage/in a way that keeps the canonical hashing helper in a single place. Acceptable options: (a) moveDCRKey+ itsScopesHashconstructor frompkg/authserver/runner/intopkg/authserver/storage/and update the runner to depend on it; (b) leaveDCRKeyin the runner and reference it via type alias in storage. Pick one and document the choice in the commit message. Do NOT duplicate the hashing logic.
DCRCredentialStore interface — pkg/authserver/storage/types.go
-
DCRCredentialStoreinterface is declared inpkg/authserver/storage/types.gowith:GetDCRCredentials(ctx context.Context, key DCRKey) (*DCRCredentials, error)returningErrNotFound(already defined intypes.go:36) when the key is absent.StoreDCRCredentials(ctx context.Context, creds *DCRCredentials) error.- Optionally
DeleteDCRCredentials(ctx context.Context, key DCRKey) errorif needed for tests; otherwise omit.
- The interface is added to the
//go:generate mockgendirective at the top oftypes.gosotask genproduces a mock inpkg/authserver/storage/mocks/. - The runner-side
DCRCredentialStoreinterface from Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 is either (a) replaced by this storage-level interface everywhere inpkg/authserver/runner/, or (b) kept as a thinner adapter that delegates to the storage-level one. Pick the cleaner of the two — no duplicated abstraction.
In-memory backend — pkg/authserver/storage/memory.go
-
MemoryStoragegains adcrCredentials map[DCRKey]*DCRCredentialsfield guarded by the existingsync.RWMutex. -
NewMemoryStorageinitializes the map. -
StoreDCRCredentialsperforms a defensive copy of the input before storing (matching theStoreUpstreamTokenspattern atmemory.go:693-734). -
GetDCRCredentialsreturns a defensive copy; returnsErrNotFound(wrapped per the existing convention:fmt.Errorf("%w: ...", ErrNotFound, ...)) on miss. - Compile-time interface-compliance assertion is added at the bottom of the file:
_ DCRCredentialStore = (*MemoryStorage)(nil). - DCR credentials are intentionally excluded from the periodic
cleanupExpiredloop (they are long-lived; the Redis backend applies TTL viaSetEXinstead of in-process cleanup).
Redis backend — pkg/authserver/storage/redis.go + redis_keys.go
- Add
KeyTypeDCR = "dcr"topkg/authserver/storage/redis_keys.goadjacent to the existingKeyType*consts. - Add a DCR key helper (e.g.
redisDCRKey(prefix string, key DCRKey) string) that produces{prefix}dcr:<id>where<id>is a deterministic, collision-free encoding of(issuer, redirect_uri, scopes_hash). Two safe encodings: (a) a length-prefixed format mirroringredisProviderKeyatredis_keys.go:87-89; (b) a single SHA-256 hex over the tuple. Either is acceptable — pick one and document it adjacent to the helper. DO NOT use plainfmt.Sprintf("%s:%s:%s", ...)becauseredirect_uricontains colons. -
RedisStorage.StoreDCRCredentialsJSON-marshals theDCRCredentialsvalue and callsSetEXwith a TTL derived from the upstream'sclient_secret_expires_at:- When the AS advertised
client_secret_expires_at > 0(captured at registration time — plumb it throughDCRCredentialsor computettl = expiresAt - time.Now()at the call site and document the source), usettlas the Redis TTL. - When
client_secret_expires_at == 0or not provided, useSetwith no expiration (long-lived).
- When the AS advertised
-
RedisStorage.GetDCRCredentialsJSON-unmarshals the value; returnsErrNotFoundonredis.Nil; returns the unwrapped error otherwise. - Compile-time interface-compliance assertion is added at the bottom of the file:
_ DCRCredentialStore = (*RedisStorage)(nil). - Connection-error handling follows the existing
drainCloseErr/warnOnCleanupErrpatterns already used inredis.go.
Wiring — pkg/authserver/runner/embeddedauthserver.go
- The
EmbeddedAuthServerstruct field that holds the DCR store (introduced in Authserver DCR integration (Phase 2, Steps 2a-2g) #4978) is now typed against the storage-levelDCRCredentialStoreinterface. -
NewEmbeddedAuthServerderives the DCR store from the sameStoragevalue returned bycreateStorage(ctx, cfg.Storage)(seeembeddedauthserver.go:97and:455). Since bothMemoryStorageandRedisStoragenow implement the storage-levelDCRCredentialStoreinterface, a plainstor.(DCRCredentialStore)type assertion is sufficient. Do NOT add a second storage-selection branch. - The Phase 2 standalone in-memory stub from
pkg/authserver/runner/dcr_store.gois removed (or reduced to a re-export/alias) so there is exactly oneDCRCredentialStoreimplementation per backend. Document this in the commit message. -
buildPureOAuth2Configremains pure (unchanged signature, noctx, no I/O) — the architectural gate established in Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 is preserved.
Regenerate mocks
-
task genis rerun; the new mock forDCRCredentialStoreappears inpkg/authserver/storage/mocks/mock_storage.goand compiles.
Cross-cutting
-
task build,task test,task lint-fix, andtask license-checkall pass. - No secrets appear in any log record (grep assertion from Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 applies unchanged:
client_secret,registration_access_token,initial_access_token, refresh tokens are never arguments toslog.*calls). - Code reviewed and approved.
Out of Scope
- Automatic re-register on upstream
invalid_clientat the token endpoint. Phase 2 ships only theslog.Warnbreadcrumb atpkg/auth/monitored_token_source.go:361; auto-recovery (with singleflight + per-key rate limiter) is a future follow-up. - RFC 7592 PUT-based
client_secretrotation.RegistrationAccessTokenandRegistrationClientURIare persisted so the future rotation path has what it needs, but no rotation logic is written in this PR. - Cross-replica session / token delivery. This task shares DCR metadata across replicas via Redis; it does NOT share in-flight authorization sessions or upstream tokens (separate storage + separate concerns, already segregated in
pkg/authserver/storage/types.go). - Any change to
pkg/auth/monitored_token_source.go,pkg/authserver/server/handlers/dcr.go,pkg/authserver/config.go, orpkg/oauthproto/— all those touchpoints are Rename pkg/oauth to pkg/oauthproto and relocate DCR primitives #4977 / Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 scope and stay untouched by Phase 3. - Authserver OTEL metrics + tracing (separate work).
- CLI persistence of
registration_client_uriinpkg/auth/remote/config.go(one-line follow-up; candidate for a small side PR). - Provider-specific quirks (
login.microsoftonline.comresourceparam,mcp.zoho.comaccess_type). - A DCR-credentials delete / invalidation endpoint. The operator remediation path today is "delete the Redis key and restart"; a formal API is a follow-up.
References
- Parent story: Authserver-driven DCR for upstream OAuth 2.1 MCP servers #4976 — "Authserver-driven DCR for upstream OAuth 2.1 MCP servers".
- Upstream dependency: #Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 (Phase 2 defines
DCRCredentialStore+DCRKey+DCRResolutionand captures RFC 7592 fields required here). .claude/rules/go-style.md— §"Copy Before Mutating Caller Input", §"Write to Durable Storage Before Updating In-Memory State", SPDX headers, constructor fail-loud validation, no-secrets-in-logs..claude/rules/testing.md— testify overt.Fatal,t.Cleanupoverdefer,t.Setenv, no Ginkgo inpkg/authserver/, random ports..claude/rules/security.md— §"Don't Store Internal Addressing in Shared State". DCR credentials are per-upstream-provider protocol state, not internal addressing, so this PR does not violate the rule — but theDCRCredentials.ProviderNamefield is debug/audit only and must NOT be used to route requests or bypass security controls..claude/rules/pr-creation.md— 400-LOC / 10-file PR cap; this PR is additive topkg/authserver/storage/plus a small wiring change and should fit comfortably.CLAUDE.md— always usetask(nevergo test/golangci-lintdirectly).- RFC 7591 §3.2.1 (
client_secret_expires_atsemantics:0means "never", unix seconds otherwise). - RFC 7592 (DCR Management Protocol — fields persisted, management endpoints deferred).
Activity