Skip to content

Move checking for relative path to dedicated function - #15

Merged
JAORMX merged 1 commit into
mainfrom
don-comment
Mar 26, 2025
Merged

JAORMX merged 1 commit into
mainfrom
don-comment

Conversation

@JAORMX

@JAORMX JAORMX commented Mar 26, 2025

Copy link
Copy Markdown
Collaborator

per Don's request.

Signed-off-by: Juan Antonio Osorio [email protected]

per Don's request.

Signed-off-by: Juan Antonio Osorio <[email protected]>
@JAORMX
JAORMX merged commit b7f981a into main Mar 26, 2025
@JAORMX
JAORMX deleted the don-comment branch March 26, 2025 12:26
tgrunnagle added a commit that referenced this pull request Apr 29, 2026
Closes the 14 review threads from review #4199898531 that are scoped to
this PR; #3 and #5 are intentionally deferred to PR #5044 which is the
PR that consumes the ClientSecret plumbing and RedirectURI propagation.

Behaviour fixes:

- #2 synthesiseRegistrationEndpoint and resolveUpstreamRedirectURI now
  preserve the issuer's path component, so multi-tenant upstreams that
  ship DCR without advertising it (or this auth server when it itself
  has a tenant prefix in its issuer) keep their tenant prefix in the
  synthesised URL and the defaulted redirect URI.
- #7 resolveDCRCredentials wraps registration in a package-level
  singleflight.Group keyed by DCRKey so concurrent callers for the same
  upstream coalesce into a single RFC 7591 registration. The leader's
  closure rechecks the cache before any network I/O so followers that
  arrive just after a Put returns observe the fresh entry.
- #9 applyResolution writes ClientID only when the run-config copy
  leaves it empty, treating it symmetrically with the endpoint writes.
  This is defence-in-depth for callers that bypass the resolver's
  validateResolveInputs precondition check.
- #10 the cfg.RegistrationEndpoint short-circuit branch in
  resolveDCREndpoints validates URL well-formedness and HTTPS-or-
  loopback locally, so a non-HTTPS endpoint fails before
  performRegistration constructs a bearer-token transport for it.
- #13 endpointsFromMetadata validates discovered authorization_endpoint
  and token_endpoint before populating dcrEndpoints, so a self-
  consistent metadata document with http:// URLs cannot flow through
  to the auth-code or token-exchange path.

Doc / scope:

