Repository navigation
Support Entra on-behalf-of backend auth in OSS - #7201
tgrunnagle wants to merge 12 commits into
Conversation
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>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
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>
tgrunnagle
left a comment
There was a problem hiding this comment.
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
clientSecretEnvfor inline OBO backends. The pre-existing YAML loader resolves it intoclientSecretwithout clearing the env field, and the validator and the newparseOBOConfigreject 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 staleValid=Falseon 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.SecretEnvVarsno longer applies on the vMCP path, and the regenerated swagger renames exported types in the separatesdk/gomodule (wire format unchanged). Neither is called out in the PR description, which also says the factory "registers it directly" (it goes throughauth.NewOBOStrategy) and cites a function name that does not exist. - Documentation.
docs/middleware.mdhas a broken#9-audit-middlewarelink 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.mdor.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 onlyclientSecretEnvinto the vMCP ConfigMap and mounts the Secret under that env var. At startupYAMLLoader.Load(pkg/vmcp/config/yaml_loader.go:163-169) copies the env value intoobo.ClientSecretbut leavesClientSecretEnvset, andDefaultValidator.Validate(validator.go:307-308) then rejects the strategy with "clientSecret and clientSecretEnv are mutually exclusive", sothv vmcp serveandthv vmcp validateabort. The newparseOBOConfig(pkg/vmcp/auth/strategies/obo.go:287) enforces the same rule on every request. Discovered mode is unaffected becauseResolveSecretsclearsClientSecretEnv. 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 atyaml_loader.go:168as the token-exchange case does (yaml_loader.go:136-142only checks the env var is set andOBOStrategy.resolveClientSecretreads it at request time), or setobo.ClientSecretEnv = ""after resolving. Add a test that loads YAML withclientSecretEnv, runs the validator, thenOBOStrategy.Validate. Raised by: correctness-operator-vmcp. - [MEDIUM] A stale
Valid=False / InvalidConfigcan 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 surfacedEnterpriseRequired; now a malformed one surfacesInvalidConfig, the reasonownedByLocalValidation(external_auth_mirror.go:93) andsetMCPServerExternalAuthConfigValidConditiontreat 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 butownedByLocalValidationis true, so the condition is not removed, andsetMCPServerExternalAuthConfigValidConditionsees 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 fakeSourceRejectedreason 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 mirroredInvalidConfigat 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): TheRegenerate swagger and SDK for schema ordercommit is not a pure reorder. Indocs/server/swagger.yamlthe componentsgithub_com_stacklok_toolhive_pkg_auth_awssts.Configand.RoleMappingbecomeawssts.Configandawssts.RoleMapping, and in the separatesdk/gomodule the exportedAuthAWSSTSConfig,AuthAWSSTSRoleMappingandOptAuthAWSSTSConfigbecomeAWSSTSConfig,AWSSTSRoleMappingandOptAWSSTSConfig, with theRunnerRunConfiggetter and setter signatures changing. The JSON wire format is unchanged. The cause is swag switching between long and short schema names when the newpkg/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:136also still maps the long name toAuthAWSSTSConfig. 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 incmd/help/openapi-normalize/main.goor a swag@nameoverride onawssts.Config) so it cannot flip again. Raised by: api-design. - [MEDIUM]
docs/middleware.mdlinks 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) Middlewaresection 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 fromdocs/arch/02,03andvmcp-librarystill 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-281splicesAdditionalMiddlewareConfigsafter 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. ThediscoverInlineExternalAuthConfigSecrets/discoverExternalAuthConfigSecretstests 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 theClientSecretEnvproduced byconvertExternalAuthConfigToStrategy. Raised by: tests-operator.
How to test
- Run
task test,task lint,task operator-test-integrationandtask license-check; all should pass as the PR body reports. - Reproduce finding 1: load a vMCP YAML config whose OBO backend sets only
clientSecretEnv(with that variable set) throughconfig.YAMLLoaderandDefaultValidator.Validate; it currently fails with "clientSecret and clientSecretEnv are mutually exclusive". On a cluster, aVirtualMCPServerwith an inline OBO backend should crash-loop at startup with the same message. - Mutation checks for the test findings, each of which currently leaves the suite green: delete
|| tr.Error != ""atexchanger.go:396; deleteclient.CheckRedirect = ...in theinjected == nilbranch atexchanger.go:243; removeio.LimitReaderatexchanger.go:326; makesubjectTokenfall back toidentity.Tokenin provider mode; return the bare exchanger fromdefaultBuildOBOExchanger. A regression-catching test should fail for each. - Stale mirrored condition: create an obo
MCPExternalAuthConfigwith a valid spec, an MCPServer that references it, then make the spec invalid and revert it to the same valid spec; check the MCPServer'sExternalAuthConfigValidatedcondition clears. - Two OBO configs named
my-cfgandmy.cfgin oneVirtualMCPServershould 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
left a comment
There was a problem hiding this comment.
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
clientSecretEnvfor inline OBO backends. The pre-existing YAML loader resolves it intoclientSecretwithout clearing the env field, and the validator and the newparseOBOConfigreject 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 staleValid=Falseon 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.SecretEnvVarsno longer applies on the vMCP path, and the regenerated swagger renames exported types in the separatesdk/gomodule (wire format unchanged). Neither is called out in the PR description, which also says the factory "registers it directly" (it goes throughauth.NewOBOStrategy) and cites a function name that does not exist. - Documentation.
docs/middleware.mdhas a broken#9-audit-middlewarelink 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.mdor.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 onlyclientSecretEnvinto the vMCP ConfigMap and mounts the Secret under that env var. At startupYAMLLoader.Load(pkg/vmcp/config/yaml_loader.go:163-169) copies the env value intoobo.ClientSecretbut leavesClientSecretEnvset, andDefaultValidator.Validate(validator.go:307-308) then rejects the strategy with "clientSecret and clientSecretEnv are mutually exclusive", sothv vmcp serveandthv vmcp validateabort. The newparseOBOConfig(pkg/vmcp/auth/strategies/obo.go:287) enforces the same rule on every request. Discovered mode is unaffected becauseResolveSecretsclearsClientSecretEnv. 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 atyaml_loader.go:168as the token-exchange case does (yaml_loader.go:136-142only checks the env var is set andOBOStrategy.resolveClientSecretreads it at request time), or setobo.ClientSecretEnv = ""after resolving. Add a test that loads YAML withclientSecretEnv, runs the validator, thenOBOStrategy.Validate. Raised by: correctness-operator-vmcp. - [MEDIUM] A stale
Valid=False / InvalidConfigcan 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 surfacedEnterpriseRequired; now a malformed one surfacesInvalidConfig, the reasonownedByLocalValidation(external_auth_mirror.go:93) andsetMCPServerExternalAuthConfigValidConditiontreat 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 butownedByLocalValidationis true, so the condition is not removed, andsetMCPServerExternalAuthConfigValidConditionsees 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 fakeSourceRejectedreason 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 mirroredInvalidConfigat 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): TheRegenerate swagger and SDK for schema ordercommit is not a pure reorder. Indocs/server/swagger.yamlthe componentsgithub_com_stacklok_toolhive_pkg_auth_awssts.Configand.RoleMappingbecomeawssts.Configandawssts.RoleMapping, and in the separatesdk/gomodule the exportedAuthAWSSTSConfig,AuthAWSSTSRoleMappingandOptAuthAWSSTSConfigbecomeAWSSTSConfig,AWSSTSRoleMappingandOptAWSSTSConfig, with theRunnerRunConfiggetter and setter signatures changing. The JSON wire format is unchanged. The cause is swag switching between long and short schema names when the newpkg/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:136also still maps the long name toAuthAWSSTSConfig. 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 incmd/help/openapi-normalize/main.goor a swag@nameoverride onawssts.Config) so it cannot flip again. Raised by: api-design. - [MEDIUM]
docs/middleware.mdlinks 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) Middlewaresection 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 fromdocs/arch/02,03andvmcp-librarystill 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-281splicesAdditionalMiddlewareConfigsafter 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. ThediscoverInlineExternalAuthConfigSecrets/discoverExternalAuthConfigSecretstests 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 theClientSecretEnvproduced byconvertExternalAuthConfigToStrategy. Raised by: tests-operator.
How to test
- Run
task test,task lint,task operator-test-integrationandtask license-check; all should pass as the PR body reports. - Reproduce finding 1: load a vMCP YAML config whose OBO backend sets only
clientSecretEnv(with that variable set) throughconfig.YAMLLoaderandDefaultValidator.Validate; it currently fails with "clientSecret and clientSecretEnv are mutually exclusive". On a cluster, aVirtualMCPServerwith an inline OBO backend should crash-loop at startup with the same message. - Mutation checks for the test findings, each of which currently leaves the suite green: delete
|| tr.Error != ""atexchanger.go:396; deleteclient.CheckRedirect = ...in theinjected == nilbranch atexchanger.go:243; removeio.LimitReaderatexchanger.go:326; makesubjectTokenfall back toidentity.Tokenin provider mode; return the bare exchanger fromdefaultBuildOBOExchanger. A regression-catching test should fail for each. - Stale mirrored condition: create an obo
MCPExternalAuthConfigwith a valid spec, an MCPServer that references it, then make the spec invalid and revert it to the same valid spec; check the MCPServer'sExternalAuthConfigValidatedcondition clears. - Two OBO configs named
my-cfgandmy.cfgin oneVirtualMCPServershould 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.
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>
|
Replies to the review-body findings that have no inline thread (review 5982042243):
|
tgrunnagle
left a comment
There was a problem hiding this comment.
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,parseOBOConfigand the validator agree, andTestOBOIntegration_InlineConfigFileLoadruns the loader, validator and strategy together. Discovered mode is unchanged. - Mirrored conditions. The prefix approach fixes the stale mirrored
InvalidConfigafter a source heals to its exact spec, andTestExternalAuthMirror_OBOSourceHealsToSameSpecexercises it with the real reasons. The same-hash guard can still hold a locally produced obo-without-OIDCInvalidConfigwhen 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 indocs/arch/09anddocs/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_clientthat 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.mdor 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 / InvalidConfigcan 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.mdlinks 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
ClientSecretEnvbranch 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-cfgvsmy.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
- Run
task test,task lint,task operator-test-integrationandtask license-check. - Inline backend: load a vMCP YAML config whose OBO backend sets only
clientSecretEnv(variable set) throughconfig.YAMLLoaderandDefaultValidator.Validate, then callOBOStrategy.Validate; all should pass. With the variable unset the loader should fail withenvironment variable ... not set. - Stale local condition (finding 1): create a valid non-obo
MCPExternalAuthConfig, an MCPServer withoutoidcConfigRefthat references it, change the source to obo (consumer becomesInvalidConfig), then revert the source to the original spec; theExternalAuthConfigValidatedcondition should go back to True, and today it stays False. - Mutation checks that should fail but currently pass: delete the
Getenv(...) == ""check atyaml_loader.go:169; replacereturn ctrl.Result{}, statusErrwithreturn ctrl.Result{}, nilin the MCPServer terminal branch; delete thelogExchangeFailurecalls instrategies/obo.go. - Edge inputs: a 429 with an empty or HTML body against
entra.NewFromTokenURLshould be transient; an inline config withclientId: " "should be rejected byOBOStrategy.Validate. - Run
TestOBOGetOrCreateExchanger_BuildsOnceUnderContentionon 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.
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>
tgrunnagle
left a comment
There was a problem hiding this comment.
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_clientmessage change makes the vMCP strategy consistent with the proxy middleware's opaque 502.errors.Isstill matches the sentinel, so callers that branch on it are unaffected. - The
afterReadMisshook on a production struct deviates from.claude/rules/testing.mdand 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/09now describes it, and the PR body should carry the before/after as well. Validatefails late for a whitespacetokenUrl(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
InvalidConfigafter the source reverted (cmd/thv-operator/controllers/mcpserver_controller.go:2583,mcpremoteproxy_controller.go:1132) - [MEDIUM]
TestOBOGetOrCreateExchanger_BuildsOnceUnderContentionwas 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_clientclass to MCP clients (pkg/vmcp/auth/strategies/obo.go:256) - [LOW] Whitespace-only
clientIdpassed 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
task test,task lint,task operator-test-integration,task license-check.- Mutation checks, each of which should fail the named test:
- Remove the
Message != ctrlutil.MsgOBORequiresIncomingAuthclause from either same-hash guard:TestExternalAuthMirror_OBOIncomingAuthRejectionClearsOnRevertfails for that consumer. - Delete the second check after
s.mu.Lock()ingetOrCreateExchanger:TestOBOGetOrCreateExchanger_BuildsOnceUnderContentionreports 8 builds. - Revert
isTransientStatusinparseResponsetostatus >= 500: the 429 and 408 rows fail. - Delete the
logExchangeFailurecalls:TestOBOAuthenticate_ExchangeErrorMappingfails.
- Remove the
- Mutation checks that still pass (findings 1 and 3): make a production CA-bundle message start with
Referenced MCPExternalAuthConfig, or make themissing-configrow fail for a different reason. - Configure a vMCP OBO backend with
tokenUrl: " "and callValidate; 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")), |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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}, |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
|
|
||
| **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. |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
Addressed in 065a770: the "(previously the source message alone)" parenthetical is removed and the doc notes that the ":
| // 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() |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
| } | ||
| cfg := strategy.OBO | ||
|
|
||
| if cfg.TokenURL == "" { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
Addressed in 5027c70: parseOBOConfig checks strings.TrimSpace(cfg.TokenURL) == "", and TestOBOValidate_Invalid has a "whitespace token url" row.
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>
Summary
ErrEnterpriseRequired(operator) or a 503 (proxy), so anoboMCPExternalAuthConfigshowedValid=False / Reason=EnterpriseRequired. OBO is now a community feature, so this PR makes it a working built-in strategy.jwt-bearergrant withrequested_token_use=on_behalf_of), a per-(user token hash, exchange target) token cache, and the real proxy middleware underpkg/auth/obo/.... These packages do not link Kubernetes; a guard test enforces that.MCPServerandMCPRemoteProxy, and a real converter and outgoing strategy forVirtualMCPServerbackends (inline, discovered, andMCPServerEntry).oboconfig on anMCPServerorMCPRemoteProxythat has nooidcConfigRefwithInvalidConfig. OBO needs an authenticated user token, and without this check every request would fail with 401 at runtime.my-cfg,my.cfg) stay distinct.RegisterOBOHandler,obo.RegisterFactory,auth.RegisterOBOStrategy,ErrEnterpriseRequired,ConditionReasonEnterpriseRequired) stay exported and markedDeprecated:. Removal is tracked in Remove deprecated OBO enterprise hooks and sentinels #7200.Closes #7199
Type of change
Test plan
task test)task test-e2e)task lint)Also run:
task operator-test-integration(envtest),task license-checkandtask docs-verify. Results are quoted under Verification.task test-e2ewas not run.API Compatibility
v1beta1API, OR theapi-break-allowedlabel 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
pkg/auth/obo/exchangeToken,Exchanger,TokenExchanger,Target(audience, scopes). It exists to avoid anobo -> entra -> oboimport cycle.pkg/auth/obo/entrainteraction_required/ claims challenge / AADSTS50076 and 50079,invalid_grant,invalid_client, transient including 429, 408 andtemporarily_unavailable), redirects refused, 1 MiB response cap. The constructor isNewFromTokenURL(TokenURL(tenant, authority), ...).pkg/auth/obo/cachepkg/auth/oboMiddlewareParameterswithValidate/ExchangeTarget.DefaultFactoryis the real middleware and the default behindCreateMiddleware. Guard testTestPackages_DoNotLinkKubernetes.pkg/runner/middleware.gocmd/thv-operator/pkg/controllerutil/obo.goExternalAuthTypeswitches.OBOHandlerintokenexchange.gois now a deprecated override of the built-in.cmd/thv-operator/controllersMCPExternalAuthConfig:*obo.ValidationErrormaps toInvalidConfigwith no requeue, other errors requeue.MCPServerandMCPRemoteProxy: terminalExternalAuthConfigValidated=False / InvalidConfigwithoutoidcConfigRef.VirtualMCPServer: per-config OBO secret env vars. Mirrored source conditions carry aReferenced MCPExternalAuthConfig '<name>' is invalid:message prefix so they are not mistaken for a consumer's own validation failure (now that an invalid obo source reportsInvalidConfig).cmd/thv-operator/pkg/vmcpconfig/converter.gopkg/vmcp/auth/converters/obo.goOBOConverter: CRD toauthtypes.OBOConfig(tenant/authority to token URL,cacheSkewto seconds);ResolveSecretsreads the client secret.pkg/vmcp/auth/strategies/obo.gofactory.NewOutgoingAuthRegistryregisters it throughauth.NewOBOStrategy, which returns this strategy unless the deprecated override is set.pkg/vmcp/config/yaml_loader.goclientSecretEnvis checked but no longer copied intoclientSecret, so the operator-rendered inline config passes the validator (as tokenExchange already did).cmd/help/openapi-normalizeawssts.*schema names to the path form, so the generated SDK keepsAuthAWSSTSConfigand friends regardless of which name swag emits once the OBO packages are in the import graph.pkg/vmcp/auth/obo.goErrEnterpriseRequiredstub is removed.NewOBOStrategyis kept and returns the built-in strategy;RegisterOBOStrategyis deprecated but still overrides.docs/operator/crd-api.md, chart CRD copiesdocs/middleware.md,docs/arch/09,docs/arch/10obo_reconcile_test.goforValid=True/InvalidConfig. vMCP integration testtest/integration/vmcp/obo_integration_test.goagainst a mock Entra token endpoint, including YAML loader → validator → strategy for an inline backend. Tests that assertedEnterpriseRequiredare rewritten.Does this introduce a user-facing change?
Yes.
oboMCPExternalAuthConfigshowedValid=False / Reason=EnterpriseRequired. Proxies returned 503 for OBO, and vMCP backends failed to authenticate.oboconfig reconciles toValid=True. OBO works forMCPServer,MCPRemoteProxy,VirtualMCPServerandMCPServerEntrybackends. A config with a missing tenant, client ID or client secret ref, with neither audience nor scopes, or with a negativecacheSkewor one above MaxInt32 seconds showsValid=False / Reason=InvalidConfig. AnMCPServerorMCPRemoteProxythat references anoboconfig withoutoidcConfigRefshowsExternalAuthConfigValidated=False / Reason=InvalidConfig.Authorizationwith the exchanged token. Failure responses are generic: 401 for a missing token orinvalid_grant, 403 plus anobo_token_exchangeaudit event for a conditional-access or claims challenge, 502 forinvalid_client, Entra 5xx, 429, 408,temporarily_unavailable, timeouts or unclassified failures (a throttled reply is a 502 whatever its body; Entra'sRetry-Afteris not forwarded). These are documented indocs/middleware.mdsection 9.error_description. It names at most the failure class (denied, invalid grant, transient); a rejected client credential reads as a plainobo: token exchange failed, matching the proxy's opaque 502; the detail is logged by vMCP (DEBUG forinvalid_grant, WARN otherwise), and conditional-access denials are audited as on the proxy. Each OBO backend's secret is mounted on the vMCP pod asTOOLHIVE_OBO_CLIENT_SECRET_<CONFIG_NAME>_<HASH8>.MCPServerandMCPRemoteProxy(any external auth type). Before:ExternalAuthConfigValidated=Falsecarried 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 sameConfigHash.thv runhas no OBO flags (out of scope). A RunConfig carrying the middleware config works.Special notes for reviewers
RegisterOBOHandler,obo.RegisterFactoryorauth.RegisterOBOStrategy, its implementation wins over the built-in. That keeps the overlay compiling and behaving until it is deleted. One deliberate exception: a registeredOBOHandler.SecretEnvVarsdoes not apply toVirtualMCPServer, which always uses the per-config name so OBO backends cannot collide (stated in theDeprecated:notes).TOOLHIVE_OBO_CLIENT_SECRET(one OBO config per proxy). vMCP usesGenerateUniqueOBOSecretEnvVarName(configName)(sanitized name plus the first 8 hex characters of its SHA-256), viaOBOVMCPSecretEnvVars. The other generators (token exchange, XAA, header injection) share the sanitize-only weakness; that is pre-existing and left alone here. The vMCP converter leavesClientSecretEnvempty and the two inline enrichment sites set it (theVirtualMCPServercontroller and thevmcpconfigconverter); discovered mode usesResolveSecrets.*obo.ValidationErroris a terminalInvalidConfig(no requeue). Anything else, such as a Secret not yet available, requeues.clientSecretRefthat resolves to an empty value atResolveSecrets(the other converters defer that to request time), and a whitespace-onlyclientId, matching the operator; the vMCP strategy'sValidaterejects a whitespace-onlyclientIdortokenUrltoo, 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.MCPRemoteProxynow returns the status-write error when recording anInvalidConfigrejection, so a failed write is retried, asMCPServeralready did.entra.Configandentra.Neware gone; nothing in this repo used them, andentra.NewFromTokenURL(entra.TokenURL(tenant, authority), ...)covers the same case. The package is new in OSS, so no released caller exists.AddOBOSecretEnvVarsno longer swallows errors. TheMCPServerbuilder logs and continues while the drift check returns true. This divergence already existed and is documented at the site.operator-crdsChart.yamlonly changes in release PRs (git logshows only "Release vX" commits touching it), so the CRD files and templates are regenerated but the version is not bumped.docs/remote-mcp-authentication.mdnot changed. It documents the CLI's client-side remote MCP auth and has no external-auth content. The OBO docs went todocs/middleware.md,docs/arch/09-operator-architecture.mdanddocs/arch/10-virtual-mcp-architecture.md.thv runCLI flags for OBO, and certificate or workload-identity client authentication for Entra.Verification
Run at 5027c70 (after review fixes):
task lint: exit 0, "0 issues."task test: exit 0, no FAIL or DATA RACE linestask 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 0task docs-verify: exit 0 (generatedsdk/gois identical to main)Acceptance criteria:
TestMCPExternalAuthConfigReconciler_OBO_Validation; envtestobo_reconcile_test.go("reconciles a well-formed obo config to Valid=True", DescribeTable for missing tenant, client ID, secret ref and target).TestAddExternalAuthConfigOptions_OBO;TestMCPServerDeployment_OBOSecretEnvVars;TestMCPRemoteProxyDeployment_OBOSecretEnvVars; runnerTestOBORegistration(mock Entra, header replaced);pkg/auth/obomiddleware tests.TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth; MCPRemoteProxy table cases;TestAddExternalAuthConfigOptions_OBOErrors; envtest "rejects an MCPServer ... without oidcConfigRef".MCPServerEntryviaDiscoverAndResolveAuth), distinct env vars:test/integration/vmcpTestOBOIntegration_DiscoveredAuthPath,TestOBOIntegration_InlineTwoBackendsandTestOBOIntegration_InlineConfigFileLoad; operatorTestDiscoverExternalAuthConfigSecrets_TwoOBOBackends;TestGetExternalAuthConfigSecretEnvVars_OBO;TestConvertExternalAuthConfigToStrategy(obo case); vmcpconfigTestConvertExternalAuthConfigToStrategy_OBOUsesPerConfigSecretEnv.ErrEnterpriseRequiredor 503 in OSS:git grepshowsErrEnterpriseRequiredonly declared (deprecated) inpkg/auth/obo/errors.go; the stub is removed;TestNewOutgoingAuthRegistry"obo strategy is the built-in Entra OBO strategy".pkg/auth/oboTestPackages_DoNotLinkKubernetes.EnterpriseRequiredtests rewritten. Review-fix coverage:TestMiddleware_ContextErrors,TestExchanger_ExchangeToken_ClientTimeoutIsTransient.Breaking changes
None for the
v1beta1API. Observable change: the operator no longer emitsReason=EnterpriseRequired; the exported identifiers that referenced it remain, deprecated.🤖 Generated with Claude Code