Skip to content

Support Entra on-behalf-of backend auth in OSS - #7201

Merged
tgrunnagle merged 19 commits into
mainfrom
tgrunnagle/7199-oss-entra-obo
Nov 23, 2026
Merged

tgrunnagle merged 19 commits into
mainfrom
tgrunnagle/7199-oss-entra-obo

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Entra on-behalf-of (OBO) was declared in the CRDs but inert in OSS. Every runtime dispatch point was a stub that returned ErrEnterpriseRequired (operator) or a 503 (proxy), so an obo MCPExternalAuthConfig showed Valid=False / Reason=EnterpriseRequired. OBO is now a community feature, so this PR makes it a working built-in strategy.
  • Adds the Entra exchanger (RFC 7523 jwt-bearer grant with requested_token_use=on_behalf_of), a per-(user token hash, exchange target) token cache, and the real proxy middleware under pkg/auth/obo/.... These packages do not link Kubernetes; a guard test enforces that.
  • Implements OBO validation, RunConfig generation and secret env var injection in the operator for MCPServer and MCPRemoteProxy, and a real converter and outgoing strategy for VirtualMCPServer backends (inline, discovered, and MCPServerEntry).
  • Rejects an obo config on an MCPServer or MCPRemoteProxy that has no oidcConfigRef with InvalidConfig. OBO needs an authenticated user token, and without this check every request would fail with 401 at runtime.
  • Fixes a collision in the port: two OBO backends in one vMCP would have shared one secret env var name. vMCP now uses a per-config name with a short hash of the config name, so even names that sanitize alike (my-cfg, my.cfg) stay distinct.
  • The old hooks (RegisterOBOHandler, obo.RegisterFactory, auth.RegisterOBOStrategy, ErrEnterpriseRequired, ConditionReasonEnterpriseRequired) stay exported and marked Deprecated:. Removal is tracked in Remove deprecated OBO enterprise hooks and sentinels #7200.

Closes #7199

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint)
  • Manual testing (describe below)

Also run: task operator-test-integration (envtest), task license-check and task docs-verify. Results are quoted under Verification. task test-e2e was not run.

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.

No field, type, enum value or validation marker changed. The CRD diffs are description text only (the "requires an enterprise build" wording is removed).

Changes

Area Change
pkg/auth/obo/exchange New stdlib-only leaf package: Token, Exchanger, TokenExchanger, Target(audience, scopes). Target sends space-joined scopes, or else the audience as <audience>/.default. The package exists to avoid an obo -> entra -> obo import cycle.
pkg/auth/obo/entra Entra exchanger: tenant (GUID or domain) and authority validation, token URL construction, error classification (interaction_required / claims challenge / AADSTS50076 and 50079, invalid_grant, invalid_client, transient including 429, 408 and temporarily_unavailable), redirects refused, 1 MiB response cap. The constructor is NewFromTokenURL(TokenURL(tenant, authority), ...).
pkg/auth/obo/cache Token cache with expiry skew; concurrent identical exchanges share one request; recovers from a panicking delegate.
pkg/auth/obo MiddlewareParameters with Validate / ExchangeTarget. DefaultFactory is the real middleware and the default behind CreateMiddleware. NewCachedExchanger builds the cached Entra exchanger for both the middleware and the vMCP strategy. Guard test TestPackages_DoNotLinkKubernetes.
pkg/runner/middleware.go Registers the real OBO factory. Behind an embedded auth server, defaults an empty OBO subjectTokenProviderName to the upstream that upstream swap uses.
pkg/transport/http.go The remote token injector is skipped when the OBO middleware is present, as it already was for token exchange.
cmd/thv-operator/pkg/controllerutil/obo.go OBO validate, RunConfig and secret env var generation, called from the existing ExternalAuthType switches. OBOHandler in tokenexchange.go is now a deprecated override of the built-in.
cmd/thv-operator/controllers MCPExternalAuthConfig: *obo.ValidationError maps to InvalidConfig with no requeue, other errors requeue. MCPServer and MCPRemoteProxy: terminal ExternalAuthConfigValidated=False / InvalidConfig without oidcConfigRef. VirtualMCPServer: per-config OBO secret env vars. Mirrored source conditions carry a Referenced MCPExternalAuthConfig '<name>' is invalid: message prefix so they are not mistaken for a consumer's own validation failure (now that an invalid obo source reports InvalidConfig).
cmd/thv-operator/pkg/vmcpconfig/converter.go Inline OBO backends get the per-config secret env var name.
pkg/vmcp/auth/converters/obo.go Real OBOConverter: CRD to authtypes.OBOConfig (tenant/authority to token URL, cacheSkew to seconds); ResolveSecrets reads the client secret.
pkg/vmcp/auth/strategies/obo.go Real strategy: one cached exchanger per (token URL, client, skew, secret fingerprint), and a new secret for the same client replaces the old exchanger; Validate checks the tokenUrl shape; skips health checks; audit event on interaction required. The error returned to MCP clients wraps only the failure sentinel; Entra's detail goes to the log. factory.NewOutgoingAuthRegistry registers it through auth.NewOBOStrategy, which returns this strategy unless the deprecated override is set.
pkg/vmcp/auth/types/defaults.go DefaultSubjectProviderName defaults an empty obo subjectTokenProviderName to the embedded auth server's upstream, and returns ErrAmbiguousSubjectProvider with more than one, as xaa does.
pkg/vmcp/config/yaml_loader.go OBO clientSecretEnv is checked but no longer copied into clientSecret, so the operator-rendered inline config passes the validator (as tokenExchange already did).
cmd/help/openapi-normalize Maps swag's short awssts.* schema names to the path form, so the generated SDK keeps AuthAWSSTSConfig and friends regardless of which name swag emits once the OBO packages are in the import graph.
pkg/vmcp/auth/obo.go The ErrEnterpriseRequired stub is removed. NewOBOStrategy is kept and returns the built-in strategy; RegisterOBOStrategy is deprecated but still overrides.
CRDs, docs/operator/crd-api.md, chart CRD copies Regenerated from the updated Go doc comments.
docs/middleware.md, docs/arch/09, docs/arch/10 New OBO middleware section (renumbers the following sections) and operator and vMCP architecture updates.
Tests Unit tests for exchanger, cache, middleware, parameters, converter, strategy and operator. Envtest obo_reconcile_test.go for Valid=True / InvalidConfig. vMCP integration test test/integration/vmcp/obo_integration_test.go against a mock Entra token endpoint, including YAML loader → validator → strategy for an inline backend. Tests that asserted EnterpriseRequired are rewritten.

Does this introduce a user-facing change?

Yes.

  • Before: an obo MCPExternalAuthConfig showed Valid=False / Reason=EnterpriseRequired. Proxies returned 503 for OBO, and vMCP backends failed to authenticate.
  • After: a well-formed obo config reconciles to Valid=True. OBO works for MCPServer, MCPRemoteProxy, VirtualMCPServer and MCPServerEntry backends. A config with a missing tenant, client ID or client secret ref, with neither audience nor scopes, or with a negative cacheSkew or one above MaxInt32 seconds shows Valid=False / Reason=InvalidConfig. An MCPServer or MCPRemoteProxy that references an obo config without oidcConfigRef shows ExternalAuthConfigValidated=False / Reason=InvalidConfig. A referenced client Secret whose key is missing or empty holds the workload back (requeued) instead of producing a pod that crash-loops.
  • audience is a resource (Application ID URI or client ID) and is sent to Entra as <audience>/.default; specific delegated permissions go in scopes.
  • Behind an embedded auth server, an omitted subjectTokenProviderName defaults to the auth server's upstream on proxies and on vMCP, so the subject is the upstream IdP token rather than ToolHive's session token. A VirtualMCPServer whose embedded auth server has more than one upstream must set it (AmbiguousSubjectProvider). A proxy takes the first upstream, as upstream swap does; the operator admits only one upstream for MCPServer and MCPRemoteProxy, so that case does not arise through it.
  • Proxy runtime: the middleware replaces Authorization with the exchanged token. Failure responses are generic: 401 with a WWW-Authenticate: Bearer error="invalid_token" challenge for a missing token or invalid_grant (a re-authentication challenge in upstream-provider mode; that challenge cures an expired token but not missing consent, which Entra also reports as invalid_grant), 403 plus an obo_token_exchange audit event for a conditional-access or claims challenge, 502 for invalid_client, Entra 5xx, 429, 408, temporarily_unavailable, timeouts or unclassified failures (a throttled reply is a 502 whatever its body; Entra's Retry-After is not forwarded). These are documented in docs/middleware.md section 9, which also explains why the 403 departs from Microsoft's insufficient_claims 401 guidance.
  • vMCP: a failed OBO exchange returns a generic error to the MCP client without Entra's error code or error_description. It names at most the failure class (denied, invalid grant, transient); a rejected client credential reads as a plain obo: token exchange failed, matching the proxy's opaque 502; the detail is logged by vMCP (DEBUG for invalid_grant, WARN otherwise), and conditional-access denials are audited as on the proxy. Each OBO backend's secret is mounted on the vMCP pod as TOOLHIVE_OBO_CLIENT_SECRET_<CONFIG_NAME>_<HASH8>.
  • Mirrored condition message on MCPServer and MCPRemoteProxy (any external auth type). Before: ExternalAuthConfigValidated=False carried the referenced config's message verbatim. After: Referenced MCPExternalAuthConfig '<name>' is invalid: <source message>. The condition clears when the source becomes valid again, and the consumer's own obo-without-OIDC rejection clears when the source stops being obo, even if it returns to a spec with the same ConfigHash.
  • thv run has no OBO flags (out of scope). A RunConfig carrying the middleware config works.

Special notes for reviewers

  • Size: this goes past the 400-line / 10-file guideline on purpose. Splitting it would leave OBO half-working across releases. The size limit was waived for a single PR (decision recorded on the issue).
  • Deprecated hooks keep working as overrides. If the enterprise overlay registers RegisterOBOHandler, obo.RegisterFactory or auth.RegisterOBOStrategy, its implementation wins over the built-in. That keeps the overlay compiling and behaving until it is deleted. One deliberate exception: a registered OBOHandler.SecretEnvVars does not apply to VirtualMCPServer, which always uses the per-config name so OBO backends cannot collide (stated in the Deprecated: notes).
  • Secret env var names. Proxy pods use the fixed TOOLHIVE_OBO_CLIENT_SECRET (one OBO config per proxy). vMCP uses GenerateUniqueOBOSecretEnvVarName(configName) (sanitized name plus the first 8 hex characters of its SHA-256), via OBOVMCPSecretEnvVars. The other generators (token exchange, XAA, header injection) share the sanitize-only weakness; that is pre-existing and left alone here. The vMCP converter leaves ClientSecretEnv empty and the two inline enrichment sites set it (the VirtualMCPServer controller and the vmcpconfig converter); discovered mode uses ResolveSecrets.
  • Terminal vs transient errors. *obo.ValidationError is a terminal InvalidConfig (no requeue). Anything else, such as a Secret not yet available, requeues.
  • Deviations from sibling code paths. The OBO converter rejects a clientSecretRef that resolves to an empty value at ResolveSecrets (the other converters defer that to request time), and a whitespace-only clientId, matching the operator; the vMCP strategy's Validate rejects a whitespace-only clientId or tokenUrl too, and a relative or non-https tokenUrl (the check the proxy applies at startup), for inline configs that skip the converter. The vMCP strategy validates config before the health-check skip, as token exchange does, so a misconfigured OBO backend fails its health probe. MCPRemoteProxy now returns the status-write error when recording an InvalidConfig rejection, so a failed write is retried, as MCPServer already did.
  • The runner reads the OBO parameters once. It deliberately takes the first upstream where vMCP returns ErrAmbiguousSubjectProvider; the comment on defaultOBOSubjectProvider says why. AdditionalMiddlewareConfigs are otherwise spliced in verbatim, but the runner fills in an empty subjectTokenProviderName behind an embedded auth server. It is the one place that sees both the auth server's upstreams and the OBO config. The operator's ApplyRunConfig does not see authServerRef, and that hook's signature is kept for the deprecated override. The serialized carrier keeps the operator's original, and keys the runner does not know are kept.
  • Removed exported API. entra.Config and entra.New are gone; nothing in this repo used them, and entra.NewFromTokenURL(entra.TokenURL(tenant, authority), ...) covers the same case. The package is new in OSS, so no released caller exists.
  • Hash suffix on vMCP OBO env vars only. The sibling generators (token exchange, XAA, header injection) keep their sanitize-only names, which stay byte-identical for existing pods; OBO is new, so it takes the collision-safe form from the start.
  • Pre-existing divergence kept. AddOBOSecretEnvVars no longer swallows errors. The MCPServer builder logs and continues while the drift check returns true. This divergence already existed and is documented at the site.
  • Deviation from the issue text: chart version not bumped. operator-crds Chart.yaml only changes in release PRs (git log shows only "Release vX" commits touching it), so the CRD files and templates are regenerated but the version is not bumped.
  • Deviation from the issue text: docs/remote-mcp-authentication.md not changed. It documents the CLI's client-side remote MCP auth and has no external-auth content. The OBO docs went to docs/middleware.md, docs/arch/09-operator-architecture.md and docs/arch/10-virtual-mcp-architecture.md.
  • Out of scope: thv run CLI flags for OBO, and certificate or workload-identity client authentication for Entra.
  • Related: Remove deprecated OBO enterprise hooks and sentinels #7200 (remove deprecated hooks), Document Entra OBO backend auth for community ToolHive docs-website#1360 (user docs).

Verification

Run at 825d5ec:

  • task lint: exit 0, "0 issues."
  • task test: exit 0, no FAIL or DATA RACE lines
  • task docs-verify: exit 0
  • task license-check: exit 0

Run at ec67b63 (the later commits change only comments, CRD description text and tests outside the operator):

  • task operator-test-integration: exit 0, "Ginkgo ran 12 suites ... Test Suite Passed"

Acceptance criteria:

  1. Valid=True / InvalidConfig: TestMCPExternalAuthConfigReconciler_OBO_Validation; envtest obo_reconcile_test.go ("reconciles a well-formed obo config to Valid=True", DescribeTable for missing tenant, client ID, secret ref and target).
  2. RunConfig, env var and exchange for MCPServer / MCPRemoteProxy: TestAddExternalAuthConfigOptions_OBO; TestMCPServerDeployment_OBOSecretEnvVars; TestMCPRemoteProxyDeployment_OBOSecretEnvVars; runner TestOBORegistration (mock Entra, header replaced); pkg/auth/obo middleware tests.
  3. No oidcConfig gives InvalidConfig: TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth; MCPRemoteProxy table cases; TestAddExternalAuthConfigOptions_OBOErrors; envtest "rejects an MCPServer ... without oidcConfigRef".
  4. vMCP inline and discovered (including MCPServerEntry via DiscoverAndResolveAuth), distinct env vars: test/integration/vmcp TestOBOIntegration_DiscoveredAuthPath, TestOBOIntegration_InlineTwoBackends and TestOBOIntegration_InlineConfigFileLoad; operator TestDiscoverExternalAuthConfigSecrets_TwoOBOBackends; TestGetExternalAuthConfigSecretEnvVars_OBO; TestConvertExternalAuthConfigToStrategy (obo case); vmcpconfig TestConvertExternalAuthConfigToStrategy_OBOUsesPerConfigSecretEnv.
  5. No ErrEnterpriseRequired or 503 in OSS: git grep shows ErrEnterpriseRequired only declared (deprecated) in pkg/auth/obo/errors.go; the stub is removed; TestNewOutgoingAuthRegistry "obo strategy is the built-in Entra OBO strategy".
  6. Kubernetes-free: pkg/auth/obo TestPackages_DoNotLinkKubernetes.
  7. Tests ported and updated: entra, cache, middleware, parameters, converter, strategy and operator unit tests; envtest and vMCP integration tests added; EnterpriseRequired tests rewritten. Review-fix coverage: TestMiddleware_ContextErrors, TestExchanger_ExchangeToken_ClientTimeoutIsTransient.
  8. CRDs, CRD API doc and architecture docs regenerated or updated. Chart version not bumped (see special notes).

Breaking changes

None for the v1beta1 API. Observable change: the operator no longer emits Reason=EnterpriseRequired; the exported identifiers that referenced it remain, deprecated.

🤖 Generated with Claude Code

tgrunnagle and others added 2 commits November 19, 2026 10:31
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]>
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]>
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 19, 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 Nov 19, 2026
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.03665% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.80%. Comparing base (4dcddda) to head (825d5ec).
⚠️ Report is 24 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/obo/entra/exchanger.go 96.50% 5 Missing ⚠️
cmd/thv-operator/pkg/controllerutil/obo.go 96.73% 3 Missing ⚠️
pkg/auth/obo/entra/errors.go 91.66% 2 Missing ⚠️
pkg/runner/middleware.go 93.93% 2 Missing ⚠️
...-operator/controllers/mcpremoteproxy_controller.go 96.42% 1 Missing ⚠️
cmd/thv-operator/pkg/vmcpconfig/converter.go 75.00% 1 Missing ⚠️
pkg/vmcp/auth/strategies/obo.go 99.18% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7201      +/-   ##
==========================================
+ Coverage   81.60%   81.80%   +0.19%     
==========================================
  Files         898      912      +14     
  Lines       91482    92517    +1035     