- #6 trust-assumption note added on DCRUpstreamConfig with a link to
  the follow-up SSRF-hardening issue (#5135) per the
  "Document Architectural Constraints" rule.
- #8 NewInMemoryDCRCredentialStore doc now explicitly calls out what
  the in-memory store does and does NOT solve (cross-replica sharing,
  durability, cross-process write coordination).

Test hygiene:

- #4 deleted the literal-equals-literal dcrStaleAgeThreshold test that
  added no meaningful coverage.
- #11 atomic.AddInt32 / LoadInt32 for wellKnownHits / customHits in
  TestFetchAuthorizationServerMetadataFromURL, matching the sibling
  pattern in dcr_test.go.
- #12 new failingDCRStore test double + two cases asserting the
  cache.Get / cache.Put wrap messages ("dcr: cache lookup", "dcr: cache
  put") that operators see when a future Redis backend errors.
- #14 renamed the TestNeedsDCR case from
  "client_id with dcr (invalid but returns false)" to
  "client_id wins over dcr_config (defensive AND semantic)" so the
  case label describes the intentional defensive behaviour rather
  than reading like a bug report.
- #15 removed a //nolint:lll directive that was suppressing a non-
  existent violation (the line is 108 chars; the limit is 130).
- #16 new TestInMemoryDCRCredentialStore_ConcurrentAccess fans out
  16 goroutines doing alternating Put/Get against overlapping and
  disjoint keys, with a fail-fast deadline, so go test -race actually
  exercises the sync.RWMutex guard.

New tests cover each behaviour change:

- TestResolveDCRCredentials_SingleflightCoalescesConcurrentCallers
  pins exactly-one-registration under N concurrent callers.
- TestSynthesiseRegistrationEndpoint_PreservesIssuerPath /
  TestResolveUpstreamRedirectURI_PreservesIssuerPath cover the path-
  preservation fix.
- TestApplyResolution_DoesNotOverwritePreProvisionedClientID covers
  the symmetric ClientID write.
- TestResolveDCREndpoints_DirectRegistrationEndpointValidated covers
  the local registration-endpoint guard.
- TestEndpointsFromMetadata_RejectsInsecureDiscoveredEndpoints covers
  the metadata authz/token endpoint guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tgrunnagle added a commit that referenced this pull request Apr 29, 2026
Closes the 14 review threads from review #4199898531 that are scoped to
this PR; #3 and #5 are intentionally deferred to PR #5044 which is the
PR that consumes the ClientSecret plumbing and RedirectURI propagation.

Behaviour fixes:

- #2 synthesiseRegistrationEndpoint and resolveUpstreamRedirectURI now
  preserve the issuer's path component, so multi-tenant upstreams that
  ship DCR without advertising it (or this auth server when it itself
  has a tenant prefix in its issuer) keep their tenant prefix in the
  synthesised URL and the defaulted redirect URI.
- #7 resolveDCRCredentials wraps registration in a package-level
  singleflight.Group keyed by DCRKey so concurrent callers for the same
  upstream coalesce into a single RFC 7591 registration. The leader's
  closure rechecks the cache before any network I/O so followers that
  arrive just after a Put returns observe the fresh entry.
- #9 applyResolution writes ClientID only when the run-config copy
  leaves it empty, treating it symmetrically with the endpoint writes.
  This is defence-in-depth for callers that bypass the resolver's
  validateResolveInputs precondition check.
- #10 the cfg.RegistrationEndpoint short-circuit branch in
  resolveDCREndpoints validates URL well-formedness and HTTPS-or-
  loopback locally, so a non-HTTPS endpoint fails before
  performRegistration constructs a bearer-token transport for it.
- #13 endpointsFromMetadata validates discovered authorization_endpoint
  and token_endpoint before populating dcrEndpoints, so a self-
  consistent metadata document with http:// URLs cannot flow through
  to the auth-code or token-exchange path.

Doc / scope:

- #6 trust-assumption note added on DCRUpstreamConfig with a link to
  the follow-up SSRF-hardening issue (#5135) per the
  "Document Architectural Constraints" rule.
- #8 NewInMemoryDCRCredentialStore doc now explicitly calls out what
  the in-memory store does and does NOT solve (cross-replica sharing,
  durability, cross-process write coordination).

Test hygiene:

- #4 deleted the literal-equals-literal dcrStaleAgeThreshold test that
  added no meaningful coverage.
- #11 atomic.AddInt32 / LoadInt32 for wellKnownHits / customHits in
  TestFetchAuthorizationServerMetadataFromURL, matching the sibling
  pattern in dcr_test.go.
- #12 new failingDCRStore test double + two cases asserting the
  cache.Get / cache.Put wrap messages ("dcr: cache lookup", "dcr: cache
  put") that operators see when a future Redis backend errors.
- #14 renamed the TestNeedsDCR case from
  "client_id with dcr (invalid but returns false)" to
  "client_id wins over dcr_config (defensive AND semantic)" so the
  case label describes the intentional defensive behaviour rather
  than reading like a bug report.
- #15 removed a //nolint:lll directive that was suppressing a non-
  existent violation (the line is 108 chars; the limit is 130).
- #16 new TestInMemoryDCRCredentialStore_ConcurrentAccess fans out
  16 goroutines doing alternating Put/Get against overlapping and
  disjoint keys, with a fail-fast deadline, so go test -race actually
  exercises the sync.RWMutex guard.

New tests cover each behaviour change:

- TestResolveDCRCredentials_SingleflightCoalescesConcurrentCallers
  pins exactly-one-registration under N concurrent callers.
- TestSynthesiseRegistrationEndpoint_PreservesIssuerPath /
  TestResolveUpstreamRedirectURI_PreservesIssuerPath cover the path-
  preservation fix.
- TestApplyResolution_DoesNotOverwritePreProvisionedClientID covers
  the symmetric ClientID write.
- TestResolveDCREndpoints_DirectRegistrationEndpointValidated covers
  the local registration-endpoint guard.
- TestEndpointsFromMetadata_RejectsInsecureDiscoveredEndpoints covers
  the metadata authz/token endpoint guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tgrunnagle added a commit that referenced this pull request May 1, 2026
* Add authserver DCR credential store and resolver

Implements Phase 2 steps 2f/2c of the DCR story (#5038):

- DCRCredentialStore interface with in-memory implementation keyed by
  (Issuer, RedirectURI, ScopesHash). No TTL — RFC 7591 registrations
  are long-lived and only purged by explicit deregistration. The
  ScopesHash tuple is designed to compose a Redis key segment in
  Phase 3 without redefining the canonical form.
- resolveDCRCredentials performs cache lookup, authorization server
  metadata discovery (or direct registration endpoint), explicit
  endpoint override, auth-method intersection against the preference
  order private_key_jwt > client_secret_basic > client_secret_post >
  none, synthesis of {origin}/register when metadata omits
  registration_endpoint, and a single call to
  oauthproto.RegisterClientDynamically with the initial access token
  injected as Authorization: Bearer via a wrapping RoundTripper.
- Resolution stored before returning, per the write-durable-first
  rule in .claude/rules/go-style.md.

Address code review feedback on DCR resolver

Fixed issues from code review:

- HIGH: DCRUpstreamConfig.DiscoveryURL now honoured. Added
  oauthproto.FetchAuthorizationServerMetadataFromURL which fetches
  the operator-configured URL exactly (no well-known-path fallback)
  and enforces RFC 8414 §3.3 issuer equality. Updated field doc
  comments to match behaviour.
- HIGH: TestResolveDCRCredentials_CacheHitShortCircuits rewritten
  to wire the count-everything server as the issuer and assert
  totalRequests == 0, so a regression that moved discovery before
  the cache lookup would actually fail the test.
- MEDIUM: Added tests for discovered-scopes fallback and empty-scope
  omitted-field branches.
- MEDIUM: Exposed oauthproto.NewDefaultDCRClient so newDCRHTTPClient
  inherits the canonical DCR timeout policy rather than duplicating
  it — future timeout changes propagate automatically.
- MEDIUM: Replaced hand-rolled readAll / readAllResp helpers with
  io.ReadAll.
- MEDIUM: Documented that direct RegistrationEndpoint disables
  server-capability negotiation.
- MEDIUM: Documented that applyResolution always overwrites ClientID
  and explained the precondition enforcement.
- MEDIUM: scopesHash now deduplicates (slices.Compact) so scope sets
  that differ only by duplicated values share a canonical digest.
  Test subtests updated accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address PR #5042 review feedback

Refuse HTTP redirects on DCR registration so an upstream cannot 30x us
into re-issuing the registration request — and the attached RFC 7591
initial access token — against a foreign origin. RFC 7591 §3 does not
require redirect support, so refusing them is the conservative fix.

- newDCRHTTPClient now sets http.Client.CheckRedirect to refuse all
  redirects (errDCRRedirectRefused), regardless of whether an initial
  access token is configured. The bearerTokenTransport itself is
  unchanged; the redirect block is the actual mitigation, not a header
  scrub inside RoundTrip.
- New TestResolveDCRCredentials_DoesNotForwardBearerOnRedirect: stands
  up an upstream whose /register 302s to a separate "foreign" httptest
  server, and asserts (a) the resolver errors with errDCRRedirectRefused
  and (b) the foreign server receives zero requests — proving the
  bearer never crossed origins.

Also includes a stray blank-line whitespace fix to discovery_test.go
left from the earlier rebase conflict resolution.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address remaining PR #5042 review feedback

Closes the 14 review threads from review #4199898531 that are scoped to
this PR; #3 and #5 are intentionally deferred to PR #5044 which is the
PR that consumes the ClientSecret plumbing and RedirectURI propagation.

Behaviour fixes:

- #2 synthesiseRegistrationEndpoint and resolveUpstreamRedirectURI now
  preserve the issuer's path component, so multi-tenant upstreams that
  ship DCR without advertising it (or this auth server when it itself
  has a tenant prefix in its issuer) keep their tenant prefix in the
  synthesised URL and the defaulted redirect URI.
- #7 resolveDCRCredentials wraps registration in a package-level
  singleflight.Group keyed by DCRKey so concurrent callers for the same
  upstream coalesce into a single RFC 7591 registration. The leader's
  closure rechecks the cache before any network I/O so followers that
  arrive just after a Put returns observe the fresh entry.
- #9 applyResolution writes ClientID only when the run-config copy
  leaves it empty, treating it symmetrically with the endpoint writes.
  This is defence-in-depth for callers that bypass the resolver's
  validateResolveInputs precondition check.
- #10 the cfg.RegistrationEndpoint short-circuit branch in
  resolveDCREndpoints validates URL well-formedness and HTTPS-or-
  loopback locally, so a non-HTTPS endpoint fails before
  performRegistration constructs a bearer-token transport for it.
- #13 endpointsFromMetadata validates discovered authorization_endpoint
  and token_endpoint before populating dcrEndpoints, so a self-
  consistent metadata document with http:// URLs cannot flow through
  to the auth-code or token-exchange path.

Doc / scope:

- #6 trust-assumption note added on DCRUpstreamConfig with a link to
  the follow-up SSRF-hardening issue (#5135) per the
  "Document Architectural Constraints" rule.
- #8 NewInMemoryDCRCredentialStore doc now explicitly calls out what
  the in-memory store does and does NOT solve (cross-replica sharing,
  durability, cross-process write coordination).

Test hygiene:

- #4 deleted the literal-equals-literal dcrStaleAgeThreshold test that
  added no meaningful coverage.
- #11 atomic.AddInt32 / LoadInt32 for wellKnownHits / customHits in
  TestFetchAuthorizationServerMetadataFromURL, matching the sibling
  pattern in dcr_test.go.
- #12 new failingDCRStore test double + two cases asserting the
  cache.Get / cache.Put wrap messages ("dcr: cache lookup", "dcr: cache
  put") that operators see when a future Redis backend errors.
- #14 renamed the TestNeedsDCR case from
  "client_id with dcr (invalid but returns false)" to
  "client_id wins over dcr_config (defensive AND semantic)" so the
  case label describes the intentional defensive behaviour rather
  than reading like a bug report.
- #15 removed a //nolint:lll directive that was suppressing a non-
  existent violation (the line is 108 chars; the limit is 130).
- #16 new TestInMemoryDCRCredentialStore_ConcurrentAccess fans out
  16 goroutines doing alternating Put/Get against overlapping and
  disjoint keys, with a fail-fast deadline, so go test -race actually
  exercises the sync.RWMutex guard.

New tests cover each behaviour change:

- TestResolveDCRCredentials_SingleflightCoalescesConcurrentCallers
  pins exactly-one-registration under N concurrent callers.
- TestSynthesiseRegistrationEndpoint_PreservesIssuerPath /
  TestResolveUpstreamRedirectURI_PreservesIssuerPath cover the path-
  preservation fix.
- TestApplyResolution_DoesNotOverwritePreProvisionedClientID covers
  the symmetric ClientID write.
- TestResolveDCREndpoints_DirectRegistrationEndpointValidated covers
  the local registration-endpoint guard.
- TestEndpointsFromMetadata_RejectsInsecureDiscoveredEndpoints covers
  the metadata authz/token endpoint guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Gate DCR "none" auth method on S256 PKCE advertisement

RFC 7636 §4.2 / OAuth 2.1 require S256 PKCE for public clients. The
resolver previously accepted the "none" token-endpoint auth method
whenever an upstream advertised it, with no check against
code_challenge_methods_supported. Registering as "none" against an
upstream that only advertises "plain" — or omits the field entirely —
would either break at runtime (our auth-code path always sends
code_challenge_method=S256) or silently downgrade to a non-compliant
plain-PKCE flow.

- dcrEndpoints now carries codeChallengeMethodsSupported, populated
  from metadata.CodeChallengeMethodsSupported in endpointsFromMetadata.
- selectTokenEndpointAuthMethod takes the slice as a second argument
  and skips "none" when S256 is not advertised, falling through to
  the next less-preferred method. When "none" is the only mutually
  supported method and S256 is missing, the function returns an
  explicit error citing the spec so operators see a clear failure
  at boot rather than a silent runtime downgrade.
- TestResolveDCRCredentials_AuthMethodPreference's "falls back to
  none" case now also advertises S256 to reflect the compliant flow.
- New TestResolveDCRCredentials_RefusesNoneWithoutS256 pins the
  rejection in both shapes the upstream can take it (field omitted,
  field lists only plain).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Capture RFC 7591 client_secret_expires_at and refetch on expiry

oauthproto decodes RFC 7591 §3.2.1 client_id_issued_at and
client_secret_expires_at, but buildResolution dropped both. The
authoritative consequence was for client_secret_expires_at: a non-zero
upstream-asserted expiry was invisible to lookupCachedResolution, so
the cache served an expired secret indefinitely, every token-endpoint
call after the upstream's expiry would 401, and the resolver had no
signal to refetch.

The 90-day dcrStaleAgeThreshold added for Step 2g observability is a
separate, heuristic signal ("consider rotating") and does not address
this — the upstream-asserted expiry is authoritative.

- DCRResolution now carries ClientIDIssuedAt and ClientSecretExpiresAt
  as time.Time. The wire convention "0 means absent / does not expire"
  maps to the zero time.Time so callers can use IsZero() uniformly,
  via a small epochSecondsToTime helper.
- buildResolution populates both fields by converting the int64 epoch
  values from the registration response.
- lookupCachedResolution treats an entry with a non-zero
  ClientSecretExpiresAt that has passed as a cache miss, so the
  singleflight body re-runs registerAndCache and overwrites the stale
  entry via the existing cache.Put. A Debug log attributes the
  refetch to client_secret_expires_at so operators can correlate the
  re-registration with the upstream's expiry rather than guessing.

Tests:

- TestBuildResolution_PopulatesRFC7591ExpiryFields covers all three
  shapes (both populated, expires_at omitted, both omitted) and that
  zero on the wire becomes the zero time.Time.
- TestResolveDCRCredentials_RefetchesOnExpiredCachedSecret pins the
  cache-miss-on-expiry behaviour: an upstream that returns an already-
  expired secret causes back-to-back resolver calls to register twice.
- TestResolveDCRCredentials_HonoursFutureExpiryAndZero pins the cache-
  hit path: future expiry and the zero-means-does-not-expire wire
  convention both serve from the cache without re-registering.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Recover panics inside the DCR singleflight closure

singleflight.Group re-panics the leader's panic in every follower, so
without recovery a panic in registerAndCache (or anything it calls —
the registration HTTP exchange, the cache.Put, etc.) would crash the
leader goroutine and every concurrent follower for the same DCRKey
with the same value. Net effect: a single bad upstream response could
take out N goroutines instead of one error path.

- The dcrFlight.Do closure now installs a defer/recover that converts
  a panic into a normal error. The recovered value is logged at
  slog.Error with a full debug.Stack() so the panic is not silently
  swallowed; the returned error wraps the recovered value so callers
  can react to it as a normal failure mode.
- Doc comment on the singleflight call expanded to explain why the
  recover is necessary (the fan-out semantics of singleflight).

Tests:

- panickingPutDCRStore: a new test double whose Put panics with a
  configured value while Get returns a normal cache miss, so callers
  reach the singleflight closure and trigger the panic via cache.Put
  inside registerAndCache.
- TestResolveDCRCredentials_RecoversPanicInsideSingleflight: spawns
  N=6 concurrent callers for the same DCRKey, each with its own
  defer/recover so an un-recovered panic is captured as a test
  failure rather than crashing the suite. Asserts every caller
  received an error containing the panic-marker string and the
  recovered value, and that none of them observed an actual panic.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Tighten singleflight coalescing test to fail loudly on timing slip

The existing assertion "registrationCalls == 1" is necessary but not
sufficient: a goroutine that reached resolveDCRCredentials after the
leader's cache.Put returned would short-circuit through
lookupCachedResolution, take the cache hit, and still leave the count
at 1. Under CI load the 50ms gate window was easy to miss, which would
silently weaken what the test claims to cover.

- Wrap the in-memory store in a countingStore decorator that records
  every Get that returned a hit.
- Assert cache.hits.Load() == 0 after wg.Wait — any non-zero value
  means a late-arriver took the lookupCachedResolution short-circuit
  instead of joining the singleflight, and the coalescing path was
  not actually exercised.
- Bump the gate window from 50ms to 250ms for headroom under CI load.
  The countingStore assertion turns any remaining timing slip into a
  loud failure rather than a silent regression.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Consolidate validateResolveInputs tests into one table

The previous TestResolveDCRCredentials_RequiresClientIDEmpty and
TestResolveDCRCredentials_RequiresDCRConfig each exercised one branch
of validateResolveInputs, leaving three uncovered: nil run-config,
empty issuer, and nil credential store. Per
.claude/rules/testing.md "Consolidation", folding into one table-
driven test covers every branch in one place and shrinks duplicated
setup.

- Replace the two single-branch tests with
  TestResolveDCRCredentials_RejectsInvalidInputs, which iterates over
  all five branches and asserts the wrapped error message contains
  the expected substring drawn from validateResolveInputs's literals.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Note in-memory DCR store is for tests / single-replica dev

Reviewer asked us to confirm the framing and document it on the
constructor. The unbounded-cache concern in .claude/rules/go-style.md
"Resource Leaks" does not bite for this implementation because the
key space is bounded by the operator-configured upstream count and
because Phase 3 Redis is the production answer; the doc now states
that explicitly so a future reader does not assume this is a
production-grade store.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Reject nil resolution in DCRCredentialStore.Put

A nil resolution previously fell through as a silent no-op: the caller
got a successful return, the next Get returned a miss, and there was
no error trail to debug from. Per the constructor-validation rule in
.claude/rules/go-style.md, fail loudly at the boundary.

- inMemoryDCRCredentialStore.Put returns an explicit error when the
  resolution is nil, before taking the lock.
- DCRCredentialStore.Put interface doc records the contract so future
  backends (e.g. the Phase 3 Redis store) behave consistently.
- New TestInMemoryDCRCredentialStore_Put_RejectsNilResolution pins the
  rejection and asserts the rejected Put did not leave any partial
  entry behind.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Disambiguate local vs upstream issuer in DCR resolver

The resolveDCRCredentials doc said "issuer is the upstream authorization
server's issuer identifier used both for discovery and for keying the
cache." That was wrong on both counts: the upstream's issuer is
recovered separately from rc.DCRConfig.DiscoveryURL via
deriveExpectedIssuerFromDiscoveryURL, and the parameter actually names
*this* auth server. An inline comment in registerAndCache already
contradicted the public doc, and a future caller reading only the
public doc would have produced (a) a wrong-origin default redirect URI
under the upstream IdP and (b) a cache key that does not identify the
auth-server context.

Renaming the parameter and documenting the contract closes the trap.

- resolveDCRCredentials: parameter renamed issuer → localIssuer; doc
  rewritten to spell out that it is *this* auth server's issuer, used
  to key the cache and default the redirect URI, and that the
  upstream's issuer is recovered separately. Same rename applied to
  validateResolveInputs, registerAndCache, lookupCachedResolution,
  chooseRegistrationScopes, and resolveUpstreamRedirectURI for
  internal consistency.
- endpointsFromMetadata, synthesiseRegistrationEndpoint: parameter
  renamed issuer → upstreamIssuer (it is in fact the upstream's,
  recovered from the DiscoveryURL) so the local/upstream split is
  symmetric.
- DCRKey.Issuer: doc clarifies the field carries *this* auth server's
  local issuer; two different local issuers registering against the
  same upstream are distinct OAuth clients and must not share cache
  entries.
- Structured-log keys "issuer" → "local_issuer" everywhere the value
  is the local issuer, so operators can tell the two apart in logs
  too.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Require explicit endpoints when DCR bypasses discovery

When dcr_config.registration_endpoint is set, the resolver bypasses
RFC 8414 / OIDC Discovery and therefore cannot populate
authorization_endpoint or token_endpoint from server metadata. The
operator-facing prose on DCRUpstreamConfig already says the run-config
must supply both, but neither validator enforced it. The downstream
effect was silent: dcrEndpoints came back with empty authorize/token
URLs, applyExplicitEndpointOverrides only filled them from rc, and
applyResolution only wrote when rc fields were empty — so a
misconfigured run-config completed registration successfully and only
broke at the first authorize or token-exchange call.

- OAuth2UpstreamRunConfig.Validate now rejects a config that sets
  DCRConfig.RegistrationEndpoint without both AuthorizationEndpoint
  and TokenEndpoint, with an error message that names the field and
  explains the discovery-bypass rationale.
- The discovery-flow path (DCRConfig.DiscoveryURL) is unaffected:
  metadata populates the endpoints there, so leaving them empty in
  the run-config remains valid.
- Existing test case "DCRConfig with only registration_endpoint is
  valid" updated to also set authorize/token endpoints (the path it
  was claiming to cover); two new cases pin the rejection when each
  endpoint is missing; one new case pins that DiscoveryURL is still
  valid without explicit endpoints.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
tgrunnagle added a commit that referenced this pull request Nov 19, 2026
Address review findings on the Entra OBO port so the tests fail when
the behavior they cover breaks, and tighten a few error paths.

Behavior changes:
- #18 Classify HTTP 429, HTTP 408 and the OAuth error
  temporarily_unavailable as transient (the proxy answers 502).
- #29 The vMCP strategy no longer returns Entra's error and
  error_description to MCP clients. It logs the detail server-side and
  returns a generic error that wraps only the entra sentinel.
- #8 The vMCP converter rejects an empty client secret value when it
  resolves the secret. It also rejects a whitespace-only clientId, as
  the operator does.
- #20 Remove the unused entra.Config and entra.New. Production code
  uses TokenURL with NewFromTokenURL; the tests now do too.

Test hardening:
- pkg/auth/obo: #2 provider-mode identities carry an inbound token
  that must not be used as a fallback; #15 DefaultFactory's skew
  wiring; #16 audit event table and port-stripped source; #17 test
  rename, t.Cleanup.
- entra: #3 the body-cap test needs truncation to fail; #4 redirect
  refusal for default and injected clients, 307 and 308; #5 and #21
  more classification rows (2xx with an error member, claims-only,
  AADSTS50079-only, 5xx precedence, lower-case bearer, body read
  failure, zero and negative expires_in).
- cache: #6 timeouts on every blocking wait; #22 coalescing test
  proves followers join the flight; #23 coalesced error, the exact
  skew boundary, TTL shorter than skew, WithClock(nil).
- pkg/runner: #24 RegisterFactory override reaches the runner, and
  assert instead of require in the handler.
- pkg/vmcp/auth: #7 Authenticate error branches and pinned
  config-before-health-check order; #27 env.Reader reaches the
  registered factory; #28 comment fix; #31 and #35 real-builder
  caching per user and skew; #32 exchanger cache key table; #33
  double-checked lock under contention; #34 unset ClientSecretEnv.

Cleanup: #14 move NewInteractionRequiredAuditEvent to audit.go; #19
reword the validateTenant comment; #30a comment the strategy's mu and
exchangers fields separately; #30b make parseResponse a plain function
that takes the receive time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tgrunnagle added a commit that referenced this pull request Nov 23, 2026
* Support Entra OBO backend auth in OSS

Microsoft Entra on-behalf-of was a working strategy only in the private
enterprise overlay; OSS builds exposed the CRD but every dispatch point
returned ErrEnterpriseRequired or a 503 stub. Make it a built-in
strategy for MCPServer, MCPRemoteProxy, VirtualMCPServer and
MCPServerEntry backends (issue #7199):

- Port the Entra exchanger, token cache and exchange contract into
  pkg/auth/obo/{entra,cache,exchange}, kept free of Kubernetes imports
  (guard test), and make the real middleware the default factory.
- Validate obo configs, build the RunConfig middleware and mount the
  client secret in controllerutil. Reject an MCPServer or MCPRemoteProxy
  that references obo without oidcConfigRef as InvalidConfig.
- Add the real vMCP converter and strategy. Mount each OBO backend's
  secret in the vMCP pod under a per-config env var so two OBO backends
  no longer collide on TOOLHIVE_OBO_CLIENT_SECRET.
- Keep RegisterOBOHandler, obo.RegisterFactory, RegisterOBOStrategy,
  ErrEnterpriseRequired and ConditionReasonEnterpriseRequired as
  deprecated overrides so the enterprise overlay keeps compiling until
  it is removed (#7200).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Return 502 when the Entra endpoint times out

The HTTP client's own timeout matches context.DeadlineExceeded, so the
exchanger reported it as caller cancellation and the OBO middleware
wrote no response, giving a still-connected client an empty 200. Only
treat a context error as cancellation when the caller's context is
done; a token endpoint timeout is now a transient failure (502).

Also rename the vMCP env var helper to GenerateUniqueOBOSecretEnvVarName,
the name the issue specifies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix codespell findings in OBO code

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Regenerate swagger and SDK for schema order

Swag orders the awssts schemas differently once the OBO packages are in
the import graph; the content is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep OBO clientSecretEnv unresolved at load

The operator renders inline VirtualMCPServer OBO backends with only
clientSecretEnv. The YAML loader copied the env value into clientSecret
without clearing clientSecretEnv, so the validator and the OBO strategy
rejected the backend as setting both, and vMCP failed at startup. The
loader now only checks the variable is set, as it does for
tokenExchange; the strategy reads it at request time.

Addresses #7201 review comments:
- HIGH pkg/vmcp/config/yaml_loader.go:163 (review body): operator-generated
  inline OBO backends fail vMCP startup validation

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Pin SDK awssts names and fix middleware docs

Swag emits the awssts schemas under their short name once the OBO
packages are in the import graph, which renamed the exported SDK types
(AuthAWSSTSConfig became AWSSTSConfig). The normalizer now maps the
short form to the path form, so the SDK matches main again regardless
of which name swag picks.

docs/middleware.md: fix the audit anchor broken by the renumbering and
list the OBO middleware in the chain overview and execution order.

Addresses #7201 review comments:
- MEDIUM sdk/go/client/oas_schemas_gen.go (review body): swagger
  regeneration renamed exported SDK types
- MEDIUM docs/middleware.md:50 (review body): broken #9-audit-middleware link
- MEDIUM docs/middleware.md:11 (review body): OBO missing from the chain
  overview and execution-order lists

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Address operator review findings for OBO

Review findings on the OBO operator port (PR #7201):

- #10: a mirrored Valid=False/InvalidConfig from a malformed obo source
  was mistaken for a locally-owned failure and stuck on MCPServer and
  MCPRemoteProxy after the source healed to the same spec. Mirrored
  condition messages now carry a fixed prefix, and the mirror clear and
  both same-hash guards skip conditions that carry it.
- #9, #42: Reconcile-level tests for the terminal obo-without-OIDC path
  on MCPServer and MCPRemoteProxy; MCPRemoteProxy now retries when that
  rejection cannot be persisted instead of dropping it.
- #40: split the MCPServer terminal branch into its own early return.
- #41: table-test logOBOSecretEnvVarError redaction, and add an
  MCPRemoteProxy OBO env var error-path test.
- #43, #44, #25, #26: fix stale or inconsistent comments, including the
  deprecation notes and the vMCP exception for registered handlers.
- #37: rename OBOVMCPSecretEnvVar to OBOVMCPSecretEnvVars.
- #36, #38: reject cacheSkew above MaxInt32 seconds as the vMCP
  converter does, and cover blank fields, truncation and Reason.
- #39: append a hash of the raw config name to the vMCP OBO env var so
  names that sanitize alike no longer collide.
- #45: two-OBO-backend cases for the vMCP secret discovery paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Harden OBO tests and error handling

Address review findings on the Entra OBO port so the tests fail when
the behavior they cover breaks, and tighten a few error paths.

Behavior changes:
- #18 Classify HTTP 429, HTTP 408 and the OAuth error
  temporarily_unavailable as transient (the proxy answers 502).
- #29 The vMCP strategy no longer returns Entra's error and
  error_description to MCP clients. It logs the detail server-side and
  returns a generic error that wraps only the entra sentinel.
- #8 The vMCP converter rejects an empty client secret value when it
  resolves the secret. It also rejects a whitespace-only clientId, as
  the operator does.
- #20 Remove the unused entra.Config and entra.New. Production code
  uses TokenURL with NewFromTokenURL; the tests now do too.

Test hardening:
- pkg/auth/obo: #2 provider-mode identities carry an inbound token
  that must not be used as a fallback; #15 DefaultFactory's skew
  wiring; #16 audit event table and port-stripped source; #17 test
  rename, t.Cleanup.
- entra: #3 the body-cap test needs truncation to fail; #4 redirect
  refusal for default and injected clients, 307 and 308; #5 and #21
  more classification rows (2xx with an error member, claims-only,
  AADSTS50079-only, 5xx precedence, lower-case bearer, body read
  failure, zero and negative expires_in).
- cache: #6 timeouts on every blocking wait; #22 coalescing test
  proves followers join the flight; #23 coalesced error, the exact
  skew boundary, TTL shorter than skew, WithClock(nil).
- pkg/runner: #24 RegisterFactory override reaches the runner, and
  assert instead of require in the handler.
- pkg/vmcp/auth: #7 Authenticate error branches and pinned
  config-before-health-check order; #27 env.Reader reaches the
  registered factory; #28 comment fix; #31 and #35 real-builder
  caching per user and skew; #32 exchanger cache key table; #33
  double-checked lock under contention; #34 unset ClientSecretEnv.

Cleanup: #14 move NewInteractionRequiredAuditEvent to audit.go; #19
reword the validateTenant comment; #30a comment the strategy's mu and
exchangers fields separately; #30b make parseResponse a plain function
that takes the receive time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Clear stale OBO incoming-auth rejection on revert

The same-hash guard held the local obo-without-OIDC InvalidConfig after
the referenced config reverted from obo to its earlier spec, because the
rejection returns before the stored hash advances. The guard no longer
holds that condition; it is re-derived on every reconcile.

Addresses #7201 review comments:
- MEDIUM cmd/thv-operator/controllers/mcpserver_controller.go:2580 (4635357068): same-hash guard holds stale local obo InvalidConfig
- LOW cmd/thv-operator/controllers/external_auth_mirror.go:37 (4635357091): document mirrored message format, test prefix invariant
- LOW cmd/thv-operator/controllers/mcpserver_externalauth_test.go:969 (4635357099): test MCPServer terminal status-write failure

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tighten OBO vMCP errors, validation and tests

A rejected client credential now reads as a generic exchange failure to
MCP clients, a whitespace clientId fails strategy validation, and a 429
or 408 with an unparsable body is transient like one with a JSON body.

Addresses #7201 review comments:
- MEDIUM pkg/vmcp/auth/strategies/obo_test.go:699 (4635357079): deterministic exchanger contention test
- MEDIUM pkg/vmcp/config/yaml_loader_test.go:772 (4635357085): loader OBO error-path tests
- LOW docs/middleware.md:529 (4635357111): split the OBO 502 table row
- LOW pkg/auth/obo/entra/exchanger.go:343 (4635357122): unparsable 429/408 is transient
- LOW pkg/vmcp/auth/strategies/obo.go:248 (4635357133): opaque invalid_client error
- LOW pkg/vmcp/auth/strategies/obo.go:322 (4635357139): reject whitespace clientId
- LOW pkg/vmcp/auth/strategies/obo_test.go:460 (4635357146): assert diagnostic log per error class

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Share CA bundle message and tighten operator tests

Addresses #7201 review comments:
- LOW cmd/thv-operator/controllers/external_auth_mirror_test.go:378 (4661456788): controllers and the prefix test share ctrlutil.InvalidCABundleMessage; the CA bundle entry uses InvalidCABundle
- LOW cmd/thv-operator/controllers/mcpserver_controller.go:2571 (4661456797): doc comment names handleExternalAuthConfig
- LOW cmd/thv-operator/controllers/mcpserver_externalauth_test.go:968 (4661456805): missing-config row asserts the not-found error and that no obo rejection is recorded
- LOW docs/arch/09-operator-architecture.md:241 (4661456811): drop change history, note the empty-message form

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Replace OBO test hook with a store seam

Addresses #7201 review comments:
- LOW pkg/vmcp/auth/strategies/obo.go:67 (4661456815): the exchanger map moves behind an unexported oboExchangerStore interface that the contention test wraps, removing the afterReadMiss hook field
- LOW pkg/vmcp/auth/strategies/obo.go:351 (4661456823): a whitespace-only tokenUrl fails validation

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Align OBO test messages and CA bundle doc

Addresses #7201 review comments:
- LOW pkg/vmcp/auth/strategies/obo_test.go:712 (4667645696): barrier
  test messages use the store seam's vocabulary
- LOW cmd/thv-operator/pkg/controllerutil/ca_bundle.go:41 (4667645702):
  doc comment states the mirrored-prefix invariant instead of naming a
  test in another package
- LOW cmd/thv-operator/controllers/mcpserver_externalauth_test.go:1013
  (4667645707): missing-config row asserts no Validated condition

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add OBO 401 challenges and audience as resource

Addresses #7201 review comments (review 6024926356):
- body:www-authenticate: every OBO 401 carries a Bearer invalid_token
  challenge; invalid_grant in upstream-provider mode asks the client to
  re-authenticate with the embedded auth server
- body:audience-scope: a bare audience is sent to Entra as
  <audience>/.default, as MSAL treats a resource; the field docs say so
- body:remote-injector: the remote token injector is skipped when the
  OBO middleware is present, not only token exchange
- body:docs: docs/middleware.md section 9 records the 403 departure from
  Microsoft's insufficient_claims guidance; disableUpstreamTokenInjection
  lists OBO among the incompatible middlewares

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Default OBO subject provider behind auth server

Addresses #7201 review comments (review 6024926356):
- body:subject-provider: vMCP defaults an empty obo
  subjectTokenProviderName to the embedded auth server's upstream, and
  rejects it as ambiguous with more than one upstream, as xaa does; the
  proxy runner defaults it to the upstream the upstream swap middleware
  uses, so OBO no longer sends ToolHive's session JWT to Entra

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tighten OBO secret, skew and token URL checks

Addresses #7201 review comments (review 6024926356):
- body:empty-secret: verifyOBOClientSecret rejects an empty Secret value,
  which the proxy's middleware factory would refuse at startup
- body:skew-bound: MiddlewareParameters.Validate caps cacheSkewSeconds at
  MaxInt32, the operator's bound, so a hand-written RunConfig cannot
  overflow time.Duration in cache.New
- body:token-url: the vMCP strategy validates tokenUrl with
  entra.ValidateTokenURL, so a relative or non-https URL fails Validate
  instead of passing health checks and failing every call
- body:env-var-cases: TestAddOBOSecretEnvVars covers every external auth
  type again

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Share OBO exchanger builder and drop stale ones

Addresses #7201 review comments (review 6024926356):
- body:shared-builder: obo.NewCachedExchanger builds the cached Entra
  exchanger for both the proxy middleware and the vMCP strategy, so the
  two no longer need a comment asking to keep them in parity
- body:store: the vMCP exchanger store is a mutex and a map; building
  does no I/O, so the read-write lock and double check are gone
- body:eviction: a new client secret for a client the strategy already
  serves replaces the exchanger built with the old secret, so a rotation
  does not leave the old secret and its cached tokens in memory

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Document OBO limits and runner default choice

Addresses #7201 review comments:
- LOW mcpexternalauthconfig_types.go:269 (4669447143): CacheSkew doc
  states the math.MaxInt32 bound; vMCP OBOConfig comment mirrors it
- LOW docs/arch/10-virtual-mcp-architecture.md:1091 (4669447157): one
  exchanger per client replaced on rotation, subject default, audience
- LOW docs/middleware.md:532 (4669447171): split the invalid_grant row
  by subject source
- LOW pkg/auth/obo/middleware.go:290 (4669447186): state that the
  re-auth challenge does not cure missing consent
- LOW pkg/runner/middleware.go:317 (4669447223): state the deliberate
  first-upstream divergence from vMCP and why

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Strengthen OBO tests the review found loose

Addresses #7201 review comments:
- LOW pkg/auth/obo/middleware_test.go:673 (4669447196): exact-match the
  upstream re-auth challenge and body; declare challenges up front
- LOW pkg/auth/obo/parameters_test.go:52 (4669447206): table test for
  exchange.Target, including "/" and a ".default/" audience
- LOW pkg/runner/middleware_test.go:471 (4669447240): several, unnamed
  and zero upstreams, and a non-OBO middleware beside an OBO one
- LOW pkg/runner/middleware_test.go:471 (4669447257): non-object and
  non-string parameter errors, and null parameters
- LOW pkg/vmcp/auth/strategies/obo_test.go:646 (4669447271): hold the
  first build open so a lost lock yields one build per caller
- LOW pkg/vmcp/auth/strategies/obo_test.go:685 (4669447286): a failed
  build for a rotated secret keeps the working Exchanger

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants