Repository navigation
Description
Description
Wire the new obo external auth type into the three operator dispatch sites and prove the wiring end-to-end with envtest integration tests. After this task, applying an obo-typed MCPExternalAuthConfig from any of the three consumer CRs (MCPServer, MCPRemoteProxy, VirtualMCPServer) surfaces a uniform status.conditions[Valid] = False / Reason: EnterpriseRequired outcome instead of the generic "unsupported external auth type" or "unknown middleware type" error that would otherwise leak from the default: arms of the existing switches.
This is purely the dispatch + test layer. The default stubs and exported symbols this task consumes (OBOHandler, RegisterOBOHandler, OBOValidate, OBOSecretEnvVars, ErrEnterpriseRequired, MiddlewareType, the registered OBOConverterStub) all land in the dependency task and exist at compile time before this task starts.
Context
This is the third of four flat technical tasks under the parent OSS story. The parent story establishes the function-pointer override hook design for obo. The first task factors the operator and proxyrunner mains. The second task ("default handler infrastructure") creates the default-stub package surface this task wires into.
What lands here:
- Two operator-side switch arms — one new
case mcpv1beta1.ExternalAuthTypeOBOarm placed before thedefault:in each of the two existingswitch externalAuthConfig.Spec.Typeblocks. Both arms route through the function-pointer hook from the dependency task; neither falls through to thedefault:'s "unsupported external auth type" path. - One new reconcile-loop branch — a branch in
cmd/thv-operator/controllers/mcpexternalauthconfig_controller.gothat invokescontrollerutil.OBOValidateand mapsErrEnterpriseRequiredtostatus.conditions[Valid] = False/Reason: EnterpriseRequiredviacontrollerutil.MutateAndPatchStatus. The exact reason stringEnterpriseRequiredis part of the user-facing contract — external consumers pattern-match on it. - Integration tests — applying an
obo-typedMCPExternalAuthConfigto an envtest cluster, referenced from each of the three consumer CR types, and asserting theValid=False/EnterpriseRequiredcondition propagates correctly. A separate guard asserts neither the reconciler logs nor the resource status surface a generic "unsupported external auth type" or "unknown middleware type" string.
Dependencies: #5325 (parent story), #5327 (consumes OBOHandler, RegisterOBOHandler, OBOValidate, OBOSecretEnvVars, ErrEnterpriseRequired, MiddlewareType, and the registered OBOConverterStub — none of these symbols exist before #5327 merges).
Blocks: #5329 (CRD enum admission — the LAST OSS task, which lights up apiserver-level admission of obo typed configs).
Acceptance Criteria
Code surface:
- In
cmd/thv-operator/pkg/controllerutil/tokenexchange.goAddExternalAuthConfigOptions, the switch at line 101 admitscase mcpv1beta1.ExternalAuthTypeOBOas a new arm placed before thedefault:. The seven existing arms (tokenExchange,headerInjection,bearerToken,unauthenticated,embeddedAuthServer,awsSts,upstreamInject) and thedefault:arm are byte-identical to before. - In
cmd/thv-operator/controllers/virtualmcpserver_deployment.go(*VirtualMCPServerReconciler).getExternalAuthConfigSecretEnvVar, the switch at line 789 admitscase mcpv1beta1.ExternalAuthTypeOBOas a new arm placed before thedefault:. The seven existing arms and thedefault:arm are byte-identical to before. - In
cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go, a new branch checkscfg.Spec.Type == mcpv1beta1.ExternalAuthTypeOBO, callscontrollerutil.OBOValidate(cfg), and on error setsstatus.conditions[Valid] = Falseviacontrollerutil.MutateAndPatchStatus(NOTr.Status().Update). The reason string is exactlyEnterpriseRequiredwhenerrors.Is(err, controllerutil.ErrEnterpriseRequired)is true, and exactlyInvalidConfigfor any other error. - The existing
r.Status().Update(ctx, externalAuthConfig)call sites at lines 108 and 137 of the reconciler are unchanged. (Refactoring them is explicitly out of scope — see "Out of Scope" below.)
Behavior:
- Applying an
obo-typedMCPExternalAuthConfigreferenced from anMCPServercauses theMCPExternalAuthConfigresource to transition tostatus.conditions[Valid] = FalsewithReason: EnterpriseRequiredand a fixed, human-readable message describing the registration requirement. - Applying an
obo-typedMCPExternalAuthConfigreferenced from anMCPRemoteProxyproduces the same transition on theMCPExternalAuthConfigresource. - Applying an
obo-typedMCPExternalAuthConfigreferenced from aVirtualMCPServerproduces the same transition on theMCPExternalAuthConfigresource. The vMCP converter path wraps the sentinel throughpkg/vmcp/auth/converters/interface.go:191("failed to convert to strategy: %w"); the reconciler recognizes the wrapped sentinel viaerrors.Is(err, externalauth.ErrEnterpriseRequired), not by matching the wrap prefix. - In all three consumer CR cases, the consumer (
MCPServer/MCPRemoteProxy/VirtualMCPServer) surfaces a parallelValid=False/EnterpriseRequiredcondition. It does NOT surface a generic "unsupported external auth type" error. - Generic-error guard: applying any
obo-typed CR — across all three consumer paths — does not cause any reconciler log line or any status message to contain the substrings "unsupported external auth type" or "unknown middleware type".
Regression:
- Every existing integration test under
cmd/thv-operator/test-integration/mcp-external-auth/passes unchanged.
Hygiene:
- No new lint findings;
task lint-fixsucceeds;gofmtandgoimportsare clean. - All tests pass via
task test. - Code reviewed and approved.
Technical Approach
Recommended Implementation
(a) Switch arm in cmd/thv-operator/pkg/controllerutil/tokenexchange.go
Add one new arm to the existing 7-arm switch at line 101. Place it immediately before the default: arm. The dependency task introduced oboHandler as a package-level OBOHandler value; this arm calls through its ApplyRunConfig method so an out-of-tree-registered handler dispatches first and the default surfaces ErrEnterpriseRequired:
case mcpv1beta1.ExternalAuthTypeOBO:
return oboHandler.ApplyRunConfig(ctx, c, namespace, externalAuthConfig, options)The seven existing arms (tokenExchange, headerInjection, bearerToken, unauthenticated, embeddedAuthServer, awsSts, upstreamInject) and the default: are unchanged. The new arm short-circuits before the default:'s fmt.Errorf("unsupported external auth type: %s", externalAuthConfig.Spec.Type) so the user-visible error path stays inside the ErrEnterpriseRequired chain.
(b) Switch arm in cmd/thv-operator/controllers/virtualmcpserver_deployment.go
Add one new arm to the existing 7-arm switch at line 789, placed before the default:. This switch returns *corev1.EnvVar (or nil, nil if the type doesn't need a secret env var). The dependency task introduced the controllerutil.OBOSecretEnvVars wrapper that calls through oboHandler.SecretEnvVars:
case mcpv1beta1.ExternalAuthTypeOBO:
envVars, err := ctrlutil.OBOSecretEnvVars(externalAuthConfig)
if err != nil {
return nil, err
}
if len(envVars) == 0 {
return nil, nil
}
return &envVars[0], nilThe shape matches the other arms in the function: each existing arm either returns (nil, nil) (no secret to mount), or builds an EnvVar from the type-specific secret ref and returns it. Routing OBO through the function-pointer hook preserves the same shape while letting the default stub surface ErrEnterpriseRequired.
The seven existing arms and the default: are unchanged.
(c) Reconcile-loop branch in cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go
Add a new branch that runs the OBO function-pointer validation after the existing Validate() call succeeds, then maps the result to a Valid=False condition with the right reason string:
if cfg.Spec.Type == mcpv1beta1.ExternalAuthTypeOBO {
if err := controllerutil.OBOValidate(cfg); err != nil {
reason := "InvalidConfig"
if errors.Is(err, controllerutil.ErrEnterpriseRequired) {
reason = "EnterpriseRequired"
}
return setInvalid(cfg, err, reason)
}
}Where setInvalid is a small helper that writes the condition through controllerutil.MutateAndPatchStatus per .claude/rules/k8s-controller.md. If a helper of this shape is not already in the file, introduce it in this task. Sketch:
func (r *MCPExternalAuthConfigReconciler) setInvalid(
ctx context.Context,
cfg *mcpv1beta1.MCPExternalAuthConfig,
err error,
reason string,
) (ctrl.Result, error) {
if patchErr := controllerutil.MutateAndPatchStatus(ctx, r.Client, cfg, func(c *mcpv1beta1.MCPExternalAuthConfig) {
meta.SetStatusCondition(&c.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeValid,
Status: metav1.ConditionFalse,
Reason: reason,
Message: err.Error(),
ObservedGeneration: c.Generation,
})
}); patchErr != nil {
return ctrl.Result{}, patchErr
}
return ctrl.Result{}, nil // Don't requeue — the user must fix the spec or register a handler.
}The Reason string MUST be the exact literal EnterpriseRequired (capital E, capital R) when errors.Is(err, controllerutil.ErrEnterpriseRequired) is true. External consumers and downstream tooling pattern-match on this exact string. For any other error from OBOValidate, use the literal InvalidConfig.
Drift caveat — r.Status().Update vs MutateAndPatchStatus in this reconciler
The existing reconciler at cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go currently writes status via r.Status().Update(ctx, externalAuthConfig) at lines 108 and 137. This pre-existing pattern is inconsistent with the operator-rules convention that all new status writes go through controllerutil.MutateAndPatchStatus.
The new OBO branch added in this task MUST use controllerutil.MutateAndPatchStatus.
Refactoring the existing r.Status().Update call sites at lines 108 and 137 is OUT OF SCOPE. That cleanup is a separate concern, tracked outside this work. Reviewers should not request it as part of this task — coupling the cleanup to this task would inflate the diff and introduce unrelated regression risk into a task whose central change is the new OBO dispatch.
CRD-enum sequencing caveat for integration tests
This task does NOT depend on the CRD admitting obo typed configs at the apiserver level — that change is the next task in the OSS sequence. Until that task lands, the dispatch arms added here are reachable only via paths that bypass the apiserver enum validation.
For the integration tests in this task, the practical options are:
- Use envtest's looser CRD enum validation (envtest can accept CRs the production apiserver would reject because envtest does not run all the same admission webhooks by default), OR
- Temporarily mutate the CRD enum schema in test setup to admit
obofor the duration of the test suite, OR - Drive the reconciler directly at the Go level (instantiate the reconciler and call
Reconcile()with a hand-built*MCPExternalAuthConfig), bypassing the apiserver entirely.
Pick whichever option fits the existing cmd/thv-operator/test-integration/mcp-external-auth/suite_test.go shape best. The integration-test goal is to prove the dispatch wiring routes obo correctly across all three consumer paths; the apiserver-level admission test belongs to the CRD enum admission task.
Patterns & Frameworks
- Switch arm placement — every new arm goes immediately before the
default:so the generic "unsupported" error never fires forobo. The existing seven arms are not reordered. - Status write —
MutateAndPatchStatus— required by.claude/rules/k8s-controller.md. Pass a mutate closure that usesmeta.SetStatusConditionso condition ordering andObservedGenerationstay consistent with the existing call sites in this reconciler. - Sentinel error matching —
errors.Is— required by the project'sgo-style.md. The sentinel passes throughfmt.Errorf("...: %w", ...)wraps unchanged;errors.Iswalks the wrap chain. - Integration-test pattern — match the existing
suite_test.goenvtest setup. Apply a CR, wait for the controller to reconcile, fetch the updated resource, assert on itsStatus.Conditions. Useassert.Eventually(...)(orgomega.Eventually(...), whichever the existing tests use) to ride out the reconcile latency.
Code Pointers
(All verified against upstream toolhive v0.27.2 / 97b0cc3f.)
cmd/thv-operator/pkg/controllerutil/tokenexchange.go:101—AddExternalAuthConfigOptionsswitch site. Existing seven cases +default:. Newcase ExternalAuthTypeOBOarm placed beforedefault:.cmd/thv-operator/controllers/virtualmcpserver_deployment.go:789—(*VirtualMCPServerReconciler).getExternalAuthConfigSecretEnvVarswitch site. Existing seven cases +default:. Newcase ExternalAuthTypeOBOarm placed beforedefault:.cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go— the reconciler whoseReconcile()method gains the new OBO branch. Existingr.Status().Update(ctx, externalAuthConfig)call sites are at lines 108 and 137; both stay unchanged.cmd/thv-operator/pkg/controllerutil/status.go:77—MutateAndPatchStatussignature. The helper is generic overT client.Objectand takes amutate func(T)closure.pkg/vmcp/auth/converters/interface.go:191—"failed to convert to strategy: %w"wrap site insideDiscoverAndResolveAuth. The vMCP integration test exercises this wrap; the reconciler must useerrors.Is(err, externalauth.ErrEnterpriseRequired)to recognize the sentinel through it (matching by string would be brittle and is forbidden).cmd/thv-operator/test-integration/mcp-external-auth/suite_test.go— existing envtest harness for this directory; new tests slot in alongside the existingmcpexternalauthconfig_controller_integration_test.go.
Component Interfaces
This task does not add any new exported types. It consumes the symbols defined in the dependency task:
// In cmd/thv-operator/pkg/controllerutil (from the dependency task):
var ErrEnterpriseRequired error
func OBOValidate(cfg *mcpv1beta1.MCPExternalAuthConfig) error
func OBOSecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error)
// oboHandler.ApplyRunConfig is called directly from the switch arm.
// In cmd/thv-operator/api/v1beta1 (from the dependency task):
const ExternalAuthTypeOBO ExternalAuthType = "obo"The only new private helper introduced here is setInvalid (or equivalent) on the reconciler if one of that shape is not already present.
Testing Strategy
Unit tests — none net new for the switch arms themselves; their behavior is covered by the integration tests below. If the new setInvalid helper has non-trivial logic (e.g., picks reason string from error wrap), add a small table-driven test next to the reconciler asserting:
- Given
controllerutil.ErrEnterpriseRequired, the helper writesReason: EnterpriseRequired. - Given a wrapped
controllerutil.ErrEnterpriseRequired(fmt.Errorf("...: %w", ErrEnterpriseRequired)), the helper still writesReason: EnterpriseRequired(i.e., it useserrors.Is, not equality). - Given any other error, the helper writes
Reason: InvalidConfig.
Integration tests — in cmd/thv-operator/test-integration/mcp-external-auth/ (build tag //go:build integration). Add three test cases (one per consumer CR type) plus a guard. Each follows the same shape: apply an obo-typed MCPExternalAuthConfig, apply a consumer CR referencing it, wait for the reconciler to settle, assert on the MCPExternalAuthConfig's Status.Conditions and on the consumer CR's surfaced condition.
-
MCPServerconsumer path: Apply anoboMCPExternalAuthConfig, then anMCPServerwithspec.externalAuthreferencing it. Assert theMCPExternalAuthConfighasstatus.conditions[Valid] = False,Reason: EnterpriseRequired, with a fixed message describing the registration requirement. Assert theMCPServersurfaces a parallelValid=False/EnterpriseRequiredcondition. -
MCPRemoteProxyconsumer path: Same as above but with the consumer being anMCPRemoteProxyreferencing theoboconfig. -
VirtualMCPServerconsumer path: Same as above but with the consumer being aVirtualMCPServer. The vMCP runtime'sconverters.DiscoverAndResolveAuthatpkg/vmcp/auth/converters/interface.go:191wraps the converter result with"failed to convert to strategy: %w"; the test confirms the reconciler recognizes the sentinel through the wrap viaerrors.Is(err, externalauth.ErrEnterpriseRequired)(not by string match) and still surfacesReason: EnterpriseRequired. - Generic-error guard (a single test, or assertions woven into the three above): collect the reconciler logs and the consumer-CR /
MCPExternalAuthConfigstatus messages across the three test cases above. Assert NONE of these substrings appear in any of those strings:"unsupported external auth type","unknown middleware type". (This guards against thedefault:arm or the runner's middleware-map lookup leaking through forobo.)
Edge cases
- CRD-enum bypass for tests: ensure the envtest setup admits
obotyped configs. Document the chosen bypass strategy (envtest's looser validation, in-test CRD mutation, or direct-reconciler invocation) in the test file's package comment so the next maintainer doesn't get blindsided.
Regression
- All existing tests under
cmd/thv-operator/test-integration/mcp-external-auth/pass unchanged.
Out of Scope
- Kubebuilder
+kubebuilder:validation:Enum=...;obomarker update onMCPExternalAuthConfigSpec.Type. (Next OSS task — CRD enum admission.) OBOConfigplaceholder struct definition +OBO *OBOConfigfield onMCPExternalAuthConfigSpec. (Next OSS task.)- CEL rule
self.type == 'obo' ? has(self.obo) : !has(self.obo). (Next OSS task.) - New row in
validateTypeConfigConsistencyfor theOBOConfigfield. (Next OSS task.) - No-op
case mcpv1beta1.ExternalAuthTypeOBOarm in theValidate()switch atcmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go:1019. (Next OSS task.) - Regenerated
deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yamlandtask crdref-genoutput. (Next OSS task.) - Refactoring the existing
r.Status().Update(ctx, externalAuthConfig)call sites at lines 108 and 137 ofcmd/thv-operator/controllers/mcpexternalauthconfig_controller.goto usecontrollerutil.MutateAndPatchStatus. Only the new OBO branch must useMutateAndPatchStatus. The cleanup of the pre-existing call sites is a separate concern, tracked outside this work. - The stub middleware factory itself, the default
OBOHandlerglobal, theErrEnterpriseRequiredsentinel, and theOBOConverterStub— those are the dependency task's scope. - Refactoring either operator-side switch into a registry. The two-switch shape (with one new arm per switch) is intentional for the minimal-variant rollout.
- Refactoring the literal middleware-factory map at
pkg/runner/middleware.go:30-49into a registry. Same rationale.
References
cmd/thv-operator/pkg/controllerutil/tokenexchange.go:101— first dispatch site.cmd/thv-operator/controllers/virtualmcpserver_deployment.go:789— second dispatch site.cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go— reconciler whose new OBO branch is added by this task. Pre-existingr.Status().Updatecall sites at lines 108 and 137 are explicitly out of scope.cmd/thv-operator/pkg/controllerutil/status.go:77—MutateAndPatchStatussignature.pkg/vmcp/auth/converters/interface.go:191— error-wrap site for the vMCP integration test path.- RFC 8693 — OAuth 2.0 Token Exchange — standards basis for the broader on-behalf-of pattern.
- Upstream code pointers cited above, all anchored to
stacklok/toolhivev0.27.2(97b0cc3f).
Activity
oboexternal auth type and function-pointer override hooks #5325Move OBO sentinel to pkg/auth/obo; address review hygiene
Address code review feedback
Move OBO sentinel to pkg/auth/obo; address review hygiene
Add default OBO handler hooks and vMCP/proxy converter stubs (#5338)
Wire OBO dispatch arms and reconciler branch
Address PR review feedback: comment hygiene, test guards, reason-sele…
Wire OBO dispatch arms and reconciler branch (#5345)
Forward all OBO env vars from VirtualMCPServer
Wire OBO SecretEnvVars into MCPServer and MCPRemoteProxy (#5540)