==========================================
+ Hits        74651    75679    +1028     
- Misses      16826    16833       +7     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 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.

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]>
@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 Nov 19, 2026

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

Review

This is a new-feature PR (about 8.5k changed lines, of which roughly 5.2k are tests and 1.8k are generated) that moves Entra on-behalf-of from a private overlay into OSS: the Kubernetes-free pkg/auth/obo/{entra,cache,exchange} packages, the proxy middleware, operator validation, RunConfig and secret env var generation, and the vMCP converter and strategy. The approach is sound and matches the issue's design. Exchange failures fail closed, proxy response bodies are generic, the token cache is keyed per (user token hash, audience) with shared in-flight exchanges, redirects are refused, the client secret travels only as an env var name, and the deprecated hooks keep compiling and overriding. The main concern is that an inline outgoingAuth OBO backend on a VirtualMCPServer fails vMCP startup validation (finding 1), so the issue's fourth acceptance criterion is not met end to end. The remaining findings are mostly tests that would still pass if the source they cover were broken, plus a few documentation and PR-description inaccuracies.

Cross-cutting observations

  • Inline vMCP path. The operator emits only clientSecretEnv for inline OBO backends. The pre-existing YAML loader resolves it into clientSecret without clearing the env field, and the validator and the new parseOBOConfig reject both being set. The vMCP integration test constructs the strategy directly, and no test runs loader, then validator, then strategy, which is why it passed. Discovered mode is unaffected.
  • Test strength. Much of the suite is strong: the Entra error classification matrix, middleware status mapping, non-disclosure checks, cache isolation and expiry, operator validation, and the deprecated-override tests all assert real behaviour. The gaps are specific branches whose tests would stay green if the source were broken (the 2xx-with-error body, the response-size cap, redirect refusal on the default client, upstream-provider mode falling back to the inbound token) and missing Reconcile-level assertions for the new terminal no-requeue handling.
  • Mirrored conditions. A malformed obo source now surfaces InvalidConfig, the same reason the consumer controllers treat as locally owned. Reverting a source to its exact last-valid spec appears to leave a stale Valid=False on MCPServer and MCPRemoteProxy consumers, and the mirror tests use a fake reason that avoids this path.
  • Backwards compatibility. The deprecated hook signatures are unchanged, but a registered OBOHandler.SecretEnvVars no longer applies on the vMCP path, and the regenerated swagger renames exported types in the separate sdk/go module (wire format unchanged). Neither is called out in the PR description, which also says the factory "registers it directly" (it goes through auth.NewOBOStrategy) and cites a function name that does not exist.
  • Documentation. docs/middleware.md has a broken #9-audit-middleware link after the renumbering, and the chain overview and execution-order lists do not mention OBO.
  • Instruction files. The diff does not change any CLAUDE.md, AGENTS.md or .claude/rules/ file.

Findings

# Severity Finding Location Raised by
1 HIGH Operator-generated inline OBO backends fail vMCP startup validation pkg/vmcp/config/yaml_loader.go:163 correctness-operator-vmcp
2 MEDIUM Upstream-provider mode 'must not fall back to the inbound token' is not pinned by tests pkg/auth/obo/middleware.go:222 tests-obo
3 MEDIUM Response-size-cap test would pass even if the 1 MiB cap were removed pkg/auth/obo/entra/exchanger.go:326 tests-obo
4 MEDIUM Redirect refusal tested only for a caller-injected client, not the default client production uses pkg/auth/obo/entra/exchanger.go:243 tests-obo
5 MEDIUM A 2xx response carrying an OAuth error field is untested pkg/auth/obo/entra/exchanger.go:396 tests-obo
6 MEDIUM Concurrent cache tests block on bare channel receives/WaitGroup with no timeout (testing.md violation) pkg/auth/obo/cache/cache.go:202 tests-obo
7 MEDIUM Authenticate error branches of the vMCP strategy are untested pkg/vmcp/auth/strategies/obo.go:107 tests-vmcp
8 MEDIUM ResolveSecrets test asserts ClientSecretEnv is cleared but the input never sets it; several branches untested pkg/vmcp/auth/converters/obo.go:148 tests-vmcp
9 MEDIUM MCPServer.Reconcile terminal branch for obo ValidationError has no test asserting no requeue cmd/thv-operator/controllers/mcpserver_controller.go:400 tests-operator
10 MEDIUM A stale Valid=False / InvalidConfig can stay mirrored onto consumers after the OBO source heals cmd/thv-operator/controllers/external_auth_mirror.go:93 tests-operator
11 MEDIUM Regenerated swagger renames exported SDK types; the commit and PR body describe it as a reorder sdk/go/client/oas_schemas_gen.go api-design
12 MEDIUM docs/middleware.md links to #9-audit-middleware, which no longer exists after renumbering docs/middleware.md:50 readability, scope
13 MEDIUM OBO middleware is missing from the chain overview and execution-order lists in docs/middleware.md docs/middleware.md:11 readability
14 LOW Exported NewInteractionRequiredAuditEvent sits below private helpers pkg/auth/obo/middleware.go:307 readability
15 LOW DefaultFactory CacheSkewSeconds-to-cache wiring is never exercised with a positive value pkg/auth/obo/middleware.go:144 tests-obo
16 LOW Interaction-required audit event details only partly asserted pkg/auth/obo/middleware.go:307 tests-obo
17 LOW Test naming/cleanup nits in middleware_test.go (name/comment mismatch, defer srv.Close in parallel test) pkg/auth/obo/middleware_test.go:197 tests-obo
18 LOW HTTP 429/408 from Entra classified as permanent KindUnknown instead of transient pkg/auth/obo/entra/exchanger.go:429 correctness-obo
19 LOW validateTenant comment refers to a 'previous, looser check' that does not exist in this repo pkg/auth/obo/entra/exchanger.go:256 readability
20 LOW entra.Config and entra.New have no production caller and duplicate NewFromTokenURL pkg/auth/obo/entra/exchanger.go:132 readability, scope
21 LOW Interaction-required fallbacks and success-path variants not individually covered pkg/auth/obo/entra/exchanger.go:459 tests-obo
22 LOW Concurrent-coalescing cache test does not reliably fail if single-flight is broken pkg/auth/obo/cache/cache.go:147 tests-obo
23 LOW Coalesced-error path and skew boundaries untested in cache pkg/auth/obo/cache/cache.go:178 tests-obo
24 LOW Runner-level test no longer pins that the factory map dispatches through obo.CreateMiddleware (override path) pkg/runner/middleware.go:44 tests-obo
25 LOW Inconsistent deprecation lifetime wording across deprecated symbols cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go:2592 api-design
26 LOW Registered OBOHandler.SecretEnvVars no longer applies on the vMCP path, contradicting 'overrides keep winning' cmd/thv-operator/pkg/controllerutil/obo.go:165 api-design
27 LOW NewOBOStrategy forwarding of env.Reader to a registered override is no longer tested pkg/vmcp/auth/obo.go:42 tests-vmcp
28 LOW Factory test comment disagrees with its assertion and PR body says 'registers it directly' while code goes through auth.NewOBOStrategy pkg/vmcp/auth/factory/outgoing.go:76 tests-vmcp
29 LOW vMCP OBO strategy surfaces Entra's raw error description to MCP clients pkg/vmcp/auth/strategies/obo.go:218 security
30 LOW exchangers field comment sits above mu; parseResponse comment gives a reason that does not hold pkg/vmcp/auth/strategies/obo.go:59 readability
31 LOW No test pins that the vMCP strategy wraps the Entra exchanger in the token cache pkg/vmcp/auth/strategies/obo.go:260 tests-vmcp
32 LOW Exchanger cache key (token URL/client/skew/secret fingerprint) untested except 'same config builds once' pkg/vmcp/auth/strategies/obo.go:324 tests-vmcp
33 LOW No concurrency test for getOrCreateExchanger's double-checked lock pkg/vmcp/auth/strategies/obo.go:189 tests-vmcp
34 LOW Unset or empty ClientSecretEnv branch of the vMCP strategy is untested pkg/vmcp/auth/strategies/obo.go:172 tests-vmcp
35 LOW Real-exchanger skew test passes even if the skew gate is removed pkg/vmcp/auth/strategies/obo.go:266 tests-vmcp
36 LOW cacheSkew upper bound enforced by the vMCP converter but not by operator OBO validation cmd/thv-operator/pkg/controllerutil/obo.go:239 correctness-operator-vmcp
37 LOW OBOVMCPSecretEnvVar has a singular name but returns a slice; PR body cites a function name that does not exist cmd/thv-operator/pkg/controllerutil/obo.go:165 api-design
38 LOW OBO validation edge cases and reconcile-level cases untested cmd/thv-operator/pkg/controllerutil/obo.go:229 tests-operator
39 LOW Per-config vMCP secret env var names can collide (my-cfg vs my.cfg) cmd/thv-operator/pkg/controllerutil/externalauth.go:80 security, tests-operator
40 LOW Repeated 'if terminal' branching makes the MCPServer external-auth error path hard to follow cmd/thv-operator/controllers/mcpserver_controller.go:389 readability
41 LOW logOBOSecretEnvVarError redaction behaviour untested; MCPRemoteProxy has no error-path test for the OBO env var cmd/thv-operator/controllers/mcpserver_controller.go:1204 tests-operator
42 LOW MCPRemoteProxy.Reconcile terminal (no-requeue) handling of obo-without-oidcConfigRef is untested cmd/thv-operator/controllers/mcpremoteproxy_controller.go:190 tests-operator
43 LOW Stale comment still describes the removed registered-OBO-handler dispatch in the MCPRemoteProxy deployment builder cmd/thv-operator/controllers/mcpremoteproxy_deployment.go:311 correctness-operator-vmcp
44 LOW triageOBOValidation is now a one-line wrapper over applyOBOValidationResult cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go:365 readability, scope
45 LOW No test builds the vMCP pod env vars for two OBO backends cmd/thv-operator/controllers/virtualmcpserver_deployment.go:590 tests-operator

