Skip to content

Extract DCR resolver into pkg/auth/dcr#5198

Merged
tgrunnagle merged 4 commits into
mainfrom
dcr-4a_issue_5145
May 12, 2026
Merged

Extract DCR resolver into pkg/auth/dcr#5198
tgrunnagle merged 4 commits into
mainfrom
dcr-4a_issue_5145

Conversation

@tgrunnagle
Copy link
Copy Markdown
Contributor

@tgrunnagle tgrunnagle commented May 5, 2026

Summary

  • Why: Issue Consolidate the two RFC 7591 DCR client implementations into pkg/auth/dcr #5145 calls for consolidating two parallel RFC 7591 Dynamic Client Registration (DCR) implementations (pkg/authserver/runner/dcr.go and pkg/auth/discovery::PerformOAuthFlow) into a single shared pkg/auth/dcr package, so review-derived behaviours (S256 PKCE gate, RFC 7591 §3.2.1 expiry refetch, redirect refusal, panic recovery, singleflight) cannot diverge between the embedded authserver and the CLI flow as future consumers land. The full migration is too large for a single PR, so this slice (sub-issue 4a) does the package extraction and migrates the embedded authserver only.
  • What: Extracts the DCR resolver and credential store from pkg/authserver/runner into a new pkg/auth/dcr package and migrates EmbeddedAuthServer to consume it. File moves use git mv so the diff renders as renames rather than delete+add. Public symbols are renamed to drop the redundant DCR prefix on packagisation (e.g., DCRResolutiondcr.Resolution, DCRCredentialStoredcr.CredentialStore, resolveDCRCredentialsdcr.ResolveCredentials). Adds a parallel TestResolveSecret suite mirroring the runner-package twin so any future drift between the two resolveSecret copies fails CI.

Closes #5220 (sub-issue 4a). Part of #5145 — does not close the parent. Sibling sub-issue #5219 (4b — CLI flow migration in pkg/auth/discovery::PerformOAuthFlow) closes #5145 when it lands; AC#1, AC#3, and AC#4 of the parent depend on it.

Stacking

This branch is stacked on PR #5196 (dcr-3c_issue_5185 — "Wire persistent DCRCredentialStore into EmbeddedAuthServer"), which is itself stacked on PRs #5186 and #5195. The earlier commits on this branch (c0fed523 through 781a0b97) implement sub-issues #5183 / #5184 / #5185 (the persistent DCR store and Redis backend) and are shown for context only — review against PR #5196 once it merges, or review the two commits unique to this branch in isolation:

  • df84256f Extract DCR resolver into pkg/auth/dcr
  • 633ed9ed Address code review feedback

Type of change

  • Refactoring (no behavior change)

Test plan

  • Unit tests (task test) — go test -count=1 -race ./pkg/auth/dcr/... ./pkg/authserver/... all pass
  • Linting (task lint-fix) — 0 issues
  • License check (task license-check) — clean

Changes

File Change
pkg/auth/dcr/resolver.go Renamed from pkg/authserver/runner/dcr.go; public symbols renamed to drop the DCR prefix; package doc updated with a # Concurrency section documenting the process-global singleflight; new flightKeyOf(Key) helper makes the canonical key shape inspectable; endpointsFromMetadata gains a defensive nil check and an oauthproto contract note.
pkg/auth/dcr/store.go Renamed from pkg/authserver/runner/dcr_store.go; constructors renamed (NewInMemoryStore, NewStorageBackedStore); type renamed to CredentialStore.
pkg/auth/dcr/resolver_test.go Renamed from pkg/authserver/runner/dcr_test.go; updated for new package boundary and renamed symbols.
pkg/auth/dcr/store_test.go Renamed from pkg/authserver/runner/dcr_store_test.go; updated for new package boundary.
pkg/auth/dcr/secret_test.go New parallel resolveSecret suite that mirrors the runner-package twin's observable contract so future drift between the two duplicated helpers fails CI on at least one side.
pkg/authserver/runner/embeddedauthserver.go Migrated to consume pkg/auth/dcr; doc comments on buildUpstreamConfigs and DCRStore() updated to use the new public names.
pkg/authserver/runner/embeddedauthserver_test.go Updated import paths and constructor names for the moved types.

Does this introduce a user-facing change?

No. This is an internal refactor. The embedded authserver's externally-observable DCR behaviour (registration, caching, error reporting, structured logging, expiry refetch, S256 gating) is unchanged.

