Skip to content

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

Draft
tgrunnagle wants to merge 12 commits into
mainfrom
tgrunnagle/7199-oss-entra-obo
Draft

tgrunnagle wants to merge 12 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). It 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. Guard test TestPackages_DoNotLinkKubernetes.
pkg/runner/middleware.go Registers the real OBO factory.
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), 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/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.
  • Proxy runtime: the middleware replaces Authorization with the exchanged token. Failure responses are generic: 401 for a missing token or 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.
  • 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, 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.
  • 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 5027c70 (after review fixes):

  • task lint: exit 0, "0 issues."
  • task test: exit 0, no FAIL or DATA RACE lines
  • task operator-test-integration: exit 0, "Ginkgo ran 12 suites ... Test Suite Passed"

Run at 2f12135 (the later commits add no files and do not touch API or swagger sources):

  • task license-check: exit 0
  • task docs-verify: exit 0 (generated sdk/go is identical to main)

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 19, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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 97.88434% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.74%. Comparing base (4dcddda) to head (5027c70).
⚠️ Report is 14 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/obo/entra/exchanger.go 96.47% 5 Missing ⚠️
cmd/thv-operator/pkg/controllerutil/obo.go 96.73% 3 Missing ⚠️
pkg/auth/obo/cache/cache.go 96.87% 2 Missing ⚠️
pkg/auth/obo/entra/errors.go 91.66% 2 Missing ⚠️
pkg/vmcp/auth/strategies/obo.go 98.43% 2 Missing ⚠️
...-operator/controllers/mcpremoteproxy_controller.go 96.42% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7201      +/-   ##
==========================================
+ Coverage   81.60%   81.74%   +0.14%     
==========================================
  Files         898      906       +8     
  Lines       91482    92251     +769     
==========================================
+ Hits        74651    75408     +757     
- Misses      16826    16838      +12     
  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 <noreply@anthropic.com>
@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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@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.