Additional findings

These sit outside the changed lines of the diff, or too far from the nearest changed line for an inline comment.

  • [HIGH] Operator-generated inline OBO backends fail vMCP startup validation (pkg/vmcp/config/yaml_loader.go:163): For an inline (outgoingAuth) OBO backend the operator writes only clientSecretEnv into the vMCP ConfigMap and mounts the Secret under that env var. At startup YAMLLoader.Load (pkg/vmcp/config/yaml_loader.go:163-169) copies the env value into obo.ClientSecret but leaves ClientSecretEnv set, and DefaultValidator.Validate (validator.go:307-308) then rejects the strategy with "clientSecret and clientSecretEnv are mutually exclusive", so thv vmcp serve and thv vmcp validate abort. The new parseOBOConfig (pkg/vmcp/auth/strategies/obo.go:287) enforces the same rule on every request. Discovered mode is unaffected because ResolveSecrets clears ClientSecretEnv. The loader and validator lines are outside this diff and predate it, but this PR is what makes the path reachable. No test runs loader, then validator, then strategy for OBO, and the vMCP integration test builds the strategy directly, so it never reaches the loader. This was traced by reading the code, not by running it. Recommendation: Drop the copy at yaml_loader.go:168 as the token-exchange case does (yaml_loader.go:136-142 only checks the env var is set and OBOStrategy.resolveClientSecret reads it at request time), or set obo.ClientSecretEnv = "" after resolving. Add a test that loads YAML with clientSecretEnv, runs the validator, then OBOStrategy.Validate. Raised by: correctness-operator-vmcp.
  • [MEDIUM] A stale Valid=False / InvalidConfig can stay mirrored onto consumers after the OBO source heals (cmd/thv-operator/controllers/external_auth_mirror.go:93) (outside the changed lines of the diff, so no inline comment): Before this PR an obo source surfaced EnterpriseRequired; now a malformed one surfaces InvalidConfig, the reason ownedByLocalValidation (external_auth_mirror.go:93) and setMCPServerExternalAuthConfigValidCondition treat as locally owned. Sequence: the source goes invalid, the consumer mirrors False/InvalidConfig and its stored hash stays at the last-valid hash; the user reverts the source to that exact last-valid spec, so the source is Valid=True with the same hash; the mirror is nil but ownedByLocalValidation is true, so the condition is not removed, and setMCPServerExternalAuthConfigValidCondition sees the same reason, generation and hash and returns early without writing True. Editing the source to a different spec changes the hash and clears it. MCPRemoteProxy behaves the same. All mirror tests use a fake SourceRejected reason and never cover this sequence. Recommendation: Add tests with a real obo source going InvalidConfig, then back to the same spec, for MCPServer and MCPRemoteProxy. If the condition stays False, distinguish locally owned from mirrored InvalidConfig at both same-hash guard sites. Raised by: tests-operator.
  • [MEDIUM] Regenerated swagger renames exported SDK types; the commit and PR body describe it as a reorder (sdk/go/client/oas_schemas_gen.go): The Regenerate swagger and SDK for schema order commit is not a pure reorder. In docs/server/swagger.yaml the components github_com_stacklok_toolhive_pkg_auth_awssts.Config and .RoleMapping become awssts.Config and awssts.RoleMapping, and in the separate sdk/go module the exported AuthAWSSTSConfig, AuthAWSSTSRoleMapping and OptAuthAWSSTSConfig become AWSSTSConfig, AWSSTSRoleMapping and OptAWSSTSConfig, with the RunnerRunConfig getter and setter signatures changing. The JSON wire format is unchanged. The cause is swag switching between long and short schema names when the new pkg/auth/obo/... packages enter the import graph, so the SDK surface depends on which packages the generator happens to load. The PR body's API Compatibility section covers only the CRDs. cmd/help/openapi-normalize/main_test.go:136 also still maps the long name to AuthAWSSTSConfig. The commit message body was not read during verification. Recommendation: State the rename in the PR body and decide whether the SDK break is acceptable. Better, pin the name (an explicit mapping in cmd/help/openapi-normalize/main.go or a swag @name override on awssts.Config) so it cannot flip again. Raised by: api-design.
  • [MEDIUM] docs/middleware.md links to #9-audit-middleware, which no longer exists after renumbering (docs/middleware.md:50) (outside the changed lines of the diff, so no inline comment): The new ### 9. On-Behalf-Of (OBO) Middleware section renumbers Audit to 10, Recovery to 11 and Header Forward to 12. The webhook section at line 50 still links #9-audit-middleware; it is the only broken link (the anchors used from docs/arch/02, 03 and vmcp-library still resolve). Recommendation: Change the link to #10-audit-middleware, or append the OBO section as 13 so nothing is renumbered. Raised by: readability, scope.
  • [MEDIUM] OBO middleware is missing from the chain overview and execution-order lists in docs/middleware.md (docs/middleware.md:11) (outside the changed lines of the diff, so no inline comment): The new OBO section says it runs after authentication and before recovery, but the component list (lines 11-23) and the "Middleware Execution Order" list (lines 1233-1247, "steps 1-15", plus the ordering rules and the step count at line 1264) do not mention it. pkg/runner/middleware.go:263-281 splices AdditionalMiddlewareConfigs after awssts and header-forward and before recovery. CLAUDE.md asks for observable behaviour to be documented on the subsystem page. Recommendation: Add OBO to both lists with an ordering note that it needs the authentication middleware's identity, and update the step count. Raised by: readability.
  • [LOW] Runner-level test no longer pins that the factory map dispatches through obo.CreateMiddleware (override path) (pkg/runner/middleware.go:44) (outside the changed lines of the diff, so no inline comment): The PR deleted TestGetSupportedMiddlewareFactories_OBODispatchesToCurrentFactory; TestOBORegistration never overrides, so changing line 44 to obo.DefaultFactory would pass while the deprecated RegisterFactory override silently stops working. TestOBORegistration also calls require.* inside the httptest handler goroutine. Recommendation: Restore a small variant (non-parallel, cleanup restores DefaultFactory) and use assert in handler goroutines. Raised by: tests-obo.
  • [LOW] Factory test comment disagrees with its assertion and PR body says 'registers it directly' while code goes through auth.NewOBOStrategy (pkg/vmcp/auth/factory/outgoing.go:76) (outside the changed lines of the diff, so no inline comment): NewOutgoingAuthRegistry registers auth.NewOBOStrategy(envReader) (which honours the deprecated override), not the strategy directly as the PR body says; in TestNewOutgoingAuthRegistry the comment says 'no token URL' but the strategy has a nil OBO and the assertion is 'OBO configuration is required'. Recommendation: Fix the test comment and the PR body wording. Raised by: tests-vmcp.
  • [LOW] Stale comment still describes the removed registered-OBO-handler dispatch in the MCPRemoteProxy deployment builder (cmd/thv-operator/controllers/mcpremoteproxy_deployment.go:311): Comment says OBO env vars are 'Dispatched through the registered OBO handler; inert in builds without one', but OBO is built in and errors are now returned and logged. The MCPServer sibling comment was updated; go-style.md requires comments in sync. (File is not in the diff.) Recommendation: Replace with wording like the MCPServer comment. Raised by: correctness-operator-vmcp.
  • [LOW] No test builds the vMCP pod env vars for two OBO backends (cmd/thv-operator/controllers/virtualmcpserver_deployment.go:590) (outside the changed lines of the diff, so no inline comment): Distinct env vars per OBO config is covered only per config (TestGetExternalAuthConfigSecretEnvVars_OBO) and by the strategy-conversion case. The discoverInlineExternalAuthConfigSecrets / discoverExternalAuthConfigSecrets tests contain no OBO config, so nothing asserts that two OBO backends put both env vars on the pod or that the name written into the strategy matches a mounted one. Dedupe, sort and log-and-continue are type-agnostic and tested for other types. Recommendation: Add an OBO case with two configs to both discover tables and assert both distinct env vars and that each equals the ClientSecretEnv produced by convertExternalAuthConfigToStrategy. Raised by: tests-operator.

How to test

  1. Run task test, task lint, task operator-test-integration and task license-check; all should pass as the PR body reports.
  2. Reproduce finding 1: load a vMCP YAML config whose OBO backend sets only clientSecretEnv (with that variable set) through config.YAMLLoader and DefaultValidator.Validate; it currently fails with "clientSecret and clientSecretEnv are mutually exclusive". On a cluster, a VirtualMCPServer with an inline OBO backend should crash-loop at startup with the same message.
  3. Mutation checks for the test findings, each of which currently leaves the suite green: delete || tr.Error != "" at exchanger.go:396; delete client.CheckRedirect = ... in the injected == nil branch at exchanger.go:243; remove io.LimitReader at exchanger.go:326; make subjectToken fall back to identity.Token in provider mode; return the bare exchanger from defaultBuildOBOExchanger. A regression-catching test should fail for each.
  4. Stale mirrored condition: create an obo MCPExternalAuthConfig with a valid spec, an MCPServer that references it, then make the spec invalid and revert it to the same valid spec; check the MCPServer's ExternalAuthConfigValidated condition clears.
  5. Two OBO configs named my-cfg and my.cfg in one VirtualMCPServer should end up with distinct secret env vars on the vMCP pod.

