Repository navigation
Add authserver DCR discovery and config surface - #5041
Conversation
7398513 to
d578dfe
Compare
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
5e365c9 to
16e2153
Compare
d578dfe to
000369f
Compare
000369f to
9ea4a15
Compare
There was a problem hiding this comment.
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 transformationAlternative:
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.
PR size has been reduced below the XL threshold. Thank you for splitting this up!
|
✅ 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! |
9ea4a15 to
2557afc
Compare
tgrunnagle
left a comment
There was a problem hiding this comment.
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
jhrozek
left a comment
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
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 transformationAlternative:
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.
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.
e6588ea to
7dc73f8
Compare
Large PR justification has been provided. Thank you!
|
✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review. |
Summary
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.oauthproto.FetchAuthorizationServerMetadata— a bounded, leaf-package RFC 8414 / OIDC Discovery client implementing the three-path fallback required to resolveregistration_endpointfrom a bare issuer URL.DCRUpstreamConfigand aDCRConfig *DCRUpstreamConfigfield onOAuth2UpstreamRunConfig, plus exactly-one-of validation rules (ClientIDxorDCRConfig, andDiscoveryURLxorRegistrationEndpoint) so misconfiguration fails at startup rather than silently degrading at runtime.Closes #5037
Type of change
Test plan
task test)task lint-fix)New table-driven tests cover:
httptest.NewServerper path), with the bare-path test using a non-empty tenant so the third fallback is actually exercised.ErrRegistrationEndpointMissingreturned with a non-nil partial metadata document when the winning response omitsregistration_endpoint.http://, andftp://schemes are rejected; loopbackhttp://is allowed.context.Backgroundcaller (uses a package-privatediscoveryTimeoutvar so the test does not have to wait the full 10 s).ClientID×DCRConfigcombinations onOAuth2UpstreamRunConfig.Validate, plus theDiscoveryURLxorRegistrationEndpointrule onDCRUpstreamConfig.Validate.API Compatibility
v1beta1API, OR theapi-break-allowedlabel is applied and the migration guidance is described above.Changes
pkg/oauthproto/discovery.goFetchAuthorizationServerMetadatawith three-path fallback, bounded timeout, issuer-equality check, andErrRegistrationEndpointMissingpartial-success contract.pkg/oauthproto/discovery_test.gopkg/oauthproto/errors.goErrRegistrationEndpointMissingsentinel.pkg/authserver/config.goDCRUpstreamConfigstruct,DCRConfigfield onOAuth2UpstreamRunConfig, andValidate()methods enforcing exactly-one-of rules.pkg/authserver/config_test.goDoes 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
3cb8de58which is thepkg/oauth->pkg/oauthprotorename 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 tomain, 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.FetchAuthorizationServerMetadata: returns(metadata, ErrRegistrationEndpointMissing)rather than(nil, err)when the document is otherwise valid but lacksregistration_endpoint, so callers that only needTokenEndpoint/JWKSURIcan still use the result. This deviates from the usual Go "err != nil ⇒ value invalid" idiom; the doc comment includes a workederrors.Isexample and the test asserts the partial document fields are populated.pkg/oauthprotomust not importpkg/networking, so the per-call timeout, body cap (1 MBio.LimitReader),Acceptheader, and content-type check are implemented directly insidediscovery.gorather than reused frompkg/networking/utilities.go. This duplication is intentional and is documented in the package doc.discoveryTimeoutis avar, not aconst: 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.buildDiscoveryURLsdeduplication: 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 newClientID/DCRmutual-exclusion rules are specific toOAuth2UpstreamRunConfigand 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:
FetchAuthorizationServerMetadatainpkg/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,ErrRegistrationEndpointMissingsentinel for partial success. Mirrors the plumbing ofpkg/auth/discovery/discovery.go:FetchResourceMetadata(bounded HTTP client,Accept: application/json,io.LimitReader, content-type check) but stays in the leaf package — nopkg/networkingimport.DCRUpstreamConfigstruct inpkg/authserver/config.gowithDiscoveryURL,RegistrationEndpoint,InitialAccessTokenFile,InitialAccessTokenEnvVar,SoftwareID,SoftwareStatementfields (JSON + YAML tags). AddsDCRConfig *DCRUpstreamConfigfield toOAuth2UpstreamRunConfig.OAuth2UpstreamRunConfig.Validate()and addsDCRUpstreamConfig.Validate()to reject all three invalid combinations: both missing, both set, andDiscoveryURL/RegistrationEndpointboth 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