localMessages := map[string]string{
"obo incoming auth": ctrlutil.MsgOBORequiresIncomingAuth,
"CA bundle": fmt.Sprintf("invalid CA bundle: %v", errors.New("missing key")),

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.

[LOW] Prefix-invariant test copies the CA-bundle message format, so it only pins the obo constant

TestMirroredMessagePrefix_NotUsedByLocalMessages uses the real ctrlutil.MsgOBORequiresIncomingAuth, but the CA-bundle entry is a private copy, fmt.Sprintf("invalid CA bundle: %v", ...), of the format used in mcpserver_controller.go (2511, 2698), mcpremoteproxy_controller.go (153, 1072, 1248) and virtualmcpserver_controller.go (647). A production message that gained the Referenced MCPExternalAuthConfig prefix would not fail the test. The entry is also built with ConditionReasonInvalidConfig, where production writes InvalidCABundle. The comment at external_auth_mirror.go:36-37 says the test "checks the fixed ones", which overstates what it protects.

Recommendation: Share the CA-bundle message through a helper or constant that production and the test both use, and build that entry with ConditionReasonInvalidCABundle. Otherwise reword the test name and the comment to say it pins the obo message only.

Raised by: tests, readability.

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.

Addressed in 065a770: the CA bundle message now comes from ctrlutil.InvalidCABundleMessage, used by all seven controller sites and by the test, and the test builds that entry with ConditionReasonInvalidCABundle. The mirror comment now names exactly what the test pins.

// MCPExternalAuthConfig (see isLocalValidationFailure): the source can heal
// back to an unchanged ConfigHash, and holding it would then be permanent too.
// The obo incoming-auth rejection (ctrlutil.MsgOBORequiresIncomingAuth) is not
// held either: it re-runs earlier in this same function and returns before the

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.

[LOW] Doc comment says the check re-runs "in this same function", but it sits on the setter

The added sentence says the obo incoming-auth rejection "re-runs earlier in this same function". The comment is on setMCPServerExternalAuthConfigValidCondition; the re-run happens in handleExternalAuthConfig, which calls the setter. The MCPRemoteProxy copy of the sentence names handleExternalAuthConfig correctly, so the two disagree.

Recommendation: Write "earlier in handleExternalAuthConfig" to match mcpremoteproxy_controller.go.

Raised by: readability.

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.

Addressed in 065a770: both sentences in the MCPServer doc comment now say "earlier in handleExternalAuthConfig", matching the MCPRemoteProxy copy.

}{
{name: "rejection is persisted and not requeued", authRef: "obo-config"},
{name: "failed status write is retried", authRef: "obo-config", interceptor: &failRejectionWrite, wantErr: statusErr},
{name: "non-validation error is requeued", authRef: "missing-config", wantAnyErr: true},

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.

[LOW] "non-validation error is requeued" row passes on any error

The row uses authRef: "missing-config" (the fixture config is obo-config) and only runs require.Error. Nothing shows the error came from the missing referenced config, and a regression that took the terminal obo path with some other error would also pass. The row returns before asserting the result or the persisted status, so the table drives three differently shaped assertion paths.

Recommendation: Replace wantAnyErr with an expected error text (the not-found error) and assert that the persisted MCPServer has no InvalidConfig condition carrying MsgOBORequiresIncomingAuth.

Raised by: tests.

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.

Addressed in 065a770: the row (now "missing referenced config is requeued") asserts the exact error "MCPExternalAuthConfig missing-config not found in namespace default", and checks that the persisted MCPServer carries no ExternalAuthConfigValidated condition with MsgOBORequiresIncomingAuth.

Comment thread docs/arch/09-operator-architecture.md Outdated

**Entra on-behalf-of (`type: obo`)**: the MCPExternalAuthConfig reconciler validates what the schema cannot (a tenant, `clientId`, `clientSecretRef`, at least one of `audience`/`scopes`, a `cacheSkew` that is non-negative and at most MaxInt32 seconds, and a usable tenant/authority) and reports a violation as `Valid=False / Reason=InvalidConfig` without requeueing. For MCPServer and MCPRemoteProxy the operator (`cmd/thv-operator/pkg/controllerutil/obo.go`) appends an `obo` middleware config to the RunConfig and mounts the client secret into the proxyrunner pod as `TOOLHIVE_OBO_CLIENT_SECRET`; a workload that references an `obo` config without `oidcConfigRef` is rejected with `ExternalAuthConfigValidated=False / Reason=InvalidConfig`, because OBO needs an authenticated user token. VirtualMCPServer mounts each OBO backend's secret under a per-config name (`TOOLHIVE_OBO_CLIENT_SECRET_<CONFIG_NAME>_<HASH8>`, where `<HASH8>` is the first 8 hex characters of the SHA-256 of the config name, so `my-cfg` and `my.cfg` stay distinct) so several OBO backends in one pod do not collide. See [Virtual MCP outgoing authentication](10-virtual-mcp-architecture.md#outgoing-authentication) and the [OBO middleware](../middleware.md#9-on-behalf-of-obo-middleware).

**Referenced config failures on consumers**: when a referenced MCPExternalAuthConfig is `Valid=False`, MCPServer and MCPRemoteProxy copy its reason onto their `ExternalAuthConfigValidated` condition with the message `Referenced MCPExternalAuthConfig '<name>' is invalid: <source message>` (previously the source message alone). The prefix tells a copied `InvalidConfig` from one the consumer set itself, such as the obo incoming-auth rejection, so the copied one clears when the source heals even if its `ConfigHash` is unchanged.

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.

[LOW] Architecture doc narrates change history ("previously the source message alone")

The new paragraph ends its message-format sentence with "(previously the source message alone)". Architecture pages describe the current system, and the parenthetical will read oddly after merge. CLAUDE.md puts the before/after in the PR body's user-facing section. The format itself matches mirroredConditionMessage in external_auth_mirror.go, which also drops the : <source message> suffix when the source message is empty; the doc does not say so.

Recommendation: Delete the parenthetical and keep the before/after in the PR body. Optionally note that the suffix is omitted for an empty source message.

Raised by: readability.

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.

Addressed in 065a770: the "(previously the source message alone)" parenthetical is removed and the doc notes that the ": " suffix is dropped when the source message is empty. The before/after is in the PR body's user-facing section.

Comment thread pkg/vmcp/auth/strategies/obo.go Outdated
Comment on lines +64 to +67
// afterReadMiss, when set, runs in getOrCreateExchanger between the
// read-locked miss and taking the write lock. Tests use it to make every
// caller miss before any of them builds; production leaves it nil.
afterReadMiss func()

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.

[LOW] afterReadMiss is a nil-in-production test hook on OBOStrategy

afterReadMiss func() is a nil-checked field documented as nil in production, called from getOrCreateExchanger on every cache miss (obo.go:214). .claude/rules/testing.md ("Test Hooks in Production Structs") says to avoid test-only hook fields and not to expand existing ones. The existing buildExchanger hook runs only under the write lock, so it cannot observe the read-miss to write-lock gap this test needs. Nothing at the site states a deliberate deviation. The cost is a nil check on a cold path.

Recommendation: Put the exchanger map behind a small unexported seam the test wraps to add the barrier, or expose the barrier only through a constructor option. If the hook stays, say so at the site and in the PR body.

Raised by: tests.

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.

Addressed in 5027c70: the afterReadMiss field is gone. The exchanger map now sits behind an unexported oboExchangerStore interface (lookup / lookupOrStore, production rwExchangerStore). The contention test wraps the store with a barrier on lookup misses, so the double-check inside lookupOrStore stays production code under test.

Comment thread pkg/vmcp/auth/strategies/obo.go Outdated
}
cfg := strategy.OBO

if cfg.TokenURL == "" {

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.

[LOW] Whitespace-only tokenUrl passes validation and fails on the first request

parseOBOConfig now rejects a whitespace-only clientId with strings.TrimSpace, but the tokenUrl check on the line above still compares with "". entra.NewFromTokenURL trims and rejects a blank URL (exchanger.go:161), but it is reached only through getOrCreateExchanger during Authenticate, so a whitespace tokenUrl passes Validate and fails with "obo: build exchanger: ..." on the first request. The two required fields are now validated differently.

Recommendation: Use strings.TrimSpace(cfg.TokenURL) == "" and add a whitespace tokenUrl row beside the whitespace clientId row in TestOBOValidate_Invalid.

Raised by: correctness.

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.

Addressed in 5027c70: parseOBOConfig checks strings.TrimSpace(cfg.TokenURL) == "", and TestOBOValidate_Invalid has a "whitespace token url" row.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Addresses #7201 review comments:
- LOW pkg/vmcp/auth/strategies/obo.go:67 (4661456815): the exchanger map moves behind an unexported oboExchangerStore interface that the contention test wraps, removing the afterReadMiss hook field
- LOW pkg/vmcp/auth/strategies/obo.go:351 (4661456823): a whitespace-only tokenUrl fails validation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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

This branch has not been deployed

No deployments
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

1 participant