Documentation updates

Fix the docs/middleware.md anchor and add OBO to its chain and execution-order lists. Correct the PR description (SDK type rename, the factory registering through auth.NewOBOStrategy, the identifier GenerateUniqueOBOSecretEnvVarName, and the vMCP env var name no longer honouring an overlay handler).

Recommendation

REQUEST CHANGES: the inline vMCP OBO failure would break the documented feature on merge. It is posted as a comment because this is a draft PR authored by the reviewing account.


Reviewed by dev:review-pr (finders: correctness, security, readability, API design, scope discipline, test coverage). Generated with Claude Code.

Comment thread pkg/auth/obo/middleware.go Resolved
Comment thread pkg/auth/obo/entra/exchanger.go Resolved
Comment thread pkg/auth/obo/entra/exchanger.go Resolved
Comment thread pkg/auth/obo/entra/exchanger.go Resolved
Comment thread pkg/auth/obo/cache/cache.go Resolved

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

Review

This is a new-feature PR (about 8.5k changed lines, of which roughly 5.2k are tests and 1.8k are generated) that moves Entra on-behalf-of from a private overlay into OSS: the Kubernetes-free pkg/auth/obo/{entra,cache,exchange} packages, the proxy middleware, operator validation, RunConfig and secret env var generation, and the vMCP converter and strategy. The approach is sound and matches the issue's design. Exchange failures fail closed, proxy response bodies are generic, the token cache is keyed per (user token hash, audience) with shared in-flight exchanges, redirects are refused, the client secret travels only as an env var name, and the deprecated hooks keep compiling and overriding. The main concern is that an inline outgoingAuth OBO backend on a VirtualMCPServer fails vMCP startup validation (finding 1), so the issue's fourth acceptance criterion is not met end to end. The remaining findings are mostly tests that would still pass if the source they cover were broken, plus a few documentation and PR-description inaccuracies.

Cross-cutting observations

  • Inline vMCP path. The operator emits only clientSecretEnv for inline OBO backends. The pre-existing YAML loader resolves it into clientSecret without clearing the env field, and the validator and the new parseOBOConfig reject both being set. The vMCP integration test constructs the strategy directly, and no test runs loader, then validator, then strategy, which is why it passed. Discovered mode is unaffected.
  • Test strength. Much of the suite is strong: the Entra error classification matrix, middleware status mapping, non-disclosure checks, cache isolation and expiry, operator validation, and the deprecated-override tests all assert real behaviour. The gaps are specific branches whose tests would stay green if the source were broken (the 2xx-with-error body, the response-size cap, redirect refusal on the default client, upstream-provider mode falling back to the inbound token) and missing Reconcile-level assertions for the new terminal no-requeue handling.
  • Mirrored conditions. A malformed obo source now surfaces InvalidConfig, the same reason the consumer controllers treat as locally owned. Reverting a source to its exact last-valid spec appears to leave a stale Valid=False on MCPServer and MCPRemoteProxy consumers, and the mirror tests use a fake reason that avoids this path.
  • Backwards compatibility. The deprecated hook signatures are unchanged, but a registered OBOHandler.SecretEnvVars no longer applies on the vMCP path, and the regenerated swagger renames exported types in the separate sdk/go module (wire format unchanged). Neither is called out in the PR description, which also says the factory "registers it directly" (it goes through auth.NewOBOStrategy) and cites a function name that does not exist.
  • Documentation. docs/middleware.md has a broken #9-audit-middleware link after the renumbering, and the chain overview and execution-order lists do not mention OBO.
  • Instruction files. The diff does not change any CLAUDE.md, AGENTS.md or .claude/rules/ file.

Findings

# Severity Finding Location Raised by
1 HIGH Operator-generated inline OBO backends fail vMCP startup validation pkg/vmcp/config/yaml_loader.go:163 correctness-operator-vmcp
2 MEDIUM Upstream-provider mode 'must not fall back to the inbound token' is not pinned by tests pkg/auth/obo/middleware.go:222 tests-obo
3 MEDIUM Response-size-cap test would pass even if the 1 MiB cap were removed pkg/auth/obo/entra/exchanger.go:326 tests-obo
4 MEDIUM Redirect refusal tested only for a caller-injected client, not the default client production uses pkg/auth/obo/entra/exchanger.go:243 tests-obo
5 MEDIUM A 2xx response carrying an OAuth error field is untested pkg/auth/obo/entra/exchanger.go:396 tests-obo
6 MEDIUM Concurrent cache tests block on bare channel receives/WaitGroup with no timeout (testing.md violation) pkg/auth/obo/cache/cache.go:202 tests-obo
7 MEDIUM Authenticate error branches of the vMCP strategy are untested pkg/vmcp/auth/strategies/obo.go:107 tests-vmcp
8 MEDIUM ResolveSecrets test asserts ClientSecretEnv is cleared but the input never sets it; several branches untested pkg/vmcp/auth/converters/obo.go:148 tests-vmcp
9 MEDIUM MCPServer.Reconcile terminal branch for obo ValidationError has no test asserting no requeue cmd/thv-operator/controllers/mcpserver_controller.go:400 tests-operator
10 MEDIUM A stale Valid=False / InvalidConfig can stay mirrored onto consumers after the OBO source heals cmd/thv-operator/controllers/external_auth_mirror.go:93 tests-operator
11 MEDIUM Regenerated swagger renames exported SDK types; the commit and PR body describe it as a reorder sdk/go/client/oas_schemas_gen.go api-design
12 MEDIUM docs/middleware.md links to #9-audit-middleware, which no longer exists after renumbering docs/middleware.md:50 readability, scope
13 MEDIUM OBO middleware is missing from the chain overview and execution-order lists in docs/middleware.md docs/middleware.md:11 readability
14 LOW Exported NewInteractionRequiredAuditEvent sits below private helpers pkg/auth/obo/middleware.go:307 readability
15 LOW DefaultFactory CacheSkewSeconds-to-cache wiring is never exercised with a positive value pkg/auth/obo/middleware.go:144 tests-obo
16 LOW Interaction-required audit event details only partly asserted pkg/auth/obo/middleware.go:307 tests-obo
17 LOW Test naming/cleanup nits in middleware_test.go (name/comment mismatch, defer srv.Close in parallel test) pkg/auth/obo/middleware_test.go:197 tests-obo
18 LOW HTTP 429/408 from Entra classified as permanent KindUnknown instead of transient pkg/auth/obo/entra/exchanger.go:429 correctness-obo
19 LOW validateTenant comment refers to a 'previous, looser check' that does not exist in this repo pkg/auth/obo/entra/exchanger.go:256 readability
20 LOW entra.Config and entra.New have no production caller and duplicate NewFromTokenURL pkg/auth/obo/entra/exchanger.go:132 readability, scope
21 LOW Interaction-required fallbacks and success-path variants not individually covered pkg/auth/obo/entra/exchanger.go:459 tests-obo
22 LOW Concurrent-coalescing cache test does not reliably fail if single-flight is broken pkg/auth/obo/cache/cache.go:147 tests-obo
23 LOW Coalesced-error path and skew boundaries untested in cache pkg/auth/obo/cache/cache.go:178 tests-obo
24 LOW Runner-level test no longer pins that the factory map dispatches through obo.CreateMiddleware (override path) pkg/runner/middleware.go:44 tests-obo
25 LOW Inconsistent deprecation lifetime wording across deprecated symbols cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go:2592 api-design
26 LOW Registered OBOHandler.SecretEnvVars no longer applies on the vMCP path, contradicting 'overrides keep winning' cmd/thv-operator/pkg/controllerutil/obo.go:165 api-design
27 LOW NewOBOStrategy forwarding of env.Reader to a registered override is no longer tested pkg/vmcp/auth/obo.go:42 tests-vmcp
28 LOW Factory test comment disagrees with its assertion and PR body says 'registers it directly' while code goes through auth.NewOBOStrategy pkg/vmcp/auth/factory/outgoing.go:76 tests-vmcp
29 LOW vMCP OBO strategy surfaces Entra's raw error description to MCP clients pkg/vmcp/auth/strategies/obo.go:218 security
30 LOW exchangers field comment sits above mu; parseResponse comment gives a reason that does not hold pkg/vmcp/auth/strategies/obo.go:59 readability
31 LOW No test pins that the vMCP strategy wraps the Entra exchanger in the token cache pkg/vmcp/auth/strategies/obo.go:260 tests-vmcp
32 LOW Exchanger cache key (token URL/client/skew/secret fingerprint) untested except 'same config builds once' pkg/vmcp/auth/strategies/obo.go:324 tests-vmcp
33 LOW No concurrency test for getOrCreateExchanger's double-checked lock pkg/vmcp/auth/strategies/obo.go:189 tests-vmcp
34 LOW Unset or empty ClientSecretEnv branch of the vMCP strategy is untested pkg/vmcp/auth/strategies/obo.go:172 tests-vmcp
35 LOW Real-exchanger skew test passes even if the skew gate is removed pkg/vmcp/auth/strategies/obo.go:266 tests-vmcp
36 LOW cacheSkew upper bound enforced by the vMCP converter but not by operator OBO validation cmd/thv-operator/pkg/controllerutil/obo.go:239 correctness-operator-vmcp
37 LOW OBOVMCPSecretEnvVar has a singular name but returns a slice; PR body cites a function name that does not exist cmd/thv-operator/pkg/controllerutil/obo.go:165 api-design
38 LOW OBO validation edge cases and reconcile-level cases untested cmd/thv-operator/pkg/controllerutil/obo.go:229 tests-operator
39 LOW Per-config vMCP secret env var names can collide (my-cfg vs my.cfg) cmd/thv-operator/pkg/controllerutil/externalauth.go:80 security, tests-operator
40 LOW Repeated 'if terminal' branching makes the MCPServer external-auth error path hard to follow cmd/thv-operator/controllers/mcpserver_controller.go:389 readability
41 LOW logOBOSecretEnvVarError redaction behaviour untested; MCPRemoteProxy has no error-path test for the OBO env var cmd/thv-operator/controllers/mcpserver_controller.go:1204 tests-operator
42 LOW MCPRemoteProxy.Reconcile terminal (no-requeue) handling of obo-without-oidcConfigRef is untested cmd/thv-operator/controllers/mcpremoteproxy_controller.go:190 tests-operator
43 LOW Stale comment still describes the removed registered-OBO-handler dispatch in the MCPRemoteProxy deployment builder cmd/thv-operator/controllers/mcpremoteproxy_deployment.go:311 correctness-operator-vmcp
44 LOW triageOBOValidation is now a one-line wrapper over applyOBOValidationResult cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go:365 readability, scope
45 LOW No test builds the vMCP pod env vars for two OBO backends cmd/thv-operator/controllers/virtualmcpserver_deployment.go:590 tests-operator

Additional findings