Implementation plan

Approved implementation plan

Sub-issue 4a (#5220) of #5145 — extract the resolver into pkg/auth/dcr and migrate the embedded authserver only. Defer the pkg/auth/discovery::PerformOAuthFlow migration to sub-issue 4b (#5219) so this slice stays under the 400-line / 10-file PR-size limit.

Profile-neutral input shape: the package's API still takes embedded-authserver types directly. Designing a profile-neutral input type with only one consumer in hand would be speculative; the right design moment is when 4b lands the CLI flow as the second consumer. The package doc comment in pkg/auth/dcr/resolver.go calls this coupling out explicitly and labels the profile-agnostic framing as a target state for 4b rather than the current API shape.

Duplication of resolveSecret: deliberately duplicated across pkg/authserver/runner and pkg/auth/dcr because the DCR package must stay reachable-from-runner-but-not-back. Promoting to a shared helper is deferred until 4b lands a third call site. Drift between the two copies is guarded by parallel test suites with identical observable contracts.

Special notes for reviewers

  • Why renames, not delete+add: file moves use git mv so the diff renders as renames. The percentage similarity in git log --stat --follow reflects that the bulk of the move is mechanical and the substantive deltas are confined to (a) the package doc rewrite at the top of resolver.go, (b) the flightKeyOf extraction and singleflight comment, (c) the endpointsFromMetadata nil guard, and (d) the import/symbol rename sweep in embeddedauthserver.go.
  • Singleflight is process-global, not per-instance: documented at the package surface and on the dcrFlight var. The cross-consumer caveat ("third consumer with colliding redirect URI" failure mode) is named explicitly so the next migration cannot silently re-introduce a collision.
  • Acceptance criteria status against Consolidate the two RFC 7591 DCR client implementations into pkg/auth/dcr #5145 (as per the commit message of df84256f):

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels May 5, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 5, 2026

Codecov Report

❌ Patch coverage is 71.42857% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.17%. Comparing base (9211a36) to head (cf6e17c).
⚠️ Report is 25 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/dcr/resolver.go 72.50% 8 Missing and 3 partials ⚠️
pkg/auth/dcr/store.go 75.00% 1 Missing and 1 partial ⚠️
pkg/authserver/runner/embeddedauthserver.go 71.42% 1 Missing and 1 partial ⚠️
pkg/authserver/server/handlers/dcr.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5198      +/-   ##
==========================================
+ Coverage   67.91%   68.17%   +0.25%     
==========================================
  Files         610      618       +8     
  Lines       62522    63146     +624     
==========================================
+ Hits        42464    43049     +585     
- Misses      16879    16885       +6     
- Partials     3179     3212      +33     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sub-issue 4a of #5145. Creates the shared pkg/auth/dcr package and
migrates the embedded authserver to consume it. The CLI flow
migration (pkg/auth/discovery::PerformOAuthFlow) is left to
sub-issue 4b (#5219) so this slice stays under the project's
PR-size limit.

Files moved (renamed via git mv so the diff shows as renames, not
deletions + additions):

  pkg/authserver/runner/dcr.go              -> pkg/auth/dcr/resolver.go
  pkg/authserver/runner/dcr_store.go        -> pkg/auth/dcr/store.go
  pkg/authserver/runner/dcr_test.go         -> pkg/auth/dcr/resolver_test.go
  pkg/authserver/runner/dcr_store_test.go   -> pkg/auth/dcr/store_test.go
  pkg/authserver/runner/dcr_testhelpers_test.go -> pkg/auth/dcr/testhelpers_test.go

Public API surface (renamed from runner-package internals because
they now cross a package boundary):

  Resolution            (was DCRResolution)
  Key                   (was DCRKey, alias to storage.DCRKey unchanged)
  CredentialStore       (was the package-private dcrResolutionCache)
  ResolveCredentials    (was resolveDCRCredentials)
  NeedsDCR              (was needsDCR)
  ConsumeResolution     (was consumeResolution)
  ApplyResolutionToOAuth2Config (was applyResolutionToOAuth2Config)
  LogStepError          (was logDCRStepError)
  NewInMemoryStore      (new convenience constructor wrapping
                         storage.NewMemoryStorage; mirrors the pattern
                         the per-test newMemoryDCRStore helpers use)
  NewStorageBackedStore (was the package-private newStorageBackedStore)
  SanitizeErrorForLog   (was sanitizeErrorForLog; promoted to
                         exported because the deferred-cleanup log
                         path in pkg/authserver/runner needs it)

Names follow the pkg/auth/dcr.* form so the linter's stuttering
check (revive: dcr.DCRResolution would stutter) passes and the
surface reads as ordinary package API.

resolveSecret was duplicated into the dcr package because
pkg/auth/dcr must stay profile-agnostic and cannot reach back into
pkg/authserver/runner. The duplication is intentional and called
out in a comment; future consolidation can move it into a shared
helper if a third caller appears. A parallel TestResolveSecret /
TestResolveSecretWithEnvVar suite in pkg/auth/dcr/secret_test.go
mirrors the runner-package twin's observable contract so any
future drift between the two copies fails CI on at least one side.

Review-feedback bits applied alongside the move:

- Package doc comment in pkg/auth/dcr/resolver.go now documents the
  process-global singleflight in a Concurrency section, and labels
  the profile-agnostic framing as a target state for sub-issue 4b
  rather than as a description of the current API shape (the
  package's public API still takes embedded-authserver types).
- dcrFlight var doc gains a cross-consumer caveat naming the
  "third consumer with colliding redirect URI" failure mode.
- Flight-key construction extracted into flightKeyOf(Key) string so
  the canonical key shape is inspectable rather than buried in a
  string-concatenation literal.
- endpointsFromMetadata gains a defensive nil check; the function's
  doc comment names the oauthproto contract being defended.
- newMemoryDCRStore test helper is duplicated across the two
  packages because Go test helpers cannot be shared without
  exporting them; the duplication is documented at both sites.

Acceptance criteria status (#5145):

  AC#1 (pkg/auth/dcr exists, exports a stateful resolver, consumed
       by both call sites): partially met — package exists and is
       consumed by EmbeddedAuthServer. CLI flow migration is
       sub-issue 4b (#5219).
  AC#2 (stateless RFC 7591 helpers in pkg/oauthproto): met
       (already satisfied before this PR).
  AC#3 (no direct oauthproto.RegisterClientDynamically calls
       outside pkg/auth/dcr): not yet met — pkg/auth/discovery
       still calls it. Resolved by sub-issue 4b (#5219).
  AC#4 (review-property behaviours apply to CLI flow): not yet
       met — same dependency on 4b (#5219).

Closes #5220.

Verified via task lint-fix (0 issues), task license-check (clean),
and go test -count=1 -race ./pkg/auth/dcr/... ./pkg/authserver/...
(all pass).
@tgrunnagle tgrunnagle force-pushed the dcr-4a_issue_5145 branch from 633ed9e to 81b9e02 Compare May 8, 2026 20:13
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels May 8, 2026
Copy link
Copy Markdown
Contributor Author

@tgrunnagle tgrunnagle left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multi-Agent Consensus Review

Agents consulted: api-design, concurrency/refactor, security, test-quality, documentation, cross-cutting (codex skipped — CLI not installed)

Consensus Summary

# Finding Score Severity Action
1 NewInMemoryStore returns store whose cleanup goroutine cannot be stopped 9/10 MEDIUM Fix
2 pkg/authserver/storage/types.go "Converter contract" doc points at deleted files/types 9/10 MEDIUM Fix (out-of-diff)
3 dcrFlight doc names EmbeddedAuthServer.dcrStore field that no longer exists post-#5196 8/10 MEDIUM Fix
4 Drift-guard cross-reference is one-way — runner-package twin lacks pointer back 8/10 MEDIUM Fix
5 NewStorageBackedStore accepts nil backend silently; panics on first call 7/10 MEDIUM Fix
6 SanitizeErrorForLog exported as a generic-looking URL sanitiser, only handles http(s) 8/10 LOW Discuss
7 Stale path pkg/authserver/runner/dcr.go in handlers/dcr.go:109 comment 7/10 LOW Fix (out-of-diff)
8 Package doc lists *authserver.DCRUpstreamConfig as parameter type; no exported function takes it 7/10 LOW Fix
9 flightKeyOf doc cites RFC 6749 §3.3 (scope tokens) for the ScopesHash hex-digest field 7/10 LOW Fix
10 Stale "DCRKey" mentions in embeddedauthserver_test.go comments and assertion messages 7/10 LOW Fix
11 Singleflight global state will become a cross-consumer hazard once 4b lands 7/10 LOW Discuss
12 dcr.resolveSecret has zero production callers; #nosec G304 staged ahead of caller 7/10 LOW Discuss

Overall

This is a clean refactor that extracts the DCR resolver from pkg/authserver/runner into a new pkg/auth/dcr package, with public-symbol renames on packagisation. All reviewable behaviours — S256 PKCE gate, redirect refusal, RFC 7591 §3.2.1 expiry refetch, panic recovery, package-global singleflight semantics, URL log sanitisation — are preserved across the move and verified case-by-case by the specialist agents. The only genuinely new code in the diff is flightKeyOf (extraction of an inlined string concatenation, byte-identical output) and a defensive nil-guard in endpointsFromMetadata (catches a hypothetical oauthproto contract regression). Six specialist agents reviewed in parallel; no specialist dismissed another's concern in a way that triggered conflict resolution.

The 12 surviving consensus findings split between three buckets: (a) out-of-diff documentation debt — the rename sweep missed pkg/authserver/storage/types.go and pkg/authserver/server/handlers/dcr.go, both of which still name pre-rename paths or types; (b) constructor-validation hardening for NewInMemoryStore (resource leak — the cleanup goroutine cannot be stopped through the returned interface) and NewStorageBackedStore (silent nil acceptance); (c) forward-looking concerns for sub-issue 4b — the package-global singleflight, the duplicated resolveSecret with no production caller in this PR, and the SanitizeErrorForLog export of a function that reads as generic but only handles http(s).

None of the findings are blocking. The PR is in DRAFT status which is consistent with this state. Recommendation is COMMENT — the bucket-(a) and bucket-(b) items are easy to address in this PR (small, mechanical); bucket-(c) items are reasonable to defer to 4b with explicit tracking links.

Out-of-diff documentation debt

Three items live outside the PR's diff and need to be pulled in (or filed as a follow-up explicitly linked from this PR):

  • pkg/authserver/storage/types.go:235-243DCRCredentials "Converter contract" doc names pkg/authserver/runner/dcr_store.go, *DCRResolution, and pkg/authserver/runner/dcr_store_test.go. After this PR, the converters live in pkg/auth/dcr/store.go and the test in pkg/auth/dcr/store_test.go. Update those three references to the new paths and to *dcr.Resolution. (Finding #2, MEDIUM)
  • pkg/authserver/server/handlers/dcr.go:109 — comment names pkg/authserver/runner/dcr.go. The resolver now lives at pkg/auth/dcr/resolver.go. (Finding #7, LOW)
  • pkg/authserver/runner/embeddedauthserver_test.go:289-374TestResolveSecret and TestResolveSecretWithEnvVar should carry a doc comment naming the new pkg/auth/dcr/secret_test.go twin so a future bug fix on the runner side has a proximate hint that the dcr-side parallel test must be updated too. The dcr-side comment already names the runner-side twin; the back-pointer is missing. (Inline comment on the dcr-side at secret_test.go:17 discusses this further.) (Finding #4, MEDIUM)

Items to keep in mind for sub-issue 4b

Three of the LOW findings are forward-looking and become more expensive once 4b lands the CLI flow:

  • The package-global singleflight.Group will be shared across both consumers. Consider including a consumer identifier in the flight key now (cheap) or filing a tracking issue.
  • dcr.resolveSecret has no production caller in this PR — either defer to 4b or extract into a shared helper (pkg/auth/secretref or similar) in this PR with both consumers migrated.
  • SanitizeErrorForLog is exported as a generic-looking URL sanitiser but only handles http(s); a future caller wrapping a redis://user:pass@… error would silently leak credentials. Tighten the doc comment, move the helper to a small shared package, or keep it unexported behind a narrower SanitizeDCRError wrapper.

What's good

All specialists confirmed the refactor preserves observable behaviour. The rename sweep is exhaustive within the 9 diffed files (the misses are in three external files). flightKeyOf produces byte-identical output to the inlined concatenation. Singleflight semantics, panic recovery, and t.Cleanup placements are correct. The new defensive nil-guard in endpointsFromMetadata is well-documented and turns a future contract regression into a clean error rather than a nil-deref panic. The drift-guard tests for resolveSecret are observably equivalent to the runner-package twin (case-by-case audit). 25+ NO-ISSUES verifications across the specialists are recorded in the local review.


Generated with Claude Code

Comment thread pkg/auth/dcr/store.go Outdated
Comment thread pkg/auth/dcr/store.go
Comment thread pkg/auth/dcr/resolver.go
Comment thread pkg/auth/dcr/resolver.go Outdated
Comment thread pkg/auth/dcr/resolver.go Outdated
Comment thread pkg/auth/dcr/resolver.go Outdated
Comment thread pkg/auth/dcr/resolver.go
Comment thread pkg/auth/dcr/resolver.go
Comment thread pkg/auth/dcr/secret_test.go
Comment thread pkg/authserver/runner/embeddedauthserver_test.go Outdated
Addresses #5198 review comments:
- MEDIUM pkg/auth/dcr/store.go (3219717154): remove NewInMemoryStore
  — its CredentialStore return type has no Close method, so the
  storage.NewMemoryStorage cleanup goroutine the constructor spawns
  cannot be stopped through the returned interface. With no
  production caller in this PR (the test helpers wire their own
  *MemoryStorage with t.Cleanup), removing it is the lightest fix
  and resolves the "public API ahead of caller" smell. A real
  consumer with lifecycle management can reintroduce the appropriate
  shape (e.g. returning a paired shutdown func, or adding Close to
  CredentialStore) when 4b lands.
- MEDIUM pkg/auth/dcr/store.go (3219717166): panic on nil backend in
  NewStorageBackedStore. Per .claude/rules/go-style.md "Constructor
  Validation: Fail Loudly on Invalid Input" — a nil backend is
  unambiguously a programming error and silent acceptance would only
  delay the nil-pointer dereference to the first Get/Put call, far
  from the constructor site.
Addresses #5198 review comments:
- MEDIUM pkg/authserver/storage/types.go (review body finding #2):
  DCRCredentials "Converter contract" doc named the now-deleted
  pkg/authserver/runner/dcr_store.go path and the *DCRResolution
  type. Updated to pkg/auth/dcr/store.go, *dcr.Resolution, and
  pkg/auth/dcr/store_test.go (the rename sweep had missed this
  out-of-diff file).
- MEDIUM pkg/auth/dcr/resolver.go (3219717202): dcrFlight doc named
  EmbeddedAuthServer.dcrStore, a field #5196 removed. Reframed the
  lifetime contrast in terms of the public injection point — the
  CredentialStore the embedded authserver constructs and injects
  into ResolveCredentials — rather than a private field across a
  package boundary.
- MEDIUM pkg/authserver/runner/embeddedauthserver_test.go
  (3219717294): drift-guard cross-reference was one-way. Added
  reciprocal doc comments on TestResolveSecret and
  TestResolveSecretWithEnvVar naming the dcr-side twin at
  pkg/auth/dcr/secret_test.go, mirroring the dcr-side comment that
  already names the runner-side twin.
- LOW pkg/auth/dcr/resolver.go (3219717277): SanitizeErrorForLog
  reads as a generic URL sanitiser but only handles http(s);
  tightened the doc with an "IMPORTANT — caller responsibility"
  warning that callers receiving non-http(s) URLs with
  credential-bearing components (redis://user:pass@host, postgres://,
  etc.) MUST verify those separately. Long-term consolidation into
  a shared helper appropriate for sub-issue 4b.
- LOW pkg/authserver/server/handlers/dcr.go (review body finding #7):
  log-correlation comment named pkg/authserver/runner/dcr.go;
  updated to pkg/auth/dcr/resolver.go (also missed by the rename
  sweep).
- LOW pkg/auth/dcr/resolver.go (3219717222): package doc listed
  *authserver.DCRUpstreamConfig as a parameter type — no exported
  function takes it; it is reached transitively via
  OAuth2UpstreamRunConfig.DCRConfig. Applied the reviewer's
  suggested wording.
- LOW pkg/auth/dcr/resolver.go (3219717247): flightKeyOf doc cited
  RFC 6749 §3.3 (scope tokens) for the ScopesHash field, which is a
  hex digest, not a scope token. Removed the misaligned citation.
- LOW pkg/authserver/runner/embeddedauthserver_test.go (3219717303):
  qualified four bare "DCRKey" references to "storage.DCRKey" in
  comments and an assertion message; also fixed a sibling staleness
  in the same test-doc block where the comment named the deleted
  dcrStore field.
- LOW pkg/auth/dcr/resolver.go (3219717270): added a
  TODO(#5219) on dcrFlight noting that the flight key must gain a
  consumer-identifier component when sub-issue 4b wires the CLI
  flow as the second consumer. The colliding-Key risk is theoretical
  today; once two profiles share this group it becomes a correctness
  hazard. Cross-consumer caveat above already describes the failure
  mode; this TODO ties it to the resolution PR.
- LOW pkg/auth/dcr/resolver.go (3219717285): resolveSecret has no
  production caller in this PR. Tightened the duplication doc to
  state that the helper is staged for sub-issue 4b (#5219) to wire
  as part of the CLI flow migration, and that at that point this
  copy SHOULD be promoted to a shared helper with both consumers
  migrated in the same PR — i.e., the threshold for consolidation
  is "second caller wires up", not "third caller appears".
@tgrunnagle
Copy link
Copy Markdown
Contributor Author

Addressing the two out-of-diff documentation-debt findings from the review body:

  • Finding Do we want the container monitor? #2pkg/authserver/storage/types.go DCRCredentials Converter contract doc named the deleted pkg/authserver/runner/dcr_store.go path and *DCRResolution type. Fixed in 29c751a (paths updated to pkg/auth/dcr/store.go and pkg/auth/dcr/store_test.go; type updated to *dcr.Resolution).
  • Finding Create proxy subcommand #7pkg/authserver/server/handlers/dcr.go:109 named the deleted pkg/authserver/runner/dcr.go path. Fixed in the same commit (updated to pkg/auth/dcr/resolver.go).

Both files were outside the original PR diff; pulling them in here rather than filing a follow-up since they are mechanical rename-sweep misses and small enough to live alongside the doc-sweep commit.

@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels May 11, 2026
@tgrunnagle tgrunnagle marked this pull request as ready for review May 11, 2026 14:57
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels May 11, 2026
jhrozek
jhrozek previously approved these changes May 12, 2026
Copy link
Copy Markdown
Contributor

@jhrozek jhrozek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Solid refactor; the move preserves the security defences and the tests pin them.

One non-blocking suggestion inline on ConsumeResolution about the caller-mutation pattern. Fine to address in a follow-up before 4b lands.

Comment thread pkg/auth/dcr/resolver.go Outdated
Addresses #5198 review comments:
- INFO pkg/auth/dcr/resolver.go (3227004701): ConsumeResolution and
  ApplyResolutionToOAuth2Config mutated caller-supplied pointers and
  documented the "pass a copy" invariant only in prose. Converted
  both to value-in / value-out signatures so the no-caller-mutation
  contract is compile-time enforced rather than a prose discipline
  the second consumer (CLI flow in sub-issue 4b, #5219) would have
  to remember.

The change is structural but small: two signature changes
(ConsumeResolution / ApplyResolutionToOAuth2Config), two function
bodies returning the modified value, and call-site updates in
embeddedauthserver.go (1 production call site per function) and
resolver_test.go (4 test call sites for ConsumeResolution; zero for
ApplyResolutionToOAuth2Config).

Doc comments updated to describe the new value-in / value-out shape;
the "pass a copy of the run-config" prose-discipline paragraph is
removed because the type system now enforces it. Pointer-typed fields
inside the struct (DCRConfig) still share storage with the caller
via the shallow copy, but the only mutation here is nil-assignment to
the copy's DCRConfig field, which does not reach back through the
caller's pointer; this nuance is now called out in the doc comment.

ResolveCredentials is left as *authserver.OAuth2UpstreamRunConfig
deliberately: its rc input is read-only (no mutation), so the
pointer is just for avoiding a struct copy on the hot path.

Satisfies .claude/rules/go-style.md "Copy Before Mutating Caller
Input".
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels May 12, 2026
tgrunnagle added a commit that referenced this pull request May 12, 2026
Sub-issue 4b of #5145. The CLI OAuth flow at
pkg/auth/discovery::PerformOAuthFlow used to call
oauthproto.RegisterClientDynamically directly, so it did not inherit the
review-property behaviours added during #5042 (S256 PKCE gating, RFC 7591
§3.2.1 expiry-driven refetch, bearer-token transport with redirect
refusal, panic recovery, singleflight deduplication). This commit routes
that call site through the shared pkg/auth/dcr resolver introduced in
sub-issue 4a (PR #5198) and pins the invariant with a CI grep guard.

Profile-neutral resolver input: pkg/auth/dcr now exposes a Request struct
that carries exactly the fields the resolver reads (issuer, redirect
URI, scopes, discovery URL or registration endpoint, optional explicit
endpoint overrides, initial access token, client name, public-client
flag). ResolveCredentials takes a Request and no longer imports
authserver / upstream domain types. The embedded-authserver adapter
helpers (needsDCR, consumeResolution, applyResolutionToOAuth2Config)
move to pkg/authserver/runner/dcr_adapter.go where they belong by
ownership.

CLI persistence model: option (b) from the issue. The resolver runs
against an in-memory dcr.CredentialStore scoped to one PerformOAuthFlow
invocation. Cross-invocation persistence is handled outside the resolver
by pkg/auth/remote/handler.go's existing CachedClientID /
CachedClientSecretRef fields, which already preserved cross-invocation
reuse and continue to do so unchanged. Wrapping the secretProvider into
a CredentialStore adapter (option (a)) was rejected as out-of-scope
churn — the existing remote-handler caching is sufficient.

PublicClient flag: a new bool on dcr.Request tells the resolver to
register as a public PKCE client (token_endpoint_auth_method=none).
The S256 gate still fires — the CLI surfaces a clear resolver error
rather than silently downgrading when upstream advertises only "plain".

Invariant guard: Taskfile target check-dcr-isolation (wired into task
lint) and a matching CI step in .github/workflows/lint.yml fail if
oauthproto.RegisterClientDynamically is referenced anywhere outside
pkg/auth/dcr or pkg/oauthproto.

Tests added for the CLI's inherited properties (S256 gating, redirect
refusal, singleflight deduplication) in
pkg/auth/discovery/dcr_resolver_test.go. The fallback error message for
upstreams that omit registration_endpoint is preserved verbatim and
pinned by TestHandleDynamicRegistration_MissingRegistrationEndpoint.

Closes #5145.
@tgrunnagle tgrunnagle merged commit 3fa65b0 into main May 12, 2026
102 of 107 checks passed
@tgrunnagle tgrunnagle deleted the dcr-4a_issue_5145 branch May 12, 2026 15:39
tgrunnagle added a commit that referenced this pull request May 12, 2026
Sub-issue 4b of #5145. The CLI OAuth flow at
pkg/auth/discovery::PerformOAuthFlow used to call
oauthproto.RegisterClientDynamically directly, so it did not inherit the
review-property behaviours added during #5042 (S256 PKCE gating, RFC 7591
§3.2.1 expiry-driven refetch, bearer-token transport with redirect
refusal, panic recovery, singleflight deduplication). This commit routes
that call site through the shared pkg/auth/dcr resolver introduced in
sub-issue 4a (PR #5198) and pins the invariant with a CI grep guard.

Profile-neutral resolver input: pkg/auth/dcr now exposes a Request struct
that carries exactly the fields the resolver reads (issuer, redirect
URI, scopes, discovery URL or registration endpoint, optional explicit
endpoint overrides, initial access token, client name, public-client
flag). ResolveCredentials takes a Request and no longer imports
authserver / upstream domain types. The embedded-authserver adapter
helpers (needsDCR, consumeResolution, applyResolutionToOAuth2Config)
move to pkg/authserver/runner/dcr_adapter.go where they belong by
ownership.

CLI persistence model: option (b) from the issue. The resolver runs
against an in-memory dcr.CredentialStore scoped to one PerformOAuthFlow
invocation. Cross-invocation persistence is handled outside the resolver
by pkg/auth/remote/handler.go's existing CachedClientID /
CachedClientSecretRef fields, which already preserved cross-invocation
reuse and continue to do so unchanged. Wrapping the secretProvider into
a CredentialStore adapter (option (a)) was rejected as out-of-scope
churn — the existing remote-handler caching is sufficient.

PublicClient flag: a new bool on dcr.Request tells the resolver to
register as a public PKCE client (token_endpoint_auth_method=none).
The S256 gate still fires — the CLI surfaces a clear resolver error
rather than silently downgrading when upstream advertises only "plain".

Invariant guard: Taskfile target check-dcr-isolation (wired into task
lint) and a matching CI step in .github/workflows/lint.yml fail if
oauthproto.RegisterClientDynamically is referenced anywhere outside
pkg/auth/dcr or pkg/oauthproto.

Tests added for the CLI's inherited properties (S256 gating, redirect
refusal, singleflight deduplication) in
pkg/auth/discovery/dcr_resolver_test.go. The fallback error message for
upstreams that omit registration_endpoint is preserved verbatim and
pinned by TestHandleDynamicRegistration_MissingRegistrationEndpoint.

Closes #5145.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

2 participants