Skip to content

Add authserver DCR discovery and config surface - #5041

Merged
tgrunnagle merged 2 commits into
mainfrom
issue_5037_dcr-2a
Apr 29, 2026
Merged

tgrunnagle merged 2 commits into
mainfrom
issue_5037_dcr-2a

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • The authserver currently requires every OAuth2 upstream to be pre-provisioned with a ClientID, which blocks operators who would prefer to register the client at runtime against the IdP. Phase 2 of the DCR story (Authserver DCR integration (Phase 2, Steps 2a-2g) #4978) introduces RFC 7591 Dynamic Client Registration; this sub-issue lays the leaf-package and config foundation needed by every later step.
  • Adds oauthproto.FetchAuthorizationServerMetadata — a bounded, leaf-package RFC 8414 / OIDC Discovery client implementing the three-path fallback required to resolve registration_endpoint from a bare issuer URL.
  • Adds DCRUpstreamConfig and a DCRConfig *DCRUpstreamConfig field on OAuth2UpstreamRunConfig, plus exactly-one-of validation rules (ClientID xor DCRConfig, and DiscoveryURL xor RegistrationEndpoint) so misconfiguration fails at startup rather than silently degrading at runtime.
  • Purely additive — no behavior change, no CRD changes, no consumer wired up yet. Sub-issue B (credential store + resolver) consumes this surface area.

Closes #5037

Type of change

  • New feature

Test plan

  • Unit tests (task test)
  • Linting (task lint-fix)

New table-driven tests cover:

  • All three RFC 8414 / OIDC Discovery fallback paths (one httptest.NewServer per path), with the bare-path test using a non-empty tenant so the third fallback is actually exercised.
  • RFC 8414 §3.3 issuer-equality enforcement (mismatch surfaces a descriptive error).
  • ErrRegistrationEndpointMissing returned with a non-nil partial metadata document when the winning response omits registration_endpoint.
  • Issuer URL validation: empty, malformed, missing scheme/host, non-loopback http://, and ftp:// schemes are rejected; loopback http:// is allowed.
  • Internal 10 s timeout overrides a context.Background caller (uses a package-private discoveryTimeout var so the test does not have to wait the full 10 s).
  • All four ClientID × DCRConfig combinations on OAuth2UpstreamRunConfig.Validate, plus the DiscoveryURL xor RegistrationEndpoint rule on DCRUpstreamConfig.Validate.

API Compatibility

  • This PR does not break the v1beta1 API, OR the api-break-allowed label is applied and the migration guidance is described above.

Changes

File Change
pkg/oauthproto/discovery.go Add FetchAuthorizationServerMetadata with three-path fallback, bounded timeout, issuer-equality check, and ErrRegistrationEndpointMissing partial-success contract.
pkg/oauthproto/discovery_test.go Table-driven tests for all three discovery paths, issuer mismatch, missing registration endpoint, issuer validation, loopback carve-out, and timeout override.
pkg/oauthproto/errors.go Add ErrRegistrationEndpointMissing sentinel.
pkg/authserver/config.go Add DCRUpstreamConfig struct, DCRConfig field on OAuth2UpstreamRunConfig, and Validate() methods enforcing exactly-one-of rules.
pkg/authserver/config_test.go Table-driven tests for the new validation rules.

Does this introduce a user-facing change?

No — the new config fields are not yet consumed by any code path, and the discovery function is not yet called from the authserver. User-visible DCR behavior arrives in later sub-issues of #4978.

Special notes for reviewers

  • Rebase note: this branch contains commit 3cb8de58 which is the pkg/oauth -> pkg/oauthproto rename from Rename pkg/oauth to pkg/oauthproto and relocate DCR primitives #4977 (PR Rename pkg/oauth to pkg/oauthproto and move DCR primitives #5036). Rename pkg/oauth to pkg/oauthproto and move DCR primitives #5036 is still open as of this PR's creation; once it merges to main, this branch should be rebased so only the three commits scoped to Authserver DCR: discovery function and config structs (Phase 2, Steps 2a/2b/2e) #5037 remain (b408d6b2, a7de63d6, 73985137). The 5037-only diff touches just five files.
  • Partial-success error contract on FetchAuthorizationServerMetadata: returns (metadata, ErrRegistrationEndpointMissing) rather than (nil, err) when the document is otherwise valid but lacks registration_endpoint, so callers that only need TokenEndpoint / JWKSURI can still use the result. This deviates from the usual Go "err != nil ⇒ value invalid" idiom; the doc comment includes a worked errors.Is example and the test asserts the partial document fields are populated.
  • Leaf-package invariant: pkg/oauthproto must not import pkg/networking, so the per-call timeout, body cap (1 MB io.LimitReader), Accept header, and content-type check are implemented directly inside discovery.go rather than reused from pkg/networking/utilities.go. This duplication is intentional and is documented in the package doc.
  • discoveryTimeout is a var, not a const: required so the timeout-override test can shorten it to keep the test suite fast. Production code MUST NOT mutate it; the comment on the declaration says so explicitly.
  • buildDiscoveryURLs deduplication: when the issuer has no path component, the path-insertion URL and the bare URL are identical, so the function emits only the deduplicated set to avoid a redundant round-trip and a misleading "tried 3 URLs" error message.
  • CommonOAuthConfig.Validate() is intentionally not modified — the new ClientID/DCR mutual-exclusion rules are specific to OAuth2UpstreamRunConfig and do not belong in the shared validator.

Implementation plan

Approved implementation plan

This PR implements Steps 2a, 2b, and 2e of the Phase 2 plan tracked in #4978:

  • Step 2a — FetchAuthorizationServerMetadata in pkg/oauthproto/discovery.go. Three-path RFC 8414 / OIDC Discovery fallback (path-insertion, then OIDC Discovery, then bare RFC 8414), bounded 10 s per-call timeout, RFC 8414 §3.3 issuer equality check, ErrRegistrationEndpointMissing sentinel for partial success. Mirrors the plumbing of pkg/auth/discovery/discovery.go:FetchResourceMetadata (bounded HTTP client, Accept: application/json, io.LimitReader, content-type check) but stays in the leaf package — no pkg/networking import.
  • Step 2b — DCRUpstreamConfig struct in pkg/authserver/config.go with DiscoveryURL, RegistrationEndpoint, InitialAccessTokenFile, InitialAccessTokenEnvVar, SoftwareID, SoftwareStatement fields (JSON + YAML tags). Adds DCRConfig *DCRUpstreamConfig field to OAuth2UpstreamRunConfig.
  • Step 2e — Extends OAuth2UpstreamRunConfig.Validate() and adds DCRUpstreamConfig.Validate() to reject all three invalid combinations: both missing, both set, and DiscoveryURL/RegistrationEndpoint both set or both missing. CommonOAuthConfig.Validate() is left alone.

Steps 2c and 2d (credential store + resolver) are deferred to sub-issue B per #4978.

Large PR Justification

  • Majority lines are generated docs and tests

@tgrunnagle
tgrunnagle changed the base branch from main to worktree-issue_4977 April 23, 2026 17:02
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Apr 23, 2026
@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 Apr 23, 2026
@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.03419% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.34%. Comparing base (b59514f) to head (7dc73f8).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
pkg/oauthproto/discovery.go 83.52% 10 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5041      +/-   ##
==========================================
+ Coverage   67.30%   67.34%   +0.03%     
==========================================
  Files         598      598              
  Lines       60348    60465     +117     
==========================================
+ Hits        40617    40718     +101     
- Misses      16658    16667       +9     
- Partials     3073     3080       +7     

☔ 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.

@tgrunnagle
tgrunnagle force-pushed the worktree-issue_4977 branch 2 times, most recently from 5e365c9 to 16e2153 Compare April 27, 2026 13:21
Base automatically changed from worktree-issue_4977 to main April 27, 2026 14:47
@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 Apr 27, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

@tgrunnagle
tgrunnagle changed the base branch from main to fallback-userInfo_2026-04-28 April 29, 2026 15:07
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 29, 2026
@github-actions
github-actions Bot dismissed their stale review April 29, 2026 15:13

PR size has been reduced below the XL threshold. Thank you for splitting this up!

@github-actions

Copy link
Copy Markdown
Contributor

✅ PR size has been reduced below the XL threshold. The size review has been dismissed and this PR can now proceed with normal review. Thank you for splitting this up!

@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 Apr 29, 2026
@tgrunnagle
tgrunnagle marked this pull request as ready for review April 29, 2026 15:15

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

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: security/oauth-compliance, go-style, test-quality, config-and-api-design, general-code-quality

Consensus Summary

# Finding Consensus Severity Action
1 OAuth2UpstreamRunConfig.Validate() is orphaned (no caller) 9/10 HIGH Wire it in or document
2 InitialAccessToken{File,EnvVar} doc says "mutually exclusive" but Validate() does not enforce 9/10 MEDIUM Fix
3 path.Join(WellKnownOAuthServerPath, parsed.EscapedPath()) risks double-encoding tenants with special chars 8/10 MEDIUM Fix
4 Aggregated attempt errors flatten to string and lose errors.Is/errors.As reachability 8/10 MEDIUM Fix (use errors.Join)
5 Early return (metadata, ErrRegistrationEndpointMissing) from URL #1 short-circuits URLs #2/#3 7/10 HIGH Discuss
6 No test asserts buildDiscoveryURLs deduplication for tenant-less issuers 7/10 MEDIUM Add test
7 DCRUpstreamConfig.Validate() does not enforce HTTPS or URL well-formedness 7/10 MEDIUM Fix
8 Two parallel OAuth2 config structs (OAuth2UpstreamRunConfig vs upstream.OAuth2Config) widening drift 7/10 MEDIUM Note
9 DCRConfig is silently dropped by buildPureOAuth2Config conversion (DCR-only configs cannot reach runtime) 7/10 HIGH Document or wire
10 Public Validate methods placed at bottom of config.go, after private helpers 7/10 LOW Move

Overall

This is a well-executed groundwork PR. Commits are tight, doc comments are thorough, the SPDX header migration is correct, the leaf-package invariant for pkg/oauthproto is preserved, and the partial-success error contract on FetchAuthorizationServerMetadata is conscientiously documented. Test coverage exercises all three RFC 8414 / OIDC fallback paths, the loopback HTTP carve-out, the issuer-mismatch enforcement, and the four-quadrant config validation matrix.

The findings cluster around three themes. Validation completeness: the new Validate() methods are honest about their scope but two real gaps slipped through — the InitialAccessToken{File,EnvVar} xor that the doc comments promise but the validator never checks (with a test that codifies the contradiction), and the OAuth2UpstreamRunConfig.Validate() having no caller in the tree today (the runtime path is validateUpstreamType -> upstream.OAuth2Config.Validate, a parallel struct that doesn't know about DCR). Both are addressable in this PR or with a clearly-scoped follow-up commit; neither is a blocker on its own. URL handling subtleties in discovery.go: path.Join on EscapedPath() will double-escape tenants containing % characters, and the aggregated multi-attempt error drops the wrap chain rather than using errors.Join. Both are fixable in a few lines. Design questions: the early-return on missing registration_endpoint is documented but arguably wrong — RFC 8414 fallback semantics suggest continuing through remaining URLs and only returning partial success if all attempts fail. This is the one item that warrants explicit discussion rather than a mechanical fix.

The scope is honest about deferrals (sub-issues B onward) but the PR description's claim that mutual-exclusion is "enforced" is technically false today since nothing calls the new method. Worth either tightening the wording or adding a one-line wiring change so the validator actually runs.

Nothing here blocks the foundational direction; the surface area being added is the right shape for what sub-issue B will need.


Generated with Claude Code

Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/oauthproto/discovery.go Resolved
Comment thread pkg/oauthproto/discovery.go Resolved
Comment thread pkg/oauthproto/discovery.go Resolved
Comment thread pkg/oauthproto/discovery_test.go Resolved
jhrozek
jhrozek previously approved these changes Apr 29, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving — purely additive surface, tests are thorough, lint clean. Two non-blocking suggestions inline that can land as follow-up PRs after sub-issue B starts wiring up consumers.

Comment thread pkg/oauthproto/discovery.go Resolved
Comment thread pkg/oauthproto/discovery.go Resolved
tgrunnagle added a commit that referenced this pull request Apr 29, 2026
Wire the new run-config validators into the load path and tighten the
discovery fallback so feedback from review #4198420468 stops being a
documentation-only promise.

- Call OAuth2UpstreamRunConfig.Validate from buildPureOAuth2Config so the
  ClientID/DCRConfig mutual-exclusion rule actually runs at the
  RunConfig→upstream-config conversion boundary, not as dead code.
- Move OAuth2UpstreamRunConfig.Validate and DCRUpstreamConfig.Validate
  next to Config.Validate to satisfy the public-methods-on-top rule.
- Reject configs that set both InitialAccessTokenFile and
  InitialAccessTokenEnvVar; the docs already promised mutual exclusion
  and silent precedence would mask credential rotation.
- Validate DiscoveryURL / RegistrationEndpoint via
  networking.ValidateEndpointURL so malformed or non-loopback-HTTP URLs
  fail at startup instead of at first DCR call.
- Stop short-circuiting in FetchAuthorizationServerMetadata when an
  issuer-validated document is missing registration_endpoint: stash it
  and keep iterating so a later URL with a full document wins. Real
  IdPs sometimes advertise DCR only on the OIDC document.
- Aggregate per-attempt discovery errors with errors.Join + %w so
  callers can still inspect causes through errors.Is / errors.As.
- Use parsed.Path instead of parsed.EscapedPath when building discovery
  URLs so url.URL.String escapes the tenant exactly once; tenants with
  characters like spaces no longer become "%2520".

Tests cover each change, including a regression test that pins the
deduplication of path-insertion and bare RFC 8414 URLs for tenant-less
issuers.
@github-actions github-actions Bot removed the size/L Large PR: 600-999 lines changed label Apr 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Apr 29, 2026
Base automatically changed from fallback-userInfo_2026-04-28 to main April 29, 2026 16:11
@tgrunnagle
tgrunnagle dismissed jhrozek’s stale review April 29, 2026 16:11

The base branch was changed.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 29, 2026
tgrunnagle and others added 2 commits April 29, 2026 09:13
Implements phase 2 (steps 2a/2b/2e) of the authserver Dynamic Client
Registration story (#4978, sub-issue A of #5037). Purely additive: no
behavior change, no CRD changes.

- pkg/oauthproto: FetchAuthorizationServerMetadata with three-path RFC 8414
  / OIDC Discovery fallback, bounded per-call timeout, RFC 8414 §3.3 issuer
  equality check, and ErrRegistrationEndpointMissing sentinel. Leaf-package
  invariant preserved (no pkg/networking import).
- pkg/authserver: DCRUpstreamConfig struct plus DCRConfig field on
  OAuth2UpstreamRunConfig for operators who want runtime RFC 7591
  registration instead of a pre-provisioned ClientID.
- pkg/authserver: OAuth2UpstreamRunConfig.Validate and
  DCRUpstreamConfig.Validate enforce exactly-one-of for
  ClientID vs DCRConfig and DiscoveryURL vs RegistrationEndpoint;
  CommonOAuthConfig.Validate is unchanged.

Address code review feedback on DCR discovery

Fixed issues from code review of commit b408d6b:

- HIGH: bare-path discovery test now uses a non-empty tenant path so all
  three well-known URLs are distinct, proving the third-iteration fallback
  actually runs.
- HIGH: buildDiscoveryURLs deduplicates path-insertion and bare URLs when
  the issuer has no tenant path, avoiding a redundant round-trip and
  duplicate entries in the aggregated error.
- MEDIUM: deferred body drain no longer wraps resp.Body in io.LimitReader,
  so large responses are fully drained for connection reuse; the JSON
  decode path still bounds accepted bytes.
- MEDIUM: expanded FetchAuthorizationServerMetadata doc comment with a
  worked errors.Is example for the (metadata,
  ErrRegistrationEndpointMissing) return contract; tightened the
  corresponding test to assert the partial document fields.
- MEDIUM: added TestFetchAuthorizationServerMetadata_InvalidIssuer covering
  empty issuer, malformed URL, missing scheme/host, http non-loopback, and
  ftp scheme; added TestFetchAuthorizationServerMetadata_AllowsLoopbackHTTP
  to lock the loopback carve-out.
- MEDIUM: added TestFetchAuthorizationServerMetadata_TimeoutOverridesCallerContext
  that shortens the timeout via a new discoveryTimeout var and asserts the
  function honors its internal bound even when the caller passes
  context.Background.
- MEDIUM: normalized struct-tag spacing on DCRUpstreamConfig to match the
  surrounding single-space style; kept //nolint:lll only on fields whose
  tag line actually exceeds 120 characters.
- MEDIUM: replaced the 13-line Apache header with the 2-line SPDX header
  on pkg/oauthproto/discovery.go, discovery_test.go, and errors.go to
  match the project convention already used elsewhere in the package.

Fix misordered nolint:paralleltest comment on timeout test

The comment block above
TestFetchAuthorizationServerMetadata_TimeoutOverridesCallerContext split
a single sentence across the //nolint directive in the wrong order, so
reading top to bottom the explanation appeared before the directive
ended mid-phrase. Reword the prose onto three lines above the test and
drop a single-line //nolint:paralleltest directive directly above func.

- MEDIUM: readability fix only — no behavior, assertions, or public
  surface changed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Wire the new run-config validators into the load path and tighten the
discovery fallback so feedback from review #4198420468 stops being a
documentation-only promise.

- Call OAuth2UpstreamRunConfig.Validate from buildPureOAuth2Config so the
  ClientID/DCRConfig mutual-exclusion rule actually runs at the
  RunConfig→upstream-config conversion boundary, not as dead code.
- Move OAuth2UpstreamRunConfig.Validate and DCRUpstreamConfig.Validate
  next to Config.Validate to satisfy the public-methods-on-top rule.
- Reject configs that set both InitialAccessTokenFile and
  InitialAccessTokenEnvVar; the docs already promised mutual exclusion
  and silent precedence would mask credential rotation.
- Validate DiscoveryURL / RegistrationEndpoint via
  networking.ValidateEndpointURL so malformed or non-loopback-HTTP URLs
  fail at startup instead of at first DCR call.
- Stop short-circuiting in FetchAuthorizationServerMetadata when an
  issuer-validated document is missing registration_endpoint: stash it
  and keep iterating so a later URL with a full document wins. Real
  IdPs sometimes advertise DCR only on the OIDC document.
- Aggregate per-attempt discovery errors with errors.Join + %w so
  callers can still inspect causes through errors.Is / errors.As.
- Use parsed.Path instead of parsed.EscapedPath when building discovery
  URLs so url.URL.String escapes the tenant exactly once; tenants with
  characters like spaces no longer become "%2520".

Tests cover each change, including a regression test that pins the
deduplication of path-insertion and bare RFC 8414 URLs for tenant-less
issuers.
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 29, 2026
@github-actions
github-actions Bot dismissed their stale review April 29, 2026 16:13

Large PR justification has been provided. Thank you!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 29, 2026
@tgrunnagle
tgrunnagle requested a review from jhrozek April 29, 2026 16:39
@tgrunnagle tgrunnagle changed the title Add authserver DCR discovery and config surface (Phase 2, 2a/2b/2e) Add authserver DCR discovery and config surface Apr 29, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 29, 2026
@tgrunnagle
tgrunnagle merged commit d3922ce into main Apr 29, 2026
44 checks passed
@tgrunnagle
tgrunnagle deleted the issue_5037_dcr-2a branch April 29, 2026 18:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Authserver DCR: discovery function and config structs (Phase 2, Steps 2a/2b/2e)

2 participants