These sit outside the changed lines of the diff, or too far from the nearest changed line for an inline comment.

  • [HIGH] Operator-generated inline OBO backends fail vMCP startup validation (pkg/vmcp/config/yaml_loader.go:163): For an inline (outgoingAuth) OBO backend the operator writes only clientSecretEnv into the vMCP ConfigMap and mounts the Secret under that env var. At startup YAMLLoader.Load (pkg/vmcp/config/yaml_loader.go:163-169) copies the env value into obo.ClientSecret but leaves ClientSecretEnv set, and DefaultValidator.Validate (validator.go:307-308) then rejects the strategy with "clientSecret and clientSecretEnv are mutually exclusive", so thv vmcp serve and thv vmcp validate abort. The new parseOBOConfig (pkg/vmcp/auth/strategies/obo.go:287) enforces the same rule on every request. Discovered mode is unaffected because ResolveSecrets clears ClientSecretEnv. The loader and validator lines are outside this diff and predate it, but this PR is what makes the path reachable. No test runs loader, then validator, then strategy for OBO, and the vMCP integration test builds the strategy directly, so it never reaches the loader. This was traced by reading the code, not by running it. Recommendation: Drop the copy at yaml_loader.go:168 as the token-exchange case does (yaml_loader.go:136-142 only checks the env var is set and OBOStrategy.resolveClientSecret reads it at request time), or set obo.ClientSecretEnv = "" after resolving. Add a test that loads YAML with clientSecretEnv, runs the validator, then OBOStrategy.Validate. Raised by: correctness-operator-vmcp.
  • [MEDIUM] A stale Valid=False / InvalidConfig can stay mirrored onto consumers after the OBO source heals (cmd/thv-operator/controllers/external_auth_mirror.go:93) (outside the changed lines of the diff, so no inline comment): Before this PR an obo source surfaced EnterpriseRequired; now a malformed one surfaces InvalidConfig, the reason ownedByLocalValidation (external_auth_mirror.go:93) and setMCPServerExternalAuthConfigValidCondition treat as locally owned. Sequence: the source goes invalid, the consumer mirrors False/InvalidConfig and its stored hash stays at the last-valid hash; the user reverts the source to that exact last-valid spec, so the source is Valid=True with the same hash; the mirror is nil but ownedByLocalValidation is true, so the condition is not removed, and setMCPServerExternalAuthConfigValidCondition sees the same reason, generation and hash and returns early without writing True. Editing the source to a different spec changes the hash and clears it. MCPRemoteProxy behaves the same. All mirror tests use a fake SourceRejected reason and never cover this sequence. Recommendation: Add tests with a real obo source going InvalidConfig, then back to the same spec, for MCPServer and MCPRemoteProxy. If the condition stays False, distinguish locally owned from mirrored InvalidConfig at both same-hash guard sites. Raised by: tests-operator.
  • [MEDIUM] Regenerated swagger renames exported SDK types; the commit and PR body describe it as a reorder (sdk/go/client/oas_schemas_gen.go): The Regenerate swagger and SDK for schema order commit is not a pure reorder. In docs/server/swagger.yaml the components github_com_stacklok_toolhive_pkg_auth_awssts.Config and .RoleMapping become awssts.Config and awssts.RoleMapping, and in the separate sdk/go module the exported AuthAWSSTSConfig, AuthAWSSTSRoleMapping and OptAuthAWSSTSConfig become AWSSTSConfig, AWSSTSRoleMapping and OptAWSSTSConfig, with the RunnerRunConfig getter and setter signatures changing. The JSON wire format is unchanged. The cause is swag switching between long and short schema names when the new pkg/auth/obo/... packages enter the import graph, so the SDK surface depends on which packages the generator happens to load. The PR body's API Compatibility section covers only the CRDs. cmd/help/openapi-normalize/main_test.go:136 also still maps the long name to AuthAWSSTSConfig. The commit message body was not read during verification. Recommendation: State the rename in the PR body and decide whether the SDK break is acceptable. Better, pin the name (an explicit mapping in cmd/help/openapi-normalize/main.go or a swag @name override on awssts.Config) so it cannot flip again. Raised by: api-design.
  • [MEDIUM] docs/middleware.md links to #9-audit-middleware, which no longer exists after renumbering (docs/middleware.md:50) (outside the changed lines of the diff, so no inline comment): The new ### 9. On-Behalf-Of (OBO) Middleware section renumbers Audit to 10, Recovery to 11 and Header Forward to 12. The webhook section at line 50 still links #9-audit-middleware; it is the only broken link (the anchors used from docs/arch/02, 03 and vmcp-library still resolve). Recommendation: Change the link to #10-audit-middleware, or append the OBO section as 13 so nothing is renumbered. Raised by: readability, scope.
  • [MEDIUM] OBO middleware is missing from the chain overview and execution-order lists in docs/middleware.md (docs/middleware.md:11) (outside the changed lines of the diff, so no inline comment): The new OBO section says it runs after authentication and before recovery, but the component list (lines 11-23) and the "Middleware Execution Order" list (lines 1233-1247, "steps 1-15", plus the ordering rules and the step count at line 1264) do not mention it. pkg/runner/middleware.go:263-281 splices AdditionalMiddlewareConfigs after awssts and header-forward and before recovery. CLAUDE.md asks for observable behaviour to be documented on the subsystem page. Recommendation: Add OBO to both lists with an ordering note that it needs the authentication middleware's identity, and update the step count. Raised by: readability.
  • [LOW] Runner-level test no longer pins that the factory map dispatches through obo.CreateMiddleware (override path) (pkg/runner/middleware.go:44) (outside the changed lines of the diff, so no inline comment): The PR deleted TestGetSupportedMiddlewareFactories_OBODispatchesToCurrentFactory; TestOBORegistration never overrides, so changing line 44 to obo.DefaultFactory would pass while the deprecated RegisterFactory override silently stops working. TestOBORegistration also calls require.* inside the httptest handler goroutine. Recommendation: Restore a small variant (non-parallel, cleanup restores DefaultFactory) and use assert in handler goroutines. Raised by: tests-obo.
  • [LOW] Factory test comment disagrees with its assertion and PR body says 'registers it directly' while code goes through auth.NewOBOStrategy (pkg/vmcp/auth/factory/outgoing.go:76) (outside the changed lines of the diff, so no inline comment): NewOutgoingAuthRegistry registers auth.NewOBOStrategy(envReader) (which honours the deprecated override), not the strategy directly as the PR body says; in TestNewOutgoingAuthRegistry the comment says 'no token URL' but the strategy has a nil OBO and the assertion is 'OBO configuration is required'. Recommendation: Fix the test comment and the PR body wording. Raised by: tests-vmcp.
  • [LOW] Stale comment still describes the removed registered-OBO-handler dispatch in the MCPRemoteProxy deployment builder (cmd/thv-operator/controllers/mcpremoteproxy_deployment.go:311): Comment says OBO env vars are 'Dispatched through the registered OBO handler; inert in builds without one', but OBO is built in and errors are now returned and logged. The MCPServer sibling comment was updated; go-style.md requires comments in sync. (File is not in the diff.) Recommendation: Replace with wording like the MCPServer comment. Raised by: correctness-operator-vmcp.
  • [LOW] No test builds the vMCP pod env vars for two OBO backends (cmd/thv-operator/controllers/virtualmcpserver_deployment.go:590) (outside the changed lines of the diff, so no inline comment): Distinct env vars per OBO config is covered only per config (TestGetExternalAuthConfigSecretEnvVars_OBO) and by the strategy-conversion case. The discoverInlineExternalAuthConfigSecrets / discoverExternalAuthConfigSecrets tests contain no OBO config, so nothing asserts that two OBO backends put both env vars on the pod or that the name written into the strategy matches a mounted one. Dedupe, sort and log-and-continue are type-agnostic and tested for other types. Recommendation: Add an OBO case with two configs to both discover tables and assert both distinct env vars and that each equals the ClientSecretEnv produced by convertExternalAuthConfigToStrategy. Raised by: tests-operator.

How to test

  1. Run task test, task lint, task operator-test-integration and task license-check; all should pass as the PR body reports.
  2. Reproduce finding 1: load a vMCP YAML config whose OBO backend sets only clientSecretEnv (with that variable set) through config.YAMLLoader and DefaultValidator.Validate; it currently fails with "clientSecret and clientSecretEnv are mutually exclusive". On a cluster, a VirtualMCPServer with an inline OBO backend should crash-loop at startup with the same message.
  3. Mutation checks for the test findings, each of which currently leaves the suite green: delete || tr.Error != "" at exchanger.go:396; delete client.CheckRedirect = ... in the injected == nil branch at exchanger.go:243; remove io.LimitReader at exchanger.go:326; make subjectToken fall back to identity.Token in provider mode; return the bare exchanger from defaultBuildOBOExchanger. A regression-catching test should fail for each.
  4. Stale mirrored condition: create an obo MCPExternalAuthConfig with a valid spec, an MCPServer that references it, then make the spec invalid and revert it to the same valid spec; check the MCPServer's ExternalAuthConfigValidated condition clears.
  5. Two OBO configs named my-cfg and my.cfg in one VirtualMCPServer should end up with distinct secret env vars on the vMCP pod.

Documentation updates

Fix the docs/middleware.md anchor and add OBO to its chain and execution-order lists. Correct the PR description (SDK type rename, the factory registering through auth.NewOBOStrategy, the identifier GenerateUniqueOBOSecretEnvVarName, and the vMCP env var name no longer honouring an overlay handler).

Recommendation

REQUEST CHANGES: the inline vMCP OBO failure would break the documented feature on merge. It is posted as a comment because this is a draft PR authored by the reviewing account.


Reviewed by dev:review-pr (finders: correctness, security, readability, API design, scope discipline, test coverage). Generated with Claude Code.

tgrunnagle and others added 4 commits November 19, 2026 12:16
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]>
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]>
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]>
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]>
@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 Nov 19, 2026
@tgrunnagle

Copy link
Copy Markdown
Collaborator Author

Replies to the review-body findings that have no inline thread (review 5982042243):

  • [HIGH] Operator-generated inline OBO backends fail vMCP startup validation: addressed in bead6e7. The YAML loader now only checks that clientSecretEnv is set, as it does for tokenExchange, and no longer copies the value into clientSecret, so the validator and parseOBOConfig accept the operator-rendered config. A loader→validator table row and TestOBOIntegration_InlineConfigFileLoad (YAML loader → DefaultValidator → strategy Validate → real exchange against a mock Entra) cover it.
  • [MEDIUM] Stale Valid=False / InvalidConfig mirrored onto consumers after the source heals: addressed in eae5487. Reproduced with a real obo source (valid → missing clientId → the same valid spec) for MCPServer and MCPRemoteProxy. Mirrored conditions now carry the message prefix Referenced MCPExternalAuthConfig '<name>' is invalid: , and isLocalValidationFailure uses it to tell them apart from local failures in ownedByLocalValidation and both same-hash guards.
  • [MEDIUM] Regenerated swagger renamed exported SDK types: addressed in 50bff0d. cmd/help/openapi-normalize maps swag's short awssts.* names back to the path form, so sdk/go is byte-identical to main again (AuthAWSSTSConfig, AuthAWSSTSRoleMapping, OptAuthAWSSTSConfig) whichever name swag picks.
  • [MEDIUM] Broken #9-audit-middleware link and [MEDIUM] OBO missing from the chain and execution-order lists: addressed in 50bff0d (anchor is now #10-audit-middleware; OBO added to both lists, with an ordering note and the step count updated to 16).
  • [LOW] Runner test no longer pins dispatch through obo.CreateMiddleware: addressed in b36366d (TestOBOFactoryHonorsRegisterFactory, non-parallel with t.Cleanup; TestOBORegistration's handler uses assert).
  • [LOW] Factory test comment and "registers it directly" wording: the test comment is fixed in b36366d; the PR body now says the factory registers through auth.NewOBOStrategy.
  • [LOW] Stale comment in the MCPRemoteProxy deployment builder: addressed in eae5487.
  • [LOW] No test builds the vMCP pod env vars for two OBO backends: addressed in eae5487 (TestDiscoverExternalAuthConfigSecrets_TwoOBOBackends, discovered and inline, with configs obo-a and obo.a, which also exercises the env var name collision fix).

@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 Nov 19, 2026

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

Review

This is an incremental review of the four commits pushed since the last review (bead6e7ef, 50bff0db8, eae5487e5, b36366d3e; about 4,000 changed lines across 50 files, roughly three quarters of it tests and generated SDK code). They respond to the earlier review: the vMCP YAML loader no longer copies clientSecretEnv into clientSecret, the mirrored-condition fix uses a message prefix to tell a mirrored InvalidConfig from a locally owned one, the OpenAPI normalizer pins the awssts schema names so the SDK matches main again, docs/middleware.md is corrected, and the tests are rewritten so the behaviours they cover can no longer break silently. Behaviour changes ride along: HTTP 429, 408 and temporarily_unavailable are now transient (the proxy answers 502), the vMCP strategy returns a generic error and logs Entra's detail server-side, vMCP OBO secret env vars carry a hash suffix, the operator rejects cacheSkew above MaxInt32 seconds, and the unused entra.Config/entra.New are gone. All 45 findings from the earlier review, including the HIGH inline-backend startup failure, are settled in the code. The new findings are three MEDIUM and seven LOW, none of which blocks the approach.

Cross-cutting observations

  • Issue #7199 acceptance. Inline (outgoingAuth) OBO backends now load, validate and exchange: the loader only checks that the variable is set, parseOBOConfig and the validator agree, and TestOBOIntegration_InlineConfigFileLoad runs the loader, validator and strategy together. Discovered mode is unchanged.
  • Mirrored conditions. The prefix approach fixes the stale mirrored InvalidConfig after a source heals to its exact spec, and TestExternalAuthMirror_OBOSourceHealsToSameSpec exercises it with the real reasons. The same-hash guard can still hold a locally produced obo-without-OIDC InvalidConfig when the source goes obo and then reverts to the spec it had before (finding 1). The prefix is also the only discriminator between mirrored and local failures, and nothing enforces that no local message starts with it.
  • Observable changes to document. The mirrored condition message changes from the source's text to Referenced MCPExternalAuthConfig '<name>' is invalid: <msg> for every mirrored source, and the vMCP OBO env var name gains a hash suffix. The suffix is documented in docs/arch/09 and docs/arch/10; the message format is not (CLAUDE.md asks for before and after in the PR body and the subsystem docs).
  • Error disclosure. The vMCP client error is now generic apart from a static sentinel; for invalid_client that still tells any authenticated user the backend credential failed, which the proxy middleware does not (finding 8).
  • Tests. The earlier gaps are closed with mutation-sensitive rows. The remaining gaps are the loader's own OBO error branches, the new server-side log, the MCPServer status-write failure path, and one contention test that is heavier than the code it guards.
  • Verification limits. Every finding was checked by reading the code at b36366d3e; nothing was run, so the test claims rest on tracing the mutations by hand.
  • Instruction files. The four commits do not change CLAUDE.md, AGENTS.md or any .claude/rules/ file.

Findings

# Severity Finding Location Raised by
1 MEDIUM Same-hash guard still holds a stale local obo-incoming-auth InvalidConfig after the source reverts to its earlier spec cmd/thv-operator/controllers/mcpserver_controller.go:2580 correctness-operator
2 MEDIUM TestOBOGetOrCreateExchanger_BuildsOnceUnderContention is brittle, skips silently on small runners and can fail on loaded CI pkg/vmcp/auth/strategies/obo_test.go:699 readability, tests
3 MEDIUM Loader's OBO error paths (env var unset, both secret sources set, nil obo) have no test pkg/vmcp/config/yaml_loader_test.go:772 tests
4 LOW Mirrored-condition message prefix changes an observable status message, is undocumented, and its ownership invariant is unenforced cmd/thv-operator/controllers/external_auth_mirror.go:37 api-design, readability
5 LOW MCPServer terminal-branch status-write failure path is untested while MCPRemoteProxy's is cmd/thv-operator/controllers/mcpserver_externalauth_test.go:969 tests
6 LOW OBO error-status table row packs several conditions and an ambiguous parenthetical docs/middleware.md:529 api-design, readability
7 LOW 429/408 with an unparsable body is classified permanent, not transient pkg/auth/obo/entra/exchanger.go:343 correctness-pkg
8 LOW vMCP error returned to MCP clients still discloses the failure class for invalid_client pkg/vmcp/auth/strategies/obo.go:248 security
9 LOW Whitespace-only clientId passes strategy validation but fails on every request pkg/vmcp/auth/strategies/obo.go:322 correctness-pkg
10 LOW Server-side logging of Entra error detail is untested, so deleting it keeps the strategy tests green pkg/vmcp/auth/strategies/obo_test.go:460 tests

Resolved since the last review

All 45 findings from the previous review are settled in the code at b36366d3e; the 36 that have inline threads are answered and resolved there.

High

  • Operator-generated inline OBO backends fail vMCP startup validation (pkg/vmcp/config/yaml_loader.go)

Medium

  • Upstream-provider mode 'must not fall back to the inbound token' is not pinned by tests (pkg/auth/obo/middleware.go)
  • Response-size-cap test would pass even if the 1 MiB cap were removed (pkg/auth/obo/entra/exchanger.go)
  • Redirect refusal tested only for a caller-injected client, not the default client production uses (pkg/auth/obo/entra/exchanger.go)
  • A 2xx response carrying an OAuth error field is untested (pkg/auth/obo/entra/exchanger.go)
  • Concurrent cache tests block on bare channel receives/WaitGroup with no timeout (testing.md violation) (pkg/auth/obo/cache/cache.go)
  • Authenticate error branches of the vMCP strategy are untested (pkg/vmcp/auth/strategies/obo.go)
  • ResolveSecrets test asserts ClientSecretEnv is cleared but the input never sets it; several branches untested (pkg/vmcp/auth/converters/obo.go)
  • MCPServer.Reconcile terminal branch for obo ValidationError has no test asserting no requeue (cmd/thv-operator/controllers/mcpserver_controller.go)
  • A stale Valid=False / InvalidConfig can stay mirrored onto consumers after the OBO source heals (cmd/thv-operator/controllers/external_auth_mirror.go)
  • Regenerated swagger renames exported SDK types; the commit and PR body describe it as a reorder (sdk/go/client/oas_schemas_gen.go)
  • docs/middleware.md links to #9-audit-middleware, which no longer exists after renumbering (docs/middleware.md)
  • OBO middleware is missing from the chain overview and execution-order lists in docs/middleware.md (docs/middleware.md)

Low

  • Exported NewInteractionRequiredAuditEvent sits below private helpers (pkg/auth/obo/middleware.go)
  • DefaultFactory CacheSkewSeconds-to-cache wiring is never exercised with a positive value (pkg/auth/obo/middleware.go)
  • Interaction-required audit event details only partly asserted (pkg/auth/obo/middleware.go)
  • Test naming/cleanup nits in middleware_test.go (name/comment mismatch, defer srv.Close in parallel test) (pkg/auth/obo/middleware_test.go)
  • HTTP 429/408 from Entra classified as permanent KindUnknown instead of transient (pkg/auth/obo/entra/exchanger.go)
  • validateTenant comment refers to a 'previous, looser check' that does not exist in this repo (pkg/auth/obo/entra/exchanger.go)
  • entra.Config and entra.New have no production caller and duplicate NewFromTokenURL (pkg/auth/obo/entra/exchanger.go)
  • Interaction-required fallbacks and success-path variants not individually covered (pkg/auth/obo/entra/exchanger.go)
  • Concurrent-coalescing cache test does not reliably fail if single-flight is broken (pkg/auth/obo/cache/cache.go)
  • Coalesced-error path and skew boundaries untested in cache (pkg/auth/obo/cache/cache.go)
  • Inconsistent deprecation lifetime wording across deprecated symbols (cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go)
  • Registered OBOHandler.SecretEnvVars no longer applies on the vMCP path, contradicting 'overrides keep winning' (cmd/thv-operator/pkg/controllerutil/obo.go)
  • NewOBOStrategy forwarding of env.Reader to a registered override is no longer tested (pkg/vmcp/auth/obo.go)
  • vMCP OBO strategy surfaces Entra's raw error description to MCP clients (pkg/vmcp/auth/strategies/obo.go)
  • exchangers field comment sits above mu; parseResponse comment gives a reason that does not hold (pkg/vmcp/auth/strategies/obo.go)
  • No test pins that the vMCP strategy wraps the Entra exchanger in the token cache (pkg/vmcp/auth/strategies/obo.go)
  • Exchanger cache key (token URL/client/skew/secret fingerprint) untested except 'same config builds once' (pkg/vmcp/auth/strategies/obo.go)
  • No concurrency test for getOrCreateExchanger's double-checked lock (pkg/vmcp/auth/strategies/obo.go)
  • Unset or empty ClientSecretEnv branch of the vMCP strategy is untested (pkg/vmcp/auth/strategies/obo.go)
  • Real-exchanger skew test passes even if the skew gate is removed (pkg/vmcp/auth/strategies/obo.go)
  • cacheSkew upper bound enforced by the vMCP converter but not by operator OBO validation (cmd/thv-operator/pkg/controllerutil/obo.go)
  • OBOVMCPSecretEnvVar has a singular name but returns a slice; PR body cites a function name that does not exist (cmd/thv-operator/pkg/controllerutil/obo.go)
  • OBO validation edge cases and reconcile-level cases untested (cmd/thv-operator/pkg/controllerutil/obo.go)
  • Per-config vMCP secret env var names can collide (my-cfg vs my.cfg) (cmd/thv-operator/pkg/controllerutil/externalauth.go)
  • Repeated 'if terminal' branching makes the MCPServer external-auth error path hard to follow (cmd/thv-operator/controllers/mcpserver_controller.go)
  • logOBOSecretEnvVarError redaction behaviour untested; MCPRemoteProxy has no error-path test for the OBO env var (cmd/thv-operator/controllers/mcpserver_controller.go)
  • MCPRemoteProxy.Reconcile terminal (no-requeue) handling of obo-without-oidcConfigRef is untested (cmd/thv-operator/controllers/mcpremoteproxy_controller.go)
  • triageOBOValidation is now a one-line wrapper over applyOBOValidationResult (cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go)
  • Runner-level test no longer pins that the factory map dispatches through obo.CreateMiddleware (override path) (pkg/runner/middleware.go)
  • Factory test comment disagrees with its assertion and PR body says 'registers it directly' while code goes through auth.NewOBOStrategy (pkg/vmcp/auth/factory/outgoing.go)
  • Stale comment still describes the removed registered-OBO-handler dispatch in the MCPRemoteProxy deployment builder (cmd/thv-operator/controllers/mcpremoteproxy_deployment.go)
  • No test builds the vMCP pod env vars for two OBO backends (cmd/thv-operator/controllers/virtualmcpserver_deployment.go)

How to test

  1. Run task test, task lint, task operator-test-integration and task license-check.
  2. Inline backend: load a vMCP YAML config whose OBO backend sets only clientSecretEnv (variable set) through config.YAMLLoader and DefaultValidator.Validate, then call OBOStrategy.Validate; all should pass. With the variable unset the loader should fail with environment variable ... not set.
  3. Stale local condition (finding 1): create a valid non-obo MCPExternalAuthConfig, an MCPServer without oidcConfigRef that references it, change the source to obo (consumer becomes InvalidConfig), then revert the source to the original spec; the ExternalAuthConfigValidated condition should go back to True, and today it stays False.
  4. Mutation checks that should fail but currently pass: delete the Getenv(...) == "" check at yaml_loader.go:169; replace return ctrl.Result{}, statusErr with return ctrl.Result{}, nil in the MCPServer terminal branch; delete the logExchangeFailure calls in strategies/obo.go.
  5. Edge inputs: a 429 with an empty or HTML body against entra.NewFromTokenURL should be transient; an inline config with clientId: " " should be rejected by OBOStrategy.Validate.
  6. Run TestOBOGetOrCreateExchanger_BuildsOnceUnderContention on a 2-CPU runner (GOMAXPROCS=2) to see it skip.

Documentation updates

Describe the new mirrored-condition message format (before and after) in the PR body and add one line to docs/arch/09-operator-architecture.md where the mirror is described. Clarify the 502 row of the OBO status table in docs/middleware.md. The PR body should also state the hash-suffix deviation from the sibling env var generators and the removal of entra.Config/entra.New.

Recommendation

APPROVE: no HIGH finding remains, and the earlier HIGH is fixed. The stale local InvalidConfig (finding 1) and the two test gaps (findings 2 and 3) are worth fixing before merge. It is posted as a comment because this is a draft PR authored by the reviewing account.


Reviewed by dev:review-pr (finders: correctness, security, readability, API design, test coverage). Generated with Claude Code.

Comment thread pkg/vmcp/auth/strategies/obo_test.go Resolved
Comment thread pkg/vmcp/config/yaml_loader_test.go Resolved
Comment thread docs/middleware.md Resolved
Comment thread pkg/auth/obo/entra/exchanger.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo_test.go Resolved
tgrunnagle and others added 2 commits November 22, 2026 18:54
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]>
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]>
@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 Nov 23, 2026

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

Review

The two new commits are follow-ups to the earlier review: a guard change in the operator's same-hash condition logic, tighter vMCP strategy errors and validation, a transient classification fix in the Entra exchanger, doc edits, and a rewrite of several tests. The approach is sound. All earlier findings are settled in the code, and the new commits introduce no correctness or security problems.

Cross-cutting observations:

  • The invalid_client message change makes the vMCP strategy consistent with the proxy middleware's opaque 502. errors.Is still matches the sentinel, so callers that branch on it are unaffected.
  • The afterReadMiss hook on a production struct deviates from .claude/rules/testing.md and is not called out at the site or in the PR (finding 5).
  • The mirrored-condition message format is an operator-visible change. docs/arch/09 now describes it, and the PR body should carry the before/after as well.
  • Validate fails late for a whitespace tokenUrl (and for a non-HTTPS one, which predates these commits). Finding 6 covers the whitespace case.

Findings

# Severity Finding Location Raised by
1 LOW Prefix-invariant test copies the CA-bundle message format, so it only pins the obo constant cmd/thv-operator/controllers/external_auth_mirror_test.go:378 tests, readability
2 LOW Doc comment says the check re-runs "in this same function", but it sits on the setter cmd/thv-operator/controllers/mcpserver_controller.go:2571 readability
3 LOW "non-validation error is requeued" row passes on any error cmd/thv-operator/controllers/mcpserver_externalauth_test.go:968 tests
4 LOW Architecture doc narrates change history ("previously the source message alone") docs/arch/09-operator-architecture.md:241 readability
5 LOW afterReadMiss is a nil-in-production test hook on OBOStrategy pkg/vmcp/auth/strategies/obo.go:67 tests
6 LOW Whitespace-only tokenUrl passes validation and fails on the first request pkg/vmcp/auth/strategies/obo.go:351 correctness

Resolved since the last review

  • [MEDIUM] Same-hash guard held a stale local obo-incoming-auth InvalidConfig after the source reverted (cmd/thv-operator/controllers/mcpserver_controller.go:2583, mcpremoteproxy_controller.go:1132)
  • [MEDIUM] TestOBOGetOrCreateExchanger_BuildsOnceUnderContention was brittle and skipped on small runners (pkg/vmcp/auth/strategies/obo_test.go:646)
  • [MEDIUM] Loader OBO error paths had no test (pkg/vmcp/config/yaml_loader_test.go:553)
  • [LOW] Mirrored-condition message prefix was undocumented and unenforced (docs/arch/09-operator-architecture.md:241)
  • [LOW] MCPServer terminal-branch status-write failure was untested (cmd/thv-operator/controllers/mcpserver_externalauth_test.go:998)
  • [LOW] OBO error-status table row was ambiguous (docs/middleware.md:529)
  • [LOW] 429/408 with an unparsable body was classified permanent (pkg/auth/obo/entra/exchanger.go:333)
  • [LOW] vMCP error still named the invalid_client class to MCP clients (pkg/vmcp/auth/strategies/obo.go:256)
  • [LOW] Whitespace-only clientId passed strategy validation (pkg/vmcp/auth/strategies/obo.go:354)
  • [LOW] Server-side logging of Entra error detail was untested (pkg/vmcp/auth/strategies/obo_test.go:450)

How to test

  1. task test, task lint, task operator-test-integration, task license-check.
  2. Mutation checks, each of which should fail the named test:
    • Remove the Message != ctrlutil.MsgOBORequiresIncomingAuth clause from either same-hash guard: TestExternalAuthMirror_OBOIncomingAuthRejectionClearsOnRevert fails for that consumer.
    • Delete the second check after s.mu.Lock() in getOrCreateExchanger: TestOBOGetOrCreateExchanger_BuildsOnceUnderContention reports 8 builds.
    • Revert isTransientStatus in parseResponse to status >= 500: the 429 and 408 rows fail.
    • Delete the logExchangeFailure calls: TestOBOAuthenticate_ExchangeErrorMapping fails.
  3. Mutation checks that still pass (findings 1 and 3): make a production CA-bundle message start with Referenced MCPExternalAuthConfig , or make the missing-config row fail for a different reason.
  4. Configure a vMCP OBO backend with tokenUrl: " " and call Validate; it passes today and fails only on the first request.

Documentation updates

Move the "previously the source message alone" before/after from docs/arch/09-operator-architecture.md into the PR body's user-facing section.

Recommendation

APPROVE: no HIGH findings remain. The six open findings are all LOW. Findings 5 and 6 are worth fixing before merge. Posted as a comment because the PR is a draft authored by the reviewing account.


Reviewed by dev:review-pr (finders: correctness, readability and docs, tests; incremental review of 2 commits). Generated with Claude Code.

Comment thread docs/arch/09-operator-architecture.md Resolved
Comment thread pkg/vmcp/auth/strategies/obo.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo.go Resolved
@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 Nov 23, 2026

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

Review

The PR ports the Entra on-behalf-of flow into OSS: Kubernetes-free exchange packages, proxy middleware mapping to 401/403/502, a vMCP OBOStrategy, and operator status handling. The operator mirrors a referenced config's Valid=False condition with a distinguishing message prefix, the CA-bundle message comes from one shared helper (ctrlutil.InvalidCABundleMessage), the exchanger map sits behind an oboExchangerStore seam, and parseOBOConfig trims tokenUrl. The approach is sound, and the correctness and security pass found no defects in the changes since the last review.

Cross-cutting notes:

  • rwExchangerStore.lookupOrStore keeps the earlier slow path exactly: write lock, re-check, build under the lock, store only on success. A build error caches nothing.
  • All seven CA-bundle writers (MCPServer, MCPRemoteProxy, VirtualMCPServer) now go through one helper, so the mirrored-prefix invariant has a single format to pin.
  • The mirrored-condition message is operator-visible, so the PR body should carry the before and after (docs/arch/09 already describes the new format).

Findings

# Severity Finding Location Raised by
1 LOW Barrier test assertion messages still describe the removed read/write-lock internals pkg/vmcp/auth/strategies/obo_test.go:712 tests, readability
2 LOW InvalidCABundleMessage doc comment names a test in a different package cmd/thv-operator/pkg/controllerutil/ca_bundle.go:41 readability
3 LOW Missing-config assertion is guarded by if validated != nil, so it never runs cmd/thv-operator/controllers/mcpserver_externalauth_test.go:1013 tests

Resolved since the last review

  • Prefix-invariant test copied the CA-bundle message format (cmd/thv-operator/controllers/external_auth_mirror_test.go:372): the entry uses ctrlutil.InvalidCABundleMessage and ConditionReasonInvalidCABundle.
  • "this same function" doc comment (cmd/thv-operator/controllers/mcpserver_controller.go:2565): it names handleExternalAuthConfig.
  • "non-validation error is requeued" row passed on any error (cmd/thv-operator/controllers/mcpserver_externalauth_test.go:1007): it asserts the exact not-found error.
  • Architecture doc narrated change history (docs/arch/09-operator-architecture.md:241): the parenthetical is gone and the empty-source-message form is documented.
  • afterReadMiss nil-in-production test hook (pkg/vmcp/auth/strategies/obo.go:64): replaced by the oboExchangerStore interface.
  • Whitespace-only tokenUrl passed validation (pkg/vmcp/auth/strategies/obo.go:370): parseOBOConfig trims it.

How to test

  1. Run task test, task lint, task operator-test-integration and task license-check.
  2. Mutation checks, each of which should fail the named test:
    • Remove the second check in rwExchangerStore.lookupOrStore: TestOBOGetOrCreateExchanger_BuildsOnceUnderContention should report 8 builds.
    • Remove strings.TrimSpace from the tokenUrl check in parseOBOConfig: the "whitespace token url" row of TestOBOValidate_Invalid should fail.
    • Make InvalidCABundleMessage start with Referenced MCPExternalAuthConfig : TestMirroredMessagePrefix_NotUsedByLocalMessages should fail.
  3. This mutation should fail a test but still passes (finding 3): make the lookup-failure path record a Validated=False condition with any message other than the obo rejection.

Reviewed by dev:review-pr (finders: correctness and security, tests, readability and docs). Generated with Claude Code.

Comment thread pkg/vmcp/auth/strategies/obo_test.go Resolved
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]>
@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 Nov 23, 2026
@tgrunnagle
tgrunnagle marked this pull request as ready for review November 23, 2026 15:35

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

Thanks for this, it's a big chunk of work and the core of it reads well. The cache keying, the detached single-flight, redirect refusal, and taking the subject from the validated Identity instead of the header all look right to me, and the mirrored-condition handling held up through every spec-edit sequence I could think of.

A few things I'd like you to look at. The first four are the ones I care about; each one lets a config reconcile to Valid=True and then fail on every request, or breaks a spec requirement.

1. 401s without a WWW-Authenticate challenge (pkg/auth/obo/middleware.go, the invalid_grant branch and the two 401s in subjectToken)

RFC 9110 requires a challenge on every 401, and MCP clients use it to decide whether to re-authenticate. Right now only the missing-provider-token path sends one, so an assertion that expired between validation and exchange gives the client a bare 401 with nothing to act on. Something like:

func writeInvalidToken(w http.ResponseWriter) {
	w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
	http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
}

and in upstream-provider mode the invalid_grant case could reuse writeUpstreamAuthRequired, since re-auth with the embedded AS is the actual recovery there. It would be nicer still to carry resource_metadata like the auth middleware does, but buildWWWAuthenticate is private to TokenValidator, so that's probably a follow-up.

2. audience goes to Entra verbatim as scope (pkg/auth/obo/exchange/exchange.go, Target)

The CRD describes audience as the backend target identifier, so audience: api://backend is the natural thing to write. It reconciles fine, but the v2 endpoint only takes scopes, so every exchange fails with AADSTS70011, which lands in KindUnknown and becomes an opaque 502. The tests use api://backend/.default as the audience, which suggests it's really a scope. Either treat it as a resource the way MSAL does:

aud := strings.TrimSuffix(strings.TrimSpace(audience), "/")
if aud == "" || strings.HasSuffix(aud, "/.default") {
	return aud
}
return aud + "/.default"

or reject a bare resource at reconcile and reword the field doc to say it's a single v2 scope. I'd lean toward the first.

3. OBO doesn't get a default subject provider (pkg/vmcp/auth/types/defaults.go, DefaultSubjectProviderName)

token_exchange, aws_sts and xaa all get SubjectProviderName filled in when an embedded auth server is in front, but there's no obo case. Behind an embedded AS with subjectTokenProviderName omitted, OBO sends ToolHive's own session JWT to Entra and every call fails with invalid_grant, while the same setup with tokenExchange just works. The CRD doc does say to set the field, but it's easy to miss. The comment above that function already explains that xaa hard-errors on ambiguity because it has no deployments to break; OBO is in the same position, so:

case StrategyTypeOBO:
	if strategy.OBO == nil || strategy.OBO.SubjectTokenProviderName != "" {
		return strategy, nil
	}
	if hasMultipleUpstreams {
		return nil, ErrAmbiguousSubjectProvider
	}
	copied := strategy.DeepCopy()
	copied.OBO.SubjectTokenProviderName = providerName
	return copied, nil

The proxy side (applyOBORunConfig for an MCPServer with authServerRef) has the same gap. Defaulting there, or rejecting it with InvalidConfig, would both be fine.

4. An empty Secret value passes reconcile and then the proxy won't start (cmd/thv-operator/pkg/controllerutil/obo.go, verifyOBOClientSecret)

It only checks that the key exists, but the middleware factory refuses an empty env var, so the pod crash-loops while the config shows valid. The vMCP converter already rejects an empty value, so this would also bring the two paths in line:

if v, ok := secret.Data[ref.Key]; !ok || len(v) == 0 {
	return fmt.Errorf("obo: referenced client secret key is missing or empty")
}

Smaller things, take or leave:

  • pkg/transport/http.go skips the remote token injector only when the token-exchange middleware is present. A hand-written RunConfig with both remoteAuth and the OBO middleware would have the injector overwrite the OBO token. The operator can't produce that combination, so it's just hardening, but it's a one-liner: also check for obo.MiddlewareType in hasTokenExchangeMiddleware (and maybe rename it). pkg/auth/obo doesn't import pkg/transport, so there's no cycle.
  • The vMCP exchanger store never evicts. In discovered mode the backend reconciler re-reads the Secret, so each rotation leaves the old exchanger in memory, still holding the old secret and its users' cached tokens. Dropping entries that share (tokenURL, clientID) when a new fingerprint arrives would be enough.
  • MiddlewareParameters.Validate checks only that cacheSkewSeconds isn't negative. A huge value in a hand-written RunConfig overflows time.Duration and panics in cache.New. Reusing the operator's MaxInt32 bound fixes it. Similarly, parseOBOConfig in the vMCP strategy accepts a relative tokenUrl, and because the health check returns before the exchanger is built, the backend looks healthy while every real call fails. Running the same URL check there as entra.NewFromTokenURL does would catch that.
  • TestAddOBOSecretEnvVars lost the unauthenticated, embeddedAuthServer, awsSts and upstreamInject cases the old table had in its "returns no env vars" list. Worth putting back.
  • The 403 on a conditional-access challenge is called out as deliberate in the PR body, which is fine, but it diverges from Microsoft's guidance (a 401 with an insufficient_claims challenge). Could you say so in docs/middleware.md §9 too, so it isn't only recorded in the PR? The disableUpstreamTokenInjection doc comment in pkg/authserver/config.go should probably list OBO next to token exchange and AWS STS as well.
  • Optional: defaultBuildOBOExchanger in the vMCP strategy and DefaultFactory in the middleware build the exchanger the same way, with a comment asking to keep them in parity. A shared helper in pkg/auth/obo would remove that need. Similarly, oboExchangerStore with its interface and double-checked RWMutex could just be a mutex and a map, since building an exchanger does no I/O.

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

One more from looking at the stacked e2e (#7251): docs/arch/10-virtual-mcp-architecture.md says OBO works for discovered MCPServer, MCPRemoteProxy and MCPServerEntry backends, but I think only MCPServerEntry can. For the other two, vMCP applies the backend's OBO config and then calls the backend's proxy Service, and since this PR requires oidcConfigRef on every OBO MCPServer and MCPRemoteProxy, that proxy rejects the exchanged token (its aud is the backend) with a 401 before Entra is ever involved. The e2e's pending spec for the MCPServer case hits the same thing. Could the doc paragraph and the PR body say discovered mode works for MCPServerEntry only, and note the other two as a known limitation until discovery stops double-applying the backend's auth config?

tgrunnagle and others added 4 commits November 23, 2026 08:23
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]>
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]>
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]>
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]>
@tgrunnagle

Copy link
Copy Markdown
Collaborator Author

Replying to this review, one line per point.

  1. 401s without a challenge. Fixed in e9a1385. Every OBO 401 now sends WWW-Authenticate: Bearer error="invalid_token". In upstream-provider mode, invalid_grant reuses writeUpstreamAuthRequired. resource_metadata is left out because buildWWWAuthenticate is private to TokenValidator; docs/middleware.md §9 says so.
  2. audience sent verbatim. Fixed in e9a1385 by treating it as a resource, the MSAL way. exchange.Target trims it, drops a trailing /, and appends /.default unless it is already there. The CRD and contract field docs say audience is an Application ID URI or client ID, and that specific permissions go in scopes.
  3. No default subject provider. Fixed in 8bbbedd.
    • vMCP: DefaultSubjectProviderName has the obo case you suggested, including ErrAmbiguousSubjectProvider with more than one upstream.
    • Proxy: the runner defaults an empty subjectTokenProviderName to the upstream that upstream swap uses, when it adds the operator's OBO config. The operator's ApplyRunConfig never sees authServerRef, but the runner sees both the auth server and the OBO config. This also covers inline auth servers and hand-written RunConfigs. The serialized AdditionalMiddlewareConfigs carrier is left untouched.
  4. Empty Secret value. Fixed in feccb4f. verifyOBOClientSecret now rejects a missing or empty value, as a transient error the reconciler requeues.

Smaller items:

  • Remote token injector. Fixed in e9a1385. The helper is renamed hasTokenInjectingMiddleware and also matches obo.MiddlewareType.
  • Exchanger store never evicts. Fixed in ec67b63. A new secret for the same token URL, client ID and skew replaces the exchanger built with the old one. Skew is part of the match so that two backends sharing a client with different skews don't evict each other.
  • cacheSkewSeconds and relative tokenUrl. Fixed in feccb4f. MiddlewareParameters.Validate caps cacheSkewSeconds at MaxInt32. parseOBOConfig runs the new entra.ValidateTokenURL, the same check NewFromTokenURL makes, so a bad URL fails Validate and the health probe.
  • TestAddOBOSecretEnvVars cases. Restored in feccb4f: unauthenticated, embeddedAuthServer, awsSts, upstreamInject, plus xaa.
  • Docs. Updated in e9a1385. docs/middleware.md §9 explains the 403's departure from the insufficient_claims guidance: an MCP client can't do Entra's interactive step-up, and the claims value would disclose the tenant's conditional-access policy. disableUpstreamTokenInjection now lists OBO.
  • Optional items. Done in ec67b63. obo.NewCachedExchanger is the shared builder for the middleware and the vMCP strategy. The store is a plain mutex and map, and the barrier test seam is gone.

@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 Nov 23, 2026

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

Review

The PR ports the Entra on-behalf-of flow into OSS: Kubernetes-free exchange packages, proxy middleware, a vMCP OBOStrategy, and operator status handling. The changes since the last review share one obo.NewCachedExchanger builder between the proxy and vMCP, evict an exchanger when a rotated secret arrives, default subjectTokenProviderName to the embedded auth server's upstream on both paths, send <audience>/.default for a bare audience, add WWW-Authenticate challenges to OBO 401s, and tighten secret, skew and tokenUrl validation. The approach is sound, and the correctness and security pass found no defects. The open items are comment, documentation and test-strength gaps.

Cross-cutting notes:

  • Several user-visible behaviors changed: the exchange scope for an audience, the 401 challenges, the subject default behind an embedded auth server, tokenUrl rejection in vMCP Validate, the cacheSkew upper bound, and a requeue on an empty client Secret value. CLAUDE.md asks for the before and after in the PR body's user-facing section.
  • The proxy defaults to the first upstream where vMCP returns ErrAmbiguousSubjectProvider. The operator admits a single upstream for MCPServer and MCPRemoteProxy, so the proxy path cannot see more than one today, but the runner comment currently says the two paths behave the same.

Findings

# Severity Finding Location Raised by
1 LOW CRD cacheSkew doc omits the upper bound that is enforced cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go:268 api
2 LOW Architecture doc still describes one exchanger per client-secret fingerprint docs/arch/10-virtual-mcp-architecture.md:1091 readability, api
3 LOW invalid_grant row says "the same challenge as the row above" docs/middleware.md:532 api, readability
4 LOW invalid_grant in upstream-provider mode always gets the re-auth challenge, even when re-auth cannot fix it pkg/auth/obo/middleware.go:290 correctness
5 LOW Upstream-provider invalid_grant challenge assertion is loose pkg/auth/obo/middleware_test.go:673 tests
6 LOW exchange.Target has no direct tests and misses audience edge cases pkg/auth/obo/parameters_test.go:52 tests
7 LOW Comment says vMCP applies "the same default", but vMCP errors on multiple upstreams pkg/runner/middleware.go:317 api, readability, correctness
8 LOW Runner OBO subject default is not tested with multiple, zero or unnamed upstreams pkg/runner/middleware_test.go:471 tests
9 LOW Error paths of defaultOBOSubjectProvider have no test pkg/runner/middleware_test.go:471 tests
10 LOW Build-once test no longer detects a lost lock deterministically pkg/vmcp/auth/strategies/obo_test.go:646 tests
11 LOW Eviction test does not cover a failed build pkg/vmcp/auth/strategies/obo_test.go:685 tests

Resolved since the last review

  • Barrier test assertion messages described removed lock internals (pkg/vmcp/auth/strategies/obo_test.go), resolved in 528ee84.
  • InvalidCABundleMessage doc comment named a test in another package (cmd/thv-operator/pkg/controllerutil/ca_bundle.go), resolved in 528ee84.
  • Missing-config assertion was guarded by if validated != nil (cmd/thv-operator/controllers/mcpserver_externalauth_test.go), resolved in 528ee84.

How to test

  1. Run task test, task lint, task operator-test-integration and task license-check, then run the repo's generation tasks for CRDs, API docs and the swagger SDK and confirm the working tree stays clean.
  2. Mutation checks, each of which should fail a test:
    • Overwrite an explicit subjectTokenProviderName in defaultOBOSubjectProvider: the explicit-value row of TestPopulateMiddlewareConfigs_OBOSubjectProviderDefault should fail.
    • Remove the eviction loop in getOrCreateExchanger: TestOBOGetOrCreateExchanger_RotatedSecretReplacesOld should fail.
    • Remove the writeInvalidToken call on the empty-token branch, or branch on providerName in the invalid_grant case: the 401 challenge tests should fail.
    • Remove the ValidateTokenURL call from parseOBOConfig: the relative and non-https tokenUrl rows of TestOBOValidate_Invalid should fail.
  3. These mutations should fail a test but still pass (findings 5, 6, 8, 10 and 11):
    • Pick the last upstream instead of the first in defaultOBOSubjectProvider.
    • Look up under the lock, unlock, then build and store in getOrCreateExchanger.
    • Move the eviction loop above the buildExchanger call.
    • Drop the Bearer error="invalid_token" prefix from the upstream re-authentication challenge.
    • Let Target("/", nil) return a non-empty value.

Documentation updates

  • docs/arch/10-virtual-mcp-architecture.md: one exchanger per client, the subject default, the audience rule.
  • docs/middleware.md: split the invalid_grant row by subject source.
  • mcpexternalauthconfig_types.go CacheSkew: the math.MaxInt32 bound (then regenerate).
  • PR body: before and after for the behavior changes listed above.

Reviewed by dev:review-pr (finders: correctness and security, tests, readability and docs, API design). Generated with Claude Code.

Comment thread docs/middleware.md Resolved
Comment thread pkg/auth/obo/middleware.go Resolved
Comment thread pkg/auth/obo/middleware_test.go Resolved
Comment thread pkg/runner/middleware.go Resolved
Comment thread pkg/runner/middleware_test.go Resolved
Comment thread pkg/runner/middleware_test.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo_test.go Resolved
Comment thread pkg/vmcp/auth/strategies/obo_test.go Resolved
tgrunnagle and others added 2 commits November 23, 2026 10:13
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]>
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]>
@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 Nov 23, 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.

Thanks for turning these around so quickly. I checked each one against the new commits and they all look good, including the runner taking the first upstream (the operator already limits proxies to one, so that's fine). One small thing still open from my follow-up: docs/arch/10-virtual-mcp-architecture.md (around line 1108) and the PR body still say discovered mode works for MCPServer and MCPRemoteProxy backends, and #7251's README now says it can't. Please fix that before merging, but I don't need another look.

@tgrunnagle
tgrunnagle merged commit 5b002a9 into main Nov 23, 2026
116 of 121 checks passed
@tgrunnagle
tgrunnagle deleted the tgrunnagle/7199-oss-entra-obo branch November 23, 2026 19:53
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.

Support Entra on-behalf-of (OBO) backend auth in OSS

2 participants