From dfa877a9567251380cd0a1f3f1a87dc1ac33b8a3 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 10:31:11 -0800 Subject: [PATCH 01/12] Support Entra OBO backend auth in OSS Microsoft Entra on-behalf-of was a working strategy only in the private enterprise overlay; OSS builds exposed the CRD but every dispatch point returned ErrEnterpriseRequired or a 503 stub. Make it a built-in strategy for MCPServer, MCPRemoteProxy, VirtualMCPServer and MCPServerEntry backends (issue #7199): - Port the Entra exchanger, token cache and exchange contract into pkg/auth/obo/{entra,cache,exchange}, kept free of Kubernetes imports (guard test), and make the real middleware the default factory. - Validate obo configs, build the RunConfig middleware and mount the client secret in controllerutil. Reject an MCPServer or MCPRemoteProxy that references obo without oidcConfigRef as InvalidConfig. - Add the real vMCP converter and strategy. Mount each OBO backend's secret in the vMCP pod under a per-config env var so two OBO backends no longer collide on TOOLHIVE_OBO_CLIENT_SECRET. - Keep RegisterOBOHandler, obo.RegisterFactory, RegisterOBOStrategy, ErrEnterpriseRequired and ConditionReasonEnterpriseRequired as deprecated overrides so the enterprise overlay keeps compiling until it is removed (#7200). Co-Authored-By: Claude Opus 5.5 --- .../v1beta1/mcpexternalauthconfig_types.go | 87 +- .../controllers/external_auth_mirror.go | 4 +- .../controllers/external_auth_mirror_test.go | 13 + .../mcpexternalauthconfig_controller.go | 53 +- .../mcpexternalauthconfig_controller_test.go | 263 +++--- ...cpremoteproxy_confighandler_status_test.go | 4 +- .../controllers/mcpremoteproxy_controller.go | 25 +- .../mcpremoteproxy_controller_test.go | 54 +- .../mcpremoteproxy_deployment_test.go | 28 +- .../controllers/mcpserver_controller.go | 60 +- .../mcpserver_externalauth_test.go | 167 ++-- .../virtualmcpserver_controller.go | 30 +- .../virtualmcpserver_deployment.go | 23 +- .../virtualmcpserver_externalauth_test.go | 119 ++- .../virtualmcpserver_vmcpconfig_test.go | 18 +- .../pkg/controllerutil/externalauth.go | 15 + cmd/thv-operator/pkg/controllerutil/obo.go | 313 ++++++++ .../pkg/controllerutil/obo_test.go | 491 ++++++++++++ .../pkg/controllerutil/tokenexchange.go | 203 +---- .../pkg/controllerutil/tokenexchange_test.go | 481 ----------- cmd/thv-operator/pkg/vmcpconfig/converter.go | 5 + .../pkg/vmcpconfig/converter_test.go | 35 + .../mcp-external-auth/obo_reconcile_test.go | 113 +++ .../mcp-external-auth/obo_validation_test.go | 6 +- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 52 +- ...olhive.stacklok.dev_virtualmcpservers.yaml | 40 +- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 52 +- ...olhive.stacklok.dev_virtualmcpservers.yaml | 40 +- docs/arch/09-operator-architecture.md | 4 +- docs/arch/10-virtual-mcp-architecture.md | 12 + docs/middleware.md | 52 +- docs/operator/crd-api.md | 44 +- pkg/auth/obo/cache/cache.go | 246 ++++++ pkg/auth/obo/cache/cache_test.go | 454 +++++++++++ pkg/auth/obo/cache/doc.go | 22 + pkg/auth/obo/deps_test.go | 56 ++ pkg/auth/obo/entra/config_test.go | 191 +++++ pkg/auth/obo/entra/doc.go | 28 + pkg/auth/obo/entra/errors.go | 159 ++++ pkg/auth/obo/entra/errors_test.go | 107 +++ pkg/auth/obo/entra/exchanger.go | 513 ++++++++++++ pkg/auth/obo/entra/exchanger_test.go | 404 ++++++++++ pkg/auth/obo/errors.go | 51 +- pkg/auth/obo/errors_test.go | 26 +- pkg/auth/obo/exchange/exchange.go | 86 ++ pkg/auth/obo/middleware.go | 379 +++++++-- pkg/auth/obo/middleware_test.go | 751 ++++++++++++++++-- pkg/auth/obo/parameters.go | 103 +++ pkg/auth/obo/parameters_test.go | 130 +++ pkg/runner/middleware.go | 2 +- pkg/runner/middleware_test.go | 84 +- pkg/vmcp/auth/converters/obo.go | 178 ++++- pkg/vmcp/auth/converters/obo_test.go | 295 ++++--- pkg/vmcp/auth/factory/outgoing.go | 4 +- pkg/vmcp/auth/factory/outgoing_test.go | 27 +- pkg/vmcp/auth/obo.go | 78 +- pkg/vmcp/auth/obo_test.go | 127 +-- pkg/vmcp/auth/strategies/obo.go | 339 ++++++++ pkg/vmcp/auth/strategies/obo_test.go | 425 ++++++++++ pkg/vmcp/auth/types/types.go | 18 +- test/integration/vmcp/obo_integration_test.go | 274 +++++++ 61 files changed, 6708 insertions(+), 1755 deletions(-) create mode 100644 cmd/thv-operator/controllers/external_auth_mirror_test.go create mode 100644 cmd/thv-operator/pkg/controllerutil/obo.go create mode 100644 cmd/thv-operator/pkg/controllerutil/obo_test.go delete mode 100644 cmd/thv-operator/pkg/controllerutil/tokenexchange_test.go create mode 100644 cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go create mode 100644 pkg/auth/obo/cache/cache.go create mode 100644 pkg/auth/obo/cache/cache_test.go create mode 100644 pkg/auth/obo/cache/doc.go create mode 100644 pkg/auth/obo/deps_test.go create mode 100644 pkg/auth/obo/entra/config_test.go create mode 100644 pkg/auth/obo/entra/doc.go create mode 100644 pkg/auth/obo/entra/errors.go create mode 100644 pkg/auth/obo/entra/errors_test.go create mode 100644 pkg/auth/obo/entra/exchanger.go create mode 100644 pkg/auth/obo/entra/exchanger_test.go create mode 100644 pkg/auth/obo/exchange/exchange.go create mode 100644 pkg/auth/obo/parameters.go create mode 100644 pkg/auth/obo/parameters_test.go create mode 100644 pkg/vmcp/auth/strategies/obo.go create mode 100644 pkg/vmcp/auth/strategies/obo_test.go create mode 100644 test/integration/vmcp/obo_integration_test.go diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index d4da70ed1d..c75e12043a 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -44,11 +44,9 @@ const ( // This injects an upstream IdP access token as the Authorization: Bearer header ExternalAuthTypeUpstreamInject ExternalAuthType = "upstreamInject" - // ExternalAuthTypeOBO is the type for on-behalf-of (OBO) flows. - // This type requires a build with an OBO handler registered via - // controllerutil.RegisterOBOHandler; an upstream-only build surfaces - // status.conditions[Valid] = False with Reason: EnterpriseRequired - // when an obo-typed MCPExternalAuthConfig is applied. + // ExternalAuthTypeOBO is the type for Microsoft Entra on-behalf-of (OBO) + // flows: the proxy exchanges the authenticated user's token for a + // backend-scoped token issued for that same user. ExternalAuthTypeOBO ExternalAuthType = "obo" // ExternalAuthTypeXAA is the type for XAA (Cross-Application Access) auth. @@ -78,10 +76,6 @@ type ExternalAuthType string //nolint:lll // CEL validation rules exceed line length limit type MCPExternalAuthConfigSpec struct { // Type is the type of external authentication to configure. - // When set to "obo", the cluster must run a build that has registered an - // OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds - // surface status.conditions[Valid] = False with Reason: EnterpriseRequired - // for obo-typed configs. // +kubebuilder:validation:Enum=tokenExchange;headerInjection;bearerToken;unauthenticated;embeddedAuthServer;awsSts;upstreamInject;obo;xaa // +kubebuilder:validation:Required Type ExternalAuthType `json:"type"` @@ -116,11 +110,8 @@ type MCPExternalAuthConfigSpec struct { // +optional UpstreamInject *UpstreamInjectSpec `json:"upstreamInject,omitempty"` - // OBO configures On-Behalf-Of (OBO) authentication. - // Only used when Type is "obo". Setting this field on an upstream-only build - // causes the MCPExternalAuthConfig to transition to - // status.conditions[Valid] = False with Reason: EnterpriseRequired, because - // no OBO handler is registered. See OBOConfig for the field-to-runtime + // OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication. + // Only used when Type is "obo". See OBOConfig for the field-to-runtime // contract mapping. // +optional OBO *OBOConfig `json:"obo,omitempty"` @@ -134,27 +125,25 @@ type MCPExternalAuthConfigSpec struct { // OBOConfig holds configuration for the On-Behalf-Of (OBO) external auth type. // Only used when Type is "obo". // -// This is the user-facing CRD surface for the Microsoft Entra OBO flow. It is -// structurally valid in upstream (OSS) builds but inert: an upstream-only build -// returns obo.ErrEnterpriseRequired at reconcile (Valid=False, Reason: -// EnterpriseRequired) because no OBO handler is registered via -// controllerutil.RegisterOBOHandler. A build with the enterprise OBO handler -// translates these fields into the runtime wire contract obo.MiddlewareParameters, -// so the field names and semantics here track that contract rather than the -// upstream TokenExchangeConfig (which uses different names, e.g. +// This is the user-facing CRD surface for the Microsoft Entra OBO flow. The +// operator translates these fields into the runtime wire contract +// obo.MiddlewareParameters (MCPServer, MCPRemoteProxy) or the vMCP OBOConfig +// (VirtualMCPServer), so the field names and semantics here track that +// contract rather than TokenExchangeConfig (which uses different names, e.g. // subjectProviderName / externalTokenHeaderName). In particular there is no // externalTokenHeaderName: the OBO subject is sourced from the authenticated -// Identity, never from an inbound request header. +// Identity, never from an inbound request header. An MCPServer or +// MCPRemoteProxy that references an obo config must also set oidcConfigRef, +// so it has an authenticated user token to exchange. // -// Field-to-contract mapping performed by the operator's OBO handler: +// Field-to-contract mapping performed by the operator: // - tenantId (+ optional authority) → tokenUrl // (https://login.microsoftonline.com//oauth2/v2.0/token, or the // configured authority base joined with the tenant for sovereign clouds) // - clientSecretRef → resolved into a pod env var; only the env var name // travels in the contract, as clientSecretEnvVar // - audience / scopes → collapsed to a single exchange target by -// obo.MiddlewareParameters.ExchangeTarget() (space-joined scopes win, -// otherwise audience) +// exchange.Target (space-joined scopes win, otherwise audience) // - cacheSkew → the contract's integer-seconds cacheSkewSeconds // // Every field is optional at the CRD level, and the schema deliberately carries @@ -163,8 +152,8 @@ type MCPExternalAuthConfigSpec struct { // admission rule that rejects {} would be a backward-incompatible narrowing of // an already-stored, round-trippable object. Presence and combination // requirements — a tenant, a client-auth credential, and at least one of -// audience/scopes — are therefore enforced by the registered OBO handler at -// reconcile, which reports a violation as Valid=False / Reason=InvalidConfig. +// audience/scopes — are therefore enforced by the operator at reconcile, which +// reports a violation as Valid=False / Reason=InvalidConfig. // The per-field patterns below still apply, but only to a value that is present. // //nolint:lll // the tenantId GUID/domain pattern exceeds the line length limit @@ -179,7 +168,7 @@ type OBOConfig struct { // interpolates it into the token endpoint // (//oauth2/v2.0/token), so the value is constrained to // the GUID/domain shape (no path metacharacters); the pattern and 253-char - // cap mirror the enterprise exchanger's validateTenant, so any tenantId + // cap mirror the Entra exchanger's tenant validation, so any tenantId // admitted here is one the runtime can consume. // +kubebuilder:validation:MaxLength=253 // +kubebuilder:validation:Pattern=`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$` @@ -265,12 +254,10 @@ type OBOConfig struct { // CacheSkew overrides the OBO token cache's default expiry skew (the margin // by which a cached token is treated as expired before its real expiry), // e.g. "30s". The operator converts it to the runtime contract's - // integer-seconds cacheSkewSeconds. Should not be negative, but the schema - // does not enforce that — metav1.Duration carries no numeric minimum — and - // upstream builds do not reject it. A negative value is rejected only by an - // enterprise build's OBO handler once that handler validates the converted - // parameters; it is not enforced at admission or in upstream-only builds. - // When omitted, the cache default applies. + // integer-seconds cacheSkewSeconds (truncated toward zero). Must not be + // negative; metav1.Duration carries no numeric minimum, so the operator + // rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig) + // rather than at admission. When omitted, the cache default applies. // +optional CacheSkew *metav1.Duration `json:"cacheSkew,omitempty"` } @@ -2602,16 +2589,18 @@ const ( // literals are part of the user-facing contract — external consumers and // downstream tooling pattern-match on them. const ( - // ConditionReasonEnterpriseRequired: an obo-typed MCPExternalAuthConfig - // requires an enterprise build that has registered an OBO handler via - // controllerutil.RegisterOBOHandler. Upstream-only builds surface this - // reason for every obo-typed config. + // ConditionReasonEnterpriseRequired was set on obo-typed configs before OBO + // shipped in ToolHive itself. The operator no longer sets it. + // + // Deprecated: OBO is built in. Kept for one release so out-of-tree code + // that references it keeps compiling; it will be removed. ConditionReasonEnterpriseRequired = "EnterpriseRequired" // ConditionReasonInvalidConfig: an obo-typed MCPExternalAuthConfig is - // well-formed at the CRD level but fails the registered OBO handler's - // Validate() with an error other than the enterprise-required sentinel. - // Used by out-of-tree handlers; unreachable in upstream-only builds. + // well-formed at the CRD level but fails the operator's OBO validation + // (for example a missing tenant, client ID, client secret reference, or + // both audience and scopes). Also used on a consuming MCPServer or + // MCPRemoteProxy that references an obo config without oidcConfigRef. ConditionReasonInvalidConfig = "InvalidConfig" // ConditionReasonInvalidCABundle: a referenced CA bundle ConfigMap is @@ -2797,15 +2786,11 @@ func (r *MCPExternalAuthConfig) Validate() error { // subjectTokenProviderName, scopes/cacheSkew bounds) at admission, and // only for values that are present. All presence and combination // requirements (a tenant, a client-auth credential, at least one of - // audience/scopes) and protocol-level checks are owned by the registered - // handler, not the upstream type. That handler runs at reconcile - // time via the controllerutil.OBOValidate function-pointer hook: - // upstream-only builds return obo.ErrEnterpriseRequired, which the - // reconciler maps to status.conditions[Valid] = False / Reason: - // EnterpriseRequired. Out-of-tree builds that register a handler via - // controllerutil.RegisterOBOHandler short-circuit the sentinel and - // run their own protocol-level checks. Splitting the tiers this way - // keeps the upstream CRD schema stable across builds. + // audience/scopes) and protocol-level checks are owned by the operator's + // reconcile-time OBO validation (controllerutil.OBOValidate), which maps + // a violation to status.conditions[Valid] = False / Reason: + // InvalidConfig. Splitting the tiers this way keeps the CRD schema + // backward compatible with the earlier empty placeholder. return nil default: // Unknown type - should be caught by enum validation, but handle defensively diff --git a/cmd/thv-operator/controllers/external_auth_mirror.go b/cmd/thv-operator/controllers/external_auth_mirror.go index 704c1b7b21..c3092c59d9 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror.go +++ b/cmd/thv-operator/controllers/external_auth_mirror.go @@ -16,8 +16,8 @@ import ( // Status Condition Parity machinery for #5347. The probe reads a referenced // MCPExternalAuthConfig's Valid condition; the per-consumer mirror functions // transcribe its reason+message onto the consumer CR's parallel condition. -// Without this, an obo-typed MCPExternalAuthConfig in an upstream-only build -// surfaces EnterpriseRequired only on the referenced resource and the consumer +// Without this, an invalid MCPExternalAuthConfig (for example a malformed obo +// config) surfaces its reason only on the referenced resource and the consumer // status reports only the generic dispatch failure. // fallbackInvalidReason is substituted when a source surfaces Valid=False with diff --git a/cmd/thv-operator/controllers/external_auth_mirror_test.go b/cmd/thv-operator/controllers/external_auth_mirror_test.go new file mode 100644 index 0000000000..067871be2e --- /dev/null +++ b/cmd/thv-operator/controllers/external_auth_mirror_test.go @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package controllers + +// Arbitrary source Valid=False reason and message used by the Status Condition +// Parity mirror tests. The mirror copies whatever reason the referenced +// MCPExternalAuthConfig carries, so the tests use a value no controller sets +// itself (unlike InvalidConfig, which ownedByLocalValidation treats specially). +const ( + testSourceInvalidReason = "SourceRejected" + testSourceInvalidMessage = "the referenced MCPExternalAuthConfig was rejected" +) diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go index 9262ea81ba..0a73a16b29 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go @@ -152,12 +152,10 @@ func (r *MCPExternalAuthConfigReconciler) Reconcile(ctx context.Context, req ctr return ctrl.Result{}, nil // Don't requeue on validation errors - user must fix spec } - // Dispatch OBO-typed configs through the registered handler. The default - // handler returns obo.ErrEnterpriseRequired so upstream-only builds surface - // Valid=False / Reason=EnterpriseRequired here rather than failing later - // inside a consumer reconciler with a generic "unsupported" error. The OBO - // failure path routes through setInvalid, which applies the advisory inside - // its own patch closure. + // Validate OBO-typed configs beyond what the CRD schema can express (tenant + // and authority shape, secret reference, audience or scopes). The failure + // path routes through setInvalid, which applies the advisory inside its own + // patch closure. if externalAuthConfig.Spec.Type == mcpv1beta1.ExternalAuthTypeOBO { if handled, err := r.triageOBOValidation(ctx, externalAuthConfig); handled { return ctrl.Result{}, err @@ -350,15 +348,14 @@ func (*MCPExternalAuthConfigReconciler) applyIdentitySynthesizedCondition( }) } -// triageOBOValidation runs the registered OBO handler's Validate and routes -// the result through the three-bucket contract documented on OBOHandler: +// triageOBOValidation runs the OBO validation and routes the result through +// the error contract documented on obo.ValidationError: // -// - ErrEnterpriseRequired → permanent, Reason=EnterpriseRequired // - *obo.ValidationError → permanent, Reason=InvalidConfig (the typed // error's Message is written verbatim into condition.Message) // - anything else → transient; return the error wrapped so // controller-runtime requeues with backoff and self-heals once the -// upstream dependency (Secret/JWKS/webhook) recovers +// dependency recovers // // Returns handled=true to signal the caller to return immediately (with a // zero ctrl.Result and the returned error). handled=false means Validate @@ -369,31 +366,33 @@ func (r *MCPExternalAuthConfigReconciler) triageOBOValidation( ctx context.Context, cfg *mcpv1beta1.MCPExternalAuthConfig, ) (handled bool, err error) { - validateErr := ctrlutil.OBOValidate(cfg) + return r.applyOBOValidationResult(ctx, cfg, ctrlutil.OBOValidate(cfg)) +} + +// applyOBOValidationResult routes an OBO validation error into the matching +// bucket (see triageOBOValidation). A nil validateErr returns handled=false. +func (r *MCPExternalAuthConfigReconciler) applyOBOValidationResult( + ctx context.Context, + cfg *mcpv1beta1.MCPExternalAuthConfig, + validateErr error, +) (handled bool, err error) { if validateErr == nil { return false, nil } - switch { - case stderrors.Is(validateErr, obo.ErrEnterpriseRequired): - return true, r.setInvalid(ctx, cfg, validateErr, mcpv1beta1.ConditionReasonEnterpriseRequired) - default: - var valErr *obo.ValidationError - if stderrors.As(validateErr, &valErr) { - return true, r.setInvalid(ctx, cfg, valErr, mcpv1beta1.ConditionReasonInvalidConfig) - } - // Transient: return the error so controller-runtime requeues with - // backoff. Locking the resource into a permanent InvalidConfig on a - // transient I/O blip would require the user to touch the spec for - // the failure to clear, defeating self-healing. - return true, fmt.Errorf("OBO handler validation failed: %w", validateErr) + var valErr *obo.ValidationError + if stderrors.As(validateErr, &valErr) { + return true, r.setInvalid(ctx, cfg, valErr, mcpv1beta1.ConditionReasonInvalidConfig) } + // Transient: return the error so controller-runtime requeues with backoff. + // Locking the resource into a permanent InvalidConfig on a transient I/O + // blip would require the user to touch the spec for the failure to clear. + return true, fmt.Errorf("OBO validation failed: %w", validateErr) } // setInvalid writes a Valid=False condition through MutateAndPatchStatus, // using the supplied reason string and the error's message as the condition -// message. Returns an empty result with no requeue: the spec must change (or -// an out-of-tree handler must be registered) for this branch to clear, so -// requeuing buys nothing. +// message. Returns an empty result with no requeue: the spec must change for +// this branch to clear, so requeuing buys nothing. // // The IdentitySynthesized advisory is recomputed inside the patch closure so // both the advisory transition (e.g., when a user switches a config from diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go index a6673ac689..926412f77c 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -25,9 +24,7 @@ import ( mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" - ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" "github.com/stacklok/toolhive/pkg/auth/obo" - "github.com/stacklok/toolhive/pkg/runner" ) func TestMCPExternalAuthConfigReconciler_calculateConfigHash(t *testing.T) { @@ -1087,65 +1084,104 @@ func findCondition(conditions []metav1.Condition, t string) *metav1.Condition { return nil } -// TestMCPExternalAuthConfigReconciler_OBO_DefaultHandler_SetsEnterpriseRequired -// proves the dispatch wiring: with the default OBO handler installed (the -// upstream-only state), reconciling an obo-typed MCPExternalAuthConfig surfaces -// Valid=False / Reason=EnterpriseRequired rather than the generic "unsupported -// external auth type" path. Drives the reconciler directly with a fake client -// to bypass the CRD enum (which does not admit "obo" until #5329 lands). -func TestMCPExternalAuthConfigReconciler_OBO_DefaultHandler_SetsEnterpriseRequired(t *testing.T) { +// validOBOSpec returns an obo spec the operator's OBO validation accepts. +func validOBOSpec() *mcpv1beta1.OBOConfig { + return &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "obo-secret", Key: "client-secret"}, + Audience: "api://backend/.default", + } +} + +// TestMCPExternalAuthConfigReconciler_OBO_Validation drives Reconcile for an +// obo-typed MCPExternalAuthConfig: a well-formed config becomes Valid=True, and +// each malformed config becomes Valid=False / Reason=InvalidConfig with the +// validation message. Neither path requeues. +func TestMCPExternalAuthConfigReconciler_OBO_Validation(t *testing.T) { t.Parallel() - cfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "obo-config", - Namespace: "default", + tests := []struct { + name string + spec *mcpv1beta1.OBOConfig + wantStatus metav1.ConditionStatus + wantReason string + wantMessage string + }{ + {name: "valid config", spec: validOBOSpec(), wantStatus: metav1.ConditionTrue}, + { + name: "missing tenant", + spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.TenantID = ""; return c }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "entra obo: TenantID is required", }, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, + { + name: "missing client id", + spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.ClientID = ""; return c }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: clientId is required", + }, + { + name: "missing client secret ref", + spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.ClientSecretRef = nil; return c }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: clientSecretRef must set both name and key", + }, + { + name: "neither audience nor scopes", + spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.Audience = ""; return c }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: at least one of audience or scopes is required", + }, + { + name: "empty placeholder spec", + spec: &mcpv1beta1.OBOConfig{}, + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: clientId is required", }, } - r, fakeClient := newTestMCPExternalAuthConfigReconciler(t, cfg) - req := reconcile.Request{NamespacedName: types.NamespacedName{ - Name: cfg.Name, - Namespace: cfg.Namespace, - }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() - // First reconcile adds the finalizer; the requeued reconcile runs the body. - result, err := r.Reconcile(t.Context(), req) - require.NoError(t, err) - if result.RequeueAfter > 0 { - _, err = r.Reconcile(t.Context(), req) - require.NoError(t, err) - } + cfg := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "obo-config", + Namespace: "default", + Finalizers: []string{ExternalAuthConfigFinalizerName}, + }, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: tt.spec, + }, + } - var updated mcpv1beta1.MCPExternalAuthConfig - require.NoError(t, fakeClient.Get(t.Context(), req.NamespacedName, &updated)) + r, fakeClient := newTestMCPExternalAuthConfigReconciler(t, cfg) + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: cfg.Name, Namespace: cfg.Namespace}} - validCond := findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) - require.NotNil(t, validCond, "Valid condition must be set for OBO-typed config") - assert.Equal(t, metav1.ConditionFalse, validCond.Status) - assert.Equal(t, mcpv1beta1.ConditionReasonEnterpriseRequired, validCond.Reason, - "the exact reason string is part of the user-facing contract — external consumers pattern-match on it") - - // Generic-error guard: the dispatch path must NOT leak a generic - // "unsupported external auth type" or "unknown middleware type" message. - assert.NotContains(t, validCond.Message, "unsupported external auth type") - assert.NotContains(t, validCond.Message, "unknown middleware type") - - // Positive assertion: condition.Message must surface the sentinel's - // user-facing text. Without this check a refactor that emptied or - // rewrote the message would still pass the reason-string assertion. - assert.Equal(t, obo.ErrEnterpriseRequired.Error(), validCond.Message, - "condition.Message must surface the sentinel's user-facing text") + result, err := r.Reconcile(t.Context(), req) + require.NoError(t, err) + assert.Zero(t, result.RequeueAfter) + + var updated mcpv1beta1.MCPExternalAuthConfig + require.NoError(t, fakeClient.Get(t.Context(), req.NamespacedName, &updated)) + + validCond := findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) + require.NotNil(t, validCond, "Valid condition must be set for OBO-typed config") + assert.Equal(t, tt.wantStatus, validCond.Status) + if tt.wantStatus == metav1.ConditionFalse { + assert.Equal(t, tt.wantReason, validCond.Reason) + assert.Equal(t, tt.wantMessage, validCond.Message) + } + }) + } } // TestMCPExternalAuthConfigReconciler_OBO_ClearsStaleIdentitySynthesized // proves that when a user switches an existing config from embeddedAuthServer // (which set IdentitySynthesized=True) to obo, the stale IdentitySynthesized -// condition is removed alongside the new Valid=False/EnterpriseRequired +// condition is removed alongside the new Valid=False/InvalidConfig // condition. Regression for the bug where setInvalid's MutateAndPatchStatus // diffed against an already-mutated snapshot and silently dropped the // IdentitySynthesized removal. @@ -1197,155 +1233,88 @@ func TestMCPExternalAuthConfigReconciler_OBO_ClearsStaleIdentitySynthesized(t *t assert.Nil(t, findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeIdentitySynthesized), "stale IdentitySynthesized condition must be removed once the spec leaves embeddedAuthServer") - // Valid=False/EnterpriseRequired must be set in the same reconcile pass. + // Valid=False/InvalidConfig must be set in the same reconcile pass. validCond := findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) require.NotNil(t, validCond) assert.Equal(t, metav1.ConditionFalse, validCond.Status) - assert.Equal(t, mcpv1beta1.ConditionReasonEnterpriseRequired, validCond.Reason) + assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, validCond.Reason) } -// defaultOBOHandlerStub returns a handler whose every method returns -// obo.ErrEnterpriseRequired — the same shape as the package default. Used to -// restore the registered handler after a test that overrode it. -func defaultOBOHandlerStub() ctrlutil.OBOHandler { - return ctrlutil.OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return obo.ErrEnterpriseRequired }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return obo.ErrEnterpriseRequired - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, obo.ErrEnterpriseRequired - }, - } -} - -// TestMCPExternalAuthConfigReconciler_OBO_ErrorTriageInReconcile drives the -// production three-way error triage in the OBO branch of Reconcile by -// registering a stub OBO handler whose Validate returns each test's error, -// then calling Reconcile and asserting on the resulting condition (or the -// returned error, for the transient case). The three buckets are: -// -// - errors.Is(err, ErrEnterpriseRequired) → permanent, EnterpriseRequired -// - errors.As(err, &*obo.ValidationError) → permanent, InvalidConfig -// - anything else → transient; Reconcile returns -// the error, no condition write +// TestMCPExternalAuthConfigReconciler_OBO_ErrorTriage drives the OBO error +// triage with each kind of validation error: // -// This exercises the production errors.Is decision (so a regression that -// swaps stderrors.Is for == would be caught — that would break the vMCP -// "failed to convert to strategy: %w" wrap path) AND the new errors.As -// decision for *obo.ValidationError. -// -//nolint:paralleltest // Mutates package-level oboHandler via RegisterOBOHandler. -func TestMCPExternalAuthConfigReconciler_OBO_ErrorTriageInReconcile(t *testing.T) { +// - errors.As(err, &*obo.ValidationError) → permanent, InvalidConfig, with the +// typed error's Message written verbatim (any wrap prefix is dropped) +// - anything else → transient; the error is returned +// so controller-runtime requeues, and no Valid condition is written +func TestMCPExternalAuthConfigReconciler_OBO_ErrorTriage(t *testing.T) { + t.Parallel() + tests := []struct { - name string - validateErr error - // Exactly one of these two paths is exercised per test case: - // either the reconciler writes a permanent Valid=False condition with - // the expected reason/message, or it returns a transient error and - // writes no Valid condition. + name string + validateErr error wantTransient bool - wantReason string wantMessage string }{ - { - name: "bare sentinel produces EnterpriseRequired (permanent)", - validateErr: obo.ErrEnterpriseRequired, - wantReason: mcpv1beta1.ConditionReasonEnterpriseRequired, - wantMessage: obo.ErrEnterpriseRequired.Error(), - }, - { - name: "wrapped sentinel still produces EnterpriseRequired via errors.Is", - validateErr: fmt.Errorf("outer: %w", obo.ErrEnterpriseRequired), - wantReason: mcpv1beta1.ConditionReasonEnterpriseRequired, - wantMessage: "outer: " + obo.ErrEnterpriseRequired.Error(), - }, { name: "ValidationError produces InvalidConfig (permanent)", validateErr: &obo.ValidationError{Message: "audience must be a non-empty URL"}, - wantReason: mcpv1beta1.ConditionReasonInvalidConfig, wantMessage: "audience must be a non-empty URL", }, { name: "wrapped ValidationError still produces InvalidConfig via errors.As", validateErr: fmt.Errorf("validating obo spec: %w", &obo.ValidationError{Message: "missing tokenURL"}), - wantReason: mcpv1beta1.ConditionReasonInvalidConfig, - // setInvalid is called with the unwrapped ValidationError, so its - // Message lands verbatim — the wrap prefix is discarded on purpose - // so handler-author-visible text controls what kubectl describe shows. wantMessage: "missing tokenURL", }, { - name: "unclassified error is transient — Reconcile returns it, no condition write", - validateErr: stderrors.New("transient JWKS fetch failed"), + name: "unclassified error is transient", + validateErr: stderrors.New("transient failure"), wantTransient: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // Always restore the default after the subtest so we don't leak - // the stub into other tests that share this package. - t.Cleanup(func() { ctrlutil.RegisterOBOHandler(defaultOBOHandlerStub()) }) - - // Install the per-case stub: Validate returns tt.validateErr; - // the other two methods keep the default behavior. - stub := defaultOBOHandlerStub() - stub.Validate = func(*mcpv1beta1.MCPExternalAuthConfig) error { return tt.validateErr } - ctrlutil.RegisterOBOHandler(stub) + t.Parallel() cfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "obo-config", - Namespace: "default", - }, + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, + OBO: validOBOSpec(), }, } - r, fakeClient := newTestMCPExternalAuthConfigReconciler(t, cfg) - req := reconcile.Request{NamespacedName: types.NamespacedName{ - Name: cfg.Name, - Namespace: cfg.Namespace, - }} - // First reconcile may just add the finalizer; the requeued - // reconcile runs the body that exercises the triage. - result, err := r.Reconcile(t.Context(), req) - if result.RequeueAfter > 0 { - require.NoError(t, err) - result, err = r.Reconcile(t.Context(), req) - } + handled, err := r.applyOBOValidationResult(t.Context(), cfg, tt.validateErr) + require.True(t, handled) var updated mcpv1beta1.MCPExternalAuthConfig - require.NoError(t, fakeClient.Get(t.Context(), req.NamespacedName, &updated)) + require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(cfg), &updated)) validCond := findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) if tt.wantTransient { - // Transient path: Reconcile must return an error that - // preserves the underlying cause (errors.Is must still match - // it through the wrap), and no Valid condition is written. require.Error(t, err, "transient errors must propagate so controller-runtime requeues") - assert.ErrorIs(t, err, tt.validateErr, - "the transient error must remain inspectable via errors.Is") - assert.Nil(t, validCond, - "transient errors must not write a Valid condition; "+ - "locking the resource into a permanent state would block self-healing") + assert.ErrorIs(t, err, tt.validateErr) + assert.Nil(t, validCond, "transient errors must not write a Valid condition") return } require.NoError(t, err) require.NotNil(t, validCond) assert.Equal(t, metav1.ConditionFalse, validCond.Status) - assert.Equal(t, tt.wantReason, validCond.Reason) + assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, validCond.Reason) assert.Equal(t, tt.wantMessage, validCond.Message) }) } + + t.Run("nil error is not handled", func(t *testing.T) { + t.Parallel() + r, _ := newTestMCPExternalAuthConfigReconciler(t) + handled, err := r.applyOBOValidationResult(t.Context(), &mcpv1beta1.MCPExternalAuthConfig{}, nil) + assert.False(t, handled) + assert.NoError(t, err) + }) } // TestMCPExternalAuthConfigReconciler_ReconcileKeepsExistingForeignCondition diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_confighandler_status_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_confighandler_status_test.go index 048330bc81..9d522b45a3 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_confighandler_status_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_confighandler_status_test.go @@ -75,8 +75,8 @@ func TestMCPRemoteProxyConfigHandlerFailuresClearTheStaleReadyCondition(t *testi Status: mcpv1beta1.MCPExternalAuthConfigStatus{Conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, - Reason: "EnterpriseRequired", - Message: "this type requires an enterprise license", + Reason: testSourceInvalidReason, + Message: testSourceInvalidMessage, }}}, }}, }, diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index 076c03c23d..33931042b8 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -37,6 +37,7 @@ import ( "github.com/stacklok/toolhive/cmd/thv-operator/pkg/kubernetes/rbac" "github.com/stacklok/toolhive/cmd/thv-operator/pkg/runconfig/configmap/checksum" "github.com/stacklok/toolhive/cmd/thv-operator/pkg/validation" + "github.com/stacklok/toolhive/pkg/auth/obo" ) // MCPRemoteProxyReconciler reconciles a MCPRemoteProxy object @@ -182,8 +183,12 @@ func (r *MCPRemoteProxyReconciler) Reconcile(ctx context.Context, req ctrl.Reque } return ctrl.Result{}, nil } + // A spec defect the user must fix (e.g. obo without incoming OIDC) has + // already been recorded on status; do not requeue. + var validationErr *obo.ValidationError if stderrors.Is(err, errInvalidMCPRemoteProxyPodTemplateSpec) || - stderrors.Is(err, errTerminalCABundleHandled) { + stderrors.Is(err, errTerminalCABundleHandled) || + stderrors.As(err, &validationErr) { return ctrl.Result{}, nil } return ctrl.Result{}, err @@ -1014,13 +1019,25 @@ func (r *MCPRemoteProxyReconciler) handleExternalAuthConfig(ctx context.Context, } // Mirror the referenced MCPExternalAuthConfig's Valid=False condition onto - // the MCPRemoteProxy so the failure is visible on the consumer CR (e.g. - // obo-typed configs surface Valid=False/EnterpriseRequired here without the - // user having to inspect the referenced MCPExternalAuthConfig). + // the MCPRemoteProxy so the failure is visible on the consumer CR without + // the user having to inspect the referenced MCPExternalAuthConfig. if mirrored, err := mirrorInvalidOnRemoteProxy(proxy, externalAuthConfig); mirrored { return err } + // OBO exchanges the authenticated user's token, so it needs incoming OIDC + // authentication. Terminal: Reconcile records it without requeueing. + if err := ctrlutil.ValidateOBOIncomingAuth(externalAuthConfig, proxy.Spec.OIDCConfigRef != nil); err != nil { + meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{ + Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated, + Status: metav1.ConditionFalse, + Reason: mcpv1beta1.ConditionReasonInvalidConfig, + Message: err.Error(), + ObservedGeneration: proxy.Generation, + }) + return err + } + // Resolve upstream CA dependencies before allowing any workload changes. if embeddedCfg := externalAuthConfig.Spec.EmbeddedAuthServer; embeddedCfg != nil { if err := ctrlutil.ValidateEmbeddedAuthServerCABundles(ctx, r.Client, proxy.Namespace, embeddedCfg); err != nil { diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go index 6e33fbf47e..72d83c58ee 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go @@ -530,11 +530,9 @@ func TestHandleExternalAuthConfig(t *testing.T) { }, { // Mirror added for #5347: when the referenced MCPExternalAuthConfig - // has Status.Conditions[Valid]=False (e.g. obo-typed configs that - // the default OBO handler rejected with Reason=EnterpriseRequired - // in upstream-only builds), the proxy reconciler must surface a - // parallel ExternalAuthConfigValidated=False with the same reason - // and message. + // has Status.Conditions[Valid]=False, the proxy reconciler must + // surface a parallel ExternalAuthConfigValidated=False with the + // same reason and message. name: "referenced config Valid=False is mirrored onto the proxy", proxy: v1beta1test.NewMCPRemoteProxy("obo-mirror-proxy", "default", v1beta1test.WithRemoteProxyExternalAuthConfigRef("obo-config"), @@ -554,17 +552,53 @@ func TestHandleExternalAuthConfig(t *testing.T) { Conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, - Message: "on-behalf-of (OBO) external auth type requires an enterprise build", + Reason: testSourceInvalidReason, + Message: testSourceInvalidMessage, }}, }, }, expectError: true, - errContains: "EnterpriseRequired", + errContains: testSourceInvalidReason, expectCondition: true, expectedCondStatus: metav1.ConditionFalse, - expectedCondReason: mcpv1beta1.ConditionReasonEnterpriseRequired, - expectedCondMessage: "on-behalf-of (OBO) external auth type requires an enterprise build", + expectedCondReason: testSourceInvalidReason, + expectedCondMessage: testSourceInvalidMessage, + }, + { + name: "obo config without incoming OIDC is rejected as InvalidConfig", + proxy: v1beta1test.NewMCPRemoteProxy("obo-no-oidc-proxy", "default", + v1beta1test.WithRemoteProxyExternalAuthConfigRef("obo-valid")), + externalAuth: &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-valid", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{}, + }, + }, + expectError: true, + errContains: "requires incoming authentication", + expectCondition: true, + expectedCondStatus: metav1.ConditionFalse, + expectedCondReason: mcpv1beta1.ConditionReasonInvalidConfig, + expectedCondMessage: ctrlutil.MsgOBORequiresIncomingAuth, + }, + { + name: "obo config with incoming OIDC is accepted", + proxy: v1beta1test.NewMCPRemoteProxy("obo-oidc-proxy", "default", + v1beta1test.WithRemoteProxyExternalAuthConfigRef("obo-valid"), + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Spec.OIDCConfigRef = &mcpv1beta1.MCPOIDCConfigReference{Name: "oidc"} + })), + externalAuth: &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-valid", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{}, + }, + }, + expectCondition: true, + expectedCondStatus: metav1.ConditionTrue, + expectedCondReason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigValid, }, { name: "embedded auth server with multiple upstreams rejected", diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index 93b4d94913..d21b6450da 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -35,6 +35,7 @@ import ( "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" + "github.com/stacklok/toolhive/pkg/auth/obo" "github.com/stacklok/toolhive/pkg/transport/session" ) @@ -963,18 +964,15 @@ func TestMCPRemoteProxyDeploymentNeedsUpdate_TokenExchangeDoesNotDrift(t *testin } // TestMCPRemoteProxyDeployment_OBOSecretEnvVars verifies that an obo-typed -// MCPExternalAuthConfig referenced from an MCPRemoteProxy injects the registered -// OBOHandler.SecretEnvVars output into the proxy container, and that the +// MCPExternalAuthConfig referenced from an MCPRemoteProxy mounts the OBO client +// secret into the proxy container under obo.ClientSecretEnvVar, and that the // deployment builder and drift check agree on it so a correctly-configured -// resource does not hot-loop. A stub OBO handler stands in for the out-of-tree -// enterprise handler. -// -//nolint:paralleltest // Mutates package-level oboHandler via RegisterOBOHandler. +// resource does not hot-loop. func TestMCPRemoteProxyDeployment_OBOSecretEnvVars(t *testing.T) { - t.Cleanup(func() { ctrlutil.RegisterOBOHandler(defaultOBOHandlerStub()) }) + t.Parallel() oboEnvVar := corev1.EnvVar{ - Name: "TOOLHIVE_OBO_CLIENT_SECRET", + Name: obo.ClientSecretEnvVar, ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ LocalObjectReference: corev1.LocalObjectReference{Name: "obo-secret"}, @@ -982,11 +980,6 @@ func TestMCPRemoteProxyDeployment_OBOSecretEnvVars(t *testing.T) { }, }, } - stub := defaultOBOHandlerStub() - stub.SecretEnvVars = func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return []corev1.EnvVar{oboEnvVar}, nil - } - ctrlutil.RegisterOBOHandler(stub) scheme := testutil.NewScheme(t) @@ -997,7 +990,12 @@ func TestMCPRemoteProxyDeployment_OBOSecretEnvVars(t *testing.T) { }, Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "obo-secret", Key: "client-secret"}, + Audience: "api://backend/.default", + }, }, } @@ -1021,7 +1019,7 @@ func TestMCPRemoteProxyDeployment_OBOSecretEnvVars(t *testing.T) { container := deployment.Spec.Template.Spec.Containers[0] assert.Contains(t, container.Env, oboEnvVar, - "OBO handler SecretEnvVars output must be injected into the proxy container") + "the OBO client secret must be mounted into the proxy container") assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum"), "freshly built deployment with an OBO env var must not be seen as drifted") diff --git a/cmd/thv-operator/controllers/mcpserver_controller.go b/cmd/thv-operator/controllers/mcpserver_controller.go index f26c3fe6d9..6fa7200be7 100644 --- a/cmd/thv-operator/controllers/mcpserver_controller.go +++ b/cmd/thv-operator/controllers/mcpserver_controller.go @@ -386,12 +386,24 @@ func (r *MCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ctrl.Result{}, nil } - ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") + // A spec defect the user must fix (e.g. obo without incoming OIDC) is + // recorded on status and not requeued. + var validationErr *obo.ValidationError + terminal := stderrors.As(err, &validationErr) + if !terminal { + ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") + } // Update status to reflect the error mcpServer.Status.Phase = mcpv1beta1.MCPServerPhaseFailed setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1beta1.ConditionReasonNotReady, err.Error()) if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil { ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPExternalAuthConfig error") + if terminal { + return ctrl.Result{}, statusErr + } + } + if terminal { + return ctrl.Result{}, nil } return ctrl.Result{}, err } @@ -1190,13 +1202,12 @@ func (r *MCPServerReconciler) imagePullSecretsForMCPServer( } // logOBOSecretEnvVarError logs an error from OBO secret env var generation -// without leaking sensitive detail. The OBOHandler error contract only -// guarantees *obo.ValidationError.Message is safe to surface; the transient -// bucket (e.g. "secret obo-secret/client-secret not found", JWKS URLs) carries -// no such guarantee, so anything that is not a ValidationError is logged -// generically with a pointer to the MCPExternalAuthConfig status, which the -// MCPExternalAuthConfig reconciler populates with the triaged detail. Shared by -// the MCPServer and MCPRemoteProxy proxy-env builders. +// without leaking sensitive detail. Only *obo.ValidationError.Message is +// guaranteed safe to surface; other errors (e.g. "secret obo-secret/client-secret +// not found") carry no such guarantee, so anything that is not a +// ValidationError is logged generically with a pointer to the +// MCPExternalAuthConfig status, which its reconciler populates with the triaged +// detail. Shared by the MCPServer and MCPRemoteProxy proxy-env builders. func logOBOSecretEnvVarError(ctx context.Context, err error) { logger := log.FromContext(ctx) var validationErr *obo.ValidationError @@ -1347,9 +1358,8 @@ func (r *MCPServerReconciler) deploymentForMCPServer( env = append(env, tokenExchangeEnvVars...) } - // Add OBO secret environment variables. Dispatched through the - // registered OBO handler; inert (no env vars) in builds without one. - // Must mirror deploymentNeedsUpdate exactly to avoid reconcile drift. + // Add OBO secret environment variables. Must mirror + // deploymentNeedsUpdate exactly to avoid reconcile drift. oboEnvVars, err := ctrlutil.AddOBOSecretEnvVars( ctx, r.Client, m.Namespace, m.Spec.ExternalAuthConfigRef, ) @@ -2037,12 +2047,10 @@ func (r *MCPServerReconciler) deploymentNeedsUpdate( // Add OBO secret environment variables. Must mirror // deploymentForMCPServer exactly (same call, same position) so a // correctly-configured resource does not look perpetually drifted. - // In handler-less builds the dispatcher swallows ErrEnterpriseRequired - // to (nil, nil), keeping this path symmetric with the builder. A - // genuine handler error returns true here while the builder logs and - // continues, so as long as the handler keeps erroring the operator - // re-applies an identical (OBO-env-less) Deployment each reconcile; it - // stops only once the handler succeeds. This mirrors the token-exchange + // An error returns true here while the builder logs and continues, + // so as long as it keeps erroring the operator re-applies an + // identical (OBO-env-less) Deployment each reconcile; it stops once + // the config is fixed. This mirrors the token-exchange // block above; unifying both (requeue on genuine error so neither side // acts) is out of scope for this change. oboEnvVars, err := ctrlutil.AddOBOSecretEnvVars( @@ -2458,13 +2466,25 @@ func (r *MCPServerReconciler) handleExternalAuthConfig(ctx context.Context, m *m } // Mirror the referenced MCPExternalAuthConfig's Valid=False condition onto - // the MCPServer so the failure is visible on the consumer CR (e.g. obo-typed - // configs surface Valid=False/EnterpriseRequired here without the user - // having to inspect the referenced MCPExternalAuthConfig). + // the MCPServer so the failure is visible on the consumer CR without the + // user having to inspect the referenced MCPExternalAuthConfig. if mirrored, err := mirrorInvalidOnMCPServer(m, externalAuthConfig); mirrored { return err } + // OBO exchanges the authenticated user's token, so it needs incoming OIDC + // authentication. Terminal: the caller records it without requeueing. + if err := ctrlutil.ValidateOBOIncomingAuth(externalAuthConfig, m.Spec.OIDCConfigRef != nil); err != nil { + meta.SetStatusCondition(&m.Status.Conditions, metav1.Condition{ + Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, + Status: metav1.ConditionFalse, + Reason: mcpv1beta1.ConditionReasonInvalidConfig, + Message: err.Error(), + ObservedGeneration: m.Generation, + }) + return err + } + // Resolve upstream CA dependencies before allowing any workload changes. if embeddedCfg := externalAuthConfig.Spec.EmbeddedAuthServer; embeddedCfg != nil { if err := ctrlutil.ValidateEmbeddedAuthServerCABundles(ctx, r.Client, m.Namespace, embeddedCfg); err != nil { diff --git a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go index 5332015364..fd1bbd14dc 100644 --- a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go @@ -16,7 +16,6 @@ package controllers import ( "context" - "errors" "testing" "time" @@ -34,6 +33,7 @@ import ( "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" + "github.com/stacklok/toolhive/pkg/auth/obo" "github.com/stacklok/toolhive/pkg/container/kubernetes" ) @@ -384,9 +384,8 @@ func TestMCPServerReconciler_handleExternalAuthConfig_NoHashInConfig(t *testing. // TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition verifies // the Status Condition Parity mirror added for #5347: when the referenced -// MCPExternalAuthConfig has Status.Conditions[Valid]=False (e.g. an obo-typed -// config that the default OBO handler rejected with Reason=EnterpriseRequired -// in upstream-only builds), the MCPServer reconciler must surface a parallel +// MCPExternalAuthConfig has Status.Conditions[Valid]=False, the MCPServer +// reconciler must surface a parallel // ExternalAuthConfigValidated=False condition that carries the same reason and // message — instead of silently propagating the dispatch error through the // generic phase-Failed path. @@ -399,8 +398,8 @@ func TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition(t const ( authName = "obo-config" namespace = "default" - reason = mcpv1beta1.ConditionReasonEnterpriseRequired - message = "on-behalf-of (OBO) external auth type requires an enterprise build" + reason = testSourceInvalidReason + message = testSourceInvalidMessage ) tests := []struct { @@ -412,7 +411,7 @@ func TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition(t wantMessage string }{ { - name: "source Valid=False/EnterpriseRequired is mirrored", + name: "source Valid=False/SourceRejected is mirrored", sourceValid: &metav1.Condition{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, @@ -463,7 +462,7 @@ func TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition(t preexisting: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Reason: testSourceInvalidReason, Message: "stale mirror from a previous reconcile", }}, wantMirrored: false, @@ -494,6 +493,9 @@ func TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition(t v1beta1test.WithStatus(mcpv1beta1.MCPServerStatus{Conditions: tt.preexisting}), v1beta1test.Mutate(func(m *mcpv1beta1.MCPServer) { m.Generation = serverGeneration + // obo needs incoming OIDC; without it the handler + // rejects the server before the success writer runs. + m.Spec.OIDCConfigRef = &mcpv1beta1.MCPOIDCConfigReference{Name: "oidc"} }), ) @@ -556,7 +558,7 @@ func TestMCPServerReconciler_handleExternalAuthConfig_ClearsMirrorOnRefRemoved(t Conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Reason: testSourceInvalidReason, Message: "stale mirror from when the ref pointed at an obo-typed config", }}, }), @@ -597,7 +599,7 @@ func TestMCPServerReconciler_handleExternalAuthConfig_ClearsMirrorOnSourceNotFou Conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Reason: testSourceInvalidReason, Message: "stale mirror — source has since been deleted", }}, }), @@ -839,32 +841,79 @@ func TestMCPServerReconciler_ExternalAuthConfigRefInvalidEmbeddedConfigSteadySta assert.Equal(t, initial.Status, actual.Status) } +// TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth +// verifies an MCPServer that references an obo config is rejected with +// ExternalAuthConfigValidated=False / InvalidConfig when it has no +// oidcConfigRef, and accepted once it has one. +func TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + withOIDC bool + wantStatus metav1.ConditionStatus + wantReason string + }{ + {name: "no oidcConfigRef is rejected", wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig}, + {name: "oidcConfigRef set is accepted", withOIDC: true, wantStatus: metav1.ConditionTrue, wantReason: mcpv1beta1.ConditionReasonExternalAuthConfigValid}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + scheme := testutil.NewScheme(t) + authConfig := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{}, + }, + } + mcpServer := v1beta1test.NewMCPServer("test-server", "default", + v1beta1test.WithImage("test-image"), + v1beta1test.WithExternalAuthConfigRef(authConfig.Name), + v1beta1test.Mutate(func(m *mcpv1beta1.MCPServer) { + m.Generation = 3 + if tt.withOIDC { + m.Spec.OIDCConfigRef = &mcpv1beta1.MCPOIDCConfigReference{Name: "oidc"} + } + }), + ) + fakeClient := fake.NewClientBuilder(). + WithScheme(scheme). + WithRuntimeObjects(authConfig, mcpServer). + WithStatusSubresource(&mcpv1beta1.MCPServer{}). + Build() + reconciler := newTestMCPServerReconciler(fakeClient, scheme, kubernetes.PlatformKubernetes) + + err := reconciler.handleExternalAuthConfig(t.Context(), mcpServer) + + cond := meta.FindStatusCondition(mcpServer.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + require.NotNil(t, cond) + assert.Equal(t, tt.wantStatus, cond.Status) + assert.Equal(t, tt.wantReason, cond.Reason) + if !tt.withOIDC { + var vErr *obo.ValidationError + require.ErrorAs(t, err, &vErr, "the rejection must be terminal so Reconcile does not requeue") + assert.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, cond.Message) + assert.Equal(t, int64(3), cond.ObservedGeneration) + return + } + require.NoError(t, err) + }) + } +} + // TestMCPServerDeployment_OBOSecretEnvVars verifies that an obo-typed -// MCPExternalAuthConfig referenced from an MCPServer injects the registered -// OBOHandler.SecretEnvVars output into the proxy container, and that the +// MCPExternalAuthConfig referenced from an MCPServer mounts the OBO client +// secret into the proxy container under obo.ClientSecretEnvVar, and that the // deployment builder (deploymentForMCPServer) and the drift check // (deploymentNeedsUpdate) agree on it. MCPServer assembles env in two separate -// functions, so this guards the builder/drift symmetry that prevents a reconcile -// hot-loop. A stub OBO handler stands in for the out-of-tree enterprise handler. -// -//nolint:paralleltest // Mutates package-level oboHandler via RegisterOBOHandler. +// functions, so this guards the builder/drift symmetry that prevents a +// reconcile hot-loop. func TestMCPServerDeployment_OBOSecretEnvVars(t *testing.T) { - t.Cleanup(func() { ctrlutil.RegisterOBOHandler(defaultOBOHandlerStub()) }) - - oboEnvVar := corev1.EnvVar{ - Name: "TOOLHIVE_OBO_CLIENT_SECRET", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{Name: "obo-secret"}, - Key: "client-secret", - }, - }, - } - stub := defaultOBOHandlerStub() - stub.SecretEnvVars = func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return []corev1.EnvVar{oboEnvVar}, nil - } - ctrlutil.RegisterOBOHandler(stub) + t.Parallel() scheme := testutil.NewScheme(t) @@ -872,7 +921,12 @@ func TestMCPServerDeployment_OBOSecretEnvVars(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "obo-secret", Key: "client-secret"}, + Audience: "api://backend/.default", + }, }, } mcpServer := v1beta1test.NewMCPServer("test-server", "default", @@ -891,31 +945,28 @@ func TestMCPServerDeployment_OBOSecretEnvVars(t *testing.T) { require.NotNil(t, deployment) container := deployment.Spec.Template.Spec.Containers[0] - assert.Contains(t, container.Env, oboEnvVar, - "OBO handler SecretEnvVars output must be injected into the proxy container") + assert.Contains(t, container.Env, corev1.EnvVar{ + Name: obo.ClientSecretEnvVar, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: "obo-secret"}, + Key: "client-secret", + }, + }, + }, "the OBO client secret must be mounted into the proxy container") assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, mcpServer, "test-checksum"), "builder and drift check must agree on the OBO env var (no reconcile hot-loop)") } -// TestMCPServerDeployment_OBOSecretEnvVars_GenuineErrorDivergence locks in the -// documented MCPServer builder/drift behavior when the registered OBO handler -// returns a genuine (non-ErrEnterpriseRequired) error: the builder logs and -// continues, producing an OBO-env-less Deployment without failing, while -// deploymentNeedsUpdate reports the Deployment needs an update. This divergence -// is described at the drift site and exercised nowhere else at the controller -// level. (The inert ErrEnterpriseRequired path stays symmetric — see the test -// above — because AddOBOSecretEnvVars swallows it.) -// -//nolint:paralleltest // Mutates package-level oboHandler via RegisterOBOHandler. -func TestMCPServerDeployment_OBOSecretEnvVars_GenuineErrorDivergence(t *testing.T) { - t.Cleanup(func() { ctrlutil.RegisterOBOHandler(defaultOBOHandlerStub()) }) - - stub := defaultOBOHandlerStub() - stub.SecretEnvVars = func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, errors.New("secret not yet available") - } - ctrlutil.RegisterOBOHandler(stub) +// TestMCPServerDeployment_OBOSecretEnvVars_ErrorDivergence locks in the +// documented MCPServer builder/drift behavior when the OBO secret env var cannot +// be produced (here: an obo config with no clientSecretRef): the builder logs +// and continues, producing an OBO-env-less Deployment without failing, while +// deploymentNeedsUpdate reports the Deployment needs an update. The +// MCPExternalAuthConfig reconciler surfaces the underlying InvalidConfig. +func TestMCPServerDeployment_OBOSecretEnvVars_ErrorDivergence(t *testing.T) { + t.Parallel() scheme := testutil.NewScheme(t) @@ -937,15 +988,15 @@ func TestMCPServerDeployment_OBOSecretEnvVars_GenuineErrorDivergence(t *testing. reconciler := newTestMCPServerReconciler(fakeClient, scheme, kubernetes.PlatformKubernetes) - // Builder logs-and-continues: a Deployment is still produced (no error, no - // panic), with no OBO env var injected. deployment, err := reconciler.deploymentForMCPServer(t.Context(), mcpServer, "test-checksum") - require.NoError(t, err, "builder must log-and-continue on a genuine OBO handler error, not fail") + require.NoError(t, err, "builder must log-and-continue on an OBO env var error, not fail") require.NotNil(t, deployment) + for _, ev := range deployment.Spec.Template.Spec.Containers[0].Env { + assert.NotEqual(t, obo.ClientSecretEnvVar, ev.Name) + } - // Drift check returns true on the same error — the documented divergence. assert.True(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, mcpServer, "test-checksum"), - "deploymentNeedsUpdate reports drift while the OBO handler errors") + "deploymentNeedsUpdate reports drift while the OBO env var cannot be produced") } // TestMCPServerDeployment_TLSListenerKeepsHTTPProbes verifies that enabling the diff --git a/cmd/thv-operator/controllers/virtualmcpserver_controller.go b/cmd/thv-operator/controllers/virtualmcpserver_controller.go index d1f165070e..a37393e81a 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_controller.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_controller.go @@ -86,7 +86,7 @@ type AuthConfigError struct { Error error // Reason, when non-empty, overrides the default "ConversionFailed" condition reason. // Used to mirror upstream MCPExternalAuthConfig.Status.Conditions[Valid].Reason - // (e.g. "EnterpriseRequired") onto the per-backend auth config condition so the + // (e.g. "InvalidConfig") onto the per-backend auth config condition so the // failure surfaces with the same taxonomy on the consumer CR. Reason string } @@ -2676,6 +2676,19 @@ func (*VirtualMCPServerReconciler) convertExternalAuthConfigToStrategy( // Set unique env var names per ExternalAuthConfig to avoid conflicts // when multiple configs of the same type reference different secrets + setUniqueSecretEnvNames(strategy, externalAuthConfig) + + return strategy, nil +} + +// setUniqueSecretEnvNames points each secret-bearing strategy at the env var +// name the deployment mounts its secret under (see +// getExternalAuthConfigSecretEnvVars). The names incorporate the +// ExternalAuthConfig name so several configs of one type never collide. +func setUniqueSecretEnvNames( + strategy *authtypes.BackendAuthStrategy, + externalAuthConfig *mcpv1beta1.MCPExternalAuthConfig, +) { if strategy.TokenExchange != nil && externalAuthConfig.Spec.TokenExchange != nil && externalAuthConfig.Spec.TokenExchange.ClientSecretRef != nil { @@ -2686,6 +2699,11 @@ func (*VirtualMCPServerReconciler) convertExternalAuthConfigToStrategy( externalAuthConfig.Spec.HeaderInjection.ValueSecretRef != nil { strategy.HeaderInjection.HeaderValueEnv = ctrlutil.GenerateUniqueHeaderInjectionEnvVarName(externalAuthConfig.Name) } + if strategy.OBO != nil && + externalAuthConfig.Spec.OBO != nil && + externalAuthConfig.Spec.OBO.ClientSecretRef != nil { + strategy.OBO.ClientSecretEnv = ctrlutil.GenerateUniqueOBOEnvVarName(externalAuthConfig.Name) + } if strategy.XAA != nil && externalAuthConfig.Spec.XAA != nil { if externalAuthConfig.Spec.XAA.IDPClientSecretRef != nil { strategy.XAA.IDPClientSecretEnv = ctrlutil.GenerateUniqueXAAIDPSecretEnvVarName(externalAuthConfig.Name) @@ -2694,8 +2712,6 @@ func (*VirtualMCPServerReconciler) convertExternalAuthConfigToStrategy( strategy.XAA.TargetClientSecretEnv = ctrlutil.GenerateUniqueXAATargetSecretEnvVarName(externalAuthConfig.Name) } } - - return strategy, nil } // convertBackendAuthConfigToVMCP converts a BackendAuthConfig from CRD to vmcp config. @@ -2841,9 +2857,9 @@ func (r *VirtualMCPServerReconciler) discoverExternalAuthConfigs( continue } - // Mirror the source's Valid=False condition (e.g. EnterpriseRequired for - // obo-typed configs in upstream-only builds) onto the per-backend - // condition so the failure surfaces with the same reason taxonomy. + // Mirror the source's Valid=False condition (e.g. InvalidConfig for a + // malformed obo config) onto the per-backend condition so the failure + // surfaces with the same reason taxonomy. if mirrored := mirroredExternalAuthConfigInvalid(externalAuthConfig); mirrored != nil { authErrors = append(authErrors, AuthConfigError{ Context: fmt.Sprintf("%s%s", authContextDiscoveredPrefix, workloadInfo.Name), @@ -3812,7 +3828,7 @@ func setAuthConfigConditions( if defaultAuthError != nil { // Default auth has error - set False condition. When the source's // MCPExternalAuthConfig surfaced a Valid=False condition we propagate - // the source's reason (e.g. EnterpriseRequired); otherwise we report + // the source's reason (e.g. InvalidConfig); otherwise we report // ConversionFailed. statusManager.SetAuthConfigCondition( "DefaultAuthConfig", diff --git a/cmd/thv-operator/controllers/virtualmcpserver_deployment.go b/cmd/thv-operator/controllers/virtualmcpserver_deployment.go index bf416e7d09..cee7eff522 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_deployment.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_deployment.go @@ -876,15 +876,10 @@ func (r *VirtualMCPServerReconciler) discoverInlineExternalAuthConfigSecrets( } // getExternalAuthConfigSecretEnvVars returns the environment variables for -// secrets from an ExternalAuthConfig (token exchange client secrets, header -// injection values, or — for obo — whatever the registered OBO handler asks -// for). Generates unique env var names per ExternalAuthConfig to avoid conflicts -// when multiple configs of the same type reference different secrets. -// -// The obo arm forwards every env var the handler returns (matching MCPServer and -// MCPRemoteProxy) and propagates obo.ErrEnterpriseRequired so the wired-but- -// disabled state is not masked as a no-op (see #5328); callers log-and-continue -// on error. +// secrets from an ExternalAuthConfig (token exchange, OBO, and XAA client +// secrets, or header injection values). Generates unique env var names per +// ExternalAuthConfig to avoid conflicts when multiple configs of the same type +// reference different secrets; callers log-and-continue on error. func (r *VirtualMCPServerReconciler) getExternalAuthConfigSecretEnvVars( ctx context.Context, namespace string, @@ -946,13 +941,9 @@ func (r *VirtualMCPServerReconciler) getExternalAuthConfigSecretEnvVars( return nil, nil case mcpv1beta1.ExternalAuthTypeOBO: - // Dispatch through the registered OBO handler, forwarding every env var - // it returns. OBOSecretEnvVars propagates obo.ErrEnterpriseRequired in - // upstream-only builds (unlike ctrlutil.AddOBOSecretEnvVars, which - // swallows it for MCPServer/MCPRemoteProxy builder/drift symmetry); vMCP - // must propagate it per #5328 so the wired-but-disabled state is not - // masked as a no-op. - return ctrlutil.OBOSecretEnvVars(externalAuthConfig) + // Per-config name (unlike the proxyrunner pod's fixed + // obo.ClientSecretEnvVar): one vMCP can front several OBO backends. + return ctrlutil.OBOVMCPSecretEnvVar(externalAuthConfig) case mcpv1beta1.ExternalAuthTypeXAA: return xaaSecretEnvVars(externalAuthConfig, externalAuthConfigName), nil diff --git a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go index e9972283b4..31a04b0a15 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go @@ -36,6 +36,31 @@ func TestConvertExternalAuthConfigToStrategy(t *testing.T) { expectError bool validate func(*testing.T, *authtypes.BackendAuthStrategy) }{ + { + name: "obo uses a per-config client secret env var", + externalAuthConfig: &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-backend-a", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "obo-secret", Key: "client-secret"}, + Scopes: []string{"api://backend/.default"}, + }, + }, + }, + validate: func(t *testing.T, strategy *authtypes.BackendAuthStrategy) { + t.Helper() + require.NotNil(t, strategy.OBO) + assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Type) + assert.Equal(t, "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", + strategy.OBO.TokenURL) + assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_OBO_BACKEND_A", strategy.OBO.ClientSecretEnv, + "must match the env var getExternalAuthConfigSecretEnvVars mounts") + assert.Empty(t, strategy.OBO.ClientSecret, "the secret value must not be inlined in inline mode") + }, + }, { name: "token exchange with all fields", externalAuthConfig: &mcpv1beta1.MCPExternalAuthConfig{ @@ -836,8 +861,8 @@ func TestConvertBackendAuthConfigToVMCP(t *testing.T) { // TestConvertBackendAuthConfigToVMCP_MirrorsInvalidExternalAuthConfig verifies // the mirror added for #5347: when the referenced MCPExternalAuthConfig has -// Status.Conditions[Valid]=False (e.g. obo-typed configs in upstream-only -// builds), the conversion must short-circuit before reaching the converter and +// Status.Conditions[Valid]=False (e.g. a malformed obo-typed config), +// the conversion must short-circuit before reaching the converter and // return a typed error that carries the source's reason+message so callers // (buildOutgoingAuthConfig) can propagate the reason onto the per-backend // AuthConfigError. @@ -856,8 +881,8 @@ func TestConvertBackendAuthConfigToVMCP_MirrorsInvalidExternalAuthConfig(t *test Conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, - Message: "obo enterprise required", + Reason: testSourceInvalidReason, + Message: testSourceInvalidMessage, }}, }, } @@ -880,16 +905,16 @@ func TestConvertBackendAuthConfigToVMCP_MirrorsInvalidExternalAuthConfig(t *test require.Error(t, err, "must short-circuit when source Valid=False") require.Nil(t, strategy) - assert.Equal(t, mcpv1beta1.ConditionReasonEnterpriseRequired, mirroredReasonFromError(err), + assert.Equal(t, testSourceInvalidReason, mirroredReasonFromError(err), "buildOutgoingAuthConfig depends on this reason flowing through mirroredReasonFromError") // Wrap the error exactly as buildOutgoingAuthConfig does in production // (fmt.Errorf("...: %w", err)) and assert the reason still survives the // errors.As walk. A future refactor that drops %w in favour of %v or // errors.New(fmt.Sprintf(...)) would silently break per-backend reason - // propagation and surface ConversionFailed instead of EnterpriseRequired. + // propagation and surface ConversionFailed instead of the source reason. wrapped := fmt.Errorf("failed to convert backend auth config: %w", err) - assert.Equal(t, mcpv1beta1.ConditionReasonEnterpriseRequired, mirroredReasonFromError(wrapped), + assert.Equal(t, testSourceInvalidReason, mirroredReasonFromError(wrapped), "buildOutgoingAuthConfig wraps the err once before extracting the reason; "+ "the contract must survive that wrap") } @@ -910,15 +935,15 @@ func TestMirroredExternalAuthConfigInvalid(t *testing.T) { wantMessage string }{ { - name: "Valid=False/EnterpriseRequired returns mirrored pointer", + name: "Valid=False/SourceRejected returns mirrored pointer", conditions: []metav1.Condition{{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, - Message: "obo enterprise required", + Reason: testSourceInvalidReason, + Message: testSourceInvalidMessage, }}, - wantReason: mcpv1beta1.ConditionReasonEnterpriseRequired, - wantMessage: "obo enterprise required", + wantReason: testSourceInvalidReason, + wantMessage: testSourceInvalidMessage, }, { name: "Valid=True returns nil", @@ -995,8 +1020,8 @@ func TestAuthConfigErrorReason(t *testing.T) { }, { name: "non-empty Reason is propagated verbatim", - in: &AuthConfigError{Reason: mcpv1beta1.ConditionReasonEnterpriseRequired}, - want: mcpv1beta1.ConditionReasonEnterpriseRequired, + in: &AuthConfigError{Reason: testSourceInvalidReason}, + want: testSourceInvalidReason, }, } @@ -1971,49 +1996,63 @@ func TestGetExternalAuthConfigSecretEnvVars_XAA(t *testing.T) { } // TestGetExternalAuthConfigSecretEnvVars_OBO proves the obo arm of the -// getExternalAuthConfigSecretEnvVars switch dispatches through the registered -// OBO handler. With the default handler the method must return an error -// wrapping obo.ErrEnterpriseRequired AND must not silently fall through to -// nil, nil — that would mask the wired-but-disabled state behind a no-op. This -// propagate-on-disabled contract is why vMCP calls OBOSecretEnvVars directly -// rather than the swallowing ctrlutil.AddOBOSecretEnvVars wrapper. +// getExternalAuthConfigSecretEnvVars switch mounts each OBO backend's client +// secret under a per-config env var name, so two OBO backends in one vMCP pod +// never collide, and that a config without a secret reference is an error +// rather than a silent no-op. func TestGetExternalAuthConfigSecretEnvVars_OBO(t *testing.T) { t.Parallel() scheme := testutil.NewScheme(t) - authCfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "obo-config", - Namespace: "default", - }, + newOBOConfig := func(name, secretName string) *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: secretName, Key: "client-secret"}, + Audience: "api://backend/.default", + }, + }, + } + } + backendA := newOBOConfig("obo-a", "secret-a") + backendB := newOBOConfig("obo-b", "secret-b") + noSecret := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-no-secret", Namespace: "default"}, Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ Type: mcpv1beta1.ExternalAuthTypeOBO, OBO: &mcpv1beta1.OBOConfig{}, }, } - fakeClient := fake.NewClientBuilder(). - WithScheme(scheme). - WithObjects(authCfg). - Build() - r := &VirtualMCPServerReconciler{ - Client: fakeClient, + Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(backendA, backendB, noSecret).Build(), Scheme: scheme, PlatformDetector: ctrlutil.NewSharedPlatformDetector(), } - envVars, err := r.getExternalAuthConfigSecretEnvVars(t.Context(), "default", authCfg.Name) + envA, err := r.getExternalAuthConfigSecretEnvVars(t.Context(), "default", backendA.Name) + require.NoError(t, err) + envB, err := r.getExternalAuthConfigSecretEnvVars(t.Context(), "default", backendB.Name) + require.NoError(t, err) + + require.Len(t, envA, 1) + require.Len(t, envB, 1) + assert.Equal(t, ctrlutil.GenerateUniqueOBOEnvVarName(backendA.Name), envA[0].Name) + assert.Equal(t, ctrlutil.GenerateUniqueOBOEnvVarName(backendB.Name), envB[0].Name) + assert.NotEqual(t, envA[0].Name, envB[0].Name, "two OBO backends must get distinct env vars") + assert.Equal(t, "secret-a", envA[0].ValueFrom.SecretKeyRef.Name) + assert.Equal(t, "secret-b", envB[0].ValueFrom.SecretKeyRef.Name) + + envVars, err := r.getExternalAuthConfigSecretEnvVars(t.Context(), "default", noSecret.Name) require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired, - "the default OBO handler returns obo.ErrEnterpriseRequired; the dispatch arm must propagate it") - assert.Empty(t, envVars, "no env var should be returned on the error path") - - // Generic-error guard: per issue #5328 AC, neither generic substring may - // leak from any of the three consumer dispatch paths. - assert.NotContains(t, err.Error(), "unsupported external auth type") - assert.NotContains(t, err.Error(), "unknown middleware type") + var vErr *obo.ValidationError + assert.ErrorAs(t, err, &vErr) + assert.Empty(t, envVars) } // headerInjectionAuthConfig builds an MCPExternalAuthConfig of type headerInjection diff --git a/cmd/thv-operator/controllers/virtualmcpserver_vmcpconfig_test.go b/cmd/thv-operator/controllers/virtualmcpserver_vmcpconfig_test.go index c1ead87f54..861a02033c 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_vmcpconfig_test.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_vmcpconfig_test.go @@ -926,20 +926,20 @@ func TestSetAuthConfigConditions(t *testing.T) { { Context: "default", BackendName: "", - Error: fmt.Errorf("on-behalf-of (OBO) external auth type requires an enterprise build"), - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Error: fmt.Errorf("%s", testSourceInvalidMessage), + Reason: testSourceInvalidReason, }, { Context: "discovered:discovered-backend", BackendName: "discovered-backend", - Error: fmt.Errorf("obo enterprise required"), - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Error: fmt.Errorf("%s", testSourceInvalidMessage), + Reason: testSourceInvalidReason, }, { Context: "backend:inline-backend", BackendName: "inline-backend", - Error: fmt.Errorf("obo enterprise required"), - Reason: mcpv1beta1.ConditionReasonEnterpriseRequired, + Error: fmt.Errorf("%s", testSourceInvalidMessage), + Reason: testSourceInvalidReason, }, }, validate: func(t *testing.T, mock *statusmocks.MockStatusManager) { @@ -953,7 +953,7 @@ func TestSetAuthConfigConditions(t *testing.T) { mock.EXPECT(). SetAuthConfigCondition( "DefaultAuthConfig", - mcpv1beta1.ConditionReasonEnterpriseRequired, + testSourceInvalidReason, gomock.Any(), metav1.ConditionFalse, ). @@ -961,7 +961,7 @@ func TestSetAuthConfigConditions(t *testing.T) { mock.EXPECT(). SetAuthConfigCondition( "DiscoveredAuthConfig-discovered-backend", - mcpv1beta1.ConditionReasonEnterpriseRequired, + testSourceInvalidReason, gomock.Any(), metav1.ConditionFalse, ). @@ -969,7 +969,7 @@ func TestSetAuthConfigConditions(t *testing.T) { mock.EXPECT(). SetAuthConfigCondition( "BackendAuthConfig-inline-backend", - mcpv1beta1.ConditionReasonEnterpriseRequired, + testSourceInvalidReason, gomock.Any(), metav1.ConditionFalse, ). diff --git a/cmd/thv-operator/pkg/controllerutil/externalauth.go b/cmd/thv-operator/pkg/controllerutil/externalauth.go index 5bf012a1f0..56fe42a880 100644 --- a/cmd/thv-operator/pkg/controllerutil/externalauth.go +++ b/cmd/thv-operator/pkg/controllerutil/externalauth.go @@ -68,6 +68,21 @@ func GenerateUniqueXAATargetSecretEnvVarName(configName string) string { return fmt.Sprintf("TOOLHIVE_XAA_TARGET_CLIENT_SECRET_%s", sanitized) } +// GenerateUniqueOBOEnvVarName generates a unique environment variable name for +// an OBO client secret mounted into the vMCP pod, incorporating the +// ExternalAuthConfig name so several OBO backends in one vMCP never collide. +// Used by both the converter enrichment and the deployment controller for +// consistent naming. (The proxyrunner pod carries at most one OBO config and +// uses the fixed obo.ClientSecretEnvVar.) +// +// Example: For an ExternalAuthConfig named "my-auth-config", this returns: +// "TOOLHIVE_OBO_CLIENT_SECRET_MY_AUTH_CONFIG" +func GenerateUniqueOBOEnvVarName(configName string) string { + sanitized := strings.ToUpper(strings.ReplaceAll(configName, "-", "_")) + sanitized = envVarSanitizer.ReplaceAllString(sanitized, "_") + return fmt.Sprintf("TOOLHIVE_OBO_CLIENT_SECRET_%s", sanitized) +} + // Header-forward env-var helpers (constants + name generators + the shared // header-name normalizer) moved to pkg/vmcp/headerforward/wirefmt so the // runtime can consume them without inverting Go layering. Operator code diff --git a/cmd/thv-operator/pkg/controllerutil/obo.go b/cmd/thv-operator/pkg/controllerutil/obo.go new file mode 100644 index 0000000000..88969f5ca2 --- /dev/null +++ b/cmd/thv-operator/pkg/controllerutil/obo.go @@ -0,0 +1,313 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package controllerutil + +import ( + "context" + "fmt" + "strings" + "sync" + + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/runner" + "github.com/stacklok/toolhive/pkg/transport/types" +) + +// OBO validation messages. They name neither a Secret nor a value, so they are +// safe to surface verbatim in a status condition. +const ( + msgOBOConfigRequired = "obo: configuration is required for the obo external auth type" + msgOBOClientIDRequired = "obo: clientId is required" + //nolint:gosec // G101: validation message, not a credential. + msgOBOClientSecretRef = "obo: clientSecretRef must set both name and key" + msgOBOCacheSkew = "obo: cacheSkew must not be negative" + msgOBOAudienceOrScopes = "obo: at least one of audience or scopes is required" + + // MsgOBORequiresIncomingAuth is the condition message for an obo external + // auth config referenced by an MCPServer or MCPRemoteProxy that has no + // incoming OIDC authentication. + MsgOBORequiresIncomingAuth = "obo external auth requires incoming authentication: " + + "set spec.oidcConfigRef so the proxy has an authenticated user token to exchange" +) + +// OBOHandler bundles the three operator-time OBO dispatch points. +// +// Deprecated: OBO is built in. OBOHandler and RegisterOBOHandler are kept only +// so out-of-tree code that still registers a handler keeps compiling; they will +// be removed in a future release. +type OBOHandler struct { + // Validate verifies an obo-typed MCPExternalAuthConfig is well-formed. + Validate func(*mcpv1beta1.MCPExternalAuthConfig) error + + // ApplyRunConfig appends the OBO runner options for a consuming MCPServer + // or MCPRemoteProxy. + ApplyRunConfig func( + ctx context.Context, c client.Client, namespace string, + cfg *mcpv1beta1.MCPExternalAuthConfig, + opts *[]runner.RunConfigBuilderOption, + ) error + + // SecretEnvVars returns the pod env vars the OBO proxy middleware needs. + SecretEnvVars func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) +} + +// oboMu guards reads and writes of oboHandler. +var oboMu sync.RWMutex + +// oboHandler holds the OBO dispatch functions: the built-in implementation +// unless out-of-tree code replaced it through the deprecated RegisterOBOHandler. +var oboHandler = OBOHandler{ + Validate: validateOBO, + ApplyRunConfig: applyOBORunConfig, + SecretEnvVars: oboProxySecretEnvVars, +} + +// RegisterOBOHandler replaces the built-in OBO handler. Last-write-wins. +// Panics if any of the three function fields is nil. +// +// Deprecated: OBO is built in; see OBOHandler. +func RegisterOBOHandler(h OBOHandler) { + switch { + case h.Validate == nil: + panic("controllerutil.RegisterOBOHandler: Validate is nil") + case h.ApplyRunConfig == nil: + panic("controllerutil.RegisterOBOHandler: ApplyRunConfig is nil") + case h.SecretEnvVars == nil: + panic("controllerutil.RegisterOBOHandler: SecretEnvVars is nil") + } + oboMu.Lock() + defer oboMu.Unlock() + oboHandler = h +} + +// currentOBOHandler returns a snapshot of the handler under the read lock. +func currentOBOHandler() OBOHandler { + oboMu.RLock() + defer oboMu.RUnlock() + return oboHandler +} + +// OBOValidate validates an obo-typed MCPExternalAuthConfig. Every failure the +// user can fix by editing the spec is an *obo.ValidationError, whose message is +// safe to surface in a status condition. +func OBOValidate(cfg *mcpv1beta1.MCPExternalAuthConfig) error { + return currentOBOHandler().Validate(cfg) +} + +// OBOSecretEnvVars returns the env var that mounts the OBO client secret into +// a proxyrunner pod (MCPServer or MCPRemoteProxy) under obo.ClientSecretEnvVar. +// The vMCP pod uses per-config names instead; see GenerateUniqueOBOEnvVarName. +func OBOSecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { + return currentOBOHandler().SecretEnvVars(cfg) +} + +// OBOApplyRunConfig appends the OBO middleware config for a consuming MCPServer +// or MCPRemoteProxy to opts. A malformed config is an *obo.ValidationError; a +// referenced Secret that is not available yet is a plain (transient) error. +func OBOApplyRunConfig( + ctx context.Context, + c client.Client, + namespace string, + cfg *mcpv1beta1.MCPExternalAuthConfig, + opts *[]runner.RunConfigBuilderOption, +) error { + return currentOBOHandler().ApplyRunConfig(ctx, c, namespace, cfg, opts) +} + +// ValidateOBOIncomingAuth rejects an obo-typed MCPExternalAuthConfig referenced +// by an MCPServer or MCPRemoteProxy that has no incoming OIDC authentication. +// OBO exchanges the authenticated user's token, so without incoming +// authentication every request would fail with 401 at runtime. Returns nil for +// every other external auth type. +func ValidateOBOIncomingAuth(cfg *mcpv1beta1.MCPExternalAuthConfig, hasIncomingOIDC bool) error { + if cfg == nil || cfg.Spec.Type != mcpv1beta1.ExternalAuthTypeOBO || hasIncomingOIDC { + return nil + } + return &obo.ValidationError{Message: MsgOBORequiresIncomingAuth} +} + +// AddOBOSecretEnvVars resolves ref to an MCPExternalAuthConfig and, if it is +// the obo type, returns the proxyrunner pod env var carrying its client secret. +// For every other type it returns no env vars: the other types' secret env vars +// are produced by their own per-type helpers (GenerateTokenExchangeEnvVars, +// GenerateBearerTokenEnvVar), using consumer-specific names that must stay +// byte-identical. Do not add the other types here. +// +// MCPServer and MCPRemoteProxy both route through this helper, so the +// deployment builder and the drift check compute the same env. +func AddOBOSecretEnvVars( + ctx context.Context, + c client.Client, + namespace string, + ref *mcpv1beta1.ExternalAuthConfigRef, +) ([]corev1.EnvVar, error) { + if ref == nil { + return nil, nil + } + + externalAuthConfig, err := GetExternalAuthConfigByName(ctx, c, namespace, ref.Name) + if err != nil { + return nil, fmt.Errorf("failed to get MCPExternalAuthConfig: %w", err) + } + + if externalAuthConfig.Spec.Type != mcpv1beta1.ExternalAuthTypeOBO { + return nil, nil + } + return OBOSecretEnvVars(externalAuthConfig) +} + +// OBOVMCPSecretEnvVar returns the env var that mounts an OBO client secret into +// the vMCP pod. The name is unique per MCPExternalAuthConfig so several OBO +// backends in one vMCP never collide. +func OBOVMCPSecretEnvVar(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { + if oboSpec(cfg) == nil { + return nil, &obo.ValidationError{Message: msgOBOConfigRequired} + } + if err := validateOBOSecretRef(cfg.Spec.OBO.ClientSecretRef); err != nil { + return nil, err + } + return []corev1.EnvVar{oboSecretEnvVar(GenerateUniqueOBOEnvVarName(cfg.Name), cfg.Spec.OBO.ClientSecretRef)}, nil +} + +// validateOBO is the built-in OBOHandler.Validate. +func validateOBO(cfg *mcpv1beta1.MCPExternalAuthConfig) error { + _, err := buildOBOMiddlewareParameters(oboSpec(cfg)) + return err +} + +// applyOBORunConfig is the built-in OBOHandler.ApplyRunConfig. It builds the +// obo.MiddlewareParameters contract, verifies the referenced client Secret is +// present, and appends the "obo"-typed MiddlewareConfig through the runner's +// AdditionalMiddlewareConfigs seam. It does not mutate opts on error. +func applyOBORunConfig( + ctx context.Context, + c client.Client, + namespace string, + cfg *mcpv1beta1.MCPExternalAuthConfig, + opts *[]runner.RunConfigBuilderOption, +) error { + params, err := buildOBOMiddlewareParameters(oboSpec(cfg)) + if err != nil { + return err + } + if err := verifyOBOClientSecret(ctx, c, namespace, cfg.Spec.OBO.ClientSecretRef); err != nil { + return err + } + + mwConfig, err := types.NewMiddlewareConfig(obo.MiddlewareType, params) + if err != nil { + return fmt.Errorf("obo: build middleware config: %w", err) + } + *opts = append(*opts, runner.WithAdditionalMiddlewareConfigs(mwConfig)) + return nil +} + +// oboProxySecretEnvVars is the built-in OBOHandler.SecretEnvVars. The env var +// name matches the contract's clientSecretEnvVar; the secret value never +// enters the RunConfig ConfigMap. +func oboProxySecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { + if oboSpec(cfg) == nil { + return nil, &obo.ValidationError{Message: msgOBOConfigRequired} + } + if err := validateOBOSecretRef(cfg.Spec.OBO.ClientSecretRef); err != nil { + return nil, err + } + return []corev1.EnvVar{oboSecretEnvVar(obo.ClientSecretEnvVar, cfg.Spec.OBO.ClientSecretRef)}, nil +} + +// buildOBOMiddlewareParameters maps an OBOConfig onto obo.MiddlewareParameters +// and validates what the CRD schema cannot express: clientId and +// clientSecretRef presence, a non-negative cacheSkew, a usable tenant and +// authority, and at least one of audience or scopes. Every rejection is an +// *obo.ValidationError. +func buildOBOMiddlewareParameters(oboCfg *mcpv1beta1.OBOConfig) (*obo.MiddlewareParameters, error) { + if oboCfg == nil { + return nil, &obo.ValidationError{Message: msgOBOConfigRequired} + } + if strings.TrimSpace(oboCfg.ClientID) == "" { + return nil, &obo.ValidationError{Message: msgOBOClientIDRequired} + } + if err := validateOBOSecretRef(oboCfg.ClientSecretRef); err != nil { + return nil, err + } + if oboCfg.CacheSkew != nil && oboCfg.CacheSkew.Duration < 0 { + return nil, &obo.ValidationError{Message: msgOBOCacheSkew} + } + + // entra.TokenURL is the single source of truth for the tenant/authority to + // token endpoint mapping; its messages carry no secret, so surface them. + tokenURL, err := entra.TokenURL(oboCfg.TenantID, oboCfg.Authority) + if err != nil { + return nil, &obo.ValidationError{Message: err.Error()} + } + + params := &obo.MiddlewareParameters{ + TokenURL: tokenURL, + ClientID: oboCfg.ClientID, + Audience: oboCfg.Audience, + Scopes: oboCfg.Scopes, + ClientSecretEnvVar: obo.ClientSecretEnvVar, + SubjectTokenProviderName: oboCfg.SubjectTokenProviderName, + } + // A sub-second skew truncates to 0, which the runtime treats as "use the + // cache default". The vMCP converter truncates the same way. + if oboCfg.CacheSkew != nil { + params.CacheSkewSeconds = int(oboCfg.CacheSkew.Seconds()) + } + + if params.ExchangeTarget() == "" { + return nil, &obo.ValidationError{Message: msgOBOAudienceOrScopes} + } + return params, nil +} + +// validateOBOSecretRef rejects an absent or incomplete clientSecretRef. OBO is +// a confidential-client (shared-secret) flow, so both the Secret name and key +// are required. +func validateOBOSecretRef(ref *mcpv1beta1.SecretKeyRef) error { + if ref == nil || strings.TrimSpace(ref.Name) == "" || strings.TrimSpace(ref.Key) == "" { + return &obo.ValidationError{Message: msgOBOClientSecretRef} + } + return nil +} + +// verifyOBOClientSecret confirms the referenced Secret exists and carries the +// key. A missing Secret or key is transient (the user may still create it), so +// it returns a plain error the reconciler requeues, not an *obo.ValidationError. +func verifyOBOClientSecret(ctx context.Context, c client.Client, namespace string, ref *mcpv1beta1.SecretKeyRef) error { + var secret corev1.Secret + if err := c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: ref.Name}, &secret); err != nil { + return fmt.Errorf("obo: referenced client secret is not available: %w", err) + } + if _, ok := secret.Data[ref.Key]; !ok { + return fmt.Errorf("obo: referenced client secret is missing the configured key") + } + return nil +} + +// oboSpec returns cfg's OBO spec, or nil when cfg itself is nil. +func oboSpec(cfg *mcpv1beta1.MCPExternalAuthConfig) *mcpv1beta1.OBOConfig { + if cfg == nil { + return nil + } + return cfg.Spec.OBO +} + +// oboSecretEnvVar builds an env var named name that sources its value from ref. +func oboSecretEnvVar(name string, ref *mcpv1beta1.SecretKeyRef) corev1.EnvVar { + return corev1.EnvVar{ + Name: name, + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: ref.Name}, + Key: ref.Key, + }, + }, + } +} diff --git a/cmd/thv-operator/pkg/controllerutil/obo_test.go b/cmd/thv-operator/pkg/controllerutil/obo_test.go new file mode 100644 index 0000000000..4d779aabd6 --- /dev/null +++ b/cmd/thv-operator/pkg/controllerutil/obo_test.go @@ -0,0 +1,491 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package controllerutil + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" + "github.com/stacklok/toolhive/cmd/thv-operator/pkg/oidc" + "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/runner" +) + +const ( + oboTestNamespace = "default" + oboTestSecretName = "obo-client-secret" + oboTestSecretKey = "client-secret" + oboTestSecretVal = "super-secret-value" + oboTestTenant = "contoso.onmicrosoft.com" + oboTestClientID = "11111111-1111-1111-1111-111111111111" + // oboWantTokenURL is the endpoint derived from oboTestTenant with the + // default authority, pinned so a change to the URL construction is caught. + oboWantTokenURL = "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token" +) + +// validOBOConfig returns a well-formed shared-secret OBO config. +func validOBOConfig() *mcpv1beta1.OBOConfig { + return &mcpv1beta1.OBOConfig{ + TenantID: oboTestTenant, + ClientID: oboTestClientID, + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: oboTestSecretName, Key: oboTestSecretKey}, + Audience: "api://backend/.default", + } +} + +// mutatedOBOConfig returns a valid OBO config with f applied. +func mutatedOBOConfig(f func(*mcpv1beta1.OBOConfig)) *mcpv1beta1.OBOConfig { + cfg := validOBOConfig() + f(cfg) + return cfg +} + +func oboCR(name string, cfg *mcpv1beta1.OBOConfig) *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: oboTestNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: cfg, + }, + } +} + +// oboClient returns a fake client holding objs plus the referenced client Secret. +func oboClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + objs = append(objs, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: oboTestSecretName, Namespace: oboTestNamespace}, + Data: map[string][]byte{oboTestSecretKey: []byte(oboTestSecretVal)}, + }) + return fake.NewClientBuilder().WithScheme(testutil.NewScheme(t)).WithObjects(objs...).Build() +} + +func TestOBOValidate(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + cfg *mcpv1beta1.OBOConfig + wantMsg string // empty means valid + }{ + {name: "audience only", cfg: validOBOConfig()}, + {name: "scopes only", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.Audience = "" + c.Scopes = []string{"api://backend/.default"} + })}, + {name: "GUID tenant", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.TenantID = "72f988bf-86f1-41af-91ab-2d7cd011db47" + })}, + {name: "sovereign authority", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.Authority = "https://login.microsoftonline.us" + })}, + {name: "non-negative cache skew", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.CacheSkew = &metav1.Duration{Duration: 30 * time.Second} + })}, + {name: "nil obo config", cfg: nil, wantMsg: msgOBOConfigRequired}, + { + name: "missing client id", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientID = "" }), + wantMsg: msgOBOClientIDRequired, + }, + { + name: "nil client secret ref", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }), + wantMsg: msgOBOClientSecretRef, + }, + { + name: "client secret ref missing key", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef.Key = "" }), + wantMsg: msgOBOClientSecretRef, + }, + { + name: "no audience and only blank scopes", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.Audience = "" + c.Scopes = []string{" "} + }), + wantMsg: msgOBOAudienceOrScopes, + }, + { + name: "negative cache skew", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.CacheSkew = &metav1.Duration{Duration: -time.Second} }), + wantMsg: msgOBOCacheSkew, + }, + { + name: "missing tenant", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.TenantID = "" }), + wantMsg: "entra obo: TenantID is required", + }, + { + name: "tenant neither guid nor domain", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.TenantID = "not a tenant" }), + wantMsg: "entra obo: TenantID must be a directory GUID or a domain name", + }, + { + name: "non-loopback http authority", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.Authority = "http://login.microsoftonline.com" }), + wantMsg: "entra obo: Authority must use https (http allowed only for loopback)", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := OBOValidate(oboCR("obo-config", tt.cfg)) + if tt.wantMsg == "" { + require.NoError(t, err) + return + } + var vErr *obo.ValidationError + require.ErrorAs(t, err, &vErr, "a malformed config must be a permanent ValidationError") + assert.EqualError(t, err, tt.wantMsg) + assert.NotContains(t, err.Error(), oboTestSecretName, "the message must not name the Secret") + }) + } +} + +func TestAddExternalAuthConfigOptions_OBO(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + provider string + wantProviderKey bool + }{ + {name: "inbound mode (provider empty)"}, + {name: "embedded auth server (provider set)", provider: "entra-upstream", wantProviderKey: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := validOBOConfig() + cfg.Scopes = []string{"api://backend/.default", "offline_access"} + cfg.SubjectTokenProviderName = tt.provider + cfg.CacheSkew = &metav1.Duration{Duration: 30 * time.Second} + authCfg := oboCR("obo-config", cfg) + + var opts []runner.RunConfigBuilderOption + require.NoError(t, AddExternalAuthConfigOptions( + t.Context(), oboClient(t, authCfg), oboTestNamespace, "server", + &mcpv1beta1.ExternalAuthConfigRef{Name: authCfg.Name}, + &oidc.OIDCConfig{Issuer: "https://issuer.example.com"}, &opts, + )) + require.Len(t, opts, 1, "exactly one builder option must be appended") + + rc, err := runner.NewOperatorRunConfigBuilder(t.Context(), nil, nil, nil, + append([]runner.RunConfigBuilderOption{ + runner.WithName("obo-test"), + runner.WithImage("ghcr.io/example/mcp:latest"), + }, opts...)...) + require.NoError(t, err) + require.Len(t, rc.AdditionalMiddlewareConfigs, 1) + + mc := rc.AdditionalMiddlewareConfigs[0] + assert.Equal(t, obo.MiddlewareType, mc.Type) + + var got obo.MiddlewareParameters + require.NoError(t, json.Unmarshal(mc.Parameters, &got)) + assert.Equal(t, obo.MiddlewareParameters{ + TokenURL: oboWantTokenURL, + ClientID: oboTestClientID, + Audience: "api://backend/.default", + Scopes: []string{"api://backend/.default", "offline_access"}, + ClientSecretEnvVar: obo.ClientSecretEnvVar, + SubjectTokenProviderName: tt.provider, + CacheSkewSeconds: 30, + }, got) + + // Only the env var name travels in the contract, never the value. + assert.NotContains(t, string(mc.Parameters), oboTestSecretVal) + if tt.wantProviderKey { + assert.Contains(t, string(mc.Parameters), "subjectTokenProviderName") + } else { + assert.NotContains(t, string(mc.Parameters), "subjectTokenProviderName") + } + }) + } +} + +func TestAddExternalAuthConfigOptions_OBOErrors(t *testing.T) { + t.Parallel() + + issuer := &oidc.OIDCConfig{Issuer: "https://issuer.example.com"} + scheme := testutil.NewScheme(t) + + tests := []struct { + name string + cfg *mcpv1beta1.OBOConfig + client func(t *testing.T, authCfg *mcpv1beta1.MCPExternalAuthConfig) client.Client + oidcConfig *oidc.OIDCConfig + wantPermanent bool + wantMsg string + }{ + { + name: "no incoming OIDC is a permanent ValidationError", + cfg: validOBOConfig(), + client: func(t *testing.T, a *mcpv1beta1.MCPExternalAuthConfig) client.Client { + t.Helper() + return oboClient(t, a) + }, + oidcConfig: nil, + wantPermanent: true, + wantMsg: MsgOBORequiresIncomingAuth, + }, + { + name: "malformed config is a permanent ValidationError", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.TenantID = "not a tenant" }), + client: func(t *testing.T, a *mcpv1beta1.MCPExternalAuthConfig) client.Client { + t.Helper() + return oboClient(t, a) + }, + oidcConfig: issuer, + wantPermanent: true, + }, + { + name: "missing secret is transient", + cfg: validOBOConfig(), + client: func(_ *testing.T, a *mcpv1beta1.MCPExternalAuthConfig) client.Client { + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(a).Build() + }, + oidcConfig: issuer, + }, + { + name: "secret missing the key is transient", + cfg: validOBOConfig(), + client: func(_ *testing.T, a *mcpv1beta1.MCPExternalAuthConfig) client.Client { + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(a, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: oboTestSecretName, Namespace: oboTestNamespace}, + Data: map[string][]byte{"wrong-key": []byte(oboTestSecretVal)}, + }).Build() + }, + oidcConfig: issuer, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + authCfg := oboCR("obo-config", tt.cfg) + + var opts []runner.RunConfigBuilderOption + err := AddExternalAuthConfigOptions( + t.Context(), tt.client(t, authCfg), oboTestNamespace, "server", + &mcpv1beta1.ExternalAuthConfigRef{Name: authCfg.Name}, tt.oidcConfig, &opts, + ) + require.Error(t, err) + var vErr *obo.ValidationError + assert.Equal(t, tt.wantPermanent, errors.As(err, &vErr)) + if tt.wantMsg != "" { + assert.EqualError(t, err, tt.wantMsg) + } + assert.Empty(t, opts, "no option appended on error") + }) + } +} + +func TestValidateOBOIncomingAuth(t *testing.T) { + t.Parallel() + + oboCfg := oboCR("obo-config", validOBOConfig()) + otherCfg := &mcpv1beta1.MCPExternalAuthConfig{ + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{Type: mcpv1beta1.ExternalAuthTypeTokenExchange}, + } + + tests := []struct { + name string + cfg *mcpv1beta1.MCPExternalAuthConfig + hasOIDC bool + wantErr bool + }{ + {name: "obo without incoming OIDC is rejected", cfg: oboCfg, wantErr: true}, + {name: "obo with incoming OIDC is accepted", cfg: oboCfg, hasOIDC: true}, + {name: "other types are not affected", cfg: otherCfg}, + {name: "nil config is accepted", cfg: nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := ValidateOBOIncomingAuth(tt.cfg, tt.hasOIDC) + if !tt.wantErr { + assert.NoError(t, err) + return + } + var vErr *obo.ValidationError + require.ErrorAs(t, err, &vErr) + assert.Equal(t, MsgOBORequiresIncomingAuth, vErr.Message) + }) + } +} + +// TestAddOBOSecretEnvVars covers the OBO-only secret-env dispatcher. Only obo +// contributes an env var; the other secret-bearing types are populated so the +// empty result is a real invariant, not an artifact of an absent secret ref. +func TestAddOBOSecretEnvVars(t *testing.T) { + t.Parallel() + + others := []*mcpv1beta1.MCPExternalAuthConfig{ + { + ObjectMeta: metav1.ObjectMeta{Name: "te", Namespace: oboTestNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeTokenExchange, + TokenExchange: &mcpv1beta1.TokenExchangeConfig{ + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "te-secret", Key: "client-secret"}, + }, + }, + }, + { + ObjectMeta: metav1.ObjectMeta{Name: "bt", Namespace: oboTestNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeBearerToken, + BearerToken: &mcpv1beta1.BearerTokenConfig{ + TokenSecretRef: &mcpv1beta1.SecretKeyRef{Name: "bt-secret", Key: "token"}, + }, + }, + }, + { + ObjectMeta: metav1.ObjectMeta{Name: "hi", Namespace: oboTestNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeHeaderInjection, + HeaderInjection: &mcpv1beta1.HeaderInjectionConfig{ + ValueSecretRef: &mcpv1beta1.SecretKeyRef{Name: "hi-secret", Key: "value"}, + }, + }, + }, + } + objs := []client.Object{oboCR("obo", validOBOConfig()), oboCR("obo-bad", nil)} + for _, o := range others { + objs = append(objs, o) + } + c := oboClient(t, objs...) + + tests := []struct { + name string + ref *mcpv1beta1.ExternalAuthConfigRef + wantEnvs []corev1.EnvVar + wantErr bool + }{ + {name: "nil ref returns no env vars"}, + {name: "missing config returns error", ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "missing"}, wantErr: true}, + {name: "tokenExchange contributes no env vars here", ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "te"}}, + {name: "bearerToken contributes no env vars here", ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "bt"}}, + {name: "headerInjection contributes no env vars here", ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "hi"}}, + { + name: "obo mounts the client secret under the fixed proxy env var", + ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "obo"}, + wantEnvs: []corev1.EnvVar{ + oboSecretEnvVar(obo.ClientSecretEnvVar, &mcpv1beta1.SecretKeyRef{Name: oboTestSecretName, Key: oboTestSecretKey}), + }, + }, + {name: "obo without a spec is an error", ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "obo-bad"}, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + envVars, err := AddOBOSecretEnvVars(t.Context(), c, oboTestNamespace, tt.ref) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantEnvs, envVars) + for _, ev := range envVars { + assert.Empty(t, ev.Value, "the secret value must never be inlined") + } + }) + } +} + +func TestOBOVMCPSecretEnvVar_UniquePerConfig(t *testing.T) { + t.Parallel() + + first, err := OBOVMCPSecretEnvVar(oboCR("backend-a", validOBOConfig())) + require.NoError(t, err) + second, err := OBOVMCPSecretEnvVar(oboCR("backend-b", validOBOConfig())) + require.NoError(t, err) + + require.Len(t, first, 1) + require.Len(t, second, 1) + assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_A", first[0].Name) + assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_B", second[0].Name) + assert.Equal(t, GenerateUniqueOBOEnvVarName("backend-a"), first[0].Name, + "the deployment and the converter enrichment must agree on the name") + + _, err = OBOVMCPSecretEnvVar(oboCR("bad", mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }))) + var vErr *obo.ValidationError + assert.ErrorAs(t, err, &vErr) +} + +// withOBOHandlerRestored restores the package-level OBO handler after a test +// that calls the deprecated RegisterOBOHandler. +func withOBOHandlerRestored(t *testing.T) { + t.Helper() + oboMu.RLock() + original := oboHandler + oboMu.RUnlock() + t.Cleanup(func() { + oboMu.Lock() + oboHandler = original + oboMu.Unlock() + }) +} + +//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. +func TestRegisterOBOHandler_OverridesBuiltIn(t *testing.T) { + withOBOHandlerRestored(t) + + sentinel := errors.New("registered handler") + envs := []corev1.EnvVar{{Name: "OVERRIDE", Value: "x"}} + RegisterOBOHandler(OBOHandler{ + Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return sentinel }, + ApplyRunConfig: func(context.Context, client.Client, string, + *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption) error { + return sentinel + }, + SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { return envs, nil }, + }) + + assert.ErrorIs(t, OBOValidate(nil), sentinel) + assert.ErrorIs(t, OBOApplyRunConfig(t.Context(), nil, oboTestNamespace, nil, nil), sentinel) + got, err := OBOSecretEnvVars(nil) + require.NoError(t, err) + assert.Equal(t, envs, got) +} + +func TestRegisterOBOHandler_PanicsOnNilField(t *testing.T) { + t.Parallel() + + validate := func(*mcpv1beta1.MCPExternalAuthConfig) error { return nil } + apply := func(context.Context, client.Client, string, + *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption) error { + return nil + } + secretEnvVars := func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { return nil, nil } + + for name, h := range map[string]OBOHandler{ + "Validate nil": {ApplyRunConfig: apply, SecretEnvVars: secretEnvVars}, + "ApplyRunConfig nil": {Validate: validate, SecretEnvVars: secretEnvVars}, + "SecretEnvVars nil": {Validate: validate, ApplyRunConfig: apply}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + assert.Panics(t, func() { RegisterOBOHandler(h) }) + }) + } +} diff --git a/cmd/thv-operator/pkg/controllerutil/tokenexchange.go b/cmd/thv-operator/pkg/controllerutil/tokenexchange.go index 15228b6a13..b6f090f81e 100644 --- a/cmd/thv-operator/pkg/controllerutil/tokenexchange.go +++ b/cmd/thv-operator/pkg/controllerutil/tokenexchange.go @@ -5,9 +5,7 @@ package controllerutil import ( "context" - "errors" "fmt" - "sync" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -16,146 +14,12 @@ import ( mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" "github.com/stacklok/toolhive/cmd/thv-operator/pkg/oidc" "github.com/stacklok/toolhive/pkg/auth/awssts" - "github.com/stacklok/toolhive/pkg/auth/obo" "github.com/stacklok/toolhive/pkg/auth/remote" "github.com/stacklok/toolhive/pkg/auth/tokenexchange" exchange "github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange" "github.com/stacklok/toolhive/pkg/runner" ) -// OBOHandler bundles the three operator-time dispatch points for OBO-typed -// MCPExternalAuthConfig resources. An out-of-tree build replaces the default -// instance (which returns obo.ErrEnterpriseRequired from every method) by -// calling RegisterOBOHandler once during init(). -// -// # Error contract -// -// Every method below must return one of three error categories so callers can -// triage failures consistently: -// -// - errors.Is(err, obo.ErrEnterpriseRequired) — the build is not licensed -// to run OBO. Callers treat this as permanent until an out-of-tree handler -// is registered. -// - errors.As(err, &*obo.ValidationError) — the user-supplied spec is -// malformed (missing field, schema violation, invalid URL). Callers treat -// this as permanent until the user edits the spec. The ValidationError's -// Message field is written verbatim into the surfaced condition, so -// handler authors must ensure it is safe to expose (no Secret names, no -// internal addressing, no credential fragments). -// - anything else — treated as a transient failure (Secret not yet -// available, JWKS unreachable, webhook 5xx). Callers requeue with backoff -// rather than locking the resource into a permanent state. -// -// Returning a non-ValidationError for what is genuinely a user-fix condition -// causes the reconciler to spin on backoff. Returning a ValidationError for -// what is genuinely transient locks the resource into InvalidConfig until the -// user edits the spec. Handler authors are responsible for placing each -// failure in the right bucket. -type OBOHandler struct { - // Validate is called from MCPExternalAuthConfig validation to verify the - // resource's obo-typed config is well-formed. See the type-level "Error - // contract" doc for the three-bucket triage callers apply to its return. - Validate func(*mcpv1beta1.MCPExternalAuthConfig) error - - // ApplyRunConfig is called from AddExternalAuthConfigOptions to apply - // OBO-specific runner configuration options for consuming MCPServer/ - // MCPRemoteProxy resources. See the type-level "Error contract" doc. - ApplyRunConfig func( - ctx context.Context, c client.Client, namespace string, - cfg *mcpv1beta1.MCPExternalAuthConfig, - opts *[]runner.RunConfigBuilderOption, - ) error - - // SecretEnvVars is called when computing the consuming resource's pod - // environment, to inject any secrets the OBO flow needs at runtime. See - // the type-level "Error contract" doc. - SecretEnvVars func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) -} - -// oboMu guards reads and writes of oboHandler. Reads dispatched through the -// exported OBOValidate / OBOSecretEnvVars / OBOApplyRunConfig wrappers take an -// RLock; RegisterOBOHandler takes the write lock. Production reads today all -// happen on a single reconcile-loop goroutine, but the lock is here so that -// out-of-tree builds adding a hot-reload feature or admission-webhook -// re-registration do not introduce a latent data race. -var oboMu sync.RWMutex - -// oboHandler holds the package-level OBO handler. The default implementation -// returns obo.ErrEnterpriseRequired from each method; an out-of-tree build -// replaces it via RegisterOBOHandler. Access only through currentOBOHandler -// (read) or RegisterOBOHandler (write) so the mutex contract is preserved. -var oboHandler = OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return obo.ErrEnterpriseRequired }, - ApplyRunConfig: func(context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption) error { - return obo.ErrEnterpriseRequired - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, obo.ErrEnterpriseRequired - }, -} - -// currentOBOHandler returns a snapshot of the registered handler under the -// read lock so callers can dispatch through it without holding any lock for -// the duration of the call. -func currentOBOHandler() OBOHandler { - oboMu.RLock() - defer oboMu.RUnlock() - return oboHandler -} - -// RegisterOBOHandler replaces the package-level OBO handler. It is intended -// to be called exactly once during init() in an out-of-tree package that -// blank-imports controllerutil. Calling it more than once is allowed and -// last-write-wins; no panic on double-register, matching the existing -// pkg/config.RegisterProviderFactory precedent. -// -// Panics if any of the three function fields is nil — a partial registration -// would nil-deref deep inside dispatch, far from the call site. Surfacing the -// problem at process start (init() time) is far easier to diagnose than at -// reconcile time. -func RegisterOBOHandler(h OBOHandler) { - switch { - case h.Validate == nil: - panic("controllerutil.RegisterOBOHandler: Validate is nil") - case h.ApplyRunConfig == nil: - panic("controllerutil.RegisterOBOHandler: ApplyRunConfig is nil") - case h.SecretEnvVars == nil: - panic("controllerutil.RegisterOBOHandler: SecretEnvVars is nil") - } - oboMu.Lock() - defer oboMu.Unlock() - oboHandler = h -} - -// OBOValidate runs the registered OBO handler's Validate function on the -// supplied MCPExternalAuthConfig. With the default handler it returns -// obo.ErrEnterpriseRequired. -func OBOValidate(cfg *mcpv1beta1.MCPExternalAuthConfig) error { - return currentOBOHandler().Validate(cfg) -} - -// OBOSecretEnvVars runs the registered OBO handler's SecretEnvVars function. -// With the default handler it returns (nil, obo.ErrEnterpriseRequired). -func OBOSecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return currentOBOHandler().SecretEnvVars(cfg) -} - -// OBOApplyRunConfig runs the registered OBO handler's ApplyRunConfig function. -// With the default handler it returns obo.ErrEnterpriseRequired without -// mutating the supplied options slice. Exported so that the three-method -// surface stays symmetric with OBOValidate / OBOSecretEnvVars; routes through -// the package-level OBO handler registered via RegisterOBOHandler. -func OBOApplyRunConfig( - ctx context.Context, - c client.Client, - namespace string, - cfg *mcpv1beta1.MCPExternalAuthConfig, - opts *[]runner.RunConfigBuilderOption, -) error { - return currentOBOHandler().ApplyRunConfig(ctx, c, namespace, cfg, opts) -} - // GenerateTokenExchangeEnvVars generates environment variables for token exchange func GenerateTokenExchangeEnvVars( ctx context.Context, @@ -253,11 +117,12 @@ func AddExternalAuthConfigOptions( // Upstream inject is handled by the vMCP converter at runtime return nil case mcpv1beta1.ExternalAuthTypeOBO: - // Dispatch through the registered handler. In upstream-only builds the - // default handler returns obo.ErrEnterpriseRequired; an out-of-tree - // build registers a real handler via RegisterOBOHandler. Bypass the - // default's "unsupported external auth type" path so callers can - // distinguish via errors.Is(err, obo.ErrEnterpriseRequired). + // The consuming reconcilers reject this earlier with a status + // condition (ValidateOBOIncomingAuth); this guard keeps a RunConfig + // from ever being emitted for a proxy with no user token to exchange. + if err := ValidateOBOIncomingAuth(externalAuthConfig, oidcConfig != nil); err != nil { + return err + } return OBOApplyRunConfig(ctx, c, namespace, externalAuthConfig, options) case mcpv1beta1.ExternalAuthTypeXAA: // XAA is handled by the vMCP converter at runtime @@ -267,62 +132,6 @@ func AddExternalAuthConfigOptions( } } -// AddOBOSecretEnvVars resolves ref to an MCPExternalAuthConfig and, if it is the -// obo type, returns the pod environment variables the registered OBOHandler asks -// for at runtime. For every other type it returns no env vars: this is the -// OBO-only secret-env dispatcher, deliberately narrower than its sibling -// AddExternalAuthConfigOptions (which switches on every ExternalAuthType). The -// name says "OBO" precisely so it is not mistaken for full type coverage — -// MCPServer / MCPRemoteProxy / VirtualMCPServer each produce the non-obo types' -// secret env vars through their own per-type helpers (GenerateTokenExchangeEnvVars, -// GenerateBearerTokenEnvVar, VirtualMCPServer's getExternalAuthConfigSecretEnvVars -// switch), using consumer-specific env var names that must stay byte-identical. -// Do NOT add the other types here, and do NOT drop the existing per-type calls -// assuming this helper covers them. -// -// obo is the one type a single dispatcher can own, because its env var name is -// defined by the handler and is therefore identical across consumers; the others -// are not. Routing the obo path through here is what keeps consumers from -// drifting — the failure mode #5537 fixed. -// -// A build without a registered OBO handler yields obo.ErrEnterpriseRequired from -// the dispatch; that is treated as "no env vars" (obo is inert) rather than an -// error, so the deployment builder and drift-check paths compute identical env -// and the Deployment does not enter a reconcile hot-loop. The -// MCPExternalAuthConfig reconciler is what surfaces the enterprise-required state -// to the user. (VirtualMCPServer intentionally does NOT route through this -// wrapper: its dispatch must propagate ErrEnterpriseRequired per #5328, so it -// calls OBOSecretEnvVars directly — but it likewise forwards every env var.) -func AddOBOSecretEnvVars( - ctx context.Context, - c client.Client, - namespace string, - ref *mcpv1beta1.ExternalAuthConfigRef, -) ([]corev1.EnvVar, error) { - if ref == nil { - return nil, nil - } - - externalAuthConfig, err := GetExternalAuthConfigByName(ctx, c, namespace, ref.Name) - if err != nil { - return nil, fmt.Errorf("failed to get MCPExternalAuthConfig: %w", err) - } - - if externalAuthConfig.Spec.Type != mcpv1beta1.ExternalAuthTypeOBO { - return nil, nil - } - - envVars, err := OBOSecretEnvVars(externalAuthConfig) - if errors.Is(err, obo.ErrEnterpriseRequired) { - // No OBO handler registered (upstream-only build): obo is inert. Return - // no env vars so the builder and drift paths agree; the - // MCPExternalAuthConfig reconciler surfaces EnterpriseRequired. - return nil, nil - } - // Forward every env var the handler returns. - return envVars, err -} - func addTokenExchangeConfig( ctx context.Context, c client.Client, diff --git a/cmd/thv-operator/pkg/controllerutil/tokenexchange_test.go b/cmd/thv-operator/pkg/controllerutil/tokenexchange_test.go deleted file mode 100644 index 3ddad01c04..0000000000 --- a/cmd/thv-operator/pkg/controllerutil/tokenexchange_test.go +++ /dev/null @@ -1,481 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. -// SPDX-License-Identifier: Apache-2.0 - -package controllerutil - -import ( - "context" - "errors" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" - "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" - "github.com/stacklok/toolhive/pkg/auth/obo" - "github.com/stacklok/toolhive/pkg/runner" -) - -// withDefaultOBOHandler captures the package-level OBO handler and restores it -// on cleanup so that tests which call RegisterOBOHandler do not leak state to -// other tests in the package. The capture and restore both pass through -// oboMu so they participate in the same synchronization contract as -// production reads/writes. -func withDefaultOBOHandler(t *testing.T) { - t.Helper() - oboMu.RLock() - original := oboHandler - oboMu.RUnlock() - t.Cleanup(func() { - oboMu.Lock() - oboHandler = original - oboMu.Unlock() - }) -} - -func TestDefaultOBOHandler_ReturnsEnterpriseRequired(t *testing.T) { - t.Parallel() - - // Read the default handler under the read lock so this test does not - // data-race other tests that may run sequentially and write through - // RegisterOBOHandler. The subtests below dispatch through this snapshot - // rather than through the public wrappers so the assertion targets the - // default OBOHandler value specifically. - defaults := currentOBOHandler() - - t.Run("Validate", func(t *testing.T) { - t.Parallel() - err := defaults.Validate(nil) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - }) - - t.Run("ApplyRunConfig", func(t *testing.T) { - t.Parallel() - var opts []runner.RunConfigBuilderOption - err := defaults.ApplyRunConfig(context.Background(), nil, "ns", nil, &opts) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - assert.Empty(t, opts, "default handler must not mutate the options slice") - }) - - t.Run("SecretEnvVars", func(t *testing.T) { - t.Parallel() - envVars, err := defaults.SecretEnvVars(nil) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - assert.Nil(t, envVars, "default handler must return nil envVars on the error path") - }) -} - -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestOBOValidate_DispatchesThroughRegisteredHandler(t *testing.T) { - withDefaultOBOHandler(t) - - // With the default handler, OBOValidate returns obo.ErrEnterpriseRequired. - err := OBOValidate(nil) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - - // After registering a replacement, OBOValidate must dispatch through it. - sentinel := errors.New("custom validate failure") - RegisterOBOHandler(OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return sentinel }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return nil - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, nil - }, - }) - - err = OBOValidate(nil) - require.Error(t, err) - assert.ErrorIs(t, err, sentinel, "OBOValidate must dispatch through the registered handler") -} - -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestOBOSecretEnvVars_DispatchesThroughRegisteredHandler(t *testing.T) { - withDefaultOBOHandler(t) - - // With the default handler, OBOSecretEnvVars returns obo.ErrEnterpriseRequired. - envVars, err := OBOSecretEnvVars(nil) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - assert.Nil(t, envVars) - - // After registering a replacement, OBOSecretEnvVars must dispatch through it. - expected := []corev1.EnvVar{{Name: "OBO_TEST", Value: "value"}} - RegisterOBOHandler(OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return nil }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return nil - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return expected, nil - }, - }) - - envVars, err = OBOSecretEnvVars(nil) - require.NoError(t, err) - assert.Equal(t, expected, envVars) -} - -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestOBOApplyRunConfig_DispatchesThroughRegisteredHandler(t *testing.T) { - withDefaultOBOHandler(t) - - // With the default handler, OBOApplyRunConfig returns obo.ErrEnterpriseRequired - // without mutating the options slice. - var opts []runner.RunConfigBuilderOption - err := OBOApplyRunConfig(context.Background(), nil, "ns", nil, &opts) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) - assert.Empty(t, opts, "default handler must not mutate the options slice") - - // After registering a replacement, OBOApplyRunConfig must dispatch through it. - sentinel := errors.New("custom apply failure") - RegisterOBOHandler(OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return nil }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return sentinel - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, nil - }, - }) - - err = OBOApplyRunConfig(context.Background(), nil, "ns", nil, &opts) - require.Error(t, err) - assert.ErrorIs(t, err, sentinel, "OBOApplyRunConfig must dispatch through the registered handler") -} - -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestRegisterOBOHandler_LastWriteWins(t *testing.T) { - withDefaultOBOHandler(t) - - first := errors.New("first") - second := errors.New("second") - - RegisterOBOHandler(OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return first }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return first - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, first - }, - }) - RegisterOBOHandler(OBOHandler{ - Validate: func(*mcpv1beta1.MCPExternalAuthConfig) error { return second }, - ApplyRunConfig: func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return second - }, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, second - }, - }) - - // The second registration must win on every method. - assert.ErrorIs(t, OBOValidate(nil), second) - _, err := OBOSecretEnvVars(nil) - assert.ErrorIs(t, err, second) - assert.ErrorIs(t, - OBOApplyRunConfig(context.Background(), nil, "ns", nil, nil), - second, - ) -} - -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestRegisterOBOHandler_PanicsOnNilField(t *testing.T) { - withDefaultOBOHandler(t) - - validate := func(*mcpv1beta1.MCPExternalAuthConfig) error { return nil } - applyRunConfig := func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return nil - } - secretEnvVars := func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, nil - } - - tests := []struct { - name string - handler OBOHandler - }{ - {name: "Validate nil", handler: OBOHandler{ApplyRunConfig: applyRunConfig, SecretEnvVars: secretEnvVars}}, - {name: "ApplyRunConfig nil", handler: OBOHandler{Validate: validate, SecretEnvVars: secretEnvVars}}, - {name: "SecretEnvVars nil", handler: OBOHandler{Validate: validate, ApplyRunConfig: applyRunConfig}}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Panics(t, func() { RegisterOBOHandler(tt.handler) }, - "RegisterOBOHandler must panic when any function field is nil") - }) - } -} - -// TestAddExternalAuthConfigOptions_OBO proves the obo arm of the -// AddExternalAuthConfigOptions switch dispatches through the registered OBO -// handler. With the default handler the function must return an error wrapping -// obo.ErrEnterpriseRequired AND must not fall through to the default arm's -// "unsupported external auth type" message — external consumers pattern-match -// on errors.Is, and the dispatch arm's purpose is to keep the wired-but- -// disabled state distinguishable from a genuinely unknown type. -func TestAddExternalAuthConfigOptions_OBO(t *testing.T) { - t.Parallel() - - scheme := testutil.NewScheme(t) - - authCfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "obo-config", - Namespace: "default", - }, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, - }, - } - - fakeClient := fake.NewClientBuilder(). - WithScheme(scheme). - WithObjects(authCfg). - Build() - - var options []runner.RunConfigBuilderOption - err := AddExternalAuthConfigOptions( - t.Context(), - fakeClient, - "default", - "server-name", - &mcpv1beta1.ExternalAuthConfigRef{Name: authCfg.Name}, - nil, // oidcConfig — not required for OBO - &options, - ) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired, - "the default OBO handler returns obo.ErrEnterpriseRequired; the dispatch arm must propagate it") - - // Generic-error guard: the dispatch arm must short-circuit the default - // arm's "unsupported external auth type: ..." path and must not leak the - // middleware-map lookup's "unknown middleware type" path either. - assert.NotContains(t, err.Error(), "unsupported external auth type") - assert.NotContains(t, err.Error(), "unknown middleware type") - assert.Empty(t, options, "default OBO handler must not append to the options slice") -} - -// TestAddOBOSecretEnvVars covers the OBO-only secret-env dispatcher across every -// ExternalAuthType. Only obo contributes env vars (and only when a handler is -// registered); every other type, plus a nil ref, yields no env vars. A build -// with the default OBO handler treats obo as inert (no env vars, no error) so the -// deployment builder and drift-check paths stay byte-identical. -// -// Regression guard: newConfig populates the secret-bearing sub-spec for the -// non-obo types that have one (tokenExchange, bearerToken, headerInjection), so -// the "must stay empty" assertions below would fail if a future dev ever wired -// one of those types into AddOBOSecretEnvVars — the empty result is then a real -// invariant, not an artifact of an absent secret ref. -func TestAddOBOSecretEnvVars(t *testing.T) { - t.Parallel() - - scheme := testutil.NewScheme(t) - - const ns = "default" - - newConfig := func(name string, typ mcpv1beta1.ExternalAuthType) *mcpv1beta1.MCPExternalAuthConfig { - cfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: ns}, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{Type: typ}, - } - switch typ { - case mcpv1beta1.ExternalAuthTypeTokenExchange: - cfg.Spec.TokenExchange = &mcpv1beta1.TokenExchangeConfig{ - ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: name + "-secret", Key: "client-secret"}, - } - case mcpv1beta1.ExternalAuthTypeBearerToken: - cfg.Spec.BearerToken = &mcpv1beta1.BearerTokenConfig{ - TokenSecretRef: &mcpv1beta1.SecretKeyRef{Name: name + "-secret", Key: "token"}, - } - case mcpv1beta1.ExternalAuthTypeHeaderInjection: - cfg.Spec.HeaderInjection = &mcpv1beta1.HeaderInjectionConfig{ - ValueSecretRef: &mcpv1beta1.SecretKeyRef{Name: name + "-secret", Key: "value"}, - } - case mcpv1beta1.ExternalAuthTypeOBO: - cfg.Spec.OBO = &mcpv1beta1.OBOConfig{} - case mcpv1beta1.ExternalAuthTypeUnauthenticated, - mcpv1beta1.ExternalAuthTypeEmbeddedAuthServer, - mcpv1beta1.ExternalAuthTypeAWSSts, - mcpv1beta1.ExternalAuthTypeUpstreamInject, - mcpv1beta1.ExternalAuthTypeXAA: - // No secret-bearing sub-spec to populate for these types. - } - return cfg - } - - tests := []struct { - name string - seed *mcpv1beta1.MCPExternalAuthConfig // object stored in the fake client (nil = none) - ref *mcpv1beta1.ExternalAuthConfigRef - wantErr bool - }{ - { - name: "nil ref returns no env vars", - ref: nil, - }, - { - name: "missing config returns error", - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "does-not-exist"}, - wantErr: true, - }, - { - name: "tokenExchange type contributes no env vars here", - seed: newConfig("te", mcpv1beta1.ExternalAuthTypeTokenExchange), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "te"}, - }, - { - name: "bearerToken type contributes no env vars here", - seed: newConfig("bt", mcpv1beta1.ExternalAuthTypeBearerToken), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "bt"}, - }, - { - name: "headerInjection type contributes no env vars here", - seed: newConfig("hi", mcpv1beta1.ExternalAuthTypeHeaderInjection), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "hi"}, - }, - { - name: "unauthenticated type contributes no env vars here", - seed: newConfig("un", mcpv1beta1.ExternalAuthTypeUnauthenticated), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "un"}, - }, - { - name: "embeddedAuthServer type contributes no env vars here", - seed: newConfig("eas", mcpv1beta1.ExternalAuthTypeEmbeddedAuthServer), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "eas"}, - }, - { - name: "awsSts type contributes no env vars here", - seed: newConfig("aws", mcpv1beta1.ExternalAuthTypeAWSSts), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "aws"}, - }, - { - name: "upstreamInject type contributes no env vars here", - seed: newConfig("ui", mcpv1beta1.ExternalAuthTypeUpstreamInject), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "ui"}, - }, - { - name: "obo with default handler is inert", - seed: newConfig("obo", mcpv1beta1.ExternalAuthTypeOBO), - ref: &mcpv1beta1.ExternalAuthConfigRef{Name: "obo"}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - builder := fake.NewClientBuilder().WithScheme(scheme) - if tt.seed != nil { - builder = builder.WithObjects(tt.seed) - } - - envVars, err := AddOBOSecretEnvVars(t.Context(), builder.Build(), ns, tt.ref) - if tt.wantErr { - require.Error(t, err) - return - } - require.NoError(t, err) - assert.Empty(t, envVars, "only a registered OBO handler contributes env vars through this dispatcher") - }) - } -} - -// TestAddOBOSecretEnvVars_OBOHandlerRegistered proves the obo arm forwards a -// registered handler's env vars verbatim and propagates a genuine -// (non-enterprise) handler error, while still swallowing ErrEnterpriseRequired. -// -//nolint:paralleltest // Mutates package-level oboHandler; must not race other tests. -func TestAddOBOSecretEnvVars_OBOHandlerRegistered(t *testing.T) { - withDefaultOBOHandler(t) - - scheme := testutil.NewScheme(t) - - const ns = "default" - authCfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: ns}, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, - }, - } - fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(authCfg).Build() - ref := &mcpv1beta1.ExternalAuthConfigRef{Name: authCfg.Name} - - noopValidate := func(*mcpv1beta1.MCPExternalAuthConfig) error { return nil } - noopApply := func( - context.Context, client.Client, string, - *mcpv1beta1.MCPExternalAuthConfig, *[]runner.RunConfigBuilderOption, - ) error { - return nil - } - - // A registered handler's env vars are forwarded verbatim. - expected := []corev1.EnvVar{{ - Name: "OBO_CLIENT_SECRET", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{Name: "obo-secret"}, - Key: "token", - }, - }, - }} - RegisterOBOHandler(OBOHandler{ - Validate: noopValidate, - ApplyRunConfig: noopApply, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return expected, nil - }, - }) - - envVars, err := AddOBOSecretEnvVars(t.Context(), fakeClient, ns, ref) - require.NoError(t, err) - assert.Equal(t, expected, envVars, "the dispatcher must forward the handler's env vars verbatim") - - // A genuine (non-enterprise) handler error propagates to the caller. - sentinel := errors.New("secret not found") - RegisterOBOHandler(OBOHandler{ - Validate: noopValidate, - ApplyRunConfig: noopApply, - SecretEnvVars: func(*mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { - return nil, sentinel - }, - }) - - envVars, err = AddOBOSecretEnvVars(t.Context(), fakeClient, ns, ref) - require.Error(t, err) - assert.ErrorIs(t, err, sentinel, "a genuine handler error must propagate, not be swallowed") - assert.Nil(t, envVars) -} diff --git a/cmd/thv-operator/pkg/vmcpconfig/converter.go b/cmd/thv-operator/pkg/vmcpconfig/converter.go index 23a76037a7..96b22b76e1 100644 --- a/cmd/thv-operator/pkg/vmcpconfig/converter.go +++ b/cmd/thv-operator/pkg/vmcpconfig/converter.go @@ -802,6 +802,11 @@ func (*Converter) convertExternalAuthConfigToStrategy( externalAuthConfig.Spec.HeaderInjection.ValueSecretRef != nil { strategy.HeaderInjection.HeaderValueEnv = controllerutil.GenerateUniqueHeaderInjectionEnvVarName(externalAuthConfig.Name) } + if strategy.OBO != nil && + externalAuthConfig.Spec.OBO != nil && + externalAuthConfig.Spec.OBO.ClientSecretRef != nil { + strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOEnvVarName(externalAuthConfig.Name) + } return strategy, nil } diff --git a/cmd/thv-operator/pkg/vmcpconfig/converter_test.go b/cmd/thv-operator/pkg/vmcpconfig/converter_test.go index 571093e116..fc55a98257 100644 --- a/cmd/thv-operator/pkg/vmcpconfig/converter_test.go +++ b/cmd/thv-operator/pkg/vmcpconfig/converter_test.go @@ -2410,3 +2410,38 @@ func TestConvertSessionStorage_GlobalTLS(t *testing.T) { }) } } + +// TestConvertExternalAuthConfigToStrategy_OBOUsesPerConfigSecretEnv verifies +// the inline outgoing-auth path points each OBO backend at its own client +// secret env var, so two OBO backends in one vMCP pod never collide. +func TestConvertExternalAuthConfigToStrategy_OBOUsesPerConfigSecretEnv(t *testing.T) { + t.Parallel() + + newOBO := func(name string) *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: name + "-secret", Key: "client-secret"}, + Audience: "api://backend/.default", + }, + }, + } + } + + converter := newTestConverter(t, newNoOpMockResolver(t)) + first, err := converter.convertExternalAuthConfigToStrategy(t.Context(), newOBO("obo-a")) + require.NoError(t, err) + second, err := converter.convertExternalAuthConfigToStrategy(t.Context(), newOBO("obo-b")) + require.NoError(t, err) + + require.NotNil(t, first.OBO) + require.NotNil(t, second.OBO) + assert.Equal(t, controllerutil.GenerateUniqueOBOEnvVarName("obo-a"), first.OBO.ClientSecretEnv) + assert.Equal(t, controllerutil.GenerateUniqueOBOEnvVarName("obo-b"), second.OBO.ClientSecretEnv) + assert.NotEqual(t, first.OBO.ClientSecretEnv, second.OBO.ClientSecretEnv) + assert.Empty(t, first.OBO.ClientSecret) +} diff --git a/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go new file mode 100644 index 0000000000..1d78991aab --- /dev/null +++ b/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package controllers + +import ( + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" +) + +// These tests drive the OBO reconcile-time validation through the real +// apiserver: a well-formed obo config becomes Valid=True, a malformed one +// becomes Valid=False / Reason=InvalidConfig, and an MCPServer that references +// an obo config without incoming OIDC is rejected with InvalidConfig. +var _ = Describe("MCPExternalAuthConfig OBO reconcile", Label("k8s", "obo"), func() { + const ( + namespace = "default" + timeout = 30 * time.Second + interval = 250 * time.Millisecond + ) + + validOBO := func() *mcpv1beta1.OBOConfig { + return &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "app-client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: "entra-client", Key: "clientSecret"}, + Scopes: []string{"api://backend/.default"}, + } + } + + createOBOConfig := func(name string, obo *mcpv1beta1.OBOConfig) { + Expect(k8sClient.Create(ctx, &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: obo, + }, + })).To(Succeed()) + } + + validCondition := func(name string) func() *metav1.Condition { + return func() *metav1.Condition { + updated := &mcpv1beta1.MCPExternalAuthConfig{} + if err := k8sClient.Get(ctx, types.NamespacedName{Name: name, Namespace: namespace}, updated); err != nil { + return nil + } + return meta.FindStatusCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) + } + } + + It("reconciles a well-formed obo config to Valid=True", func() { + createOBOConfig("obo-reconcile-valid", validOBO()) + + Eventually(validCondition("obo-reconcile-valid"), timeout, interval).Should( + And(Not(BeNil()), HaveField("Status", metav1.ConditionTrue))) + }) + + DescribeTable("reconciles a malformed obo config to Valid=False / InvalidConfig", + func(name string, mutate func(*mcpv1beta1.OBOConfig), wantMessage string) { + obo := validOBO() + mutate(obo) + createOBOConfig(name, obo) + + Eventually(validCondition(name), timeout, interval).Should(And( + Not(BeNil()), + HaveField("Status", metav1.ConditionFalse), + HaveField("Reason", mcpv1beta1.ConditionReasonInvalidConfig), + HaveField("Message", wantMessage), + )) + }, + Entry("missing tenant", "obo-reconcile-no-tenant", + func(c *mcpv1beta1.OBOConfig) { c.TenantID = "" }, "entra obo: TenantID is required"), + Entry("missing client id", "obo-reconcile-no-client", + func(c *mcpv1beta1.OBOConfig) { c.ClientID = "" }, "obo: clientId is required"), + Entry("missing client secret ref", "obo-reconcile-no-secret", + func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }, "obo: clientSecretRef must set both name and key"), + Entry("neither audience nor scopes", "obo-reconcile-no-target", + func(c *mcpv1beta1.OBOConfig) { c.Scopes = nil }, "obo: at least one of audience or scopes is required"), + ) + + It("rejects an MCPServer that references an obo config without oidcConfigRef", func() { + createOBOConfig("obo-reconcile-server-ref", validOBO()) + + Expect(k8sClient.Create(ctx, &mcpv1beta1.MCPServer{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-no-oidc-server", Namespace: namespace}, + Spec: mcpv1beta1.MCPServerSpec{ + Image: "ghcr.io/example/mcp:latest", + ExternalAuthConfigRef: &mcpv1beta1.ExternalAuthConfigRef{Name: "obo-reconcile-server-ref"}, + }, + })).To(Succeed()) + + Eventually(func() *metav1.Condition { + server := &mcpv1beta1.MCPServer{} + if err := k8sClient.Get(ctx, types.NamespacedName{Name: "obo-no-oidc-server", Namespace: namespace}, server); err != nil { + return nil + } + return meta.FindStatusCondition(server.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + }, timeout, interval).Should(And( + Not(BeNil()), + HaveField("Status", metav1.ConditionFalse), + HaveField("Reason", mcpv1beta1.ConditionReasonInvalidConfig), + HaveField("Message", ctrlutil.MsgOBORequiresIncomingAuth), + )) + }) +}) diff --git a/cmd/thv-operator/test-integration/mcp-external-auth/obo_validation_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/obo_validation_test.go index 5493de4dd7..7fb9b528bc 100644 --- a/cmd/thv-operator/test-integration/mcp-external-auth/obo_validation_test.go +++ b/cmd/thv-operator/test-integration/mcp-external-auth/obo_validation_test.go @@ -17,8 +17,8 @@ import ( // the real apiserver (envtest). OBOConfig has no required field and no // cross-field rule: spec.obo shipped as an empty placeholder ({}) in an earlier // release, so the schema must keep admitting {} (and any subset of fields), and -// presence/combination requirements are enforced by the registered OBO handler -// at reconcile, not at admission. Admission only validates per-field shape +// presence/combination requirements are enforced by the operator at reconcile +// (see obo_reconcile_test.go), not at admission. Admission only validates per-field shape // (patterns, length/item bounds) for values that are present — that is what // these tests pin down. var _ = Describe("MCPExternalAuthConfig OBOConfig schema validation", Label("k8s", "validation"), func() { @@ -106,7 +106,7 @@ var _ = Describe("MCPExternalAuthConfig OBOConfig schema validation", Label("k8s It("should accept a config without clientId or clientSecretRef (operator enforces per auth mode)", func() { // All presence/combination requirements (a tenant, a client-auth - // credential, an exchange target) are enforced by the operator handler + // credential, an exchange target) are enforced by the operator // at reconcile, not at admission, so future client-auth methods // (certificate, workload identity) need no breaking schema change. cfg := makeOBOConfig("obo-no-client-auth", &mcpv1beta1.OBOConfig{ diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index dd15107102..c7fa77be96 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -2755,11 +2755,8 @@ spec: type: object obo: description: |- - OBO configures On-Behalf-Of (OBO) authentication. - Only used when Type is "obo". Setting this field on an upstream-only build - causes the MCPExternalAuthConfig to transition to - status.conditions[Valid] = False with Reason: EnterpriseRequired, because - no OBO handler is registered. See OBOConfig for the field-to-runtime + OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication. + Only used when Type is "obo". See OBOConfig for the field-to-runtime contract mapping. properties: audience: @@ -2794,12 +2791,10 @@ spec: CacheSkew overrides the OBO token cache's default expiry skew (the margin by which a cached token is treated as expired before its real expiry), e.g. "30s". The operator converts it to the runtime contract's - integer-seconds cacheSkewSeconds. Should not be negative, but the schema - does not enforce that — metav1.Duration carries no numeric minimum — and - upstream builds do not reject it. A negative value is rejected only by an - enterprise build's OBO handler once that handler validates the converted - parameters; it is not enforced at admission or in upstream-only builds. - When omitted, the cache default applies. + integer-seconds cacheSkewSeconds (truncated toward zero). Must not be + negative; metav1.Duration carries no numeric minimum, so the operator + rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig) + rather than at admission. When omitted, the cache default applies. type: string clientId: description: |- @@ -2874,7 +2869,7 @@ spec: interpolates it into the token endpoint (//oauth2/v2.0/token), so the value is constrained to the GUID/domain shape (no path metacharacters); the pattern and 253-char - cap mirror the enterprise exchanger's validateTenant, so any tenantId + cap mirror the Entra exchanger's tenant validation, so any tenantId admitted here is one the runtime can consume. maxLength: 253 pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$ @@ -2950,12 +2945,7 @@ spec: - tokenUrl type: object type: - description: |- - Type is the type of external authentication to configure. - When set to "obo", the cluster must run a build that has registered an - OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds - surface status.conditions[Valid] = False with Reason: EnterpriseRequired - for obo-typed configs. + description: Type is the type of external authentication to configure. enum: - tokenExchange - headerInjection @@ -5931,11 +5921,8 @@ spec: type: object obo: description: |- - OBO configures On-Behalf-Of (OBO) authentication. - Only used when Type is "obo". Setting this field on an upstream-only build - causes the MCPExternalAuthConfig to transition to - status.conditions[Valid] = False with Reason: EnterpriseRequired, because - no OBO handler is registered. See OBOConfig for the field-to-runtime + OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication. + Only used when Type is "obo". See OBOConfig for the field-to-runtime contract mapping. properties: audience: @@ -5970,12 +5957,10 @@ spec: CacheSkew overrides the OBO token cache's default expiry skew (the margin by which a cached token is treated as expired before its real expiry), e.g. "30s". The operator converts it to the runtime contract's - integer-seconds cacheSkewSeconds. Should not be negative, but the schema - does not enforce that — metav1.Duration carries no numeric minimum — and - upstream builds do not reject it. A negative value is rejected only by an - enterprise build's OBO handler once that handler validates the converted - parameters; it is not enforced at admission or in upstream-only builds. - When omitted, the cache default applies. + integer-seconds cacheSkewSeconds (truncated toward zero). Must not be + negative; metav1.Duration carries no numeric minimum, so the operator + rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig) + rather than at admission. When omitted, the cache default applies. type: string clientId: description: |- @@ -6050,7 +6035,7 @@ spec: interpolates it into the token endpoint (//oauth2/v2.0/token), so the value is constrained to the GUID/domain shape (no path metacharacters); the pattern and 253-char - cap mirror the enterprise exchanger's validateTenant, so any tenantId + cap mirror the Entra exchanger's tenant validation, so any tenantId admitted here is one the runtime can consume. maxLength: 253 pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$ @@ -6126,12 +6111,7 @@ spec: - tokenUrl type: object type: - description: |- - Type is the type of external authentication to configure. - When set to "obo", the cluster must run a build that has registered an - OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds - surface status.conditions[Valid] = False with Reason: EnterpriseRequired - for obo-typed configs. + description: Type is the type of external authentication to configure. enum: - tokenExchange - headerInjection diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml index c03b3bec25..73bae6803c 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -3902,8 +3902,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -3912,7 +3911,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -3943,8 +3943,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -4206,8 +4206,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -4216,7 +4215,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -4247,8 +4247,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -9470,8 +9470,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -9480,7 +9479,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -9511,8 +9511,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -9774,8 +9774,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -9784,7 +9783,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -9815,8 +9815,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml index 5be6a3c7dc..61c78c7c38 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -2758,11 +2758,8 @@ spec: type: object obo: description: |- - OBO configures On-Behalf-Of (OBO) authentication. - Only used when Type is "obo". Setting this field on an upstream-only build - causes the MCPExternalAuthConfig to transition to - status.conditions[Valid] = False with Reason: EnterpriseRequired, because - no OBO handler is registered. See OBOConfig for the field-to-runtime + OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication. + Only used when Type is "obo". See OBOConfig for the field-to-runtime contract mapping. properties: audience: @@ -2797,12 +2794,10 @@ spec: CacheSkew overrides the OBO token cache's default expiry skew (the margin by which a cached token is treated as expired before its real expiry), e.g. "30s". The operator converts it to the runtime contract's - integer-seconds cacheSkewSeconds. Should not be negative, but the schema - does not enforce that — metav1.Duration carries no numeric minimum — and - upstream builds do not reject it. A negative value is rejected only by an - enterprise build's OBO handler once that handler validates the converted - parameters; it is not enforced at admission or in upstream-only builds. - When omitted, the cache default applies. + integer-seconds cacheSkewSeconds (truncated toward zero). Must not be + negative; metav1.Duration carries no numeric minimum, so the operator + rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig) + rather than at admission. When omitted, the cache default applies. type: string clientId: description: |- @@ -2877,7 +2872,7 @@ spec: interpolates it into the token endpoint (//oauth2/v2.0/token), so the value is constrained to the GUID/domain shape (no path metacharacters); the pattern and 253-char - cap mirror the enterprise exchanger's validateTenant, so any tenantId + cap mirror the Entra exchanger's tenant validation, so any tenantId admitted here is one the runtime can consume. maxLength: 253 pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$ @@ -2953,12 +2948,7 @@ spec: - tokenUrl type: object type: - description: |- - Type is the type of external authentication to configure. - When set to "obo", the cluster must run a build that has registered an - OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds - surface status.conditions[Valid] = False with Reason: EnterpriseRequired - for obo-typed configs. + description: Type is the type of external authentication to configure. enum: - tokenExchange - headerInjection @@ -5934,11 +5924,8 @@ spec: type: object obo: description: |- - OBO configures On-Behalf-Of (OBO) authentication. - Only used when Type is "obo". Setting this field on an upstream-only build - causes the MCPExternalAuthConfig to transition to - status.conditions[Valid] = False with Reason: EnterpriseRequired, because - no OBO handler is registered. See OBOConfig for the field-to-runtime + OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication. + Only used when Type is "obo". See OBOConfig for the field-to-runtime contract mapping. properties: audience: @@ -5973,12 +5960,10 @@ spec: CacheSkew overrides the OBO token cache's default expiry skew (the margin by which a cached token is treated as expired before its real expiry), e.g. "30s". The operator converts it to the runtime contract's - integer-seconds cacheSkewSeconds. Should not be negative, but the schema - does not enforce that — metav1.Duration carries no numeric minimum — and - upstream builds do not reject it. A negative value is rejected only by an - enterprise build's OBO handler once that handler validates the converted - parameters; it is not enforced at admission or in upstream-only builds. - When omitted, the cache default applies. + integer-seconds cacheSkewSeconds (truncated toward zero). Must not be + negative; metav1.Duration carries no numeric minimum, so the operator + rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig) + rather than at admission. When omitted, the cache default applies. type: string clientId: description: |- @@ -6053,7 +6038,7 @@ spec: interpolates it into the token endpoint (//oauth2/v2.0/token), so the value is constrained to the GUID/domain shape (no path metacharacters); the pattern and 253-char - cap mirror the enterprise exchanger's validateTenant, so any tenantId + cap mirror the Entra exchanger's tenant validation, so any tenantId admitted here is one the runtime can consume. maxLength: 253 pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$ @@ -6129,12 +6114,7 @@ spec: - tokenUrl type: object type: - description: |- - Type is the type of external authentication to configure. - When set to "obo", the cluster must run a build that has registered an - OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds - surface status.conditions[Valid] = False with Reason: EnterpriseRequired - for obo-typed configs. + description: Type is the type of external authentication to configure. enum: - tokenExchange - headerInjection diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml index 8cd3fe82d9..275c8bfdb6 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -3905,8 +3905,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -3915,7 +3914,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -3946,8 +3946,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -4209,8 +4209,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -4219,7 +4218,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -4250,8 +4250,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -9473,8 +9473,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -9483,7 +9482,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -9514,8 +9514,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint @@ -9777,8 +9777,7 @@ spec: obo: description: |- OBO contains configuration for on-behalf-of (OBO) auth strategy. - Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + Used when Type = "obo". properties: audience: description: Audience is the target audience (resource @@ -9787,7 +9786,8 @@ spec: cacheSkewSeconds: description: |- CacheSkewSeconds is the number of seconds to subtract from a cached token's - expiry when deciding whether to refresh it. Defaults to zero (no skew). + expiry when deciding whether to refresh it. When nil or zero the token + cache's default skew (60 seconds) applies; negative values are rejected. The operator CRD stores this as CacheSkew *metav1.Duration and converts it to an integer-seconds value for the vMCP runtime contract. format: int32 @@ -9818,8 +9818,8 @@ spec: subject (assertion) token for the OBO exchange. When set, the token is looked up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the inbound end-user token (Identity.Token) is used directly. - Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - converter maps both to the runtime contract without renaming. + Matches the operator CRD's SubjectTokenProviderName field; the OBO + converter maps it to the runtime contract without renaming. type: string tokenUrl: description: TokenURL is the Entra token endpoint diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index f0c1d6995d..3884560e01 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -231,11 +231,13 @@ For a complete example, see [`examples/operator/external-auth/mcpexternalauthcon Because appending a certificate to a referenced ConfigMap makes that CA a trust anchor — for an upstream provider's login, or for a trusted issuer's subject-token validation — restrict write access to a `caBundleRef` ConfigMap with the same RBAC care as the auth server's signing-key Secret. MCPExternalAuthConfig resources can be referenced via two paths: -- `externalAuthConfigRef` — for outgoing auth types (token exchange, AWS STS, bearer token injection). This is the original reference path. +- `externalAuthConfigRef` — for outgoing auth types (token exchange, AWS STS, bearer token injection, Entra on-behalf-of). This is the original reference path. - `authServerRef` — for the embedded auth server type (`embeddedAuthServer`) only. This dedicated reference path makes it possible to configure both incoming auth (embedded auth server) and outgoing auth (e.g., AWS STS) on the same workload resource. **Referenced by MCPServer and MCPRemoteProxy** using `externalAuthConfigRef` or `authServerRef`. +**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 non-negative `cacheSkew`, 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_`) 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). + **Controller**: `cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go` `EmbeddedAuthServerConfig` can carry top-level SPIFFE trust-domain declarations in `spiffeTrustDomains` and canonical client associations in `inboundGrants.spiffeClientAuth` (`cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go`). The operator converts these CRD fields into runtime config via `buildSPIFFETrustDomainRunConfigs`/`buildSPIFFEClientAuthRunConfigs` in `cmd/thv-operator/pkg/controllerutil/authserver.go`, and projects file-source ConfigMap data read-only. `newServer` constructs the configured bundle source and passes its X.509 and JWT views to the authorization server. `RunConfig.Validate()` accepts only the `file` bundle source, so a `bundle_endpoint` or `workload_api` source passes the CRD schema but is rejected by the MCPExternalAuthConfig validation and by the VirtualMCPServer inline `authServerConfig` validation (both through `EmbeddedAuthServerConfig.ValidateSPIFFEBundleSourceTypes`, which calls `authserver.ValidateRuntimeSPIFFEBundleSourceType`), and again by `BuildAuthServerRunConfig` when a referencing workload reconciles. With a `file` source, JWT-SVID and X.509-SVID client authentication are enforced. The proxy runner and vMCP can start the auth-server TLS listener on fixed port 8443. The operator's `embeddedAuthServer.tlsListener` field, its validation and the pod rollout rules are described in the [Operator configuration](18-spiffe-association-declarations.md#operator-configuration) section of that document. When the listener is enabled, the operator adds an `https-auth` container port and Service port 8443 (with `appProtocol: https`) alongside the existing `http` port. X.509 client authentication needs TLS passed through to the listener, because a proxy or Ingress that terminates TLS drops the client certificate. See [SPIFFE Association Declarations](18-spiffe-association-declarations.md) for current scope. diff --git a/docs/arch/10-virtual-mcp-architecture.md b/docs/arch/10-virtual-mcp-architecture.md index 99d13828d2..c8d536f3d8 100644 --- a/docs/arch/10-virtual-mcp-architecture.md +++ b/docs/arch/10-virtual-mcp-architecture.md @@ -1082,9 +1082,21 @@ Validates clients connecting to vMCP using OIDC token validation or anonymous ac Authenticates vMCP to backend MCP servers using: - **Token exchange** - RFC 8693 exchange of client token for backend-specific token +- **Entra on-behalf-of (OBO)** - Microsoft Entra exchange of the signed-in user's token for a backend-scoped token issued for that user (`pkg/vmcp/auth/strategies/obo.go`) - **Header injection** - Static API key or header injection - **Unauthenticated** - For internal/trusted backends +The OBO strategy uses the same Entra exchanger and token cache as the proxy +middleware (`pkg/auth/obo/entra`, `pkg/auth/obo/cache`), keeping one cached +exchanger per (token URL, client ID, cache skew, client-secret fingerprint). +Health-check probes carry no user and skip the exchange. A conditional-access +or claims challenge fails the backend request and writes an +`obo_token_exchange` audit event. OBO works for inline `outgoingAuth` +backends, where the operator mounts each config's client secret under +`TOOLHIVE_OBO_CLIENT_SECRET_`, and for discovered backends +(MCPServer, MCPRemoteProxy, and MCPServerEntry in the group), where the +converter reads the client secret from the referenced Secret. + Exchanged tokens are cached to avoid repeated exchange calls. **Implementation**: `pkg/vmcp/auth/`, `pkg/vmcp/cache/` diff --git a/docs/middleware.md b/docs/middleware.md index c9a38deb4e..68f9525cc7 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -482,7 +482,53 @@ on `init()` registration. Direct proxy callers use the two host constructors. **Note**: This middleware is registered in `pkg/runner/middleware.go` and can be configured through the standard middleware configuration system or used directly via the proxy command. -### 9. Audit Middleware +### 9. On-Behalf-Of (OBO) Middleware + +**Purpose**: Exchanges the authenticated user's token for a backend-scoped +token with the Microsoft Entra on-behalf-of flow (RFC 7523 `jwt-bearer` grant +with `requested_token_use=on_behalf_of`), so the backend sees a token issued +for the signed-in user. + +**Location**: `pkg/auth/obo/middleware.go` (factory and handler), +`pkg/auth/obo/entra` (Entra exchanger), `pkg/auth/obo/cache` (token cache), +and `pkg/auth/obo/exchange` (provider-agnostic contract). These packages do not +link Kubernetes code; a test in `pkg/auth/obo` enforces that. + +**Configuration**: the operator builds an `obo`-typed middleware config from an +`MCPExternalAuthConfig` of type `obo` and injects it through +`AdditionalMiddlewareConfigs`, after authentication and before recovery. Its +parameters are `obo.MiddlewareParameters`: `tokenUrl`, `clientId`, `audience`, +`scopes` (space-joined scopes win over audience), `clientSecretEnvVar` (the +name of the env var the operator mounts the client secret under, +`TOOLHIVE_OBO_CLIENT_SECRET`), optional `subjectTokenProviderName`, and +optional `cacheSkewSeconds`. The factory fails at startup if the parameters are +invalid or the secret env var is empty. There are no `thv run` flags for OBO +yet; a RunConfig carrying the middleware config works. + +**Subject token**: `Identity.Token` (the token the client presented) by +default, or `Identity.UpstreamTokens[subjectTokenProviderName]` when an +embedded auth server fronts the proxy. The authentication middleware must run +first, so an MCPServer or MCPRemoteProxy that references an `obo` config must +also set `oidcConfigRef`; the operator rejects it with +`ExternalAuthConfigValidated=False / Reason=InvalidConfig` otherwise. + +**Behavior**: on success the middleware replaces `Authorization` with +`Bearer `, so the raw user token never reaches the backend. +Exchanged tokens are cached per (hash of the user token, exchange target) +until 60 seconds (or `cacheSkewSeconds`) before they expire; concurrent +identical exchanges share one request. Failures short-circuit with a generic +body that does not disclose the provider error: + +| Condition | Status | +|---|---| +| No authenticated identity or no subject token | 401 | +| Named upstream provider token missing | 401 with `WWW-Authenticate: Bearer error="invalid_token"` | +| Entra `invalid_grant` (subject token rejected) | 401 | +| Conditional access, MFA, or claims challenge (`interaction_required`, a `claims` value, AADSTS50076/50079) | 403, plus an `obo_token_exchange` audit event with outcome `denied` | +| `invalid_client`, Entra 5xx or unreachable, or an unclassified failure | 502 | +| Client cancelled the request | no response | + +### 10. Audit Middleware **Purpose**: Logs request events for compliance, monitoring, and debugging. @@ -734,7 +780,7 @@ thv run --transport sse --name my-server --audit-config <(echo '{"component":"my } ``` -### 10. Recovery Middleware +### 11. Recovery Middleware **Purpose**: Catches panics in HTTP handlers and returns a clean HTTP 500 error response. @@ -757,7 +803,7 @@ thv run --transport sse --name my-server --audit-config <(echo '{"component":"my **Note**: Recovery middleware has no cleanup requirements (`Close()` is a no-op). -### 11. Header Forward Middleware +### 12. Header Forward Middleware **Purpose**: Injects custom headers into requests before they are forwarded to remote MCP servers. diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index f80621a716..7d3da88782 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -110,7 +110,7 @@ _Appears in:_ | `tokenExchange` _[auth.types.TokenExchangeConfig](#authtypestokenexchangeconfig)_ | TokenExchange contains configuration for token exchange auth strategy.
Used when Type = "token_exchange". | | | | `upstreamInject` _[auth.types.UpstreamInjectConfig](#authtypesupstreaminjectconfig)_ | UpstreamInject contains configuration for upstream inject auth strategy.
Used when Type = "upstream_inject". | | | | `awsSts` _[auth.types.AwsStsConfig](#authtypesawsstsconfig)_ | AwsSts contains configuration for AWS STS auth strategy.
Used when Type = "aws_sts". | | | -| `obo` _[auth.types.OBOConfig](#authtypesoboconfig)_ | OBO contains configuration for on-behalf-of (OBO) auth strategy.
Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired;
an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. | | | +| `obo` _[auth.types.OBOConfig](#authtypesoboconfig)_ | OBO contains configuration for on-behalf-of (OBO) auth strategy.
Used when Type = "obo". | | | | `xaa` _[auth.types.XAAConfig](#authtypesxaaconfig)_ | XAA contains configuration for XAA (Cross-Application Access) auth strategy.
Used when Type = "xaa". | | | @@ -141,7 +141,7 @@ OBOConfig configures the on-behalf-of (OBO) authentication strategy. This strategy uses the Entra jwt-bearer / on_behalf_of grant to exchange the incoming user token for a backend-scoped token on behalf of the user. -Field names follow the OBO runtime contract (the enterprise obo.MiddlewareParameters), +Field names follow the OBO runtime contract (obo.MiddlewareParameters), not the RFC-8693 TokenExchangeConfig, because OBO uses a distinct Entra-specific grant. @@ -157,8 +157,8 @@ _Appears in:_ | `clientSecretEnv` _string_ | ClientSecretEnv is the environment variable name containing the client secret.
The value will be resolved at runtime from this environment variable. | | | | `audience` _string_ | Audience is the target audience (resource URI) for the exchanged token. | | | | `scopes` _string array_ | Scopes are the requested scopes for the exchanged token. | | | -| `subjectTokenProviderName` _string_ | SubjectTokenProviderName selects which upstream provider's token to use as the
subject (assertion) token for the OBO exchange. When set, the token is looked
up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the
inbound end-user token (Identity.Token) is used directly.
Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO
converter maps both to the runtime contract without renaming. | | | -| `cacheSkewSeconds` _integer_ | CacheSkewSeconds is the number of seconds to subtract from a cached token's
expiry when deciding whether to refresh it. Defaults to zero (no skew).
The operator CRD stores this as CacheSkew *metav1.Duration and converts it
to an integer-seconds value for the vMCP runtime contract. | | | +| `subjectTokenProviderName` _string_ | SubjectTokenProviderName selects which upstream provider's token to use as the
subject (assertion) token for the OBO exchange. When set, the token is looked
up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the
inbound end-user token (Identity.Token) is used directly.
Matches the operator CRD's SubjectTokenProviderName field; the OBO
converter maps it to the runtime contract without renaming. | | | +| `cacheSkewSeconds` _integer_ | CacheSkewSeconds is the number of seconds to subtract from a cached token's
expiry when deciding whether to refresh it. When nil or zero the token
cache's default skew (60 seconds) applies; negative values are rejected.
The operator CRD stores this as CacheSkew *metav1.Duration and converts it
to an integer-seconds value for the vMCP runtime contract. | | | #### auth.types.RoleMapping @@ -2305,7 +2305,7 @@ _Appears in:_ | `embeddedAuthServer` | ExternalAuthTypeEmbeddedAuthServer is the type for embedded OAuth2/OIDC authorization server
This enables running an embedded auth server that delegates to upstream IDPs
| | `awsSts` | ExternalAuthTypeAWSSts is the type for AWS STS authentication
| | `upstreamInject` | ExternalAuthTypeUpstreamInject is the type for upstream token injection
This injects an upstream IdP access token as the Authorization: Bearer header
| -| `obo` | ExternalAuthTypeOBO is the type for on-behalf-of (OBO) flows.
This type requires a build with an OBO handler registered via
controllerutil.RegisterOBOHandler; an upstream-only build surfaces
status.conditions[Valid] = False with Reason: EnterpriseRequired
when an obo-typed MCPExternalAuthConfig is applied.
| +| `obo` | ExternalAuthTypeOBO is the type for Microsoft Entra on-behalf-of (OBO)
flows: the proxy exchanges the authenticated user's token for a
backend-scoped token issued for that same user.
| | `xaa` | ExternalAuthTypeXAA is the type for XAA (Cross-Application Access) auth.
XAA performs a two-step token exchange to obtain access tokens for target services:
- IdP exchange (RFC 8693): Exchange the user's ID token at their IdP for an ID-JAG JWT
- Target grant (RFC 7523): Exchange the ID-JAG at the target app's AS for an access token
| @@ -2722,14 +2722,14 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | -| `type` _[api.v1beta1.ExternalAuthType](#apiv1beta1externalauthtype)_ | Type is the type of external authentication to configure.
When set to "obo", the cluster must run a build that has registered an
OBO handler via controllerutil.RegisterOBOHandler; upstream-only builds
surface status.conditions[Valid] = False with Reason: EnterpriseRequired
for obo-typed configs. | | Enum: [tokenExchange headerInjection bearerToken unauthenticated embeddedAuthServer awsSts upstreamInject obo xaa]
Required: \{\}
| +| `type` _[api.v1beta1.ExternalAuthType](#apiv1beta1externalauthtype)_ | Type is the type of external authentication to configure. | | Enum: [tokenExchange headerInjection bearerToken unauthenticated embeddedAuthServer awsSts upstreamInject obo xaa]
Required: \{\}
| | `tokenExchange` _[api.v1beta1.TokenExchangeConfig](#apiv1beta1tokenexchangeconfig)_ | TokenExchange configures RFC-8693 OAuth 2.0 Token Exchange
Only used when Type is "tokenExchange" | | Optional: \{\}
| | `headerInjection` _[api.v1beta1.HeaderInjectionConfig](#apiv1beta1headerinjectionconfig)_ | HeaderInjection configures custom HTTP header injection
Only used when Type is "headerInjection" | | Optional: \{\}
| | `bearerToken` _[api.v1beta1.BearerTokenConfig](#apiv1beta1bearertokenconfig)_ | BearerToken configures bearer token authentication
Only used when Type is "bearerToken" | | Optional: \{\}
| | `embeddedAuthServer` _[api.v1beta1.EmbeddedAuthServerConfig](#apiv1beta1embeddedauthserverconfig)_ | EmbeddedAuthServer configures an embedded OAuth2/OIDC authorization server
Only used when Type is "embeddedAuthServer" | | Optional: \{\}
| | `awsSts` _[api.v1beta1.AWSStsConfig](#apiv1beta1awsstsconfig)_ | AWSSts configures AWS STS authentication with SigV4 request signing
Only used when Type is "awsSts" | | Optional: \{\}
| | `upstreamInject` _[api.v1beta1.UpstreamInjectSpec](#apiv1beta1upstreaminjectspec)_ | UpstreamInject configures upstream token injection for backend requests.
Only used when Type is "upstreamInject". | | Optional: \{\}
| -| `obo` _[api.v1beta1.OBOConfig](#apiv1beta1oboconfig)_ | OBO configures On-Behalf-Of (OBO) authentication.
Only used when Type is "obo". Setting this field on an upstream-only build
causes the MCPExternalAuthConfig to transition to
status.conditions[Valid] = False with Reason: EnterpriseRequired, because
no OBO handler is registered. See OBOConfig for the field-to-runtime
contract mapping. | | Optional: \{\}
| +| `obo` _[api.v1beta1.OBOConfig](#apiv1beta1oboconfig)_ | OBO configures Microsoft Entra On-Behalf-Of (OBO) authentication.
Only used when Type is "obo". See OBOConfig for the field-to-runtime
contract mapping. | | Optional: \{\}
| | `xaa` _[api.v1beta1.XAASpec](#apiv1beta1xaaspec)_ | XAA configures XAA (Cross-Application Access) auth for backend requests.
Only used when Type is "xaa". | | Optional: \{\}
| @@ -3821,27 +3821,25 @@ _Appears in:_ OBOConfig holds configuration for the On-Behalf-Of (OBO) external auth type. Only used when Type is "obo". -This is the user-facing CRD surface for the Microsoft Entra OBO flow. It is -structurally valid in upstream (OSS) builds but inert: an upstream-only build -returns obo.ErrEnterpriseRequired at reconcile (Valid=False, Reason: -EnterpriseRequired) because no OBO handler is registered via -controllerutil.RegisterOBOHandler. A build with the enterprise OBO handler -translates these fields into the runtime wire contract obo.MiddlewareParameters, -so the field names and semantics here track that contract rather than the -upstream TokenExchangeConfig (which uses different names, e.g. +This is the user-facing CRD surface for the Microsoft Entra OBO flow. The +operator translates these fields into the runtime wire contract +obo.MiddlewareParameters (MCPServer, MCPRemoteProxy) or the vMCP OBOConfig +(VirtualMCPServer), so the field names and semantics here track that +contract rather than TokenExchangeConfig (which uses different names, e.g. subjectProviderName / externalTokenHeaderName). In particular there is no externalTokenHeaderName: the OBO subject is sourced from the authenticated -Identity, never from an inbound request header. +Identity, never from an inbound request header. An MCPServer or +MCPRemoteProxy that references an obo config must also set oidcConfigRef, +so it has an authenticated user token to exchange. -Field-to-contract mapping performed by the operator's OBO handler: +Field-to-contract mapping performed by the operator: - tenantId (+ optional authority) → tokenUrl (https://login.microsoftonline.com//oauth2/v2.0/token, or the configured authority base joined with the tenant for sovereign clouds) - clientSecretRef → resolved into a pod env var; only the env var name travels in the contract, as clientSecretEnvVar - audience / scopes → collapsed to a single exchange target by - obo.MiddlewareParameters.ExchangeTarget() (space-joined scopes win, - otherwise audience) + exchange.Target (space-joined scopes win, otherwise audience) - cacheSkew → the contract's integer-seconds cacheSkewSeconds Every field is optional at the CRD level, and the schema deliberately carries @@ -3850,8 +3848,8 @@ placeholder ({}) in earlier releases, so adding a required field or an admission rule that rejects {} would be a backward-incompatible narrowing of an already-stored, round-trippable object. Presence and combination requirements — a tenant, a client-auth credential, and at least one of -audience/scopes — are therefore enforced by the registered OBO handler at -reconcile, which reports a violation as Valid=False / Reason=InvalidConfig. +audience/scopes — are therefore enforced by the operator at reconcile, which +reports a violation as Valid=False / Reason=InvalidConfig. The per-field patterns below still apply, but only to a value that is present. @@ -3861,14 +3859,14 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | -| `tenantId` _string_ | TenantID is the Microsoft Entra (Azure AD) directory (tenant) identifier.
Optional at the CRD level (see the type doc); the operator enforces its
presence, since an OBO confidential-client exchange must target a specific
tenant. When set, it must be one of the two forms the Entra v2.0 token
endpoint addresses: a directory GUID, or a verified domain name (e.g.
contoso.onmicrosoft.com). Well-known aliases such as "common",
"organizations", and "consumers" are NOT accepted. The operator
interpolates it into the token endpoint
(//oauth2/v2.0/token), so the value is constrained to
the GUID/domain shape (no path metacharacters); the pattern and 253-char
cap mirror the enterprise exchanger's validateTenant, so any tenantId
admitted here is one the runtime can consume. | | MaxLength: 253
Pattern: `^([0-9a-fA-F]\{8\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{12\}\|([a-zA-Z0-9]([a-zA-Z0-9-]\{0,61\}[a-zA-Z0-9])?\.)+[a-zA-Z]\{2,\})$`
Optional: \{\}
| +| `tenantId` _string_ | TenantID is the Microsoft Entra (Azure AD) directory (tenant) identifier.
Optional at the CRD level (see the type doc); the operator enforces its
presence, since an OBO confidential-client exchange must target a specific
tenant. When set, it must be one of the two forms the Entra v2.0 token
endpoint addresses: a directory GUID, or a verified domain name (e.g.
contoso.onmicrosoft.com). Well-known aliases such as "common",
"organizations", and "consumers" are NOT accepted. The operator
interpolates it into the token endpoint
(//oauth2/v2.0/token), so the value is constrained to
the GUID/domain shape (no path metacharacters); the pattern and 253-char
cap mirror the Entra exchanger's tenant validation, so any tenantId
admitted here is one the runtime can consume. | | MaxLength: 253
Pattern: `^([0-9a-fA-F]\{8\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{4\}-[0-9a-fA-F]\{12\}\|([a-zA-Z0-9]([a-zA-Z0-9-]\{0,61\}[a-zA-Z0-9])?\.)+[a-zA-Z]\{2,\})$`
Optional: \{\}
| | `authority` _string_ | Authority overrides the default Entra login host
(https://login.microsoftonline.com) for sovereign or national clouds, e.g.
https://login.microsoftonline.us (US Gov) or
https://login.partner.microsoftonline.cn (China). When set, the operator
builds the token endpoint by joining , , and the
v2.0 token path. Must be an HTTPS URL with no userinfo, query, fragment,
or trailing slash; a path IS permitted and is prefixed before the tenant
segment, as some sovereign / B2C / CIAM endpoints require. The OBO exchange
POSTs the client secret and the end-user assertion to this host, so it is a
credential trust boundary: HTTPS is required and userinfo (user@host) is
rejected to prevent host confusion (per RFC 3986 the real host follows the
"@", so https://login.microsoftonline.com@attacker.example targets
attacker.example). This is intentionally stricter than the downstream
exchanger's validateHTTPSURL, which also accepts http for loopback hosts
and tolerates a trailing slash — rejecting those at admission is the safe
direction. | | Pattern: `^https://[^\s?#@]+[^/\s?#@]$`
Optional: \{\}
| | `clientId` _string_ | ClientID is the confidential client's application (client) ID registered
in Entra. Emitted verbatim as the runtime contract's clientId.
Optional at the CRD level so future client-authentication methods (e.g.
certificate or workload-identity credentials, planned fast-follows) can be
added without a breaking schema change. The operator enforces that clientId
and clientSecretRef are both present for the v1 shared-secret flow. | | Optional: \{\}
| | `clientSecretRef` _[api.v1beta1.SecretKeyRef](#apiv1beta1secretkeyref)_ | ClientSecretRef references a Kubernetes Secret containing the confidential
client's secret. v1 supports a shared client secret only. The operator
injects the resolved value into the proxyrunner pod as an environment
variable and emits only that variable's name in the runtime contract, as
clientSecretEnvVar — the secret value never travels in the contract.
Optional at the CRD level for the same forward-compatibility reason as
clientId (a certificate/workload-identity flow needs no client secret);
the operator enforces presence for the v1 shared-secret flow. | | Optional: \{\}
| | `audience` _string_ | Audience is the backend target identifier requested in the exchanged
token. Used as the exchange target when Scopes is empty. At least one of
audience or scopes must be set; the operator enforces that at reconcile
(it is not an admission-time rule — see the type doc). | | Optional: \{\}
| | `scopes` _string array_ | Scopes are the delegated scopes to request for the exchanged token, e.g.
["api:///.default"]. When non-empty they take precedence over
Audience. At least one of audience or scopes must be set; the operator
enforces that at reconcile. The MaxItems and per-item length caps are
defensive bounds on an otherwise unbounded list. | | MaxItems: 20
items:MaxLength: 256
items:MinLength: 1
Optional: \{\}
| | `subjectTokenProviderName` _string_ | SubjectTokenProviderName selects the source of the OBO subject (assertion)
token from the request's authenticated Identity:
- Omitted: use the inbound end-user token the client presented
(Identity.Token) — the deployment with no embedded auth server, where
the client holds an Entra token directly.
- Set: use the named upstream provider's token
(Identity.UpstreamTokens[]) — the embedded-auth-server
deployment, where the inbound token is the proxy's own session token.
The value must match a configured upstream provider name.
The subject is always sourced from the authenticated Identity, never from
an inbound request header, so the upstream auth middleware must run first. | | MaxLength: 63
MinLength: 1
Pattern: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`
Optional: \{\}
| -| `cacheSkew` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | CacheSkew overrides the OBO token cache's default expiry skew (the margin
by which a cached token is treated as expired before its real expiry),
e.g. "30s". The operator converts it to the runtime contract's
integer-seconds cacheSkewSeconds. Should not be negative, but the schema
does not enforce that — metav1.Duration carries no numeric minimum — and
upstream builds do not reject it. A negative value is rejected only by an
enterprise build's OBO handler once that handler validates the converted
parameters; it is not enforced at admission or in upstream-only builds.
When omitted, the cache default applies. | | Optional: \{\}
| +| `cacheSkew` _[Duration](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#duration-v1-meta)_ | CacheSkew overrides the OBO token cache's default expiry skew (the margin
by which a cached token is treated as expired before its real expiry),
e.g. "30s". The operator converts it to the runtime contract's
integer-seconds cacheSkewSeconds (truncated toward zero). Must not be
negative; metav1.Duration carries no numeric minimum, so the operator
rejects a negative value at reconcile (Valid=False, Reason: InvalidConfig)
rather than at admission. When omitted, the cache default applies. | | Optional: \{\}
| #### api.v1beta1.OIDCUpstreamConfig diff --git a/pkg/auth/obo/cache/cache.go b/pkg/auth/obo/cache/cache.go new file mode 100644 index 0000000000..8a3f56a7ed --- /dev/null +++ b/pkg/auth/obo/cache/cache.go @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package cache + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "log/slog" + "runtime/debug" + "sync" + "time" + + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" +) + +// defaultSkew is how far before a token's reported expiry the cache stops +// serving it, so a token is never handed out moments before it expires. +const defaultSkew = 60 * time.Second + +// errExchangePanicked is handed to every caller coalesced on an exchange whose +// delegate panicked. The exchange runs on a detached goroutine, so the panic is +// recovered there — an unrecovered panic in a background goroutine would crash +// the process — and surfaced as this error rather than a zero token; the +// in-flight key is freed either way. +var errExchangePanicked = errors.New("obo/cache: underlying token exchange panicked") + +// Cache decorates an exchange.TokenExchanger with a session-partitioned, in-memory +// token cache and implements exchange.Exchanger. It is safe for concurrent use. +// +// Concurrent misses for the same (userToken, audience) are coalesced by +// single-flight: only one underlying exchange runs at a time per key, and the +// other callers wait for and share its result. This keeps a burst of requests +// for one session — the common case when a cached token reaches its expiry — +// from stampeding the token endpoint. The shared exchange runs on its own +// goroutine under a context detached from any single caller +// (context.WithoutCancel), so one caller's cancellation cannot fail the others; +// each caller is still released early by its own context. See fetch / runExchange. +type Cache struct { + delegate exchange.TokenExchanger + skew time.Duration + now func() time.Time + + mu sync.Mutex + entries map[string]entry + inflight map[string]*call +} + +// entry is a cached exchanged token and the instant it expires. +type entry struct { + token string + expiry time.Time +} + +// call is a single in-flight exchange that concurrent callers for the same key +// share. done is closed once token/err are populated. +type call struct { + done chan struct{} + token exchange.Token + err error +} + +// Compile-time assertion that Cache satisfies the caller-facing contract. +var _ exchange.Exchanger = (*Cache)(nil) + +// Option configures a Cache at construction time. +type Option func(*Cache) + +// WithSkew overrides the expiry skew (default 60s). A token is treated as stale +// once the current time is within skew of its expiry. A negative skew panics. +func WithSkew(skew time.Duration) Option { + return func(c *Cache) { c.skew = skew } +} + +// WithClock overrides the time source, primarily for deterministic tests. A nil +// argument is ignored and the default (time.Now) is kept. +func WithClock(now func() time.Time) Option { + return func(c *Cache) { + if now != nil { + c.now = now + } + } +} + +// New returns a Cache fronting delegate. It panics if delegate is nil or if an +// option sets a negative skew — both are programming errors that should surface +// at wiring time, not on the first exchange. +func New(delegate exchange.TokenExchanger, opts ...Option) *Cache { + if delegate == nil { + panic("obo/cache: delegate TokenExchanger is nil") + } + c := &Cache{ + delegate: delegate, + skew: defaultSkew, + now: time.Now, + entries: make(map[string]entry), + inflight: make(map[string]*call), + } + for _, opt := range opts { + opt(c) + } + if c.skew < 0 { + panic("obo/cache: skew must not be negative") + } + return c +} + +// Exchange implements exchange.Exchanger. It returns a cached token for +// (userToken, audience) when one is present and not within the skew of its +// expiry; otherwise it delegates to the underlying TokenExchanger, caches the +// result (when it carries an expiry), and returns it. Concurrent misses for the +// same key are coalesced into a single underlying exchange. +func (c *Cache) Exchange(ctx context.Context, userToken, audience string) (string, error) { + key := cacheKey(userToken, audience) + + if token, ok := c.lookup(key); ok { + return token, nil + } + + token, err := c.fetch(ctx, key, userToken, audience) + if err != nil { + return "", err + } + return token.AccessToken, nil +} + +// lookup returns the cached token for key when present and still fresh. This is +// the lock-protected fast path; it does not consult in-flight exchanges. +func (c *Cache) lookup(key string) (string, bool) { + c.mu.Lock() + defer c.mu.Unlock() + + e, ok := c.entries[key] + if !ok || !c.freshLocked(e) { + return "", false + } + return e.token, true +} + +// fetch resolves a cache miss. It serves a token another flight just cached, +// joins an in-flight exchange for the same key, or starts one. The exchange runs +// on a detached goroutine (see runExchange) so it survives any single caller's +// cancellation; every caller — including the one that started the flight — then +// waits via waitFor and is released early by its own context. +func (c *Cache) fetch(ctx context.Context, key, userToken, audience string) (exchange.Token, error) { + c.mu.Lock() + // Re-check under the lock: another flight may have cached the token between + // the lock-free lookup and now. + if e, ok := c.entries[key]; ok && c.freshLocked(e) { + c.mu.Unlock() + return exchange.Token{AccessToken: e.token, Expiry: e.expiry}, nil + } + flight, ok := c.inflight[key] + if !ok { + flight = &call{done: make(chan struct{})} + c.inflight[key] = flight + // Detach from this caller's context so a later cancellation of whichever + // caller happened to start the flight does not abort an exchange the + // coalesced followers still need. The exchange is bounded by the + // delegate's own timeout (e.g. the HTTP client Timeout). + go c.runExchange(context.WithoutCancel(ctx), key, userToken, audience, flight) + } + c.mu.Unlock() + + return waitFor(ctx, flight) +} + +// runExchange performs the single shared exchange for key on its own goroutine +// and, in a defer, frees the in-flight slot, caches a successful expiring token, +// and releases the waiters. ctx is already detached from any caller (see fetch), +// so the exchange is not aborted by a caller's cancellation. Because it runs +// detached, a panicking delegate would otherwise crash the process: the defer +// recovers it, hands every waiter errExchangePanicked instead of a zero token, +// and still frees the key. A token with no reported expiry cannot be aged out +// safely, so it is used once and never stored (see exchange.Token). +func (c *Cache) runExchange(ctx context.Context, key, userToken, audience string, flight *call) { + defer func() { + if r := recover(); r != nil { + // Surface the delegate bug instead of black-holing it: log the panic + // value and stack at WARN. It is deliberately not embedded in the + // caller-facing error, since a panic payload could rarely carry + // sensitive data. + slog.Warn("obo/cache: token exchange delegate panicked; recovered", + "recovered", r, "stack", string(debug.Stack())) + flight.err = errExchangePanicked + } + c.mu.Lock() + delete(c.inflight, key) + if flight.err == nil && !flight.token.Expiry.IsZero() { + c.sweepLocked() + c.entries[key] = entry{token: flight.token.AccessToken, expiry: flight.token.Expiry} + } + c.mu.Unlock() + close(flight.done) + }() + + flight.token, flight.err = c.delegate.ExchangeToken(ctx, userToken, audience) +} + +// waitFor blocks until the in-flight exchange completes and returns its shared +// result, or returns early if the caller's own context is cancelled first (so a +// follower is never held past its own deadline by a slow leader). +func waitFor(ctx context.Context, c *call) (exchange.Token, error) { + select { + case <-ctx.Done(): + return exchange.Token{}, ctx.Err() + case <-c.done: + return c.token, c.err + } +} + +// freshLocked reports whether e is still serveable: the current time is before +// its expiry minus the skew. The caller must hold c.mu. +func (c *Cache) freshLocked(e entry) bool { + return c.now().Before(e.expiry.Add(-c.skew)) +} + +// sweepLocked deletes entries whose expiry has already passed, bounding the map +// to tokens that are still live and keeping memory proportional to the number of +// live sessions without a background goroutine. The caller must hold c.mu. +// +// It is O(n) in the number of cached entries and runs on every cacheable write, +// so a burst of N first-time exchanges across distinct sessions is O(n²) overall, +// serialized on c.mu. This is acceptable for v1 — the work is in-memory under the +// lock, not a network stall (the delegate call happens outside the lock) — but if +// profiling shows lock contention, switch to a throttled or amortized sweep +// (e.g. at most once per K writes or T seconds). +func (c *Cache) sweepLocked() { + now := c.now() + for k, e := range c.entries { + if !now.Before(e.expiry) { + delete(c.entries, k) + } + } +} + +// cacheKey partitions the cache by session: it hashes the (secret) user token +// so the raw token is not retained as a map key, and appends the (non-secret) +// audience. The hash is fixed-width hex, so the ":" delimiter is unambiguous and +// distinct (userToken, audience) pairs cannot collide. +func cacheKey(userToken, audience string) string { + sum := sha256.Sum256([]byte(userToken)) + return hex.EncodeToString(sum[:]) + ":" + audience +} diff --git a/pkg/auth/obo/cache/cache_test.go b/pkg/auth/obo/cache/cache_test.go new file mode 100644 index 0000000000..60a6dad333 --- /dev/null +++ b/pkg/auth/obo/cache/cache_test.go @@ -0,0 +1,454 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package cache + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" +) + +// base is a fixed clock origin so TTL arithmetic is fully deterministic. +var base = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + +// fakeClock is a manually-advanced, concurrency-safe time source. +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func newFakeClock() *fakeClock { return &fakeClock{t: base} } + +func (c *fakeClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +// fakeExchanger is a configurable exchange.TokenExchanger test double that counts +// calls. fn receives the 1-based call number so tests can vary the result. +type fakeExchanger struct { + mu sync.Mutex + calls int + fn func(ctx context.Context, userToken, audience string, call int) (exchange.Token, error) +} + +var _ exchange.TokenExchanger = (*fakeExchanger)(nil) + +func (f *fakeExchanger) ExchangeToken(ctx context.Context, userToken, audience string) (exchange.Token, error) { + f.mu.Lock() + f.calls++ + call := f.calls + fn := f.fn + f.mu.Unlock() + return fn(ctx, userToken, audience, call) +} + +func (f *fakeExchanger) callCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls +} + +func TestCache_ServesCachedTokenWithinTTL(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{AccessToken: "tok", Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + first, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok", first) + + second, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok", second) + + assert.Equal(t, 1, fake.callCount(), "second call must be served from the cache") +} + +func TestCache_ReExchangesAfterExpiry(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + const ttl = 100 * time.Second + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, call int) (exchange.Token, error) { + return exchange.Token{ + AccessToken: fmt.Sprintf("tok-%d", call), + Expiry: clock.now().Add(ttl), + }, nil + }} + c := New(fake, WithClock(clock.now)) // default 60s skew → stale at base+40s + + v, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok-1", v) + assert.Equal(t, 1, fake.callCount()) + + // Still fresh just before the skew window opens. + clock.advance(39 * time.Second) // now base+39s, threshold base+40s + v, err = c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok-1", v) + assert.Equal(t, 1, fake.callCount()) + + // Inside the skew window the token is treated as stale and re-exchanged. + clock.advance(6 * time.Second) // now base+45s, past base+40s + v, err = c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok-2", v) + assert.Equal(t, 2, fake.callCount()) +} + +func TestCache_PartitionsByUserToken(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, userToken, _ string, _ int) (exchange.Token, error) { + return exchange.Token{AccessToken: "tok:" + userToken, Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + a, err := c.Exchange(t.Context(), "userA", "aud") + require.NoError(t, err) + assert.Equal(t, "tok:userA", a) + + b, err := c.Exchange(t.Context(), "userB", "aud") + require.NoError(t, err) + assert.Equal(t, "tok:userB", b) + assert.Equal(t, 2, fake.callCount(), "different user tokens must not share a cache entry") + + // Each user still reads its own cached token; no cross-contamination. + a2, err := c.Exchange(t.Context(), "userA", "aud") + require.NoError(t, err) + assert.Equal(t, "tok:userA", a2) + b2, err := c.Exchange(t.Context(), "userB", "aud") + require.NoError(t, err) + assert.Equal(t, "tok:userB", b2) + assert.Equal(t, 2, fake.callCount()) +} + +func TestCache_PartitionsByAudience(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, audience string, _ int) (exchange.Token, error) { + return exchange.Token{AccessToken: "tok:" + audience, Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + v1, err := c.Exchange(t.Context(), "user", "aud-1") + require.NoError(t, err) + assert.Equal(t, "tok:aud-1", v1) + + v2, err := c.Exchange(t.Context(), "user", "aud-2") + require.NoError(t, err) + assert.Equal(t, "tok:aud-2", v2) + assert.Equal(t, 2, fake.callCount(), "different audiences must not share a cache entry") +} + +func TestCache_DoesNotCacheTokenWithoutExpiry(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, call int) (exchange.Token, error) { + return exchange.Token{AccessToken: fmt.Sprintf("tok-%d", call)}, nil // zero Expiry + }} + c := New(fake, WithClock(clock.now)) + + for i := 1; i <= 3; i++ { + v, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, fmt.Sprintf("tok-%d", i), v) + } + assert.Equal(t, 3, fake.callCount(), "a token with no expiry is never cached") +} + +func TestCache_PropagatesDelegateError(t *testing.T) { + t.Parallel() + + sentinel := errors.New("delegate boom") + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{}, sentinel + }} + c := New(fake, WithClock(clock.now)) + + v, err := c.Exchange(t.Context(), "user", "aud") + require.ErrorIs(t, err, sentinel) + assert.Empty(t, v) + + // A failed exchange caches nothing, so the next call delegates again. + _, _ = c.Exchange(t.Context(), "user", "aud") + assert.Equal(t, 2, fake.callCount()) +} + +func TestCache_ConcurrentExchangesAreRaceFree(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, userToken, audience string, _ int) (exchange.Token, error) { + return exchange.Token{ + AccessToken: "tok:" + userToken + ":" + audience, + Expiry: clock.now().Add(time.Hour), + }, nil + }} + c := New(fake, WithClock(clock.now)) + + ctx := t.Context() + const goroutines = 64 + var wg sync.WaitGroup + wg.Add(goroutines) + for i := 0; i < goroutines; i++ { + go func(i int) { + defer wg.Done() + user := fmt.Sprintf("user-%d", i%4) + aud := fmt.Sprintf("aud-%d", i%3) + got, err := c.Exchange(ctx, user, aud) + assert.NoError(t, err) + assert.Equal(t, "tok:"+user+":"+aud, got) + }(i) + } + wg.Wait() +} + +// TestCache_StarterCancellationDoesNotPoisonOthers verifies the detached-exchange +// semantics: cancelling whichever caller happened to start the flight releases +// that caller promptly with its own error, but the shared exchange runs to +// completion (it never observes the cancellation) so the other coalesced callers +// still get a valid token. +func TestCache_StarterCancellationDoesNotPoisonOthers(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + entered := make(chan struct{}, 2) + proceed := make(chan struct{}) + fake := &fakeExchanger{fn: func(ctx context.Context, _, _ string, _ int) (exchange.Token, error) { + entered <- struct{}{} + <-proceed + // The shared exchange must not inherit the starter's cancellation. + if err := ctx.Err(); err != nil { + return exchange.Token{}, err + } + return exchange.Token{AccessToken: "shared", Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + // The starter holds a cancellable context. + starterCtx, cancelStarter := context.WithCancel(t.Context()) + starterErr := make(chan error, 1) + go func() { + _, err := c.Exchange(starterCtx, "user", "aud") + starterErr <- err + }() + <-entered // the detached exchange has begun + + // A second caller with a healthy context coalesces onto the same exchange. + followerTok := make(chan string, 1) + go func() { + v, err := c.Exchange(t.Context(), "user", "aud") + assert.NoError(t, err) + followerTok <- v + }() + + // Cancelling the starter releases it promptly with its own error... + cancelStarter() + assert.ErrorIs(t, <-starterErr, context.Canceled) + + // ...while the shared exchange completes and the follower still succeeds. + close(proceed) + assert.Equal(t, "shared", <-followerTok) + assert.Equal(t, 1, fake.callCount(), "the cancellation must not trigger a second exchange") +} + +func TestCache_CoalescesConcurrentMissesForSameKey(t *testing.T) { + t.Parallel() + + const followers = 16 + clock := newFakeClock() + // Buffered past the expected count so a (broken) extra exchange cannot + // deadlock on the signal — it would surface as a failed call-count assert. + entered := make(chan struct{}, followers+1) + release := make(chan struct{}) + var calls atomic.Int32 + + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + calls.Add(1) + entered <- struct{}{} + <-release // hold the in-flight exchange open while followers pile up + return exchange.Token{AccessToken: "shared", Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + ctx := t.Context() + results := make(chan string, followers+1) + doExchange := func() { + v, err := c.Exchange(ctx, "user", "aud") + assert.NoError(t, err) + results <- v + } + + go doExchange() // leader + <-entered // leader is registered in-flight and inside the delegate + + for i := 0; i < followers; i++ { + go doExchange() // each joins the leader's in-flight exchange + } + + close(release) // let the single exchange complete; everyone shares its result + + for i := 0; i < followers+1; i++ { + assert.Equal(t, "shared", <-results) + } + assert.Equal(t, int32(1), calls.Load(), + "concurrent misses for one key must collapse to a single underlying exchange") +} + +// TestCache_JoinsExistingInflight deterministically exercises the single-flight +// join path: a caller that finds an in-flight exchange for its key waits for and +// shares that result instead of calling the delegate. It seeds the unexported +// in-flight map so the timing is not scheduling-dependent. +func TestCache_JoinsExistingInflight(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{}, errors.New("delegate must not be called when joining an in-flight exchange") + }} + c := New(fake, WithClock(clock.now)) + + done := make(chan struct{}) + leader := &call{done: done, token: exchange.Token{AccessToken: "shared", Expiry: clock.now().Add(time.Hour)}} + key := cacheKey("user", "aud") + c.mu.Lock() + c.inflight[key] = leader + c.mu.Unlock() + close(done) // the in-flight exchange has already completed + + got, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "shared", got) + assert.Equal(t, 0, fake.callCount()) +} + +// TestCache_FollowerRespectsContextCancellation verifies that a caller waiting on +// another goroutine's in-flight exchange is released by its own context, rather +// than being held until the (here, never-completing) leader finishes. +func TestCache_FollowerRespectsContextCancellation(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{}, errors.New("delegate must not be called by a follower") + }} + c := New(fake, WithClock(clock.now)) + + key := cacheKey("user", "aud") + c.mu.Lock() + c.inflight[key] = &call{done: make(chan struct{})} // never completes + c.mu.Unlock() + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + _, err := c.Exchange(ctx, "user", "aud") + assert.ErrorIs(t, err, context.Canceled) + assert.Equal(t, 0, fake.callCount()) +} + +// TestCache_PanickingDelegateFreesKey verifies the single-flight cleanup is +// panic-safe: because the exchange runs on a detached goroutine, a panicking +// delegate is recovered and surfaced to the caller as an error (rather than +// crashing the process), and the in-flight slot is freed so the key is not +// wedged for later callers. +func TestCache_PanickingDelegateFreesKey(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + var shouldPanic atomic.Bool + shouldPanic.Store(true) + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + if shouldPanic.Load() { + panic("delegate boom") + } + return exchange.Token{AccessToken: "after-panic", Expiry: clock.now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(clock.now)) + + _, err := c.Exchange(t.Context(), "user", "aud") + assert.ErrorIs(t, err, errExchangePanicked, "a panicking delegate must surface as an error, not crash") + + c.mu.Lock() + _, wedged := c.inflight[cacheKey("user", "aud")] + c.mu.Unlock() + assert.False(t, wedged, "the in-flight slot must be freed after a panic") + + // The cache is not wedged: a later call for the same key proceeds normally. + shouldPanic.Store(false) + v, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "after-panic", v) +} + +func TestNew_PanicsOnNilDelegate(t *testing.T) { + t.Parallel() + assert.Panics(t, func() { New(nil) }) +} + +func TestNew_PanicsOnNegativeSkew(t *testing.T) { + t.Parallel() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{}, nil + }} + assert.Panics(t, func() { New(fake, WithSkew(-time.Second)) }) +} + +// TestCache_SweepEvictsExpiredColdEntries verifies the bounded-memory invariant: +// inserting a fresh entry sweeps entries whose expiry has already passed, so the +// map does not accumulate stale sessions. It reaches into unexported state +// because the eviction is an internal memory-management property, not part of +// the public contract. +func TestCache_SweepEvictsExpiredColdEntries(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{AccessToken: "t", Expiry: clock.now().Add(10 * time.Second)}, nil + }} + c := New(fake, WithClock(clock.now), WithSkew(0)) + + _, err := c.Exchange(t.Context(), "cold", "aud") // expiry = base+10s + require.NoError(t, err) + + clock.advance(20 * time.Second) // now base+20s — the cold entry has expired + + _, err = c.Exchange(t.Context(), "hot", "aud") // store() sweeps the cold entry + require.NoError(t, err) + + c.mu.Lock() + defer c.mu.Unlock() + _, coldPresent := c.entries[cacheKey("cold", "aud")] + _, hotPresent := c.entries[cacheKey("hot", "aud")] + assert.False(t, coldPresent, "expired cold entry must be swept on insert") + assert.True(t, hotPresent, "freshly inserted entry must remain") + assert.Len(t, c.entries, 1) +} diff --git a/pkg/auth/obo/cache/doc.go b/pkg/auth/obo/cache/doc.go new file mode 100644 index 0000000000..42b5f7c42c --- /dev/null +++ b/pkg/auth/obo/cache/doc.go @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package cache adds a session-partitioned, in-memory token cache in front of +// any exchange.TokenExchanger. +// +// Cache decorates a provider (entra.Exchanger today) and implements +// exchange.Exchanger, so the proxy middleware and the vMCP strategy are unaware +// of the caching. Cached tokens are partitioned by (hash(userToken), audience): +// a given user's token for a given audience is reused until it is within a +// configurable skew of its expiry, at which point the next call re-exchanges. +// Different user tokens and different audiences never collide. +// +// Typical wiring: +// +// exchanger, err := entra.New(cfg) +// if err != nil { ... } +// var oboExchanger exchange.Exchanger = cache.New(exchanger) +// +// The package links only the standard library and the stdlib-only +// pkg/auth/obo/exchange contract. +package cache diff --git a/pkg/auth/obo/deps_test.go b/pkg/auth/obo/deps_test.go new file mode 100644 index 0000000000..c7e508e6c4 --- /dev/null +++ b/pkg/auth/obo/deps_test.go @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package obo_test + +import ( + "os" + "os/exec" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestPackages_DoNotLinkKubernetes keeps the OBO protocol and middleware +// packages free of client-go, controller-runtime, and the rest of k8s.io / +// sigs.k8s.io. The proxyrunner links pkg/auth/obo through the runner's +// middleware factory map, so a Kubernetes import here would bloat it. +// +// It shells out to `go list -deps`. Without the Go toolchain it skips locally, +// but fails under CI so the guard cannot be bypassed silently. +func TestPackages_DoNotLinkKubernetes(t *testing.T) { + t.Parallel() + + goBin, err := exec.LookPath("go") + if err != nil { + if os.Getenv("CI") != "" { + t.Fatal("go toolchain required in CI to enforce the k8s-free dependency guard") + } + t.Skip("go toolchain not on PATH; skipping dependency-graph assertion") + } + + const root = "github.com/stacklok/toolhive/pkg/auth/obo" + packages := []string{ + root, + root + "/cache", + root + "/entra", + root + "/exchange", + } + forbidden := []string{"k8s.io/", "sigs.k8s.io/", "client-go", "controller-runtime"} + + for _, pkg := range packages { + t.Run(pkg, func(t *testing.T) { + t.Parallel() + + out, err := exec.Command(goBin, "list", "-deps", pkg).CombinedOutput() + require.NoError(t, err, "go list -deps failed:\n%s", out) + + deps := string(out) + for _, bad := range forbidden { + assert.NotContains(t, deps, bad, + "package %s must not transitively import %q", pkg, bad) + } + }) + } +} diff --git a/pkg/auth/obo/entra/config_test.go b/pkg/auth/obo/entra/config_test.go new file mode 100644 index 0000000000..8a4d784519 --- /dev/null +++ b/pkg/auth/obo/entra/config_test.go @@ -0,0 +1,191 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package entra_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/auth/obo/entra" +) + +func TestNew_ValidConfigs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + cfg entra.Config + }{ + { + name: "domain tenant with default authority", + cfg: entra.Config{TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret}, + }, + { + name: "GUID tenant", + cfg: entra.Config{ + TenantID: "72f988bf-86f1-41af-91ab-2d7cd011db47", ClientID: testClientID, ClientSecret: testClientSecret, + }, + }, + { + name: "explicit https authority", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "https://login.microsoftonline.us", + }, + }, + { + name: "loopback http authority permitted for tests", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "http://127.0.0.1:8080", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ex, err := entra.New(tt.cfg) + require.NoError(t, err) + assert.NotNil(t, ex) + }) + } +} + +func TestNew_InvalidConfigs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + cfg entra.Config + }{ + { + name: "missing tenant", + cfg: entra.Config{ClientID: testClientID, ClientSecret: testClientSecret}, + }, + { + name: "missing client id", + cfg: entra.Config{TenantID: testTenant, ClientSecret: testClientSecret}, + }, + { + name: "missing client secret", + cfg: entra.Config{TenantID: testTenant, ClientID: testClientID}, + }, + { + name: "tenant with path separator", + cfg: entra.Config{TenantID: "tenant/../evil", ClientID: testClientID, ClientSecret: testClientSecret}, + }, + { + name: "tenant that is neither GUID nor domain", + cfg: entra.Config{TenantID: "not a real tenant", ClientID: testClientID, ClientSecret: testClientSecret}, + }, + { + name: "single-label tenant", + cfg: entra.Config{TenantID: "contoso", ClientID: testClientID, ClientSecret: testClientSecret}, + }, + { + name: "tenant longer than the DNS limit", + cfg: entra.Config{ + TenantID: strings.Repeat("a", 254), ClientID: testClientID, ClientSecret: testClientSecret, + }, + }, + { + name: "non-https authority scheme", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "ftp://login.microsoftonline.com", + }, + }, + { + name: "non-loopback http authority", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "http://login.microsoftonline.com", + }, + }, + { + name: "authority with fragment", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "https://login.microsoftonline.com/#frag", + }, + }, + { + name: "authority with query string", + cfg: entra.Config{ + TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, + Authority: "https://login.microsoftonline.com/?foo=bar", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ex, err := entra.New(tt.cfg) + require.Error(t, err) + assert.Nil(t, ex) + // Validation errors never echo the client secret. + assert.NotContains(t, err.Error(), testClientSecret) + }) + } +} + +func TestNewFromTokenURL_Valid(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + tokenURL string + }{ + {name: "https token endpoint", tokenURL: "https://login.microsoftonline.com/test-tenant/oauth2/v2.0/token"}, + {name: "sovereign cloud https", tokenURL: "https://login.microsoftonline.us/test-tenant/oauth2/v2.0/token"}, + {name: "loopback http permitted for tests", tokenURL: "http://127.0.0.1:8080/test-tenant/oauth2/v2.0/token"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ex, err := entra.NewFromTokenURL(tt.tokenURL, testClientID, testClientSecret, nil) + require.NoError(t, err) + assert.NotNil(t, ex) + }) + } +} + +func TestNewFromTokenURL_Invalid(t *testing.T) { + t.Parallel() + + const validURL = "https://login.microsoftonline.com/test-tenant/oauth2/v2.0/token" + + tests := []struct { + name string + tokenURL string + clientID string + clientSecret string + }{ + {name: "empty token url", tokenURL: "", clientID: testClientID, clientSecret: testClientSecret}, + {name: "non-https scheme", tokenURL: "ftp://login.microsoftonline.com/t/token", clientID: testClientID, clientSecret: testClientSecret}, + {name: "non-loopback http", tokenURL: "http://login.microsoftonline.com/t/token", clientID: testClientID, clientSecret: testClientSecret}, + {name: "token url with query", tokenURL: validURL + "?foo=bar", clientID: testClientID, clientSecret: testClientSecret}, + {name: "token url with fragment", tokenURL: validURL + "#frag", clientID: testClientID, clientSecret: testClientSecret}, + {name: "missing host", tokenURL: "https:///t/token", clientID: testClientID, clientSecret: testClientSecret}, + {name: "missing client id", tokenURL: validURL, clientID: "", clientSecret: testClientSecret}, + {name: "missing client secret", tokenURL: validURL, clientID: testClientID, clientSecret: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ex, err := entra.NewFromTokenURL(tt.tokenURL, tt.clientID, tt.clientSecret, nil) + require.Error(t, err) + assert.Nil(t, ex) + // Validation errors never echo the client secret. + assert.NotContains(t, err.Error(), testClientSecret) + }) + } +} diff --git a/pkg/auth/obo/entra/doc.go b/pkg/auth/obo/entra/doc.go new file mode 100644 index 0000000000..d7dc6bdb92 --- /dev/null +++ b/pkg/auth/obo/entra/doc.go @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package entra implements the Microsoft Entra (Azure AD) variant of the +// on-behalf-of (OBO) token exchange. +// +// It performs the Entra OBO flow — the jwt-bearer grant with +// requested_token_use=on_behalf_of against the v2.0 token endpoint — and maps +// the provider's error responses onto a small typed taxonomy (see errors.go). +// Exchanger implements both exchange.Exchanger and exchange.TokenExchanger; +// wrap it in the sibling cache package to add session-partitioned token +// caching: +// +// exchanger, err := entra.New(entra.Config{ +// TenantID: "", +// ClientID: "", +// ClientSecret: "", +// }) +// if err != nil { ... } +// var oboExchanger exchange.Exchanger = cache.New(exchanger) +// +// The package links only the standard library and the stdlib-only +// pkg/auth/obo/exchange contract. It deliberately does NOT depend on the +// oauthproto helpers, which transitively pull in a large dependency graph +// (fosite, ristretto, grpc-gateway) that the proxyrunner does not otherwise +// need, and it stays free of client-go and controller-runtime (see the +// dependency guard test in pkg/auth/obo). +package entra diff --git a/pkg/auth/obo/entra/errors.go b/pkg/auth/obo/entra/errors.go new file mode 100644 index 0000000000..a0c02434dd --- /dev/null +++ b/pkg/auth/obo/entra/errors.go @@ -0,0 +1,159 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package entra + +import ( + "errors" + "fmt" +) + +// Sentinel errors for the OBO exchange failure classes. Callers compare with +// errors.Is; the concrete *ExchangeError returned by the Exchanger unwraps to +// the sentinel matching its Kind. They never carry token or secret material. +// +// This layer deliberately does no logging (it would risk leaking secrets and the +// consumer has the request context anyway). The audit record for a +// fail-fast conditional-access / claims challenge is the runtime middleware's +// and the vMCP strategy's responsibility: on errors.Is(err, ErrInteractionRequired) they +// emit the audit event using the safe-to-log fields the *ExchangeError already +// carries — Kind, OAuthError, Description, Claims, HTTPStatus — none of which +// contain credential material. +var ( + // ErrInteractionRequired indicates Entra refused the silent exchange and + // demands interactive user action — a conditional-access / MFA / claims + // challenge (for example AADSTS50076 or AADSTS50079). v1 fails fast on this + // case rather than attempting an interactive passthrough; the originating + // *ExchangeError carries the raw claims challenge for a future enhancement. + ErrInteractionRequired = errors.New("entra obo: interaction required (conditional access / claims challenge)") + + // ErrInvalidGrant indicates the subject (user) token was rejected — expired, + // malformed, or not consented for this resource. It is permanent for that + // token: re-running the exchange with the same assertion will fail again. + ErrInvalidGrant = errors.New("entra obo: subject token rejected") + + // ErrInvalidClient indicates the confidential client failed to authenticate + // (wrong client_id / client_secret, or the secret has expired). It is a + // permanent configuration error until the operator fixes the credentials. + ErrInvalidClient = errors.New("entra obo: client authentication failed") + + // ErrTransient indicates a retryable failure — a 5xx from the token endpoint + // or a transport-level error reaching it. Callers may retry with backoff. + ErrTransient = errors.New("entra obo: transient token endpoint failure") +) + +// ErrorKind classifies an OBO exchange failure so callers can decide between +// fail-fast (interaction required), permanent-error (bad grant / client), and +// retry (transient) without string-matching provider diagnostics. +type ErrorKind int + +const ( + // KindUnknown is an unclassified failure: a non-success response that did + // not match any recognised OAuth error code or status class. It is treated + // as permanent (it does not unwrap to ErrTransient) so callers do not retry + // indefinitely on an unrecognised, likely permanent, error. + KindUnknown ErrorKind = iota + + // KindInteractionRequired is a conditional-access / MFA / claims challenge. + KindInteractionRequired + + // KindInvalidGrant is a rejected subject token. + KindInvalidGrant + + // KindInvalidClient is a confidential-client authentication failure. + KindInvalidClient + + // KindTransient is a retryable server-side or transport failure. + KindTransient +) + +// ExchangeError is the typed error returned when an Entra OBO exchange fails. It +// classifies the failure (Kind) and unwraps to the matching sentinel so callers +// can use either errors.As (to read Kind / Claims / OAuthError) or errors.Is +// (against the sentinels above). +// +// It deliberately carries only non-sensitive fields: the RFC 6749 error code, +// the provider's diagnostic description, the HTTP status, and — for an +// interaction-required challenge — the raw claims request. It never contains the +// user's assertion, the client secret, or any issued access token, so it is safe +// to log and to surface in API responses. +type ExchangeError struct { + // Kind is the classified failure class. + Kind ErrorKind + + // OAuthError is the RFC 6749 "error" code from the response body (for + // example "invalid_grant"). Empty when the failure had no parseable body + // (transport error, 5xx with a non-JSON body). + OAuthError string + + // Description is the provider's "error_description" diagnostic. For Entra + // this is the human-readable "AADSTSnnnnn: ..." message. It contains no + // credential material and is safe to log. + Description string + + // Claims is the raw claims challenge from an interaction-required response + // (the "claims" field Entra returns for conditional access). It is empty for + // every other Kind. It is a request for additional claims, not a credential. + Claims string + + // HTTPStatus is the token endpoint's HTTP status code, or 0 when the request + // never produced a response (transport-level failure). + HTTPStatus int +} + +// Error implements error. It composes only the non-sensitive fields; in +// particular it never includes the subject token, client secret, or issued +// access token. +func (e *ExchangeError) Error() string { + detail := e.OAuthError + if e.Description != "" { + if detail != "" { + detail += ": " + } + detail += e.Description + } + if detail == "" && e.HTTPStatus != 0 { + detail = fmt.Sprintf("token endpoint returned HTTP %d", e.HTTPStatus) + } + if detail == "" { + detail = "no response from token endpoint" + } + return fmt.Sprintf("%s (%s)", e.kindString(), detail) +} + +// Unwrap maps the Kind onto its sentinel so errors.Is works against the +// exported sentinels. KindUnknown intentionally unwraps to nil — an unknown +// failure matches none of the sentinels and is therefore treated as permanent. +func (e *ExchangeError) Unwrap() error { + switch e.Kind { + case KindInteractionRequired: + return ErrInteractionRequired + case KindInvalidGrant: + return ErrInvalidGrant + case KindInvalidClient: + return ErrInvalidClient + case KindTransient: + return ErrTransient + case KindUnknown: + return nil + } + return nil +} + +// kindString returns a short human label for the failure class, used only to +// build Error() output. +func (e *ExchangeError) kindString() string { + switch e.Kind { + case KindInteractionRequired: + return "interaction required" + case KindInvalidGrant: + return "invalid grant" + case KindInvalidClient: + return "invalid client" + case KindTransient: + return "transient failure" + case KindUnknown: + return "exchange failed" + } + return "exchange failed" +} diff --git a/pkg/auth/obo/entra/errors_test.go b/pkg/auth/obo/entra/errors_test.go new file mode 100644 index 0000000000..5b06baa4dd --- /dev/null +++ b/pkg/auth/obo/entra/errors_test.go @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package entra_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/auth/obo/entra" +) + +func TestExchangeError_UnwrapsToSentinel(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + kind entra.ErrorKind + want error // nil means: matches none of the sentinels + }{ + {"interaction required", entra.KindInteractionRequired, entra.ErrInteractionRequired}, + {"invalid grant", entra.KindInvalidGrant, entra.ErrInvalidGrant}, + {"invalid client", entra.KindInvalidClient, entra.ErrInvalidClient}, + {"transient", entra.KindTransient, entra.ErrTransient}, + {"unknown", entra.KindUnknown, nil}, + } + + allSentinels := []error{ + entra.ErrInteractionRequired, entra.ErrInvalidGrant, + entra.ErrInvalidClient, entra.ErrTransient, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := error(&entra.ExchangeError{Kind: tt.kind}) + // Also assert matching survives one layer of fmt.Errorf wrapping, + // the way callers propagate it. + wrapped := fmt.Errorf("obo: %w", err) + + for _, s := range allSentinels { + if tt.want != nil && errors.Is(tt.want, s) { + assert.ErrorIs(t, err, s) + assert.ErrorIs(t, wrapped, s) + } else { + assert.NotErrorIs(t, err, s) + assert.NotErrorIs(t, wrapped, s) + } + } + }) + } +} + +func TestExchangeError_ErrorString(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + err *entra.ExchangeError + wantContain []string + }{ + { + name: "oauth error and description", + err: &entra.ExchangeError{Kind: entra.KindInvalidGrant, OAuthError: "invalid_grant", Description: "AADSTS50013", HTTPStatus: 400}, + wantContain: []string{"invalid grant", "invalid_grant", "AADSTS50013"}, + }, + { + name: "status only when body had no fields", + err: &entra.ExchangeError{Kind: entra.KindTransient, HTTPStatus: 503}, + wantContain: []string{"transient failure", "503"}, + }, + { + name: "transport failure with neither status nor body", + err: &entra.ExchangeError{Kind: entra.KindTransient, Description: "unable to reach the token endpoint"}, + wantContain: []string{"transient failure", "unable to reach"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := tt.err.Error() + for _, want := range tt.wantContain { + assert.Contains(t, got, want) + } + }) + } +} + +func TestExchangeError_AsExtractsClaims(t *testing.T) { + t.Parallel() + + const claims = `{"access_token":{"acrs":{"essential":true}}}` + err := fmt.Errorf("wrapped: %w", &entra.ExchangeError{ + Kind: entra.KindInteractionRequired, + Claims: claims, + }) + + var exErr *entra.ExchangeError + require.ErrorAs(t, err, &exErr) + assert.Equal(t, claims, exErr.Claims) + assert.ErrorIs(t, err, entra.ErrInteractionRequired) +} diff --git a/pkg/auth/obo/entra/exchanger.go b/pkg/auth/obo/entra/exchanger.go new file mode 100644 index 0000000000..d8872bc310 --- /dev/null +++ b/pkg/auth/obo/entra/exchanger.go @@ -0,0 +1,513 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package entra + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" +) + +// OAuth grant-type and Entra parameter values for the on-behalf-of flow. +// +//nolint:gosec // G101: these are OAuth protocol identifiers, not credentials. +const ( + // grantTypeJWTBearer is the RFC 7523 JWT bearer grant type. Entra's + // on-behalf-of flow is the jwt-bearer grant plus requested_token_use. + grantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + + // requestedTokenUseOBO is the Entra-specific marker that turns the + // jwt-bearer grant into an on-behalf-of exchange. + requestedTokenUseOBO = "on_behalf_of" + + // bearerTokenType is the only token_type the OBO flow issues. The success + // path requires it (case-insensitively): the token is later presented as a + // Bearer credential, so accepting any other type would be unsafe. + bearerTokenType = "Bearer" +) + +const ( + // defaultAuthority is the public Microsoft Entra (Azure AD) authority. It is + // overridable via Config.Authority for sovereign clouds and tests. + defaultAuthority = "https://login.microsoftonline.com" + + // tokenEndpointPath is the v2.0 token endpoint path appended after the tenant. + tokenEndpointPath = "oauth2/v2.0/token" //nolint:gosec // G101: URL path segment, not a credential. + + // defaultHTTPTimeout bounds the whole exchange when the caller injects no + // HTTP client. Generous because federated IdP chains can be slow to respond. + defaultHTTPTimeout = 30 * time.Second + + // maxResponseBodySize caps how much of the token endpoint response is read, + // so a pathological server cannot exhaust memory. 1 MiB dwarfs any real + // token response. + maxResponseBodySize = 1 << 20 // 1 MiB +) + +// maxTenantLen caps the tenant identifier at the DNS name length limit; a +// verified-domain tenant cannot be longer, and a GUID is far shorter. +const maxTenantLen = 253 + +// Tenant identifier patterns: the Entra v2.0 endpoint addresses a tenant either +// by directory GUID or by verified domain (e.g. contoso.onmicrosoft.com). +// Validating up front turns a typo into a clear wiring-time error instead of an +// opaque 400/404 from Entra on the first exchange. +var ( + tenantGUIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + tenantDomainPattern = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`) +) + +// caInteractionCodes are the AADSTS error codes that signal a conditional-access +// / MFA challenge requiring interactive user action. The "interaction_required" +// OAuth error and a non-empty claims challenge are the primary signals; these +// codes catch responses that omit the OAuth error but still demand interaction. +var caInteractionCodes = map[int]struct{}{ + 50076: {}, // AADSTS50076: MFA required by the resource. + 50079: {}, // AADSTS50079: MFA enrolment required (proof-up). +} + +// Config is the Microsoft Entra confidential-client configuration for the OBO +// exchange. v1 supports client_secret authentication only; certificate and +// workload-identity client auth are planned fast-follows. +type Config struct { + // TenantID is the Entra tenant (directory) — a GUID or a verified domain. + // Required. + TenantID string + + // ClientID is the confidential client's application (client) ID. Required. + ClientID string + + // ClientSecret is the confidential client's secret. Required in v1. + ClientSecret string //nolint:gosec // G101: field name, not a hardcoded credential. + + // Authority overrides the Entra authority base URL. Defaults to + // https://login.microsoftonline.com. Must be https, except http is allowed + // for loopback hosts so tests can point at an httptest server. + Authority string + + // HTTPClient is the HTTP client used for the exchange. When nil, a client + // with a sane default timeout that refuses redirects is used. A + // caller-injected client SHOULD likewise refuse redirects: the request body + // carries client_secret and the user assertion, which Go replays on a + // 307/308 — including to a different host. A legitimate Entra token endpoint + // never redirects. + HTTPClient *http.Client +} + +// Exchanger performs the Microsoft Entra on-behalf-of token exchange. It +// implements both exchange.Exchanger (token string only) and exchange.TokenExchanger +// (token plus expiry, consumed by the caching layer). +// +// For the Entra provider the audience argument of Exchange / ExchangeToken is +// the OAuth scope to request — typically "/.default" or an explicit +// delegated scope such as "api:///Files.Read". It is sent verbatim as +// the request's scope parameter. +type Exchanger struct { + tokenURL string + clientID string + clientSecret string + httpClient *http.Client +} + +// Compile-time assertions that Exchanger satisfies both contracts. +var ( + _ exchange.Exchanger = (*Exchanger)(nil) + _ exchange.TokenExchanger = (*Exchanger)(nil) +) + +// New validates cfg and returns an Exchanger. It fails loudly on missing +// required fields or a malformed authority rather than deferring the failure to +// the first exchange. Configuration errors are returned as plain errors, not as +// *ExchangeError (which classifies exchange-time failures only). +func New(cfg Config) (*Exchanger, error) { + tokenURL, err := TokenURL(cfg.TenantID, cfg.Authority) + if err != nil { + return nil, err + } + if strings.TrimSpace(cfg.ClientID) == "" { + return nil, fmt.Errorf("entra obo: ClientID is required") + } + if cfg.ClientSecret == "" { + return nil, fmt.Errorf("entra obo: ClientSecret is required") + } + + return &Exchanger{ + tokenURL: tokenURL, + clientID: cfg.ClientID, + clientSecret: cfg.ClientSecret, + httpClient: newHTTPClient(cfg.HTTPClient), + }, nil +} + +// TokenURL builds and validates the Entra v2.0 on-behalf-of token endpoint for a +// tenant, applying exactly the rules New uses so the URL it returns is one +// NewFromTokenURL (the proxy-runtime constructor) will also accept. The operator's +// OBO validation calls this to derive the runtime contract's tokenUrl from the +// CRD's tenantId (and optional authority) rather than re-spelling Entra's +// authority/tenant/path structure — keeping that structure defined in one place. +// +// authority defaults to the public Microsoft Entra host when empty; a non-empty +// authority must be an https URL (http only for loopback) with a host and no query +// or fragment. tenantID must be a directory GUID or a verified domain name. Errors +// are plain errors that never contain a credential. +func TokenURL(tenantID, authority string) (string, error) { + tenant := strings.TrimSpace(tenantID) + if tenant == "" { + return "", fmt.Errorf("entra obo: TenantID is required") + } + if err := validateTenant(tenant); err != nil { + return "", err + } + + if authority == "" { + authority = defaultAuthority + } + if err := validateAuthority(authority); err != nil { + return "", err + } + + tokenURL, err := url.JoinPath(authority, tenant, tokenEndpointPath) + if err != nil { + return "", fmt.Errorf("entra obo: build token URL: %w", err) + } + return tokenURL, nil +} + +// NewFromTokenURL returns an Exchanger that posts the OBO exchange to a +// fully-formed tenant token endpoint. It is the constructor for callers that +// already hold the complete token URL — notably the proxy-runtime middleware, +// which receives tokenURL verbatim from the obo.MiddlewareParameters +// contract and must not re-derive Entra's authority/tenant URL structure. +// Use New instead when the caller holds an authority + tenant pair. +// +// tokenURL is validated exactly as New validates its derived endpoint: an +// absolute https URL (http permitted only for loopback hosts, so tests can point +// at an httptest server), with a host and no query string or fragment. clientID +// and clientSecret are required. A nil httpClient gets the same redirect-refusing +// default New uses. Configuration errors are returned as plain errors, not as +// *ExchangeError (which classifies exchange-time failures only). +// +// SECURITY: tokenURL is a trust boundary. The exchange POSTs the client secret +// and the end-user assertion in the request body to tokenURL, so the caller must +// supply only a trusted Entra token endpoint. This is safe because tokenURL comes +// from operator-controlled configuration (the obo.MiddlewareParameters contract), never +// from end-user input, and the unconditional redirect guard (see newHTTPClient) +// stops a 3xx from replaying that body to another host. This constructor +// intentionally does NOT allowlist hosts or enforce a path shape: New already +// trusts an operator-supplied Authority for arbitrary hosts (sovereign clouds), +// and a hard allowlist would reject legitimate sovereign / B2C / CIAM endpoints +// (which use different hosts and token paths) while giving only false assurance. +func NewFromTokenURL(tokenURL, clientID, clientSecret string, httpClient *http.Client) (*Exchanger, error) { + if strings.TrimSpace(tokenURL) == "" { + return nil, fmt.Errorf("entra obo: token URL is required") + } + if err := validateHTTPSURL(tokenURL, "token URL"); err != nil { + return nil, err + } + if strings.TrimSpace(clientID) == "" { + return nil, fmt.Errorf("entra obo: ClientID is required") + } + if clientSecret == "" { + return nil, fmt.Errorf("entra obo: ClientSecret is required") + } + + return &Exchanger{ + tokenURL: tokenURL, + clientID: clientID, + clientSecret: clientSecret, + httpClient: newHTTPClient(httpClient), + }, nil +} + +// newHTTPClient returns the client used for the exchange. The redirect guard is +// enforced unconditionally — including over a caller-injected client — because +// the POST body carries the client_secret and user assertion, which Go replays +// on a 307/308 (possibly to a different host) when redirects are followed. A +// real Entra token endpoint never redirects, so refusing them costs nothing. +// +// An injected client is shallow-copied so its Transport/Timeout/Jar are +// preserved while CheckRedirect is overridden, and the caller's own *http.Client +// is never mutated (it may be shared). The copy is a snapshot taken at New time. +func newHTTPClient(injected *http.Client) *http.Client { + if injected == nil { + return &http.Client{Timeout: defaultHTTPTimeout, CheckRedirect: refuseRedirects} + } + client := *injected + client.CheckRedirect = refuseRedirects + return &client +} + +// refuseRedirects is a http.Client.CheckRedirect that stops the client at the +// first response instead of following a redirect. +func refuseRedirects(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse +} + +// validateTenant accepts an Entra tenant identifier in the two forms the v2.0 +// endpoint uses — a directory GUID or a verified domain — capped at the DNS name +// length. It rejects junk (including the path metacharacters the previous, +// looser check caught) at wiring time. +func validateTenant(tenant string) error { + if len(tenant) > maxTenantLen { + return fmt.Errorf("entra obo: TenantID must be at most %d characters", maxTenantLen) + } + if tenantGUIDPattern.MatchString(tenant) || tenantDomainPattern.MatchString(tenant) { + return nil + } + return fmt.Errorf("entra obo: TenantID must be a directory GUID or a domain name") +} + +// Exchange implements exchange.Exchanger: it returns just the backend-scoped access +// token, discarding the expiry the caching layer would use. +func (e *Exchanger) Exchange(ctx context.Context, userToken, audience string) (string, error) { + token, err := e.ExchangeToken(ctx, userToken, audience) + if err != nil { + return "", err + } + return token.AccessToken, nil +} + +// ExchangeToken implements exchange.TokenExchanger: it performs the Entra OBO +// exchange and returns the backend-scoped token together with its expiry. +// +// Failures fall into three error shapes: +// - Argument validation (empty userToken or audience) returns a plain error, +// not an *ExchangeError — no exchange was attempted, so there is nothing to +// classify. +// - A cancelled or timed-out context returns the wrapped context error +// (matches with errors.Is(err, context.Canceled / context.DeadlineExceeded)). +// - An HTTP-level failure returns a typed *ExchangeError; use errors.As to read +// Kind / Claims, or errors.Is against the package sentinels. +// +// No returned error ever contains the subject token, client secret, or the +// issued access token. +func (e *Exchanger) ExchangeToken(ctx context.Context, userToken, audience string) (exchange.Token, error) { + if userToken == "" { + return exchange.Token{}, fmt.Errorf("entra obo: user token is required") + } + if audience == "" { + return exchange.Token{}, fmt.Errorf("entra obo: audience (scope) is required") + } + + req, err := e.buildRequest(ctx, userToken, audience) + if err != nil { + // Unreachable for a New-built Exchanger (the endpoint was validated), but + // classified rather than panicked on if it ever happens. + return exchange.Token{}, &ExchangeError{Kind: KindTransient, Description: "unable to build the token request"} + } + + resp, err := e.httpClient.Do(req) + if err != nil { + // Surface caller-driven cancellation/timeout as-is so it is not + // misclassified as a retryable server failure. + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return exchange.Token{}, fmt.Errorf("entra obo: %w", err) + } + // Transport-level failure (DNS, dial, TLS, read). The raw error is + // dropped deliberately: it is not needed to classify the failure as + // transient, and dropping it keeps the token endpoint URL out of logs. + return exchange.Token{}, &ExchangeError{Kind: KindTransient, Description: "unable to reach the token endpoint"} + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize)) + if err != nil { + return exchange.Token{}, &ExchangeError{ + Kind: KindTransient, + HTTPStatus: resp.StatusCode, + Description: "failed to read token endpoint response", + } + } + + return e.parseResponse(resp.StatusCode, body) +} + +// buildRequest assembles the Entra OBO POST. The subject token and client +// secret travel in the form body only. It returns an error rather than papering +// over a request-build failure: New validated the endpoint, so this is +// unreachable in practice, but the caller classifies any failure instead of +// risking a nil-pointer dereference. +func (e *Exchanger) buildRequest(ctx context.Context, userToken, audience string) (*http.Request, error) { + form := url.Values{} + form.Set("grant_type", grantTypeJWTBearer) + form.Set("client_id", e.clientID) + form.Set("client_secret", e.clientSecret) + form.Set("assertion", userToken) + form.Set("scope", audience) + form.Set("requested_token_use", requestedTokenUseOBO) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.tokenURL, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + return req, nil +} + +// tokenResponse is the wire shape of an Entra token endpoint reply. It covers +// both the success and error payloads: per RFC 6749 Section 5.2 an "error" can +// appear even with a 2xx status, so the body is decoded once and the error +// fields are inspected regardless of status. +type tokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + Scope string `json:"scope"` + + Error string `json:"error"` + ErrorDescription string `json:"error_description"` + ErrorCodes []int `json:"error_codes"` + Claims string `json:"claims"` +} + +// parseResponse turns a decoded token endpoint reply into a Token or a typed +// error. It is a method only so the success path can stamp the expiry against +// the wall clock; it holds no per-request state. +func (*Exchanger) parseResponse(status int, body []byte) (exchange.Token, error) { + var tr tokenResponse + if err := json.Unmarshal(body, &tr); err != nil { + // Unparseable body: classify by status alone, without echoing the body. + kind := KindUnknown + if status >= http.StatusInternalServerError { + kind = KindTransient + } + return exchange.Token{}, &ExchangeError{ + Kind: kind, + HTTPStatus: status, + Description: "malformed token endpoint response", + } + } + + // Treat a non-2xx status OR an error field in a 2xx body as a failure. + if status < 200 || status > 299 || tr.Error != "" { + return exchange.Token{}, classifyHTTPError(status, &tr) + } + + if tr.AccessToken == "" { + return exchange.Token{}, &ExchangeError{ + Kind: KindUnknown, + HTTPStatus: status, + Description: "token response missing access_token", + } + } + + // RFC 6749 Section 5.1 / RFC 8693 Section 2.2.1 require token_type. The token + // is presented as a Bearer credential, so reject a missing or non-Bearer + // type rather than trusting a mangled 2xx. + if !strings.EqualFold(tr.TokenType, bearerTokenType) { + return exchange.Token{}, &ExchangeError{ + Kind: KindUnknown, + HTTPStatus: status, + Description: "token response has a missing or non-Bearer token_type", + } + } + + var expiry time.Time + if tr.ExpiresIn > 0 { + expiry = time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second) + } + return exchange.Token{AccessToken: tr.AccessToken, Expiry: expiry}, nil +} + +// classifyHTTPError maps an Entra error reply onto an *ExchangeError. A 5xx is +// transient regardless of body; otherwise the OAuth error code and claims +// challenge drive the classification. +func classifyHTTPError(status int, tr *tokenResponse) *ExchangeError { + kind := func() ErrorKind { + switch { + case status >= http.StatusInternalServerError: + return KindTransient + case isInteractionRequired(tr): + return KindInteractionRequired + case tr.Error == "invalid_grant": + return KindInvalidGrant + case tr.Error == "invalid_client" || tr.Error == "unauthorized_client": + return KindInvalidClient + default: + return KindUnknown + } + }() + + return &ExchangeError{ + Kind: kind, + OAuthError: tr.Error, + Description: tr.ErrorDescription, + Claims: tr.Claims, + HTTPStatus: status, + } +} + +// isInteractionRequired reports whether an Entra error reply is a +// conditional-access / MFA / claims challenge. The canonical signals are the +// "interaction_required" OAuth error and a non-empty claims challenge; the +// AADSTS code set is a fallback for replies that carry neither. +func isInteractionRequired(tr *tokenResponse) bool { + if tr.Error == "interaction_required" || tr.Claims != "" { + return true + } + for _, code := range tr.ErrorCodes { + if _, ok := caInteractionCodes[code]; ok { + return true + } + } + return false +} + +// validateAuthority enforces that the authority is an absolute https URL (http +// permitted only for loopback hosts, so tests can use httptest), with a host and +// no fragment or query string. +func validateAuthority(raw string) error { + return validateHTTPSURL(raw, "Authority") +} + +// validateHTTPSURL enforces that raw is an absolute https URL (http permitted +// only for loopback hosts, so tests can use httptest), with a host and no +// fragment or query string. label names the field in error messages so the same +// check serves both the authority (New) and the full token URL (NewFromTokenURL). +func validateHTTPSURL(raw, label string) error { + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("entra obo: %s is not a valid URL: %w", label, err) + } + if u.Host == "" { + return fmt.Errorf("entra obo: %s must include a host", label) + } + if u.Fragment != "" { + return fmt.Errorf("entra obo: %s must not contain a fragment", label) + } + if u.RawQuery != "" { + return fmt.Errorf("entra obo: %s must not contain a query string", label) + } + switch u.Scheme { + case "https": + return nil + case "http": + if isLoopbackHost(u.Hostname()) { + return nil + } + return fmt.Errorf("entra obo: %s must use https (http allowed only for loopback)", label) + default: + return fmt.Errorf("entra obo: %s scheme must be https (got %q)", label, u.Scheme) + } +} + +// isLoopbackHost reports whether host is localhost or a loopback IP literal. +func isLoopbackHost(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} diff --git a/pkg/auth/obo/entra/exchanger_test.go b/pkg/auth/obo/entra/exchanger_test.go new file mode 100644 index 0000000000..d360262bbe --- /dev/null +++ b/pkg/auth/obo/entra/exchanger_test.go @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package entra_test + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/auth/obo/entra" +) + +const ( + testTenant = "contoso.onmicrosoft.com" + testClientID = "test-client-id" + testClientSecret = "test-client-secret-VALUE" + testUserToken = "test.user.assertion-SECRET-VALUE" + testAudience = "api://backend/.default" + testAccessToken = "ISSUED-BACKEND-ACCESS-TOKEN" + + wireGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer" + wireRequestedTokenUse = "on_behalf_of" + wireTokenEndpointPath = "/contoso.onmicrosoft.com/oauth2/v2.0/token" + successResponseExpires = 3599 +) + +// newTestExchanger returns an Exchanger pointed at authority (an httptest URL). +func newTestExchanger(t *testing.T, authority string) *entra.Exchanger { + t.Helper() + ex, err := entra.New(entra.Config{ + TenantID: testTenant, + ClientID: testClientID, + ClientSecret: testClientSecret, + Authority: authority, + }) + require.NoError(t, err) + return ex +} + +// captured records what the stub token endpoint observed. It is delivered over a +// buffered channel so the assertions read it with a happens-before guarantee +// (race-detector clean) rather than racing the server goroutine. +type captured struct { + method string + path string + contentType string + form url.Values +} + +func TestExchanger_ExchangeToken_Success(t *testing.T) { + t.Parallel() + + ch := make(chan captured, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + ch <- captured{ + method: r.Method, + path: r.URL.Path, + contentType: r.Header.Get("Content-Type"), + form: r.PostForm, + } + w.Header().Set("Content-Type", "application/json") + // Build the body from the constant so the wire value and the expiry + // assertion below share a single source of truth. + _, _ = io.WriteString(w, fmt.Sprintf( + `{"token_type":"Bearer","scope":%q,"expires_in":%d,"ext_expires_in":%d,"access_token":%q}`, + testAudience, successResponseExpires, successResponseExpires, testAccessToken)) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + + start := time.Now() + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + require.NoError(t, err) + + assert.Equal(t, testAccessToken, tok.AccessToken) + assert.WithinDuration(t, start.Add(successResponseExpires*time.Second), tok.Expiry, 5*time.Second, + "expiry must be derived from expires_in") + + got := <-ch + assert.Equal(t, http.MethodPost, got.method) + assert.Equal(t, wireTokenEndpointPath, got.path) + assert.Contains(t, got.contentType, "application/x-www-form-urlencoded") + + // The exact Entra OBO request shape. + assert.Equal(t, wireGrantType, got.form.Get("grant_type")) + assert.Equal(t, testClientID, got.form.Get("client_id")) + assert.Equal(t, testClientSecret, got.form.Get("client_secret")) + assert.Equal(t, testUserToken, got.form.Get("assertion")) + assert.Equal(t, testAudience, got.form.Get("scope"), "audience argument is sent as the scope parameter") + assert.Equal(t, wireRequestedTokenUse, got.form.Get("requested_token_use")) +} + +func TestExchanger_Exchange_ReturnsAccessTokenOnly(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"token_type":"Bearer","expires_in":3599,"access_token":"`+testAccessToken+`"}`) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + token, err := ex.Exchange(t.Context(), testUserToken, testAudience) + require.NoError(t, err) + assert.Equal(t, testAccessToken, token) +} + +func TestExchanger_Exchange_PropagatesError(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":"invalid_grant","error_description":"AADSTS50013"}`) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + token, err := ex.Exchange(t.Context(), testUserToken, testAudience) + require.Error(t, err) + assert.Empty(t, token) + assert.ErrorIs(t, err, entra.ErrInvalidGrant) +} + +func TestExchanger_ExchangeToken_NoExpiryWhenExpiresInAbsent(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"token_type":"Bearer","access_token":"`+testAccessToken+`"}`) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + require.NoError(t, err) + assert.Equal(t, testAccessToken, tok.AccessToken) + assert.True(t, tok.Expiry.IsZero(), "missing expires_in yields a zero (non-cacheable) expiry") +} + +func TestExchanger_ExchangeToken_Failures(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + status int + body string + wantKind entra.ErrorKind + wantSentinel error // nil means: matches none of the sentinels + wantClaims string + }{ + { + name: "interaction required via OAuth error and claims challenge", + status: http.StatusBadRequest, + body: `{"error":"interaction_required","error_description":"AADSTS50079: proof-up required","claims":"{\"access_token\":{\"acrs\":{\"essential\":true}}}"}`, + wantKind: entra.KindInteractionRequired, + wantSentinel: entra.ErrInteractionRequired, + wantClaims: `{"access_token":{"acrs":{"essential":true}}}`, + }, + { + name: "interaction required via AADSTS code without OAuth error", + status: http.StatusBadRequest, + body: `{"error":"invalid_grant","error_description":"AADSTS50076: MFA required","error_codes":[50076]}`, + wantKind: entra.KindInteractionRequired, + wantSentinel: entra.ErrInteractionRequired, + }, + { + name: "invalid grant", + status: http.StatusBadRequest, + body: `{"error":"invalid_grant","error_description":"AADSTS50013: assertion is expired"}`, + wantKind: entra.KindInvalidGrant, + wantSentinel: entra.ErrInvalidGrant, + }, + { + name: "invalid client", + status: http.StatusUnauthorized, + body: `{"error":"invalid_client","error_description":"AADSTS7000215: invalid client secret"}`, + wantKind: entra.KindInvalidClient, + wantSentinel: entra.ErrInvalidClient, + }, + { + name: "unauthorized client maps to invalid client", + status: http.StatusBadRequest, + body: `{"error":"unauthorized_client","error_description":"AADSTS700016: app not found"}`, + wantKind: entra.KindInvalidClient, + wantSentinel: entra.ErrInvalidClient, + }, + { + name: "transient 5xx with JSON body", + status: http.StatusServiceUnavailable, + body: `{"error":"temporarily_unavailable","error_description":"AADSTS90033: transient error"}`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "transient 5xx with non-JSON body", + status: http.StatusBadGateway, + body: `502 Bad Gateway`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "unrecognised 4xx error is permanent unknown", + status: http.StatusBadRequest, + body: `{"error":"some_unmodelled_error","error_description":"AADSTS99999: brand new"}`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, + { + name: "2xx body missing access_token", + status: http.StatusOK, + body: `{"token_type":"Bearer","expires_in":3599}`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, + { + name: "2xx body missing token_type", + status: http.StatusOK, + body: `{"access_token":"x","expires_in":3599}`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, + { + name: "2xx body with non-Bearer token_type", + status: http.StatusOK, + body: `{"access_token":"x","token_type":"mac","expires_in":3599}`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, + { + name: "malformed 2xx JSON body", + status: http.StatusOK, + body: `{not valid json`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tt.status) + _, _ = io.WriteString(w, tt.body) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + + require.Error(t, err) + assert.Empty(t, tok.AccessToken) + + var exErr *entra.ExchangeError + require.ErrorAs(t, err, &exErr) + assert.Equal(t, tt.wantKind, exErr.Kind) + assert.Equal(t, tt.status, exErr.HTTPStatus) + assert.Equal(t, tt.wantClaims, exErr.Claims) + + if tt.wantSentinel != nil { + assert.ErrorIs(t, err, tt.wantSentinel) + } else { + // KindUnknown must not masquerade as any classified failure. + for _, s := range []error{ + entra.ErrInteractionRequired, entra.ErrInvalidGrant, + entra.ErrInvalidClient, entra.ErrTransient, + } { + assert.NotErrorIs(t, err, s) + } + } + + // No secret material may appear in the error string. + assert.NotContains(t, err.Error(), testUserToken) + assert.NotContains(t, err.Error(), testClientSecret) + assert.NotContains(t, err.Error(), testAccessToken) + }) + } +} + +func TestExchanger_ExchangeToken_CapsResponseBody(t *testing.T) { + t.Parallel() + + // A >1 MiB body whose valid-JSON prefix is followed by megabytes of padding. + // The 1 MiB LimitReader truncates it mid-stream, so the decode fails and the + // result is classified as a malformed (unknown) response rather than hanging + // or exhausting memory. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"`+testAccessToken+`","expires_in":3599,"pad":"`) + pad := make([]byte, 2<<20) // 2 MiB, past the 1 MiB cap + for i := range pad { + pad[i] = 'A' + } + _, _ = w.Write(pad) + _, _ = io.WriteString(w, `"}`) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + _, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + + require.Error(t, err) + var exErr *entra.ExchangeError + require.ErrorAs(t, err, &exErr) + assert.Equal(t, entra.KindUnknown, exErr.Kind, "a truncated body is a malformed response") + assert.NotContains(t, err.Error(), testAccessToken) +} + +func TestExchanger_ExchangeToken_TransientOnTransportFailure(t *testing.T) { + t.Parallel() + + // A server that is closed immediately forces a dial failure. + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + authority := srv.URL + srv.Close() + + ex := newTestExchanger(t, authority) + _, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + + require.Error(t, err) + assert.ErrorIs(t, err, entra.ErrTransient) + assert.NotContains(t, err.Error(), testUserToken) + assert.NotContains(t, err.Error(), testClientSecret) +} + +func TestExchanger_ExchangeToken_ContextCancelledPropagates(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"`+testAccessToken+`","expires_in":3599}`) + })) + t.Cleanup(srv.Close) + + ctx, cancel := context.WithCancel(t.Context()) + cancel() // cancelled before the call begins + + ex := newTestExchanger(t, srv.URL) + _, err := ex.ExchangeToken(ctx, testUserToken, testAudience) + + require.Error(t, err) + assert.ErrorIs(t, err, context.Canceled, "caller cancellation surfaces, not a transient classification") + assert.NotErrorIs(t, err, entra.ErrTransient) +} + +func TestNew_EnforcesRedirectGuardOnInjectedClient(t *testing.T) { + t.Parallel() + + var redirectFollowed atomic.Bool + mux := http.NewServeMux() + mux.HandleFunc("/leaked", func(w http.ResponseWriter, _ *http.Request) { + // Reached only if the 307 was followed, replaying the secret-bearing body. + redirectFollowed.Store(true) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"leaked","token_type":"Bearer","expires_in":3599}`) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/leaked", http.StatusTemporaryRedirect) // 307 preserves the POST body + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + // Inject a client that, left alone, would follow redirects (nil CheckRedirect). + ex, err := entra.New(entra.Config{ + TenantID: testTenant, + ClientID: testClientID, + ClientSecret: testClientSecret, + Authority: srv.URL, + HTTPClient: &http.Client{}, + }) + require.NoError(t, err) + + _, err = ex.ExchangeToken(t.Context(), testUserToken, testAudience) + require.Error(t, err) // the 307 itself is not a usable token response + assert.False(t, redirectFollowed.Load(), + "New must enforce the no-redirect guard even on a caller-injected client") +} + +func TestExchanger_ExchangeToken_RejectsEmptyArguments(t *testing.T) { + t.Parallel() + + // No server is contacted; these fail before any request is built. + ex := newTestExchanger(t, "https://login.microsoftonline.com") + + _, err := ex.ExchangeToken(t.Context(), "", testAudience) + require.Error(t, err) + + _, err = ex.ExchangeToken(t.Context(), testUserToken, "") + require.Error(t, err) +} diff --git a/pkg/auth/obo/errors.go b/pkg/auth/obo/errors.go index 8b51056028..5041405a32 100644 --- a/pkg/auth/obo/errors.go +++ b/pkg/auth/obo/errors.go @@ -5,48 +5,37 @@ package obo import "errors" -// ErrEnterpriseRequired is returned by every default OBO dispatch point — the -// controllerutil handler hook, the vMCP converter stub, and the middleware -// stub — when no out-of-tree handler/factory has been registered. Callers must -// use errors.Is to compare; the error wraps cleanly through -// fmt.Errorf("...: %w", ...). +// ErrEnterpriseRequired was returned by the OBO dispatch points before OBO +// shipped in ToolHive itself. No code path in this module returns it any more. // -// Lives in pkg/auth/obo (a leaf package) so that callers in -// cmd/thv-operator/... and pkg/vmcp/... can share the same sentinel without -// either layer importing the other. To register an out-of-tree handler, see -// controllerutil.RegisterOBOHandler (for the operator dispatch points) and -// obo.RegisterFactory (for the proxy middleware factory). +// Deprecated: OBO is built in. The sentinel is kept only so out-of-tree code +// that still references it keeps compiling; it will be removed in a future +// release. var ErrEnterpriseRequired = errors.New( "on-behalf-of (OBO) external auth type requires an enterprise build") -// ValidationError is the typed error an OBO handler returns when its input -// is genuinely malformed and the user must fix the spec for the failure to -// clear. It is the contract for the "permanent, user-fix" bucket in the -// OBOHandler error triage: +// ValidationError is the typed error OBO validation returns when its input is +// genuinely malformed and the user must fix the spec for the failure to clear. +// It is the contract for the "permanent, user-fix" bucket the operator's OBO +// error triage applies: // -// - errors.Is(err, ErrEnterpriseRequired) → not licensed; permanent until an -// out-of-tree handler is registered. -// - errors.As(err, &*ValidationError) → permanent until the user edits the +// - errors.As(err, &*ValidationError): permanent until the user edits the // spec; the operator writes condition.Reason=InvalidConfig and does not // requeue. -// - anything else → treated as transient by the reconciler, which returns -// the error so controller-runtime requeues with backoff. +// - anything else: treated as transient by the reconciler, which returns the +// error so controller-runtime requeues with backoff. // -// Handler authors must use ValidationError for any condition the user can -// fix by editing the spec (missing field, malformed URL, schema violation) -// and must return a non-ValidationError for transient I/O failures (Secret -// not yet available, JWKS unreachable, webhook 5xx) so the reconciler -// retries instead of locking the resource into a permanent InvalidConfig -// state. +// Use ValidationError for any condition the user can fix by editing the spec +// (missing field, malformed URL, schema violation), and a plain error for +// transient I/O failures (Secret not yet available) so the reconciler retries +// instead of locking the resource into a permanent InvalidConfig state. // -// The Message field is written verbatim into condition.Message — handler -// authors are responsible for ensuring it is safe to expose (no Secret -// names, no internal addressing, no credential fragments). +// The Message field is written verbatim into condition.Message, so it must be +// safe to expose (no Secret names, no internal addressing, no credential +// fragments). type ValidationError struct { Message string } -// Error returns the user-facing message verbatim. The OBO branch in the -// MCPExternalAuthConfig reconciler writes this string into the Valid -// condition's Message field. +// Error returns the user-facing message verbatim. func (e *ValidationError) Error() string { return e.Message } diff --git a/pkg/auth/obo/errors_test.go b/pkg/auth/obo/errors_test.go index 261787ee04..4647e75d2d 100644 --- a/pkg/auth/obo/errors_test.go +++ b/pkg/auth/obo/errors_test.go @@ -12,39 +12,21 @@ import ( "github.com/stretchr/testify/require" ) -func TestErrEnterpriseRequired_IsSentinel(t *testing.T) { - t.Parallel() - - // Wrapping the sentinel and unwrapping with errors.Is must work both - // directly and through fmt.Errorf("...: %w", ...). - wrapped := fmt.Errorf("outer wrap: %w", ErrEnterpriseRequired) - assert.ErrorIs(t, wrapped, ErrEnterpriseRequired) -} - func TestValidationError_ErrorAndAsThroughWrap(t *testing.T) { t.Parallel() original := &ValidationError{Message: "audience must be a non-empty URL"} - // Error() returns the Message verbatim — the reconciler writes this - // string into condition.Message, so handler authors control the - // kubectl-describe output through this field. + // Error() returns the Message verbatim: the reconciler writes this string + // into condition.Message. assert.Equal(t, "audience must be a non-empty URL", original.Error()) - // errors.As must match the typed error through a fmt.Errorf wrap so - // handler authors can wrap with extra context without breaking the - // reconciler's triage. + // errors.As must match the typed error through a fmt.Errorf wrap so callers + // can add context without breaking the reconciler's triage. wrapped := fmt.Errorf("validating obo spec: %w", original) var got *ValidationError require.True(t, errors.As(wrapped, &got), "errors.As must match *ValidationError through a fmt.Errorf wrap") assert.Same(t, original, got, "errors.As must return the same pointer that was wrapped") - - // errors.Is(err, ErrEnterpriseRequired) must NOT match a ValidationError - // — they live in different buckets of the OBOHandler error contract. - assert.False(t, errors.Is(original, ErrEnterpriseRequired), - "ValidationError must not be confused with the EnterpriseRequired sentinel") - assert.False(t, errors.Is(wrapped, ErrEnterpriseRequired), - "wrapped ValidationError must not be confused with the EnterpriseRequired sentinel") } diff --git a/pkg/auth/obo/exchange/exchange.go b/pkg/auth/obo/exchange/exchange.go new file mode 100644 index 0000000000..74bce8f6f6 --- /dev/null +++ b/pkg/auth/obo/exchange/exchange.go @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package exchange defines the provider-agnostic contract for an on-behalf-of +// (OBO) token exchange: the Exchanger and TokenExchanger interfaces, the Token +// result, and the rule that collapses an audience/scopes pair into the single +// exchange target a provider receives. +// +// It is a stdlib-only leaf so that the provider (pkg/auth/obo/entra), the cache +// decorator (pkg/auth/obo/cache), the proxy middleware (pkg/auth/obo), and the +// vMCP strategy can all share it without an import cycle and without linking +// Kubernetes code into the proxyrunner. +package exchange + +import ( + "context" + "strings" + "time" +) + +// Exchanger swaps an incoming end-user token for a backend-scoped token, +// presented to the upstream MCP server on behalf of the user. +// +// The audience parameter is a provider-defined target identifier for the +// backend the token is minted for. The Entra implementation sends it verbatim +// as the OAuth scope (typically "/.default"). It is opaque to the +// cache decorator, which only uses it to partition entries. Callers derive it +// with Target so every surface sends the provider the same value for the same +// configuration. +type Exchanger interface { + // Exchange returns the backend-scoped token to present to the upstream MCP + // server on behalf of the user identified by userToken, for the given + // audience, or an error. + // + // Implementations MUST NOT include the user token, the issued backend token, + // or any provider secret in the returned error, so callers may safely log it. + Exchange(ctx context.Context, userToken, audience string) (string, error) +} + +// Token is the result of a single on-behalf-of exchange: the backend-scoped +// access token together with the instant it expires. +// +// A zero Expiry means the provider did not report a lifetime. Callers, and the +// caching layer in particular, MUST treat such a token as non-cacheable: there +// is no safe point at which to consider it stale, so it is used once and never +// stored. +type Token struct { + // AccessToken is the backend-scoped bearer token to present to the upstream + // MCP server on behalf of the user. + AccessToken string + + // Expiry is the absolute instant the AccessToken stops being valid, derived + // from the provider's expires_in. The zero value means "lifetime unknown". + Expiry time.Time +} + +// TokenExchanger is the provider-facing contract that backs Exchanger. A +// provider returns the exchanged Token (access token plus expiry) so that a +// caching decorator can honour the provider's expires_in. Exchanger hides the +// expiry because its callers only ever want a token that is valid right now. +// +// Adding a new identity provider means adding a new TokenExchanger +// implementation; the middleware, the vMCP strategy, and the cache decorator +// are unchanged. +type TokenExchanger interface { + // ExchangeToken returns the backend-scoped Token for the user identified by + // userToken and the given audience (see Exchanger), or an error. + ExchangeToken(ctx context.Context, userToken, audience string) (Token, error) +} + +// Target collapses a configuration's distinct audience and scopes fields onto +// the single value an Exchanger takes as its audience argument. Space-joined +// scopes win when present (the Entra-native form, e.g. +// "api:///.default"); otherwise the trimmed audience is used. An empty +// result means neither was usefully set. +// +// This is the one implementation of the collapse rule. The proxy middleware, +// the operator validation, the vMCP converter, and the vMCP strategy all call +// it, so identical configuration yields the same provider scope and the same +// cache partition on every surface. +func Target(audience string, scopes []string) string { + if joined := strings.TrimSpace(strings.Join(scopes, " ")); joined != "" { + return joined + } + return strings.TrimSpace(audience) +} diff --git a/pkg/auth/obo/middleware.go b/pkg/auth/obo/middleware.go index 60ea79da98..f8b030b92a 100644 --- a/pkg/auth/obo/middleware.go +++ b/pkg/auth/obo/middleware.go @@ -1,16 +1,44 @@ // SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. // SPDX-License-Identifier: Apache-2.0 -// Package obo provides the proxy-runtime middleware factory hook for the -// on-behalf-of (OBO) external auth type. The default factory produces a -// stub middleware that responds 503 to every request. An out-of-tree build -// replaces the factory by calling RegisterFactory once during init(). +// Package obo implements the proxy-runtime middleware for the on-behalf-of +// (OBO) external auth type. +// +// Per request the middleware takes the OBO subject (assertion) token from the +// authenticated Identity that the authentication middleware placed in the +// request context, exchanges it through a cached Microsoft Entra on-behalf-of +// Exchanger for a backend-scoped token, sets Authorization: Bearer on the upstream request, and calls the downstream handler. The +// subject comes from one of two Identity sources, selected by +// MiddlewareParameters.SubjectTokenProviderName: the inbound token the client +// presented (Identity.Token, the default) or a named upstream provider's token +// (Identity.UpstreamTokens[name], when an embedded auth server fronts the +// proxy). On a conditional-access or claims challenge it fails fast with a +// generic 403 and an audit record, and the downstream handler is not called. +// +// The package, together with pkg/auth/obo/entra, pkg/auth/obo/cache, and +// pkg/auth/obo/exchange, is kept free of controller-runtime, client-go, and the +// operator API types, because the proxyrunner links it. A test in this package +// enforces that. package obo import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net" "net/http" + "os" "sync" + "time" + "github.com/stacklok/toolhive/pkg/audit" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo/cache" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" "github.com/stacklok/toolhive/pkg/transport/types" ) @@ -18,66 +46,54 @@ import ( // OBO middleware. Matches the ExternalAuthType constant value "obo". const MiddlewareType = "obo" -// stubMessage is the body returned by the default 503 handler. It is shared -// between the default handler and tests in this package so the exact literal -// is only spelled once. Unexported because no caller outside this package has -// a use for it — tests reference it directly. -const stubMessage = "obo requires a build with a registered OBO middleware factory" - -// stub is the default Middleware implementation. Its handler responds 503 -// with a body explaining that the OBO middleware factory has not been -// registered. It is never instantiated except by the default CreateMiddleware -// factory, which an out-of-tree build replaces via RegisterFactory. -type stub struct{} - -// Handler returns a MiddlewareFunction that wraps any downstream handler with -// a 503 response. The downstream handler is intentionally never called — the -// stub is the user-visible signal that the OBO middleware factory has not -// been registered. -func (*stub) Handler() types.MiddlewareFunction { - return func(http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - http.Error(w, stubMessage, http.StatusServiceUnavailable) - }) - } -} +const ( + // authorizationHeader is the upstream header the exchanged backend token is + // written to. bearerPrefix is its RFC 6750 scheme. + authorizationHeader = "Authorization" + bearerPrefix = "Bearer " +) + +// The handler's response bodies are intentionally generic: they are visible to +// any caller, so they must not disclose the provider error, the claims +// challenge, or any configuration detail. +const ( + // unauthorizedMessage is returned (401) when there is no authenticated + // identity, no subject token on it, or the IdP rejected the subject token + // (invalid_grant). + unauthorizedMessage = "missing or invalid user token" + + // forbiddenMessage is returned (403) on a fail-fast conditional-access or + // claims challenge. + forbiddenMessage = "OBO token exchange denied" + + // badGatewayMessage is returned (502) when the proxy could not obtain a + // backend token for a reason that is not the caller's fault: a + // confidential-client misconfiguration (invalid_client), a transient IdP + // failure, or an unclassified error. + badGatewayMessage = "OBO token exchange unavailable" +) -// Close is a no-op for the stub middleware. -func (*stub) Close() error { return nil } +const ( + // AuditEventType is the AuditEvent.Type for an OBO exchange decision. The + // proxy middleware and the vMCP strategy both emit it. + AuditEventType = "obo_token_exchange" -// factoryMu guards reads and writes of currentFactory. Each call to -// CreateMiddleware takes the read lock; RegisterFactory takes the write lock. -// The mutex makes hot-reload / re-registration safe in case a future caller -// (e.g. an admission webhook) wires it up, even though production today only -// ever writes during init(). + // auditComponent identifies the OBO proxy middleware as the source + // component of the audit record. + auditComponent = "toolhive-obo" +) + +// factoryMu guards reads and writes of currentFactory. var factoryMu sync.RWMutex -// currentFactory holds the actual middleware factory dispatched to by -// CreateMiddleware. The default returns a 503 stub; an out-of-tree build -// replaces it via RegisterFactory. +// currentFactory holds the factory CreateMiddleware dispatches to. It is the +// built-in DefaultFactory unless out-of-tree code replaced it through the +// deprecated RegisterFactory. var currentFactory types.MiddlewareFactory = DefaultFactory -// DefaultFactory adds a stub middleware whose handler responds 503 to every -// request. Exposed primarily so external test code (e.g. pkg/runner) can pass -// it to RegisterFactory in a t.Cleanup to restore the package's default -// behavior after a test mutates currentFactory. -func DefaultFactory(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error { - runner.AddMiddleware(config.Type, &stub{}) - return nil -} - -// CreateMiddleware is the package-level middleware factory. It is a stable -// indirection over currentFactory: each call dispatches to whatever factory -// is registered at call time, so out-of-tree builds replacing the factory -// via RegisterFactory take effect on subsequent calls even if a caller has -// already captured CreateMiddleware itself (e.g. pkg/runner builds its -// factory map once and reuses it across runner instances). The default -// produces a 503 stub. -// -// Declared as a function (matching sibling middleware packages such as -// awssts, upstreamswap, and tokenexchange) so RegisterFactory is -// the only mutation path — there is no second escape hatch via direct -// assignment to CreateMiddleware. +// CreateMiddleware is the package-level OBO middleware factory registered in +// the runner's middleware factory map. It dispatches to DefaultFactory unless +// a replacement was registered through RegisterFactory. func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error { factoryMu.RLock() f := currentFactory @@ -85,12 +101,12 @@ func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRun return f(config, runner) } -// RegisterFactory replaces the underlying middleware factory. Calling it -// more than once is allowed and last-write-wins, matching the existing -// pkg/config.RegisterProviderFactory precedent. Panics if f is nil — a nil -// factory would dispatch into a nil function on the next CreateMiddleware -// call, far from the registration site; surface the problem at init() time -// instead. +// RegisterFactory replaces the factory CreateMiddleware dispatches to. +// Last-write-wins. Panics if f is nil. +// +// Deprecated: OBO is built in and DefaultFactory is the implementation. +// RegisterFactory is kept only so out-of-tree code that still calls it keeps +// compiling; it will be removed in a future release. func RegisterFactory(f types.MiddlewareFactory) { if f == nil { panic("obo.RegisterFactory: factory is nil") @@ -99,3 +115,238 @@ func RegisterFactory(f types.MiddlewareFactory) { defer factoryMu.Unlock() currentFactory = f } + +// DefaultFactory is the built-in OBO middleware factory. It parses the +// MiddlewareParameters contract, reads the client secret from the named +// environment variable, builds the cached Entra Exchanger, and installs the +// middleware under the config's type name. It fails loudly at startup +// (returns an error, installs nothing) on malformed parameters or a missing +// secret rather than deferring the failure to the first request. +func DefaultFactory(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error { + params, err := parseParameters(config.Parameters) + if err != nil { + return err + } + + // The operator injects the secret value into the pod under this name; only + // the name travels in the contract. The error names the env var (not its + // value) so a missing injection is diagnosable. + secret := os.Getenv(params.ClientSecretEnvVar) + if secret == "" { + return fmt.Errorf("obo middleware: client secret env var %q is empty or unset", params.ClientSecretEnvVar) + } + + exchanger, err := entra.NewFromTokenURL(params.TokenURL, params.ClientID, secret, nil) + if err != nil { + return fmt.Errorf("obo middleware: build entra exchanger: %w", err) + } + + var opts []cache.Option + if params.CacheSkewSeconds > 0 { + opts = append(opts, cache.WithSkew(time.Duration(params.CacheSkewSeconds)*time.Second)) + } + + mw := newMiddleware(cache.New(exchanger, opts...), params.SubjectTokenProviderName, params.ExchangeTarget(), nil) + runner.AddMiddleware(config.Type, mw) + return nil +} + +// middleware exchanges the authenticated user's token for a backend-scoped +// token on every request and presents it upstream as Authorization: Bearer. +type middleware struct { + exchanger exchange.Exchanger + providerName string + exchangeTarget string + auditLogger *slog.Logger +} + +// newMiddleware constructs the middleware from an already-built Exchanger. An +// empty providerName selects the inbound-token source; a non-empty one selects +// that upstream provider's token. A nil auditLogger gets the default JSON +// audit logger. +func newMiddleware(exchanger exchange.Exchanger, providerName, exchangeTarget string, auditLogger *slog.Logger) *middleware { + if auditLogger == nil { + auditLogger = audit.NewAuditLogger(nil) + } + return &middleware{ + exchanger: exchanger, + providerName: providerName, + exchangeTarget: exchangeTarget, + auditLogger: auditLogger, + } +} + +// Handler returns a MiddlewareFunction that performs the per-request OBO +// exchange. On success it sets Authorization: Bearer and calls +// downstream; on failure it short-circuits with a generic 401, 403, or 502 and +// never calls downstream. +func (m *middleware) Handler() types.MiddlewareFunction { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // subjectToken writes the failure response itself when absent. + userToken, ok := m.subjectToken(w, r) + if !ok { + return + } + + backendToken, err := m.exchanger.Exchange(r.Context(), userToken, m.exchangeTarget) + if err != nil { + m.writeExchangeError(w, r, err) + return + } + + // Overwrite Authorization with the backend-scoped token so the raw + // subject token never reaches the backend. + r.Header.Set(authorizationHeader, bearerPrefix+backendToken) + next.ServeHTTP(w, r) + }) + } +} + +// Close is a no-op: the cache holds no resource that needs releasing (it runs +// no background goroutine beyond the per-exchange flight). +func (*middleware) Close() error { return nil } + +// subjectToken resolves the OBO subject (assertion) from the request's +// authenticated Identity. Inbound mode uses Identity.Token; upstream-provider +// mode uses Identity.UpstreamTokens[name]. On failure it writes a 401 (with a +// re-auth challenge for a missing provider token, mirroring upstreamswap) and +// returns ok=false. +func (m *middleware) subjectToken(w http.ResponseWriter, r *http.Request) (string, bool) { + identity, ok := auth.IdentityFromContext(r.Context()) + if !ok { + http.Error(w, unauthorizedMessage, http.StatusUnauthorized) + return "", false + } + + if m.providerName != "" { + token, ok := identity.UpstreamTokens[m.providerName] + if !ok || token == "" { + writeUpstreamAuthRequired(w) + return "", false + } + return token, true + } + + if identity.Token == "" { + http.Error(w, unauthorizedMessage, http.StatusUnauthorized) + return "", false + } + return identity.Token, true +} + +// writeUpstreamAuthRequired writes a 401 with an RFC 6750 WWW-Authenticate +// Bearer challenge, signalling that the caller must re-authenticate with the +// upstream IdP so a provider token becomes available. +func writeUpstreamAuthRequired(w http.ResponseWriter) { + w.Header().Set("WWW-Authenticate", + `Bearer error="invalid_token", error_description="upstream token is unavailable; re-authentication required"`) + http.Error(w, unauthorizedMessage, http.StatusUnauthorized) +} + +// writeExchangeError maps an exchange failure onto a generic HTTP response, +// without disclosing the provider error, the claims challenge, or any token or +// secret material. The conditional-access case also emits an audit record. +func (m *middleware) writeExchangeError(w http.ResponseWriter, r *http.Request, err error) { + switch { + case errors.Is(err, entra.ErrInteractionRequired): + // Fail fast on a conditional-access or claims challenge: record the + // decision and return a generic 403. No interactive step-up and no + // claims passthrough. + m.auditInteractionRequired(r, err) + http.Error(w, forbiddenMessage, http.StatusForbidden) + + case errors.Is(err, entra.ErrInvalidGrant): + // The end-user token was rejected by the IdP (expired, malformed, or + // not consented for this backend). + slog.DebugContext(r.Context(), "obo: subject token rejected by identity provider") + http.Error(w, unauthorizedMessage, http.StatusUnauthorized) + + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + // The client (or its deadline) went away mid-exchange. Write no + // response: a 502 would be a misleading 5xx for a request nobody is + // waiting on. + slog.DebugContext(r.Context(), "obo: token exchange cancelled before completion") + + default: + // invalid_client, a transient IdP failure, or an unclassified error. + // Only *entra.ExchangeError detail is logged: its Error() composes + // solely non-sensitive fields. Any other error is logged without its + // message so no implementation can leak credential material here. + var exErr *entra.ExchangeError + if errors.As(err, &exErr) { + slog.WarnContext(r.Context(), "obo: token exchange failed", "error", exErr.Error()) + } else { + slog.WarnContext(r.Context(), "obo: token exchange failed with an unclassified error") + } + http.Error(w, badGatewayMessage, http.StatusBadGateway) + } +} + +// auditInteractionRequired emits the audit record for a fail-fast +// conditional-access or claims challenge. +func (m *middleware) auditInteractionRequired(r *http.Request, err error) { + identity, _ := auth.IdentityFromContext(r.Context()) + event := NewInteractionRequiredAuditEvent( + audit.EventSource{Type: audit.SourceTypeNetwork, Value: clientAddr(r)}, + auditComponent, identity, m.exchangeTarget, err) + event.LogTo(r.Context(), m.auditLogger, audit.LevelAudit) +} + +// NewInteractionRequiredAuditEvent builds the audit event for an OBO exchange +// that Entra refused with a conditional-access or claims challenge. It records +// the denied subject (an identifier, not a credential) and only the +// non-sensitive fields the entra error carries: OAuthError, Description, +// HTTPStatus, and whether a claims challenge was present. It never records the +// user token, the client secret, an issued token, or the raw claims challenge. +// +// Shared by the proxy middleware and the vMCP strategy so both surfaces emit +// the same record shape. identity may be nil. +func NewInteractionRequiredAuditEvent( + source audit.EventSource, component string, identity *auth.Identity, target string, err error, +) *audit.AuditEvent { + var subjects map[string]string + if identity != nil && identity.Subject != "" { + subjects = map[string]string{"sub": identity.Subject} + } + + event := audit.NewAuditEvent(AuditEventType, source, audit.OutcomeDenied, subjects, component). + WithTarget(map[string]string{"audience": target}) + + extra := map[string]any{"reason": "interaction_required"} + var exErr *entra.ExchangeError + if errors.As(err, &exErr) { + extra["oauth_error"] = exErr.OAuthError + extra["description"] = exErr.Description + extra["http_status"] = exErr.HTTPStatus + extra["claims_challenge_present"] = exErr.Claims != "" + } + event.Metadata.Extra = extra + return event +} + +// clientAddr returns the client's IP for the audit source, stripping the port +// from RemoteAddr when present. +func clientAddr(r *http.Request) string { + if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { + return host + } + return r.RemoteAddr +} + +// parseParameters unmarshals and validates the MiddlewareParameters contract. +// Unknown fields are tolerated so the contract can grow additively. +func parseParameters(raw json.RawMessage) (*MiddlewareParameters, error) { + if len(raw) == 0 { + return nil, fmt.Errorf("obo middleware: parameters are required") + } + + var p MiddlewareParameters + if err := json.Unmarshal(raw, &p); err != nil { + return nil, fmt.Errorf("obo middleware: invalid parameters: %w", err) + } + if err := p.Validate(); err != nil { + return nil, err + } + return &p, nil +} diff --git a/pkg/auth/obo/middleware_test.go b/pkg/auth/obo/middleware_test.go index 197059be4a..8c773c45d8 100644 --- a/pkg/auth/obo/middleware_test.go +++ b/pkg/auth/obo/middleware_test.go @@ -4,147 +4,734 @@ package obo import ( + "bytes" + "context" + "encoding/json" "errors" + "fmt" + "log/slog" "net/http" "net/http/httptest" + "sync" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo/cache" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" "github.com/stacklok/toolhive/pkg/transport/types" "github.com/stacklok/toolhive/pkg/transport/types/mocks" ) -// withDefaultFactory captures the underlying middleware factory and restores -// it on cleanup so tests that call RegisterFactory do not leak state to -// other tests in the package. Capture and restore both pass through -// factoryMu so they participate in the same synchronization contract as -// production reads/writes. -func withDefaultFactory(t *testing.T) { - t.Helper() - factoryMu.RLock() - original := currentFactory - factoryMu.RUnlock() - t.Cleanup(func() { - factoryMu.Lock() - currentFactory = original - factoryMu.Unlock() +const ( + testTarget = "api://backend/.default" + testProvider = "entra" + testSubject = "user-123" +) + +// stubExchanger is a configurable exchange.Exchanger test double. It records the +// arguments of the last call and the call count. +type stubExchanger struct { + token string + err error + calls int + lastUserToken string + lastAudience string +} + +var _ exchange.Exchanger = (*stubExchanger)(nil) + +func (s *stubExchanger) Exchange(_ context.Context, userToken, audience string) (string, error) { + s.calls++ + s.lastUserToken = userToken + s.lastAudience = audience + return s.token, s.err +} + +// countingTokenExchanger is an exchange.TokenExchanger double that counts exchanges, +// used (behind a real cache) to prove the middleware reuses cached tokens. Each +// exchange mints a token expiring one hour after now(), so a test clock can drive +// the expiry→re-exchange transition deterministically. +type countingTokenExchanger struct { + mu sync.Mutex + calls int + now func() time.Time +} + +var _ exchange.TokenExchanger = (*countingTokenExchanger)(nil) + +func (c *countingTokenExchanger) ExchangeToken(_ context.Context, _, _ string) (exchange.Token, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.calls++ + return exchange.Token{AccessToken: "backend-token", Expiry: c.now().Add(time.Hour)}, nil +} + +func (c *countingTokenExchanger) callCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls +} + +// downstreamSpy records whether the downstream handler ran and the request +// headers it observed, so tests can assert short-circuiting, injection, and that +// the raw subject token is not forwarded. +type downstreamSpy struct { + called bool + authHeader string + headers http.Header +} + +func (d *downstreamSpy) handler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + d.called = true + d.headers = r.Header.Clone() + d.authHeader = r.Header.Get("Authorization") + w.WriteHeader(http.StatusOK) }) } -func TestMiddlewareType(t *testing.T) { - t.Parallel() +// serve runs req through mw wrapping a downstreamSpy and returns the recorder +// and the spy. +func serve(t *testing.T, mw *middleware, req *http.Request) (*httptest.ResponseRecorder, *downstreamSpy) { + t.Helper() + spy := &downstreamSpy{} + h := mw.Handler()(spy.handler()) + require.NotNil(t, h) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec, spy +} - assert.Equal(t, "obo", MiddlewareType, - "MiddlewareType must equal the ExternalAuthType value 'obo'") +// inboundIdentity returns an Identity carrying token as the inbound (pass-through) +// token — the inbound-mode subject source. +func inboundIdentity(token string) *auth.Identity { + return &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}, + Token: token, + } } -func TestDefaultCreateMiddleware_AddsStub(t *testing.T) { - t.Parallel() +// upstreamIdentity returns an Identity carrying token under the given upstream +// provider name — the upstream-provider-mode subject source. +func upstreamIdentity(provider, token string) *auth.Identity { + return &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}, + UpstreamTokens: map[string]string{provider: token}, + } +} + +// fakeClock is a manually-advanced, concurrency-safe time source for the cache. +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +// request builds a GET request rooted at the test's context (cancelled when the +// test ends), attaching identity when non-nil. +func request(t *testing.T, identity *auth.Identity) *http.Request { + t.Helper() + ctx := t.Context() + if identity != nil { + ctx = auth.WithIdentity(ctx, identity) + } + return httptest.NewRequest(http.MethodGet, "/anything", nil).WithContext(ctx) +} + +// TestCreateMiddleware_InstallsOBOMiddleware verifies that dispatching through +// CreateMiddleware with a valid Parameters contract installs the OBO middleware, +// and that a request through it is handled (no authenticated identity yields +// 401, never the old 503 stub). +func TestCreateMiddleware_InstallsOBOMiddleware(t *testing.T) { + t.Setenv("TEST_OBO_SECRET_INSTALL", "the-client-secret") ctrl := gomock.NewController(t) - defer ctrl.Finish() + params := map[string]any{ + "tokenUrl": "https://login.microsoftonline.com/tenant/oauth2/v2.0/token", + "clientId": "client-id", + "scopes": []string{testTarget}, + "clientSecretEnvVar": "TEST_OBO_SECRET_INSTALL", + } + cfg, err := types.NewMiddlewareConfig(MiddlewareType, params) + require.NoError(t, err) + var captured types.Middleware mockRunner := mocks.NewMockMiddlewareRunner(ctrl) - mockRunner.EXPECT().AddMiddleware(MiddlewareType, gomock.Any()).Times(1) + mockRunner.EXPECT(). + AddMiddleware(MiddlewareType, gomock.Any()). + Do(func(_ string, mw types.Middleware) { captured = mw }). + Times(1) + + require.NoError(t, CreateMiddleware(cfg, mockRunner), + "dispatch through the registered factory must succeed") + require.NotNil(t, captured) + + installed, ok := captured.(*middleware) + require.True(t, ok, "the default factory must install the OBO middleware") + assert.Empty(t, installed.providerName, "no subjectTokenProviderName means inbound mode") + + // A request with no authenticated identity must reach the OBO handler (401). + rec, spy := serve(t, installed, request(t, nil)) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.NotEqual(t, http.StatusServiceUnavailable, rec.Code) + assert.False(t, spy.called) +} + +// TestCreateMiddleware_InstallsUpstreamProviderMode verifies the factory wires the +// configured subjectTokenProviderName onto the installed middleware. +func TestRegisterFactory_InstallsUpstreamProviderMode(t *testing.T) { + t.Setenv("TEST_OBO_SECRET_PROVIDER", "the-client-secret") + + ctrl := gomock.NewController(t) + params := map[string]any{ + "tokenUrl": "https://login.microsoftonline.com/tenant/oauth2/v2.0/token", + "clientId": "client-id", + "scopes": []string{testTarget}, + "clientSecretEnvVar": "TEST_OBO_SECRET_PROVIDER", + "subjectTokenProviderName": testProvider, + } + cfg, err := types.NewMiddlewareConfig(MiddlewareType, params) + require.NoError(t, err) + + var captured types.Middleware + mockRunner := mocks.NewMockMiddlewareRunner(ctrl) + mockRunner.EXPECT(). + AddMiddleware(MiddlewareType, gomock.Any()). + Do(func(_ string, mw types.Middleware) { captured = mw }). + Times(1) - cfg := &types.MiddlewareConfig{Type: MiddlewareType} require.NoError(t, CreateMiddleware(cfg, mockRunner)) + installed, ok := captured.(*middleware) + require.True(t, ok) + assert.Equal(t, testProvider, installed.providerName) +} + +// TestDefaultFactory_InvalidParameters verifies the factory fails +// loudly (returns an error, installs nothing) for malformed parameters or a +// missing secret. A mock runner with no expectations fails the test if +// AddMiddleware is called. +func TestDefaultFactory_InvalidParameters(t *testing.T) { + t.Parallel() + + valid := map[string]any{ + "tokenUrl": "https://login.microsoftonline.com/tenant/oauth2/v2.0/token", + "clientId": "client-id", + "scopes": []string{testTarget}, + "clientSecretEnvVar": "OBO_SECRET_NEVER_SET_XYZ", + } + without := func(key string) map[string]any { + m := map[string]any{} + for k, v := range valid { + if k != key { + m[k] = v + } + } + return m + } + + tests := []struct { + name string + rawParams json.RawMessage // takes precedence when non-nil + params map[string]any + nilParams bool + wantErrContains string + }{ + {name: "nil parameters", nilParams: true, wantErrContains: "parameters are required"}, + {name: "malformed json", rawParams: json.RawMessage("{not-json"), wantErrContains: "invalid parameters"}, + {name: "missing tokenUrl", params: without("tokenUrl"), wantErrContains: "tokenUrl is required"}, + {name: "missing clientId", params: without("clientId"), wantErrContains: "clientId is required"}, + {name: "missing clientSecretEnvVar", params: without("clientSecretEnvVar"), wantErrContains: "clientSecretEnvVar is required"}, + { + name: "missing both audience and scopes", + params: map[string]any{ + "tokenUrl": valid["tokenUrl"], + "clientId": valid["clientId"], + "clientSecretEnvVar": valid["clientSecretEnvVar"], + }, + wantErrContains: "one of scopes or audience is required", + }, + { + name: "negative cacheSkewSeconds", + params: map[string]any{ + "tokenUrl": valid["tokenUrl"], + "clientId": valid["clientId"], + "scopes": []string{testTarget}, + "clientSecretEnvVar": valid["clientSecretEnvVar"], + "cacheSkewSeconds": -1, + }, + wantErrContains: "cacheSkewSeconds must not be negative", + }, + // OBO_SECRET_NEVER_SET_XYZ is never set, so the secret read fails. + {name: "secret env var unset", params: valid, wantErrContains: "client secret env var"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + // No EXPECT: any AddMiddleware call fails the test. + mockRunner := mocks.NewMockMiddlewareRunner(ctrl) + + cfg := &types.MiddlewareConfig{Type: MiddlewareType} + switch { + case tt.nilParams: + cfg.Parameters = nil + case tt.rawParams != nil: + cfg.Parameters = tt.rawParams + default: + raw, err := json.Marshal(tt.params) + require.NoError(t, err) + cfg.Parameters = raw + } + + err := DefaultFactory(cfg, mockRunner) + require.Error(t, err) + assert.ErrorContains(t, err, tt.wantErrContains) + }) + } +} + +// TestDefaultFactory_BadTokenURL verifies that an entra-build failure +// (bad token URL, secret present) is surfaced as a factory error and installs +// nothing. +func TestDefaultFactory_BadTokenURL(t *testing.T) { + t.Setenv("TEST_OBO_SECRET_BADURL", "the-client-secret") + + ctrl := gomock.NewController(t) + mockRunner := mocks.NewMockMiddlewareRunner(ctrl) // no EXPECT: AddMiddleware must not be called + + params := map[string]any{ + "tokenUrl": "ftp://login.microsoftonline.com/tenant/token", + "clientId": "client-id", + "scopes": []string{testTarget}, + "clientSecretEnvVar": "TEST_OBO_SECRET_BADURL", + } + cfg, err := types.NewMiddlewareConfig(MiddlewareType, params) + require.NoError(t, err) + + err = DefaultFactory(cfg, mockRunner) + require.Error(t, err) + assert.NotContains(t, err.Error(), "the-client-secret") +} + +// TestMiddleware_Success_Inbound verifies the inbound path: the Identity.Token is +// exchanged and the upstream request carries Authorization: Bearer , and the downstream handler runs. +func TestMiddleware_Success_Inbound(t *testing.T) { + t.Parallel() + + stub := &stubExchanger{token: "backend-token"} + mw := newMiddleware(stub, "", testTarget, nil) + + // A pre-existing inbound Authorization header must be overwritten, not + // forwarded — the backend sees only the exchanged token. + req := request(t, inboundIdentity("user-token-XYZ")) + req.Header.Set("Authorization", "Bearer ORIGINAL-INBOUND-TOKEN") + rec, spy := serve(t, mw, req) + + assert.Equal(t, http.StatusOK, rec.Code) + assert.True(t, spy.called, "downstream must be invoked on success") + assert.Equal(t, "Bearer backend-token", spy.authHeader) + assert.NotContains(t, spy.authHeader, "ORIGINAL-INBOUND-TOKEN", "the inbound Authorization must be overwritten") + assert.Equal(t, "user-token-XYZ", stub.lastUserToken, "the inbound Identity token is the subject") + assert.Equal(t, testTarget, stub.lastAudience, "scopes/audience collapse to the exchange target") +} + +// TestMiddleware_Success_UpstreamProvider verifies the upstream-provider path: the +// named provider's token from Identity.UpstreamTokens is exchanged. +func TestMiddleware_Success_UpstreamProvider(t *testing.T) { + t.Parallel() + + stub := &stubExchanger{token: "backend-token"} + mw := newMiddleware(stub, testProvider, testTarget, nil) + + rec, spy := serve(t, mw, request(t, upstreamIdentity(testProvider, "upstream-entra-token"))) + + assert.Equal(t, http.StatusOK, rec.Code) + assert.True(t, spy.called) + assert.Equal(t, "Bearer backend-token", spy.authHeader) + assert.Equal(t, "upstream-entra-token", stub.lastUserToken, + "the named upstream provider token is the subject, not the inbound token") +} + +// TestMiddleware_NoIdentity_401 verifies both modes reject a request without an +// authenticated identity, without attempting an exchange. +func TestMiddleware_NoIdentity_401(t *testing.T) { + t.Parallel() + + for _, providerName := range []string{"", testProvider} { + t.Run("provider="+providerName, func(t *testing.T) { + t.Parallel() + stub := &stubExchanger{token: "unused"} + mw := newMiddleware(stub, providerName, testTarget, nil) + + rec, spy := serve(t, mw, request(t, nil)) + + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.False(t, spy.called) + assert.Equal(t, 0, stub.calls, "no exchange without an identity") + }) + } +} + +// TestMiddleware_InboundIdentityWithoutToken_401 verifies the inbound path rejects +// an identity that carries no pass-through token. +func TestMiddleware_InboundIdentityWithoutToken_401(t *testing.T) { + t.Parallel() + + stub := &stubExchanger{token: "unused"} + mw := newMiddleware(stub, "", testTarget, nil) + + rec, spy := serve(t, mw, request(t, inboundIdentity(""))) + + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.False(t, spy.called) + assert.Equal(t, 0, stub.calls) +} + +// TestMiddleware_UpstreamProviderTokenMissing_401Challenge verifies the +// upstream-provider path returns 401 with a re-auth challenge when the configured +// provider has no usable token, mirroring upstreamswap. +func TestMiddleware_UpstreamProviderTokenMissing_401Challenge(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + identity *auth.Identity + }{ + {name: "provider absent", identity: &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}}}, + {name: "provider present but empty", identity: upstreamIdentity(testProvider, "")}, + {name: "different provider", identity: upstreamIdentity("other", "tok")}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stub := &stubExchanger{token: "unused"} + mw := newMiddleware(stub, testProvider, testTarget, nil) + + rec, spy := serve(t, mw, request(t, tt.identity)) + + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.NotEmpty(t, rec.Header().Get("WWW-Authenticate"), "a re-auth challenge must be sent") + assert.False(t, spy.called) + assert.Equal(t, 0, stub.calls) + }) + } } -func TestStubHandler_Returns503(t *testing.T) { +// TestMiddleware_InteractionRequired_403AndAudit verifies the fail-fast: +// a conditional-access / claims challenge yields a generic 403, an audit record +// (carrying the denied subject but not the token or claims), and no downstream +// call. +func TestMiddleware_InteractionRequired_403AndAudit(t *testing.T) { + t.Parallel() + + const ( + userToken = "USER-TOKEN-SECRET" + claims = "CLAIMS-CHALLENGE-BLOB" + ) + exErr := &entra.ExchangeError{ + Kind: entra.KindInteractionRequired, + OAuthError: "interaction_required", + Description: "AADSTS50079: due to a configuration change made by your administrator", + Claims: claims, + HTTPStatus: http.StatusUnauthorized, + } + require.ErrorIs(t, exErr, entra.ErrInteractionRequired) + + var auditBuf bytes.Buffer + stub := &stubExchanger{err: exErr} + mw := newMiddleware(stub, "", testTarget, slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug}))) + + rec, spy := serve(t, mw, request(t, inboundIdentity(userToken))) + + assert.Equal(t, http.StatusForbidden, rec.Code) + assert.False(t, spy.called, "downstream must not be called on a claims challenge") + assert.Contains(t, rec.Body.String(), forbiddenMessage) + + // Non-disclosure: neither the response body nor the audit record may leak + // the user token or the raw claims challenge. + assert.NotContains(t, rec.Body.String(), userToken) + assert.NotContains(t, rec.Body.String(), claims) + + auditOut := auditBuf.String() + assert.NotEmpty(t, auditOut, "a fail-fast claims challenge must emit an audit record") + assert.Contains(t, auditOut, AuditEventType) + assert.Contains(t, auditOut, "denied") + assert.Contains(t, auditOut, "interaction_required") + assert.Contains(t, auditOut, testSubject, "the audit record identifies the denied subject") + assert.NotContains(t, auditOut, userToken, "the audit record must not contain the user token") + assert.NotContains(t, auditOut, claims, "the audit record must not contain the raw claims challenge") +} + +// TestMiddleware_ExchangeErrors_StatusMapping verifies the error→status mapping +// for exchange failures other than the claims challenge. +func TestMiddleware_ExchangeErrors_StatusMapping(t *testing.T) { t.Parallel() tests := []struct { name string - downstream http.Handler - method string - path string + err error + wantStatus int + wantBody string }{ { - name: "nil downstream handler is ignored", - downstream: nil, - method: http.MethodGet, - path: "/anything", + name: "invalid grant is 401", + err: &entra.ExchangeError{Kind: entra.KindInvalidGrant, OAuthError: "invalid_grant"}, + wantStatus: http.StatusUnauthorized, + wantBody: unauthorizedMessage, + }, + { + name: "invalid client is 502", + err: &entra.ExchangeError{Kind: entra.KindInvalidClient, OAuthError: "invalid_client"}, + wantStatus: http.StatusBadGateway, + wantBody: badGatewayMessage, }, { - name: "non-nil downstream handler is not invoked", - downstream: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - // If this is ever reached, the stub leaked through — the test - // asserts on the response code below to catch that. - w.WriteHeader(http.StatusTeapot) - }), - method: http.MethodPost, - path: "/whatever", + name: "transient is 502", + err: &entra.ExchangeError{Kind: entra.KindTransient}, + wantStatus: http.StatusBadGateway, + wantBody: badGatewayMessage, + }, + { + name: "unclassified error is 502", + err: errors.New("something unexpected"), + wantStatus: http.StatusBadGateway, + wantBody: badGatewayMessage, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() + stub := &stubExchanger{err: tt.err} + mw := newMiddleware(stub, "", testTarget, nil) + + rec, spy := serve(t, mw, request(t, inboundIdentity("user-token"))) - s := &stub{} - wrapper := s.Handler() - require.NotNil(t, wrapper) - - h := wrapper(tt.downstream) - require.NotNil(t, h) - - req := httptest.NewRequest(tt.method, tt.path, nil) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, req) - - assert.Equal(t, http.StatusServiceUnavailable, rec.Code, - "stub handler must respond 503, not call downstream") - // http.Error appends a newline to the supplied message; assert on - // the exact body so the cross-file contract with stubMessage stays - // pinned (any change to stubMessage that wasn't intentional - // breaks this test loudly). - assert.Equal(t, stubMessage+"\n", rec.Body.String(), - "stub handler must echo the package stubMessage constant") + assert.Equal(t, tt.wantStatus, rec.Code) + assert.Contains(t, rec.Body.String(), tt.wantBody) + assert.False(t, spy.called, "downstream must not be called on an exchange failure") }) } } -func TestStub_Close(t *testing.T) { +// TestMiddleware_UnclassifiedError_NotLoggedToDefault covers the "no token or +// secret in logs" guarantee on the failure path that uses the package-global +// logger: an unclassified (non-entra) error must not have its content written to +// the diagnostic log, so a future non-conforming Exchanger can't leak material +// through the 502 branch. It captures slog.Default() (restored via t.Cleanup) and +// asserts a sentinel error string never appears. +// +//nolint:paralleltest // Swaps slog.Default() for the duration; must not overlap parallel tests. +func TestMiddleware_UnclassifiedError_NotLoggedToDefault(t *testing.T) { + const sentinel = "SENTINEL-MUST-NOT-REACH-LOGS" + + var buf bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))) + t.Cleanup(func() { slog.SetDefault(prev) }) + + stub := &stubExchanger{err: errors.New(sentinel)} + mw := newMiddleware(stub, "", testTarget, nil) + + rec, spy := serve(t, mw, request(t, inboundIdentity("user-token"))) + + require.Equal(t, http.StatusBadGateway, rec.Code) + assert.False(t, spy.called) + assert.NotContains(t, buf.String(), sentinel, + "an unclassified error's content must not reach the diagnostic log") +} + +// TestMiddleware_ClientCancellation_NoSpurious502 verifies that a client which +// disconnects mid-exchange does not produce a 502: context cancellation / +// deadline errors (including the entra-wrapped form) are treated as benign, with +// no error response written. +func TestMiddleware_ClientCancellation_NoSpurious502(t *testing.T) { t.Parallel() - assert.NoError(t, (&stub{}).Close(), "stub Close must be a no-op") + tests := []struct { + name string + err error + }{ + {name: "canceled", err: context.Canceled}, + {name: "deadline exceeded", err: context.DeadlineExceeded}, + {name: "entra-wrapped canceled", err: fmt.Errorf("entra obo: %w", context.Canceled)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stub := &stubExchanger{err: tt.err} + mw := newMiddleware(stub, "", testTarget, nil) + + rec, spy := serve(t, mw, request(t, inboundIdentity("user-token"))) + + assert.NotEqual(t, http.StatusBadGateway, rec.Code, "client cancellation must not be a 502") + assert.Empty(t, rec.Body.String(), "no error body is written for a cancelled request") + assert.False(t, spy.called) + assert.Equal(t, 1, stub.calls, "the exchange was attempted before cancellation") + }) + } } -//nolint:paralleltest // Mutates package-level currentFactory; must not race other tests. -func TestRegisterFactory_ReplacesDefault(t *testing.T) { - withDefaultFactory(t) +// TestMiddleware_CachesAcrossRequests verifies the acceptance criterion that +// exchanged tokens are cached across requests for the same session: with the real +// cache (driven by a fake clock) wrapping a counting exchanger, repeated requests +// for the same subject reuse one exchange within the TTL, a different subject +// triggers its own exchange, and the token is re-exchanged once it expires. +func TestMiddleware_CachesAcrossRequests(t *testing.T) { + t.Parallel() - var called bool - replacement := types.MiddlewareFactory(func(*types.MiddlewareConfig, types.MiddlewareRunner) error { - called = true - return nil - }) - RegisterFactory(replacement) + clk := &fakeClock{t: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + counting := &countingTokenExchanger{now: clk.now} + mw := newMiddleware( + cache.New(counting, cache.WithClock(clk.now), cache.WithSkew(60*time.Second)), + "", testTarget, nil, + ) - // Calling through CreateMiddleware after RegisterFactory must dispatch to - // the replacement. - require.NoError(t, CreateMiddleware(&types.MiddlewareConfig{Type: MiddlewareType}, nil)) - assert.True(t, called, "RegisterFactory must replace the underlying factory") + // Two requests for the same session, within the TTL → one exchange. + for i := 0; i < 2; i++ { + rec, spy := serve(t, mw, request(t, inboundIdentity("same-user-token"))) + require.Equal(t, http.StatusOK, rec.Code) + require.True(t, spy.called) + require.Equal(t, "Bearer backend-token", spy.authHeader) + } + assert.Equal(t, 1, counting.callCount(), "a cached token must be reused within its TTL") + + // A different session forces a fresh exchange. + serve(t, mw, request(t, inboundIdentity("other-user-token"))) + assert.Equal(t, 2, counting.callCount(), "a different session must not collide with a cached entry") + + // Advancing past the first session's expiry (issued at t0, +1h, minus 60s + // skew) makes its cached token stale, so the next request re-exchanges. + clk.advance(time.Hour) + rec, spy := serve(t, mw, request(t, inboundIdentity("same-user-token"))) + require.Equal(t, http.StatusOK, rec.Code) + require.True(t, spy.called) + assert.Equal(t, 3, counting.callCount(), "an expired token must be re-exchanged") +} + +// TestMiddleware_RealEntra_InteractionRequired_NonDisclosure exercises the full +// real path for the non-disclosure guarantee: the actual Entra classifier (entra.NewFromTokenURL against +// an httptest endpoint returning a genuine interaction_required claims challenge) +// → cache → middleware. It proves the seam between what Entra produces and what +// the middleware audits never discloses the claims challenge, the user token, or +// the client secret — and that the audit record carries exactly the expected safe +// keys, so a future widening would fail here. +func TestMiddleware_RealEntra_InteractionRequired_NonDisclosure(t *testing.T) { + t.Parallel() + + const ( + userToken = "USER-ASSERTION-SECRET" + claimsBlob = "eyJhY2Nlc3NfdG9rZW4iOnsiTUZBIjp7ImVzc2VudGlhbCI6dHJ1ZX19fQ" + clientSecret = "the-client-secret-VALUE" + ) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":"interaction_required","error_codes":[50079],` + + `"error_description":"AADSTS50079: due to a configuration change made by your administrator",` + + `"claims":"` + claimsBlob + `"}`)) + })) + defer srv.Close() + + ex, err := entra.NewFromTokenURL(srv.URL+"/tenant/oauth2/v2.0/token", "client-id", clientSecret, nil) + require.NoError(t, err) + + var auditBuf bytes.Buffer + mw := newMiddleware(cache.New(ex), "", testTarget, + slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug}))) + + rec, spy := serve(t, mw, request(t, inboundIdentity(userToken))) + + assert.Equal(t, http.StatusForbidden, rec.Code) + assert.False(t, spy.called) + assert.Contains(t, rec.Body.String(), forbiddenMessage) + assert.NotContains(t, rec.Body.String(), claimsBlob) + assert.NotContains(t, rec.Body.String(), userToken) + assert.NotContains(t, rec.Body.String(), clientSecret) + + auditOut := auditBuf.String() + require.NotEmpty(t, auditOut, "a fail-fast claims challenge must emit an audit record") + assert.NotContains(t, auditOut, claimsBlob, "the audit record must not contain the raw claims challenge") + assert.NotContains(t, auditOut, userToken) + assert.NotContains(t, auditOut, clientSecret) + + // The audit Extra carries exactly the expected safe keys — locking the record + // shape so a future change that widened it (e.g. dumping the claims blob or + // the assertion) would fail this assertion. + var record struct { + Msg string `json:"msg"` + Outcome string `json:"outcome"` + Metadata struct { + Extra map[string]any `json:"extra"` + } `json:"metadata"` + } + require.NoError(t, json.Unmarshal([]byte(auditOut), &record)) + assert.Equal(t, "audit_event", record.Msg) + assert.Equal(t, "denied", record.Outcome) + + gotKeys := make([]string, 0, len(record.Metadata.Extra)) + for k := range record.Metadata.Extra { + gotKeys = append(gotKeys, k) + } + assert.ElementsMatch(t, + []string{"reason", "oauth_error", "description", "http_status", "claims_challenge_present"}, + gotKeys) + assert.Equal(t, "interaction_required", record.Metadata.Extra["reason"]) + assert.Equal(t, true, record.Metadata.Extra["claims_challenge_present"]) +} + +// TestMiddleware_Close verifies the middleware's Close is a no-op. +func TestMiddleware_Close(t *testing.T) { + t.Parallel() + + assert.NoError(t, (&middleware{}).Close()) +} + +// withDefaultFactory restores the package factory after a test that calls the +// deprecated RegisterFactory, so the mutation does not leak to other tests. +func withDefaultFactory(t *testing.T) { + t.Helper() + factoryMu.RLock() + original := currentFactory + factoryMu.RUnlock() + t.Cleanup(func() { + factoryMu.Lock() + currentFactory = original + factoryMu.Unlock() + }) } //nolint:paralleltest // Mutates package-level currentFactory; must not race other tests. -func TestRegisterFactory_LastWriteWins(t *testing.T) { +func TestRegisterFactory_ReplacesDefault(t *testing.T) { withDefaultFactory(t) - sentinel := errors.New("second factory") - RegisterFactory(func(*types.MiddlewareConfig, types.MiddlewareRunner) error { - return errors.New("first factory") - }) - RegisterFactory(func(*types.MiddlewareConfig, types.MiddlewareRunner) error { - return sentinel - }) + sentinel := errors.New("replacement factory") + RegisterFactory(func(*types.MiddlewareConfig, types.MiddlewareRunner) error { return sentinel }) err := CreateMiddleware(&types.MiddlewareConfig{Type: MiddlewareType}, nil) - require.ErrorIs(t, err, sentinel, "second RegisterFactory must overwrite the first") + require.ErrorIs(t, err, sentinel, "CreateMiddleware must dispatch to the registered factory") } func TestRegisterFactory_PanicsOnNil(t *testing.T) { diff --git a/pkg/auth/obo/parameters.go b/pkg/auth/obo/parameters.go new file mode 100644 index 0000000000..709733031c --- /dev/null +++ b/pkg/auth/obo/parameters.go @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package obo + +import ( + "fmt" + "strings" + + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" +) + +// ClientSecretEnvVar is the environment-variable name the operator injects the +// OBO confidential-client secret into for a proxyrunner pod (MCPServer and +// MCPRemoteProxy). A proxy carries at most one OBO config, so a fixed name is +// enough. The vMCP pod can carry several OBO backends and therefore uses a +// per-config name instead (see controllerutil.GenerateUniqueOBOEnvVarName). +// +//nolint:gosec // G101: this is an environment-variable name, not a credential. +const ClientSecretEnvVar = "TOOLHIVE_OBO_CLIENT_SECRET" + +// MiddlewareParameters is the operator-to-runtime contract carried in the OBO +// middleware's MiddlewareConfig.Parameters. The operator marshals it and the +// proxy middleware factory unmarshals it, so the JSON key set is defined once. +// +// It deliberately uses only standard-library types so this package stays free +// of the Kubernetes dependencies the proxyrunner must not link. +type MiddlewareParameters struct { + // TokenURL is the fully-formed Entra tenant token endpoint, e.g. + // https://login.microsoftonline.com//oauth2/v2.0/token. + // + // SECURITY: TokenURL is an operator trust boundary. The OBO exchange POSTs + // the client secret and the end-user assertion in the request body to this + // URL, so the operator is responsible for pointing it only at a trusted + // Entra token endpoint. See entra.NewFromTokenURL. + TokenURL string `json:"tokenUrl"` + + // ClientID is the confidential client's application (client) ID. + ClientID string `json:"clientId"` + + // Audience is the backend target identifier. Used as the exchange scope when + // Scopes is empty (see ExchangeTarget). + Audience string `json:"audience"` + + // Scopes are the delegated scopes to request, e.g. + // ["api:///.default"]. When present they take precedence over + // Audience (see ExchangeTarget). + Scopes []string `json:"scopes"` + + // ClientSecretEnvVar is the name of the environment variable holding the + // client secret. The operator injects the value into the proxyrunner pod; + // only the name travels in the contract. + ClientSecretEnvVar string `json:"clientSecretEnvVar"` + + // SubjectTokenProviderName selects the source of the OBO subject (assertion) + // token from the request's authenticated Identity: + // + // - Empty (default): use the inbound token the client presented + // (Identity.Token). This is the deployment with no embedded auth server, + // where the client holds an Entra token directly. + // - Set: use the named upstream provider's token + // (Identity.UpstreamTokens[SubjectTokenProviderName]). Set this when an + // embedded auth server fronts the proxy, so the inbound token is the + // proxy's own session token rather than an Entra token. Mirrors the + // upstreamswap middleware. + // + // Either way the subject comes from the Identity, so the authentication + // middleware must run first. + SubjectTokenProviderName string `json:"subjectTokenProviderName,omitempty"` + + // CacheSkewSeconds overrides the token cache's default expiry skew. Zero + // leaves the cache default; negative is rejected by Validate. + CacheSkewSeconds int `json:"cacheSkewSeconds"` +} + +// ExchangeTarget returns the single value the Exchanger receives as its +// audience argument; see exchange.Target for the collapse rule. +func (p *MiddlewareParameters) ExchangeTarget() string { + return exchange.Target(p.Audience, p.Scopes) +} + +// Validate checks the contract's required fields and bounds, failing loudly so +// a misconfiguration surfaces when the parameters are first consumed rather +// than per request. It does not validate TokenURL's URL shape; that is entra's +// concern (see entra.NewFromTokenURL). +func (p *MiddlewareParameters) Validate() error { + if strings.TrimSpace(p.TokenURL) == "" { + return fmt.Errorf("obo parameters: tokenUrl is required") + } + if strings.TrimSpace(p.ClientID) == "" { + return fmt.Errorf("obo parameters: clientId is required") + } + if strings.TrimSpace(p.ClientSecretEnvVar) == "" { + return fmt.Errorf("obo parameters: clientSecretEnvVar is required") + } + if p.ExchangeTarget() == "" { + return fmt.Errorf("obo parameters: one of scopes or audience is required") + } + if p.CacheSkewSeconds < 0 { + return fmt.Errorf("obo parameters: cacheSkewSeconds must not be negative") + } + return nil +} diff --git a/pkg/auth/obo/parameters_test.go b/pkg/auth/obo/parameters_test.go new file mode 100644 index 0000000000..a7c75e169f --- /dev/null +++ b/pkg/auth/obo/parameters_test.go @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package obo_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/auth/obo" +) + +func TestMiddlewareParameters_ExchangeTarget(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + audience string + scopes []string + want string + }{ + {name: "single scope", scopes: []string{"api://backend/.default"}, want: "api://backend/.default"}, + { + name: "multiple scopes are space-joined", + scopes: []string{"api://backend/.default", "offline_access"}, + want: "api://backend/.default offline_access", + }, + { + name: "scopes win over audience", + audience: "api://backend", + scopes: []string{"api://backend/.default"}, + want: "api://backend/.default", + }, + {name: "audience used when no scopes", audience: "api://backend", want: "api://backend"}, + { + name: "audience used when scopes are blank", + audience: "api://backend", + scopes: []string{"", " "}, + want: "api://backend", + }, + {name: "empty when neither set", want: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + p := &obo.MiddlewareParameters{Audience: tt.audience, Scopes: tt.scopes} + assert.Equal(t, tt.want, p.ExchangeTarget()) + }) + } +} + +func TestMiddlewareParameters_Validate_Valid(t *testing.T) { + t.Parallel() + + valid := obo.MiddlewareParameters{ + TokenURL: "https://login.microsoftonline.com/tenant/oauth2/v2.0/token", + ClientID: "client-id", + Scopes: []string{"api://backend/.default"}, + ClientSecretEnvVar: "TOOLHIVE_OBO_CLIENT_SECRET", + } + + t.Run("inbound mode (no provider name)", func(t *testing.T) { + t.Parallel() + require.NoError(t, valid.Validate()) + }) + + t.Run("upstream-provider mode", func(t *testing.T) { + t.Parallel() + p := valid + p.SubjectTokenProviderName = "entra" + require.NoError(t, p.Validate()) + }) + + t.Run("audience instead of scopes", func(t *testing.T) { + t.Parallel() + p := valid + p.Scopes = nil + p.Audience = "api://backend" + require.NoError(t, p.Validate()) + }) +} + +func TestMiddlewareParameters_Validate_Invalid(t *testing.T) { + t.Parallel() + + base := obo.MiddlewareParameters{ + TokenURL: "https://login.microsoftonline.com/tenant/oauth2/v2.0/token", + ClientID: "client-id", + Scopes: []string{"api://backend/.default"}, + ClientSecretEnvVar: "TOOLHIVE_OBO_CLIENT_SECRET", + } + + tests := []struct { + name string + mutate func(p *obo.MiddlewareParameters) + wantErrText string + }{ + {name: "missing tokenUrl", mutate: func(p *obo.MiddlewareParameters) { p.TokenURL = "" }, wantErrText: "tokenUrl is required"}, + {name: "missing clientId", mutate: func(p *obo.MiddlewareParameters) { p.ClientID = "" }, wantErrText: "clientId is required"}, + { + name: "missing clientSecretEnvVar", + mutate: func(p *obo.MiddlewareParameters) { p.ClientSecretEnvVar = "" }, + wantErrText: "clientSecretEnvVar is required", + }, + { + name: "missing both scopes and audience", + mutate: func(p *obo.MiddlewareParameters) { p.Scopes = nil; p.Audience = "" }, + wantErrText: "one of scopes or audience is required", + }, + { + name: "negative cacheSkewSeconds", + mutate: func(p *obo.MiddlewareParameters) { p.CacheSkewSeconds = -1 }, + wantErrText: "cacheSkewSeconds must not be negative", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + p := base + tt.mutate(&p) + err := p.Validate() + require.Error(t, err) + assert.ErrorContains(t, err, tt.wantErrText) + }) + } +} diff --git a/pkg/runner/middleware.go b/pkg/runner/middleware.go index 90cbf790c1..5390d893e7 100644 --- a/pkg/runner/middleware.go +++ b/pkg/runner/middleware.go @@ -261,7 +261,7 @@ func PopulateMiddlewareConfigs(config *RunConfig) error { } // Additional middleware configs injected by external-auth handlers via - // WithAdditionalMiddlewareConfigs (e.g. the enterprise OBO handler). Upstream + // WithAdditionalMiddlewareConfigs (e.g. the operator's OBO config). The runner // carries these pre-built configs verbatim and does not interpret their // parameters. They are spliced into the backend-egress group here: after auth // (so the authenticated identity is available) and after the awssts / diff --git a/pkg/runner/middleware_test.go b/pkg/runner/middleware_test.go index 0d850bce68..91f6b351b4 100644 --- a/pkg/runner/middleware_test.go +++ b/pkg/runner/middleware_test.go @@ -618,39 +618,63 @@ func TestGetSupportedMiddlewareFactories(t *testing.T) { } } -// TestGetSupportedMiddlewareFactories_OBODispatchesToCurrentFactory locks the -// contract that obo.CreateMiddleware is a stable redirector: the literal map -// in GetSupportedMiddlewareFactories captures CreateMiddleware once, but each -// invocation reads obo's currentFactory under the package-level RWMutex, so -// registrations that happen AFTER the map is built still take effect. The -// register-then-call ordering exercises the production hot path; the -// call-after-register ordering exercises hot-reload / re-registration. +// TestOBORegistration exercises the proxyrunner path for an operator-injected +// obo middleware: the RunConfig round-trips through JSON, the runner's factory +// map builds the built-in OBO middleware, and a request through it has its +// subject token exchanged at a (mock) Entra token endpoint and forwarded as the +// backend bearer token. // -//nolint:paralleltest // Mutates package-level obo currentFactory; must not race other tests. -func TestGetSupportedMiddlewareFactories_OBODispatchesToCurrentFactory(t *testing.T) { - // Build the factory map first so we capture the redirector before any - // out-of-test registration happens. - factories := GetSupportedMiddlewareFactories() - factory, ok := factories[obo.MiddlewareType] - require.True(t, ok, "obo factory should be present in the map") - - sentinel := []byte("custom-obo-factory") - var observed []byte - replacement := func(cfg *types.MiddlewareConfig, _ types.MiddlewareRunner) error { - // Capture the marker the caller passes to prove which factory ran. - observed = cfg.Parameters - return nil - } +//nolint:paralleltest // Uses t.Setenv for the client secret the factory reads. +func TestOBORegistration(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseForm()) + assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", r.Form.Get("grant_type")) + assert.Equal(t, "on_behalf_of", r.Form.Get("requested_token_use")) + assert.Equal(t, "user-token", r.Form.Get("assertion")) + assert.Equal(t, "the-secret", r.Form.Get("client_secret")) + assert.Equal(t, "api://backend/.default", r.Form.Get("scope")) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"backend-token","token_type":"Bearer","expires_in":3600}`)) + })) + t.Cleanup(server.Close) + t.Setenv("TEST_RUNNER_OBO_SECRET", "the-secret") + + injected, err := types.NewMiddlewareConfig(obo.MiddlewareType, obo.MiddlewareParameters{ + TokenURL: server.URL + "/tenant/oauth2/v2.0/token", + ClientID: "client-id", + Scopes: []string{"api://backend/.default"}, + ClientSecretEnvVar: "TEST_RUNNER_OBO_SECRET", + }) + require.NoError(t, err) + + config := &RunConfig{AdditionalMiddlewareConfigs: []types.MiddlewareConfig{*injected}} + require.NoError(t, PopulateMiddlewareConfigs(config)) + serialized, err := json.Marshal(config) + require.NoError(t, err) + var restored RunConfig + require.NoError(t, json.Unmarshal(serialized, &restored)) - // Register AFTER the map was built. Because CreateMiddleware is a stable - // redirector, dispatching through the map must still hit the replacement. - obo.RegisterFactory(replacement) - t.Cleanup(func() { obo.RegisterFactory(obo.DefaultFactory) }) + runner := NewRunner(&restored, nil) + for _, cfg := range restored.MiddlewareConfigs { + if cfg.Type != obo.MiddlewareType { + continue + } + factory, ok := runner.supportedMiddleware[cfg.Type] + require.True(t, ok) + require.NoError(t, factory(&cfg, runner)) + } + require.Len(t, runner.namedMiddlewares, 1) + assert.Equal(t, obo.MiddlewareType, runner.namedMiddlewares[0].Name) - cfg := &types.MiddlewareConfig{Type: obo.MiddlewareType, Parameters: sentinel} - require.NoError(t, factory(cfg, nil)) - assert.Equal(t, sentinel, observed, - "obo.CreateMiddleware must redirect through the current factory, including after the runner map is built") + req := httptest.NewRequest(http.MethodGet, "/mcp", nil) + req.Header.Set("Authorization", "Bearer user-token") + req = req.WithContext(auth.WithIdentity(req.Context(), &auth.Identity{Token: "user-token"})) + rec := httptest.NewRecorder() + runner.namedMiddlewares[0].Function(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "Bearer backend-token", r.Header.Get("Authorization")) + w.WriteHeader(http.StatusNoContent) + })).ServeHTTP(rec, req) + assert.Equal(t, http.StatusNoContent, rec.Code) } func TestWithHeaderForwardSecretsBuilderOption(t *testing.T) { diff --git a/pkg/vmcp/auth/converters/obo.go b/pkg/vmcp/auth/converters/obo.go index 01a45f5519..6d06164012 100644 --- a/pkg/vmcp/auth/converters/obo.go +++ b/pkg/vmcp/auth/converters/obo.go @@ -6,37 +6,185 @@ package converters import ( "context" "fmt" + "math" + "strings" + "time" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" - "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" ) -// OBOConverter is the default StrategyConverter for ExternalAuthTypeOBO. -// Every method returns an error wrapping obo.ErrEnterpriseRequired. An -// out-of-tree build replaces it by calling DefaultRegistry().Register(...) -// once during init(). +// OBOConverter converts an MCPExternalAuthConfig of type "obo" into the vMCP +// BackendAuthStrategy consumed by strategies.OBOStrategy. type OBOConverter struct{} // StrategyType returns the vMCP strategy identifier for OBO. func (*OBOConverter) StrategyType() string { return authtypes.StrategyTypeOBO } -// ConvertToStrategy returns an error wrapping obo.ErrEnterpriseRequired. +// ConvertToStrategy translates an obo-typed MCPExternalAuthConfig into a vMCP +// BackendAuthStrategy. It maps the CRD's tenantId+authority into the fully-formed +// Entra token endpoint (via entra.TokenURL — the single source of truth shared +// with the operator OBO validation) and copies clientId, audience, scopes, +// subjectTokenProviderName, and the cache skew through to authtypes.OBOConfig. +// +// It fails on a malformed config: a missing clientId or clientSecretRef (the +// shared-secret flow requires both), neither audience nor scopes (no +// exchange target), a missing/invalid tenant or authority, or a negative cache +// skew — mirroring the operator's reconcile-time OBO validation for those +// fields so the two surfaces accept the same configs. SubjectTokenProviderName's +// format is enforced by the CRD schema at admission, so it is passed through +// here unvalidated rather than re-checked. +// +// Neither the client secret nor ClientSecretEnv is set here. In inline mode the +// operator sets ClientSecretEnv to the per-config name it mounts the secret +// under (controllerutil.GenerateUniqueOBOEnvVarName), so several OBO backends in +// one vMCP pod never share an env var. In discovered mode ResolveSecrets sets +// the resolved ClientSecret instead. func (*OBOConverter) ConvertToStrategy( - _ *mcpv1beta1.MCPExternalAuthConfig, + externalAuth *mcpv1beta1.MCPExternalAuthConfig, ) (*authtypes.BackendAuthStrategy, error) { - return nil, fmt.Errorf("vMCP OBO converter: %w", obo.ErrEnterpriseRequired) + cfg := externalAuth.Spec.OBO + if cfg == nil { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgOBONil) + } + + // Check the simple required credentials first, so a config missing a client + // credential reports that rather than a downstream tenant-format error. + if cfg.ClientID == "" { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgClientID) + } + // OBO is a confidential-client shared-secret flow: clientSecretRef must be + // present with a non-empty name and key. Mirrors the operator OBO validation's + // validateSecretRef depth so the two surfaces reject the same refs (a + // {name:"", key:""} ref passes the CRD's presence-only Required markers). + if ref := cfg.ClientSecretRef; ref == nil || + strings.TrimSpace(ref.Name) == "" || strings.TrimSpace(ref.Key) == "" { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgClientSecretRef) + } + + // Reuse the single audience/scopes collapse implementation to check that a + // target exists, rather than re-inspecting the fields inline — so the + // converter's notion of "has a target" is exactly what the runtime strategy + // will send to Entra. + if exchange.Target(cfg.Audience, cfg.Scopes) == "" { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgAudienceOrScopes) + } + + tokenURL, err := entra.TokenURL(cfg.TenantID, cfg.Authority) + if err != nil { + return nil, fmt.Errorf("vMCP OBO converter: %w", err) + } + + cacheSkewSeconds, err := cacheSkewToSeconds(cfg.CacheSkew) + if err != nil { + return nil, fmt.Errorf("vMCP OBO converter: %w", err) + } + + return &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{ + TokenURL: tokenURL, + ClientID: cfg.ClientID, + Audience: cfg.Audience, + Scopes: cfg.Scopes, + SubjectTokenProviderName: cfg.SubjectTokenProviderName, + CacheSkewSeconds: cacheSkewSeconds, + }, + }, nil } -// ResolveSecrets returns an error wrapping obo.ErrEnterpriseRequired. +// ResolveSecrets fetches the client secret referenced by the OBO config's +// clientSecretRef from Kubernetes and sets it on the strategy (discovered-auth +// mode, where secrets cannot be mounted as pod env vars because the vMCP pod does +// not know about backend auth configs at creation time). It clears ClientSecretEnv +// so the resolved value is the single secret source, and returns the strategy +// unchanged when no secret reference is configured. +// +// The secret value is never logged and never written to the strategy's +// non-secret fields, so it does not leak into logs or CR status; error messages +// name the secret and key, never the value. func (*OBOConverter) ResolveSecrets( - _ context.Context, - _ *mcpv1beta1.MCPExternalAuthConfig, - _ client.Client, - _ string, - _ *authtypes.BackendAuthStrategy, + ctx context.Context, + externalAuth *mcpv1beta1.MCPExternalAuthConfig, + k8sClient client.Client, + namespace string, + strategy *authtypes.BackendAuthStrategy, ) (*authtypes.BackendAuthStrategy, error) { - return nil, fmt.Errorf("vMCP OBO converter: %w", obo.ErrEnterpriseRequired) + if strategy == nil || strategy.OBO == nil { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgStrategyNil) + } + + cfg := externalAuth.Spec.OBO + if cfg == nil { + return nil, fmt.Errorf("vMCP OBO converter: %s", msgOBONil) + } + + // Nothing to resolve without a secret reference. ConvertToStrategy requires + // clientSecretRef for the v1 flow, so this guards the standalone-call path. + if cfg.ClientSecretRef == nil { + return strategy, nil + } + + secret := &corev1.Secret{} + secretKey := types.NamespacedName{Name: cfg.ClientSecretRef.Name, Namespace: namespace} + if err := k8sClient.Get(ctx, secretKey, secret); err != nil { + return nil, fmt.Errorf("vMCP OBO converter: get secret %s/%s: %w", + namespace, cfg.ClientSecretRef.Name, err) + } + + value, ok := secret.Data[cfg.ClientSecretRef.Key] + if !ok { + return nil, fmt.Errorf("vMCP OBO converter: secret %s/%s has no key %s", + namespace, cfg.ClientSecretRef.Name, cfg.ClientSecretRef.Key) + } + + strategy.OBO.ClientSecretEnv = "" + strategy.OBO.ClientSecret = string(value) + return strategy, nil } + +// cacheSkewToSeconds converts the CRD's metav1.Duration cache skew into the +// vMCP contract's integer-seconds pointer. A nil skew leaves the cache default +// (returns nil); a negative skew is rejected, matching the operator OBO validation and +// avoiding the cache constructor's negative-skew panic at request time. +// +// The duration is truncated toward zero to whole seconds — identical to the +// operator's BuildOBOMiddlewareParameters (int(d.Seconds())) — so the same +// CRD value yields the same seconds on both surfaces. A sub-second skew therefore +// becomes 0, which the runtime treats as "use the cache default"; this matches +// the operator/runtime path exactly. The result is bounded: a duration whose +// whole-seconds value would overflow int32 is rejected loudly rather than +// wrapping to a wrong (or negative) value in the contract. +func cacheSkewToSeconds(d *metav1.Duration) (*int32, error) { + if d == nil { + return nil, nil + } + if d.Duration < 0 { + return nil, fmt.Errorf("%s", msgCacheSkewNegative) + } + seconds := int64(d.Duration / time.Second) // truncates toward zero + if seconds > math.MaxInt32 { + return nil, fmt.Errorf("%s", msgCacheSkewTooLarge) + } + v := int32(seconds) //nolint:gosec // G115: bounded to [0, MaxInt32] by the negative and MaxInt32 checks above + return &v, nil +} + +// Validation messages, spelled once so the converter and its tests share the +// exact literals and the linter does not flag repeated string constants. +const ( + msgOBONil = "obo configuration is nil" + msgStrategyNil = "obo strategy is nil" + msgClientID = "clientId is required" + msgClientSecretRef = "clientSecretRef must set a name and key" + msgAudienceOrScopes = "one of audience or scopes is required" + msgCacheSkewNegative = "cacheSkew must not be negative" + msgCacheSkewTooLarge = "cacheSkew is too large" +) diff --git a/pkg/vmcp/auth/converters/obo_test.go b/pkg/vmcp/auth/converters/obo_test.go index daecaf0440..3ba93f495f 100644 --- a/pkg/vmcp/auth/converters/obo_test.go +++ b/pkg/vmcp/auth/converters/obo_test.go @@ -4,153 +4,266 @@ package converters import ( - "context" + "math" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" - "github.com/stacklok/toolhive/pkg/auth/obo" authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" ) -func TestOBOConverter_StrategyType(t *testing.T) { +const ( + testTenant = "contoso.onmicrosoft.com" + testClientID = "client-123" + testSecretName = "obo-secret" + testSecretKey = "client-secret" + testSecretValue = "s3cr3t-value" + testNamespace = "default" + + // testTokenURL is the endpoint entra.TokenURL derives from testTenant with + // the default authority — pinned here so the test fails if the mapping drifts. + testTokenURL = "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token" +) + +// validOBOCR returns a well-formed obo-typed MCPExternalAuthConfig: a domain +// tenant, a client ID, a secret reference, and a single scope. +func validOBOCR() *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: testNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: testTenant, + ClientID: testClientID, + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: testSecretName, Key: testSecretKey}, + Scopes: []string{"api://backend/.default"}, + }, + }, + } +} + +// TestOBOConverter_IsRegistered verifies the default registry resolves the obo +// type to the built-in OBOConverter. +func TestOBOConverter_IsRegistered(t *testing.T) { + t.Parallel() + + got, err := DefaultRegistry().GetConverter(mcpv1beta1.ExternalAuthTypeOBO) + require.NoError(t, err) + assert.IsType(t, &OBOConverter{}, got) + assert.Equal(t, authtypes.StrategyTypeOBO, got.StrategyType()) +} + +// TestOBOConvertToStrategy_WellFormed proves a well-formed OBO config produces a +// valid BackendAuthStrategy: tenant+authority collapsed to the Entra token +// endpoint, fields mapped through, and no secret source set (the operator sets +// a per-config ClientSecretEnv in inline mode; ResolveSecrets sets ClientSecret in +// discovered mode). +func TestOBOConvertToStrategy_WellFormed(t *testing.T) { + t.Parallel() + + cr := validOBOCR() + cr.Spec.OBO.Audience = "api://backend" + cr.Spec.OBO.SubjectTokenProviderName = "entra" + cr.Spec.OBO.CacheSkew = &metav1.Duration{Duration: 45_000_000_000} // 45s + + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + require.NotNil(t, strategy) + require.NotNil(t, strategy.OBO) + + assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Type) + assert.Equal(t, testTokenURL, strategy.OBO.TokenURL) + assert.Equal(t, testClientID, strategy.OBO.ClientID) + assert.Equal(t, "api://backend", strategy.OBO.Audience) + assert.Equal(t, []string{"api://backend/.default"}, strategy.OBO.Scopes) + assert.Equal(t, "entra", strategy.OBO.SubjectTokenProviderName) + require.NotNil(t, strategy.OBO.CacheSkewSeconds) + assert.Equal(t, int32(45), *strategy.OBO.CacheSkewSeconds) + + assert.Empty(t, strategy.OBO.ClientSecret) + assert.Empty(t, strategy.OBO.ClientSecretEnv) +} + +// TestOBOConvertToStrategy_SovereignAuthority verifies a non-default authority is +// honored in the derived token endpoint. +func TestOBOConvertToStrategy_SovereignAuthority(t *testing.T) { t.Parallel() - assert.Equal(t, authtypes.StrategyTypeOBO, (&OBOConverter{}).StrategyType()) + cr := validOBOCR() + cr.Spec.OBO.Authority = "https://login.microsoftonline.us" + + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + assert.Equal(t, + "https://login.microsoftonline.us/contoso.onmicrosoft.com/oauth2/v2.0/token", + strategy.OBO.TokenURL) } -func TestOBOConverter_ConvertToStrategy(t *testing.T) { +// TestOBOConvertToStrategy_CacheSkewTruncation proves the metav1.Duration cache skew +// is truncated toward zero to whole seconds — identical to the operator handler +// (int(d.Seconds())) — so the same CRD value yields the same seconds on both +// surfaces. A sub-second skew truncates to 0 (the runtime's "use cache default"). +func TestOBOConvertToStrategy_CacheSkewTruncation(t *testing.T) { t.Parallel() tests := []struct { - name string - externalCfg *mcpv1beta1.MCPExternalAuthConfig + name string + skew time.Duration + want int32 }{ - {name: "nil config", externalCfg: nil}, - { - name: "obo-typed config", - externalCfg: &mcpv1beta1.MCPExternalAuthConfig{ - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, - }, - }, - }, + {name: "whole seconds", skew: 45 * time.Second, want: 45}, + {name: "truncates fractional toward zero", skew: 1500 * time.Millisecond, want: 1}, + {name: "truncates just under two seconds", skew: 1900 * time.Millisecond, want: 1}, + {name: "sub-second truncates to zero", skew: 600 * time.Millisecond, want: 0}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() + cr := validOBOCR() + cr.Spec.OBO.CacheSkew = &metav1.Duration{Duration: tt.skew} - strategy, err := (&OBOConverter{}).ConvertToStrategy(tt.externalCfg) - require.Error(t, err) - assert.Nil(t, strategy, "stub must not return a strategy on the error path") - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + require.NotNil(t, strategy.OBO.CacheSkewSeconds) + assert.Equal(t, tt.want, *strategy.OBO.CacheSkewSeconds) }) } } -func TestOBOConverter_ResolveSecrets(t *testing.T) { +// TestOBOConvertToStrategy_Malformed proves malformed configs are rejected with +// a message that names the actual reason. +func TestOBOConvertToStrategy_Malformed(t *testing.T) { t.Parallel() + // wantMsg pins the specific rejection reason so a validation-ordering bug that + // reports the wrong reason is caught (not just "some error occurred"). The + // converter-owned reasons use its message constants; the tenant/authority rows + // assert the entra.TokenURL message the converter surfaces verbatim. tests := []struct { - name string - externalCfg *mcpv1beta1.MCPExternalAuthConfig - strategy *authtypes.BackendAuthStrategy + name string + mutate func(*mcpv1beta1.OBOConfig) + nilOBO bool + wantMsg string }{ - {name: "nil inputs", externalCfg: nil, strategy: nil}, - { - name: "non-nil strategy", - externalCfg: &mcpv1beta1.MCPExternalAuthConfig{ - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, - }, - }, - strategy: &authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}, - }, + {name: "nil obo", nilOBO: true, wantMsg: msgOBONil}, + {name: "missing client id", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientID = "" }, wantMsg: msgClientID}, + {name: "missing client secret ref", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef = nil }, wantMsg: msgClientSecretRef}, + {name: "empty secret ref name", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef.Name = " " }, wantMsg: msgClientSecretRef}, + {name: "empty secret ref key", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef.Key = "" }, wantMsg: msgClientSecretRef}, + {name: "no audience or scopes", mutate: func(o *mcpv1beta1.OBOConfig) { o.Scopes = nil; o.Audience = "" }, wantMsg: msgAudienceOrScopes}, + {name: "negative cache skew", mutate: func(o *mcpv1beta1.OBOConfig) { + o.CacheSkew = &metav1.Duration{Duration: -1} + }, wantMsg: msgCacheSkewNegative}, + {name: "cache skew overflows int32 seconds", mutate: func(o *mcpv1beta1.OBOConfig) { + o.CacheSkew = &metav1.Duration{Duration: (math.MaxInt32 + 1) * time.Second} + }, wantMsg: msgCacheSkewTooLarge}, + // tenant/authority rejections are delegated to entra.TokenURL, whose + // (non-secret) message the converter wraps verbatim. + {name: "missing tenant", mutate: func(o *mcpv1beta1.OBOConfig) { o.TenantID = "" }, wantMsg: "TenantID is required"}, + {name: "tenant neither guid nor domain", mutate: func(o *mcpv1beta1.OBOConfig) { o.TenantID = "not a tenant" }, wantMsg: "must be a directory GUID or a domain name"}, + {name: "tenant with path separator", mutate: func(o *mcpv1beta1.OBOConfig) { o.TenantID = "evil/../x" }, wantMsg: "must be a directory GUID or a domain name"}, + {name: "non-https authority", mutate: func(o *mcpv1beta1.OBOConfig) { o.Authority = "http://login.microsoftonline.com" }, wantMsg: "must use https"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - resolved, err := (&OBOConverter{}).ResolveSecrets( - context.Background(), tt.externalCfg, nil, "default", tt.strategy, - ) + cr := validOBOCR() + if tt.nilOBO { + cr.Spec.OBO = nil + } else { + tt.mutate(cr.Spec.OBO) + } + + strategy, err := ConvertToStrategy(cr) require.Error(t, err) - assert.Nil(t, resolved, "stub must not return a strategy on the error path") - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) + assert.Nil(t, strategy) + assert.ErrorContains(t, err, tt.wantMsg, + "the rejection must name the actual reason, not merely error") }) } } -func TestOBOConverter_RegisteredInDefaultRegistry(t *testing.T) { +// TestOBOResolveSecrets_PopulatesFromK8s proves ResolveSecrets fetches the +// referenced secret and sets it on the strategy without leaking it onto any +// non-secret field. +func TestOBOResolveSecrets_PopulatesFromK8s(t *testing.T) { t.Parallel() - converter, err := NewRegistry().GetConverter(mcpv1beta1.ExternalAuthTypeOBO) + cr := validOBOCR() + strategy, err := ConvertToStrategy(cr) require.NoError(t, err) - require.NotNil(t, converter) - assert.IsType(t, &OBOConverter{}, converter) - // DefaultRegistry should also have it. - converter, err = DefaultRegistry().GetConverter(mcpv1beta1.ExternalAuthTypeOBO) + k8sClient := fakeClientWithSecret(t, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: testSecretName, Namespace: testNamespace}, + Data: map[string][]byte{testSecretKey: []byte(testSecretValue)}, + }) + + resolved, err := ResolveSecretsForStrategy(t.Context(), cr, k8sClient, testNamespace, strategy) require.NoError(t, err) - assert.IsType(t, &OBOConverter{}, converter) + require.NotNil(t, resolved.OBO) + + assert.Equal(t, testSecretValue, resolved.OBO.ClientSecret) + assert.Empty(t, resolved.OBO.ClientSecretEnv, "the env-var reference must be cleared once resolved") + + // Non-leak: the secret value must appear nowhere but ClientSecret. + assert.NotContains(t, resolved.OBO.TokenURL, testSecretValue) + assert.NotContains(t, resolved.OBO.ClientID, testSecretValue) + assert.NotContains(t, resolved.OBO.Audience, testSecretValue) } -// TestDiscoverAndResolveAuth_OBO_SentinelSurvivesWrap proves that the -// OBO sentinel propagates through DiscoverAndResolveAuth's -// `"failed to convert to strategy: %w"` wrap at interface.go:191 and -// remains recognizable via errors.Is. The vMCP integration path is -// structurally fragile: matching by the wrap-prefix string would silently -// degrade if the message ever changed. This test is the regression guard. -func TestDiscoverAndResolveAuth_OBO_SentinelSurvivesWrap(t *testing.T) { +// TestOBOResolveSecrets_Errors proves ResolveSecrets surfaces a missing secret or +// missing key as an error without echoing any secret value. +func TestOBOResolveSecrets_Errors(t *testing.T) { t.Parallel() + t.Run("secret missing", func(t *testing.T) { + t.Parallel() + cr := validOBOCR() + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + + k8sClient := fakeClientWithSecret(t) // no secret objects + _, err = ResolveSecretsForStrategy(t.Context(), cr, k8sClient, testNamespace, strategy) + require.Error(t, err) + }) + + t.Run("key missing in secret", func(t *testing.T) { + t.Parallel() + cr := validOBOCR() + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + + client := fakeClientWithSecret(t, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: testSecretName, Namespace: testNamespace}, + Data: map[string][]byte{"some-other-key": []byte(testSecretValue)}, + }) + _, err = ResolveSecretsForStrategy(t.Context(), cr, client, testNamespace, strategy) + require.Error(t, err) + assert.NotContains(t, err.Error(), testSecretValue, "the error must not echo the secret value") + assert.Empty(t, strategy.OBO.ClientSecret, "a failed resolve must not set the secret") + }) +} + +// fakeClientWithSecret builds a controller-runtime fake client seeded with the +// given secrets under a scheme that knows core/v1. +func fakeClientWithSecret(t *testing.T, secrets ...*corev1.Secret) client.Client { + t.Helper() scheme := runtime.NewScheme() - require.NoError(t, mcpv1beta1.AddToScheme(scheme)) require.NoError(t, corev1.AddToScheme(scheme)) - - cfg := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "obo-config", - Namespace: "default", - }, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: &mcpv1beta1.OBOConfig{}, - }, + builder := fake.NewClientBuilder().WithScheme(scheme) + for _, s := range secrets { + builder = builder.WithObjects(s) } - - fakeClient := fake.NewClientBuilder(). - WithScheme(scheme). - WithObjects(cfg). - Build() - - strategy, err := DiscoverAndResolveAuth( - t.Context(), - &mcpv1beta1.ExternalAuthConfigRef{Name: cfg.Name}, - cfg.Namespace, - fakeClient, - ) - - require.Error(t, err) - assert.Nil(t, strategy) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired, - "errors.Is must match the sentinel through the convert-to-strategy wrap") - - // Sanity: the wrap prefix is present, but recognition above is via - // errors.Is, not by string matching. - assert.Contains(t, err.Error(), "failed to convert to strategy") - - // Generic-error guards: the dispatch path must not leak generic strings. - assert.NotContains(t, err.Error(), "unsupported external auth type") - assert.NotContains(t, err.Error(), "unknown middleware type") + return builder.Build() } diff --git a/pkg/vmcp/auth/factory/outgoing.go b/pkg/vmcp/auth/factory/outgoing.go index 7eb3d9dc2b..424326c6c9 100644 --- a/pkg/vmcp/auth/factory/outgoing.go +++ b/pkg/vmcp/auth/factory/outgoing.go @@ -25,9 +25,7 @@ import ( // - "token_exchange": RFC-8693 OAuth 2.0 token exchange // - "upstream_inject": Per-upstream token injection from stored credentials // - "aws_sts": AWS STS AssumeRoleWithWebIdentity + SigV4 request signing -// - "obo": On-behalf-of (OBO) Entra token exchange; default stub returns -// obo.ErrEnterpriseRequired — an out-of-tree build registers a real -// strategy via auth.RegisterOBOStrategy before this function is called. +// - "obo": Microsoft Entra on-behalf-of (OBO) token exchange // - "xaa": Cross-Application Access (two-step ID-JAG exchange per // draft-ietf-oauth-identity-assertion-authz-grant) // diff --git a/pkg/vmcp/auth/factory/outgoing_test.go b/pkg/vmcp/auth/factory/outgoing_test.go index ea08113604..33bbcfffa6 100644 --- a/pkg/vmcp/auth/factory/outgoing_test.go +++ b/pkg/vmcp/auth/factory/outgoing_test.go @@ -5,14 +5,13 @@ package factory import ( "context" - "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stacklok/toolhive-core/env" - "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/vmcp/auth/strategies" authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" ) @@ -149,31 +148,21 @@ func TestNewOutgoingAuthRegistry(t *testing.T) { assert.NoError(t, err, "unauthenticated strategy should accept empty strategy") }) - t.Run("obo strategy default stub returns ErrEnterpriseRequired", func(t *testing.T) { + t.Run("obo strategy is the built-in Entra OBO strategy", func(t *testing.T) { t.Parallel() - ctx := context.Background() - envReader := &env.OSReader{} - registry, err := NewOutgoingAuthRegistry(ctx, envReader) + registry, err := NewOutgoingAuthRegistry(context.Background(), &env.OSReader{}) require.NoError(t, err) strategy, err := registry.GetStrategy(authtypes.StrategyTypeOBO) require.NoError(t, err, "obo strategy should be registered") - require.NotNil(t, strategy) - - assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Name()) - - cfg := &authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO} - - err = strategy.Validate(cfg) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired, "Validate: default obo stub must return ErrEnterpriseRequired") + assert.IsType(t, &strategies.OBOStrategy{}, strategy) - req, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, "http://example.com", nil) - require.NoError(t, reqErr) - err = strategy.Authenticate(req.Context(), req, cfg) + // A config with no token URL is rejected by the real validator, not by a + // licensing stub. + err = strategy.Validate(&authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}) require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired, "Authenticate: default obo stub must return ErrEnterpriseRequired") + assert.ErrorContains(t, err, "OBO configuration is required") }) t.Run("all strategies have correct names", func(t *testing.T) { diff --git a/pkg/vmcp/auth/obo.go b/pkg/vmcp/auth/obo.go index a3d23be63a..6e616237ab 100644 --- a/pkg/vmcp/auth/obo.go +++ b/pkg/vmcp/auth/obo.go @@ -4,83 +4,47 @@ package auth import ( - "context" - "fmt" - "net/http" "sync" "github.com/stacklok/toolhive-core/env" - "github.com/stacklok/toolhive/pkg/auth/obo" - authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" + "github.com/stacklok/toolhive/pkg/vmcp/auth/strategies" ) -// oboStrategyStub is the default OBO Strategy. Every method returns an error -// wrapping obo.ErrEnterpriseRequired. It is replaced at process start by an -// out-of-tree build calling RegisterOBOStrategy. -type oboStrategyStub struct{} - -// Name returns the strategy identifier for OBO. -func (*oboStrategyStub) Name() string { return authtypes.StrategyTypeOBO } - -// Authenticate returns obo.ErrEnterpriseRequired — the default build has no -// real OBO executor. An out-of-tree build registers a real strategy via -// RegisterOBOStrategy. -func (*oboStrategyStub) Authenticate(_ context.Context, _ *http.Request, _ *authtypes.BackendAuthStrategy) error { - return fmt.Errorf("vMCP OBO strategy: %w", obo.ErrEnterpriseRequired) -} - -// Validate returns obo.ErrEnterpriseRequired for the same reason as Authenticate. -func (*oboStrategyStub) Validate(_ *authtypes.BackendAuthStrategy) error { - return fmt.Errorf("vMCP OBO strategy: %w", obo.ErrEnterpriseRequired) -} - -// oboMu guards reads and writes of currentOBOStrategyFactory. Each call to -// NewOBOStrategy takes the read lock; RegisterOBOStrategy takes the write -// lock. Production today registers once during init(), but the lock makes -// re-registration safe for hot-reload / test scenarios. +// oboMu guards reads and writes of oboStrategyOverride. var oboMu sync.RWMutex -// currentOBOStrategyFactory is the package-level OBO strategy factory. -// The default returns the stub; an out-of-tree build replaces it via -// RegisterOBOStrategy. Access only through NewOBOStrategy (read) or -// RegisterOBOStrategy (write) so the mutex contract is preserved. -var currentOBOStrategyFactory = func(_ env.Reader) Strategy { - return &oboStrategyStub{} -} +// oboStrategyOverride is the factory registered through the deprecated +// RegisterOBOStrategy, or nil when none was registered. +var oboStrategyOverride func(env.Reader) Strategy -// RegisterOBOStrategy replaces the package-level OBO strategy factory. It is -// intended to be called exactly once during init() in an out-of-tree package -// that blank-imports pkg/vmcp/auth. +// RegisterOBOStrategy replaces the strategy NewOBOStrategy returns. +// Last-write-wins. Panics if f is nil. // -// Calling it more than once is allowed and last-write-wins, matching the -// existing obo.RegisterFactory and controllerutil.RegisterOBOHandler -// precedents. Panics if f is nil — a nil factory would nil-deref on the next -// NewOBOStrategy call, far from the registration site; surfacing the problem -// at init() time is far easier to diagnose than at request time. -// -// The replacement is only effective if the running vMCP binary links the -// package that calls RegisterOBOStrategy. An out-of-tree binary must -// blank-import the overlay package from its cmd/vmcp entrypoint; the upstream -// cmd/vmcp does not. +// Deprecated: OBO is built in; NewOBOStrategy returns the Entra OBO strategy +// from pkg/vmcp/auth/strategies. RegisterOBOStrategy is kept only so +// out-of-tree code that still calls it keeps compiling; it will be removed in +// a future release. func RegisterOBOStrategy(f func(env.Reader) Strategy) { if f == nil { panic("auth.RegisterOBOStrategy: factory is nil") } oboMu.Lock() defer oboMu.Unlock() - currentOBOStrategyFactory = f + oboStrategyOverride = f } -// NewOBOStrategy returns the OBO Strategy produced by the currently registered -// factory. With the default factory it returns the stub (whose Authenticate -// and Validate return obo.ErrEnterpriseRequired). With a registered out-of-tree -// factory it returns the real Entra OBO executor. +// NewOBOStrategy returns the vMCP outgoing-auth strategy for on-behalf-of +// (OBO): the built-in Entra OBO strategy, or the strategy produced by a factory +// registered through the deprecated RegisterOBOStrategy. // // Called by factory.NewOutgoingAuthRegistry when building the registry; the -// returned strategy is registered once and reused for all subsequent requests. +// returned strategy is registered once and reused for all requests. func NewOBOStrategy(envReader env.Reader) Strategy { oboMu.RLock() - f := currentOBOStrategyFactory + f := oboStrategyOverride oboMu.RUnlock() - return f(envReader) + if f != nil { + return f(envReader) + } + return strategies.NewOBOStrategy(envReader) } diff --git a/pkg/vmcp/auth/obo_test.go b/pkg/vmcp/auth/obo_test.go index 8ab230be2f..7e3aa8416d 100644 --- a/pkg/vmcp/auth/obo_test.go +++ b/pkg/vmcp/auth/obo_test.go @@ -13,31 +13,26 @@ import ( "github.com/stretchr/testify/require" "github.com/stacklok/toolhive-core/env" - "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/vmcp/auth/strategies" authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" ) -// withDefaultOBOFactory captures and restores the package-level OBO strategy -// factory so tests that call RegisterOBOStrategy do not leak state. -func withDefaultOBOFactory(t *testing.T) { +// withNoOBOOverride clears and restores the package-level OBO strategy +// override so tests that call RegisterOBOStrategy do not leak state. +func withNoOBOOverride(t *testing.T) { t.Helper() - oboMu.RLock() - original := currentOBOStrategyFactory - oboMu.RUnlock() + oboMu.Lock() + original := oboStrategyOverride + oboStrategyOverride = nil + oboMu.Unlock() t.Cleanup(func() { oboMu.Lock() - currentOBOStrategyFactory = original + oboStrategyOverride = original oboMu.Unlock() }) } -// fakeEnvReader is a sentinel env.Reader used to verify that NewOBOStrategy forwards the reader to the factory. -type fakeEnvReader struct{} - -func (*fakeEnvReader) Getenv(_ string) string { return "" } -func (*fakeEnvReader) LookupEnv(_ string) (string, bool) { return "", false } - -// namedStrategy returns a distinct error message to identify which strategy instance was returned. +// namedStrategy returns its tag from Validate to identify which instance was returned. type namedStrategy struct{ tag string } func (*namedStrategy) Name() string { return authtypes.StrategyTypeOBO } @@ -48,101 +43,29 @@ func (s *namedStrategy) Validate(_ *authtypes.BackendAuthStrategy) error { return errors.New(s.tag) } -func TestOBOStrategyStub_Name(t *testing.T) { - t.Parallel() +//nolint:paralleltest // Mutates package-level oboStrategyOverride; must not race other tests. +func TestNewOBOStrategy_DefaultIsBuiltIn(t *testing.T) { + withNoOBOOverride(t) - s := &oboStrategyStub{} - assert.Equal(t, authtypes.StrategyTypeOBO, s.Name()) + got := NewOBOStrategy(&env.OSReader{}) + assert.IsType(t, &strategies.OBOStrategy{}, got) + assert.Equal(t, authtypes.StrategyTypeOBO, got.Name()) } -func TestOBOStrategyStub_Authenticate_ReturnsEnterpriseRequired(t *testing.T) { - t.Parallel() +//nolint:paralleltest // Mutates package-level oboStrategyOverride; must not race other tests. +func TestRegisterOBOStrategy_OverridesBuiltIn(t *testing.T) { + withNoOBOOverride(t) - s := &oboStrategyStub{} - ctx := context.Background() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://example.com", nil) - require.NoError(t, err) + RegisterOBOStrategy(func(_ env.Reader) Strategy { return &namedStrategy{tag: "first"} }) + RegisterOBOStrategy(func(_ env.Reader) Strategy { return &namedStrategy{tag: "second"} }) - err = s.Authenticate(req.Context(), req, &authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}) + err := NewOBOStrategy(nil).Validate(&authtypes.BackendAuthStrategy{}) require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) + assert.Equal(t, "second", err.Error(), "the last registered factory must win") } -func TestOBOStrategyStub_Validate_ReturnsEnterpriseRequired(t *testing.T) { +func TestRegisterOBOStrategy_PanicsOnNil(t *testing.T) { t.Parallel() - s := &oboStrategyStub{} - err := s.Validate(&authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}) - require.Error(t, err) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) -} - -//nolint:paralleltest // Reads package-level currentOBOStrategyFactory; must not race other tests. -func TestNewOBOStrategy_DefaultReturnsStub(t *testing.T) { - withDefaultOBOFactory(t) - - strategy := NewOBOStrategy(nil) - require.NotNil(t, strategy) - assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Name()) - - err := strategy.Validate(&authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}) - assert.ErrorIs(t, err, obo.ErrEnterpriseRequired) -} - -//nolint:paralleltest // Mutates package-level currentOBOStrategyFactory; must not race other tests. -func TestRegisterOBOStrategy_ReplacesFactory(t *testing.T) { - withDefaultOBOFactory(t) - - const tag = "registered-strategy" - RegisterOBOStrategy(func(_ env.Reader) Strategy { - return &namedStrategy{tag: tag} - }) - - got := NewOBOStrategy(nil) - err := got.Validate(&authtypes.BackendAuthStrategy{}) - require.Error(t, err) - assert.Equal(t, tag, err.Error(), "factory replacement should produce the registered strategy") - assert.NotErrorIs(t, err, obo.ErrEnterpriseRequired, "registered strategy should not return the stub error") -} - -//nolint:paralleltest // Mutates package-level currentOBOStrategyFactory; must not race other tests. -func TestRegisterOBOStrategy_LastWriteWins(t *testing.T) { - withDefaultOBOFactory(t) - - RegisterOBOStrategy(func(_ env.Reader) Strategy { - return &namedStrategy{tag: "first"} - }) - RegisterOBOStrategy(func(_ env.Reader) Strategy { - return &namedStrategy{tag: "second"} - }) - - got := NewOBOStrategy(nil) - err := got.Validate(&authtypes.BackendAuthStrategy{}) - require.Error(t, err) - assert.Equal(t, "second", err.Error(), "last RegisterOBOStrategy call should win") -} - -//nolint:paralleltest // Mutates package-level currentOBOStrategyFactory; must not race other tests. -func TestRegisterOBOStrategy_NilPanics(t *testing.T) { - withDefaultOBOFactory(t) - - assert.Panics(t, func() { - RegisterOBOStrategy(nil) - }) -} - -//nolint:paralleltest // Mutates package-level currentOBOStrategyFactory; must not race other tests. -func TestRegisterOBOStrategy_EnvReaderPassedThrough(t *testing.T) { - withDefaultOBOFactory(t) - - // Verify the envReader passed to NewOBOStrategy reaches the factory. - var captured env.Reader - fakeReader := &fakeEnvReader{} - RegisterOBOStrategy(func(r env.Reader) Strategy { - captured = r - return &oboStrategyStub{} - }) - - NewOBOStrategy(fakeReader) - assert.Equal(t, fakeReader, captured, "env.Reader must be forwarded to the factory") + assert.Panics(t, func() { RegisterOBOStrategy(nil) }) } diff --git a/pkg/vmcp/auth/strategies/obo.go b/pkg/vmcp/auth/strategies/obo.go new file mode 100644 index 0000000000..15ce2cdd72 --- /dev/null +++ b/pkg/vmcp/auth/strategies/obo.go @@ -0,0 +1,339 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package strategies + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "net/http" + "sync" + "time" + + "github.com/stacklok/toolhive-core/env" + "github.com/stacklok/toolhive/pkg/audit" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/auth/obo/cache" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" + authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" + healthcontext "github.com/stacklok/toolhive/pkg/vmcp/health/context" +) + +// oboAuditComponent identifies the vMCP OBO strategy as the source component +// of its audit records. +const oboAuditComponent = "toolhive-obo-vmcp" + +// OBOStrategy is the vMCP outgoing-auth strategy for Microsoft Entra +// on-behalf-of (OBO). At request time it takes the OBO subject (assertion) +// token from the authenticated Identity the vMCP incoming-auth layer placed in +// the request context, exchanges it through a cached Entra Exchanger for a +// backend-scoped token, and sets Authorization: Bearer on the +// outgoing request. The subject is the inbound token the client presented +// (Identity.Token, the default) or, when OBOConfig.SubjectTokenProviderName is +// set, that upstream provider's token (Identity.UpstreamTokens[name]). +// +// It is the vMCP counterpart of the proxy middleware in pkg/auth/obo: both +// derive the exchange target with exchange.Target, so identical config sends +// Entra the same scope and partitions the token cache the same way. On a +// conditional-access or claims challenge it fails fast: it records an audit +// event and returns an error without injecting a token. +// +// It caches one Entra Exchanger (fronted by the per-user token cache) per backend +// configuration, so the token cache survives across requests; per-user token +// caching is handled inside that cache. Safe for concurrent use. +type OBOStrategy struct { + envReader env.Reader + auditLogger *slog.Logger + + // buildExchanger constructs the cached Exchanger for a config. It is a field + // so tests can inject a stub Exchanger instead of a real Entra HTTP client; + // production uses defaultBuildOBOExchanger. + buildExchanger func(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) + + // exchangers caches the per-backend Exchanger keyed by oboExchangerCacheKey. Each + // is shared across all users of that backend (the cache partitions per user + // internally). + mu sync.RWMutex + exchangers map[string]exchange.Exchanger +} + +// NewOBOStrategy returns a Strategy using the default Entra+cache Exchanger builder +// and the default JSON audit logger. envReader resolves a client secret supplied +// via ClientSecretEnv (the operator-managed config path); the discovered-auth +// path supplies the resolved secret on the config directly. +func NewOBOStrategy(envReader env.Reader) *OBOStrategy { + return newOBOStrategy(envReader, nil, nil) +} + +// newOBOStrategy is the test-friendly constructor. A nil auditLogger gets the +// default JSON audit logger; a nil build gets defaultBuildOBOExchanger. +func newOBOStrategy( + envReader env.Reader, + auditLogger *slog.Logger, + build func(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error), +) *OBOStrategy { + if auditLogger == nil { + auditLogger = audit.NewAuditLogger(nil) + } + if build == nil { + build = defaultBuildOBOExchanger + } + return &OBOStrategy{ + envReader: envReader, + auditLogger: auditLogger, + buildExchanger: build, + exchangers: make(map[string]exchange.Exchanger), + } +} + +// Name returns the strategy identifier ("obo"), matching the dispatch key the +// converter and the registry use. +func (*OBOStrategy) Name() string { return authtypes.StrategyTypeOBO } + +// Authenticate exchanges the request's user token for a backend token and injects +// it. For a health-check probe (no user identity) it skips authentication. It +// returns an error — injecting nothing — when the config is invalid, no identity +// or subject token is present, or the exchange fails; a conditional-access / +// claims challenge additionally emits an audit record. +func (s *OBOStrategy) Authenticate( + ctx context.Context, req *http.Request, strategy *authtypes.BackendAuthStrategy, +) error { + cfg, clientSecret, err := s.resolveConfig(strategy) + if err != nil { + return fmt.Errorf("obo: invalid strategy configuration: %w", err) + } + + // Health probes carry no user identity, and OBO has no user to act on behalf + // of, so skip authentication and let the backend be probed unauthenticated — + // mirroring the token-exchange strategy's no-credentials health path. + if healthcontext.IsHealthCheck(ctx) { + return nil + } + + identity, ok := auth.IdentityFromContext(ctx) + if !ok { + return fmt.Errorf("obo: no identity found in context") + } + + userToken, err := oboSubjectToken(identity, cfg.SubjectTokenProviderName) + if err != nil { + return err + } + + exchanger, err := s.getOrCreateExchanger(cfg, clientSecret) + if err != nil { + return fmt.Errorf("obo: build exchanger: %w", err) + } + + target := oboExchangeTarget(cfg) + backendToken, err := exchanger.Exchange(ctx, userToken, target) + if err != nil { + return s.mapExchangeError(ctx, identity, target, err) + } + + // Overwrite Authorization with the backend-scoped token so the raw subject + // token never reaches the backend. + req.Header.Set("Authorization", "Bearer "+backendToken) + return nil +} + +// Validate checks the strategy's OBO configuration shape and that a client secret +// is resolvable, failing fast at client-creation time rather than per request. +func (s *OBOStrategy) Validate(strategy *authtypes.BackendAuthStrategy) error { + _, _, err := s.resolveConfig(strategy) + return err +} + +// resolveConfig validates the OBO config and resolves the client secret. The +// secret comes from the resolved ClientSecret (discovered-auth path) or, failing +// that, from the environment variable named by ClientSecretEnv (operator-managed +// path). Mirrors the token-exchange strategy's parse step. +func (s *OBOStrategy) resolveConfig(strategy *authtypes.BackendAuthStrategy) (*authtypes.OBOConfig, string, error) { + cfg, err := parseOBOConfig(strategy) + if err != nil { + return nil, "", err + } + secret, err := s.resolveClientSecret(cfg) + if err != nil { + return nil, "", err + } + return cfg, secret, nil +} + +// resolveClientSecret returns the client secret from the config or its named +// environment variable. ClientSecret takes precedence; the mutual-exclusion of +// ClientSecret and ClientSecretEnv is enforced in parseOBOConfig. +func (s *OBOStrategy) resolveClientSecret(cfg *authtypes.OBOConfig) (string, error) { + if cfg.ClientSecret != "" { + return cfg.ClientSecret, nil + } + if cfg.ClientSecretEnv != "" { + secret := s.envReader.Getenv(cfg.ClientSecretEnv) + if secret == "" { + return "", fmt.Errorf("environment variable %s is not set or empty", cfg.ClientSecretEnv) + } + return secret, nil + } + return "", fmt.Errorf("a client secret is required (clientSecret or clientSecretEnv)") +} + +// getOrCreateExchanger returns the cached Exchanger for cfg, building it on first +// use under a double-checked lock so the per-user token cache is shared across +// requests to the same backend. +func (s *OBOStrategy) getOrCreateExchanger(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) { + key := oboExchangerCacheKey(cfg, clientSecret) + + s.mu.RLock() + if ex, ok := s.exchangers[key]; ok { + s.mu.RUnlock() + return ex, nil + } + s.mu.RUnlock() + + s.mu.Lock() + defer s.mu.Unlock() + if ex, ok := s.exchangers[key]; ok { + return ex, nil + } + + ex, err := s.buildExchanger(cfg, clientSecret) + if err != nil { + return nil, err + } + s.exchangers[key] = ex + return ex, nil +} + +// mapExchangeError translates an exchange failure into the error the Strategy +// returns, without disclosing token or secret material (the Entra error already +// composes only non-sensitive fields). A conditional-access / claims challenge +// fails fast with an audit record; a cancelled context propagates +// as-is so it is not misreported as a backend failure. +func (s *OBOStrategy) mapExchangeError( + ctx context.Context, identity *auth.Identity, target string, err error, +) error { + switch { + case errors.Is(err, entra.ErrInteractionRequired): + s.auditInteractionRequired(ctx, identity, target, err) + return fmt.Errorf("obo: token exchange denied: %w", err) + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + return err + default: + return fmt.Errorf("obo: token exchange failed: %w", err) + } +} + +// auditInteractionRequired emits the audit record for a fail-fast +// conditional-access or claims challenge (see obo.NewInteractionRequiredAuditEvent +// for what it does and does not record). +// +// Unlike the proxy middleware, which runs on the inbound server request and +// records the client IP as a network source, this strategy runs on the +// backend-bound request, which carries no inbound client address. The source is +// therefore recorded as local to this component; the denied principal is carried +// by the subjects map. +func (s *OBOStrategy) auditInteractionRequired( + ctx context.Context, identity *auth.Identity, target string, err error, +) { + event := obo.NewInteractionRequiredAuditEvent( + audit.EventSource{Type: audit.SourceTypeLocal, Value: oboAuditComponent}, + oboAuditComponent, identity, target, err) + event.LogTo(ctx, s.auditLogger, audit.LevelAudit) +} + +// defaultBuildOBOExchanger constructs the production Exchanger: a cached Entra +// on-behalf-of Exchanger built from the config's token URL, client ID, and +// resolved client secret. +// +// A skew override is applied only when strictly positive. A resolved 0 (whether +// configured as "0s" or truncated down from a sub-second value) leaves the cache's +// default skew in place — matching the proxy-runtime middleware, whose gate is +// also `> 0` and whose contract field is a non-pointer int that cannot distinguish +// an explicit 0 from "unset". Keeping the same gate here preserves cross-surface +// parity: the same CRD value yields the same effective skew on both paths. +func defaultBuildOBOExchanger(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) { + exchanger, err := entra.NewFromTokenURL(cfg.TokenURL, cfg.ClientID, clientSecret, nil) + if err != nil { + return nil, err + } + + var opts []cache.Option + if cfg.CacheSkewSeconds != nil && *cfg.CacheSkewSeconds > 0 { + opts = append(opts, cache.WithSkew(time.Duration(*cfg.CacheSkewSeconds)*time.Second)) + } + return cache.New(exchanger, opts...), nil +} + +// parseOBOConfig validates the OBO configuration shape carried on the strategy. It +// does not resolve the client secret (see resolveClientSecret). +func parseOBOConfig(strategy *authtypes.BackendAuthStrategy) (*authtypes.OBOConfig, error) { + if strategy == nil || strategy.OBO == nil { + return nil, fmt.Errorf("OBO configuration is required") + } + cfg := strategy.OBO + + if cfg.TokenURL == "" { + return nil, fmt.Errorf("tokenUrl is required") + } + if cfg.ClientID == "" { + return nil, fmt.Errorf("clientId is required") + } + if cfg.ClientSecret != "" && cfg.ClientSecretEnv != "" { + return nil, fmt.Errorf("clientSecret and clientSecretEnv are mutually exclusive") + } + if oboExchangeTarget(cfg) == "" { + return nil, fmt.Errorf("one of audience or scopes is required") + } + if cfg.CacheSkewSeconds != nil && *cfg.CacheSkewSeconds < 0 { + return nil, fmt.Errorf("cacheSkewSeconds must not be negative") + } + return cfg, nil +} + +// oboExchangeTarget collapses the config's audience/scopes with +// exchange.Target, the same rule the proxy middleware uses, so identical config +// sends Entra the same scope and uses the same cache partition key. +func oboExchangeTarget(cfg *authtypes.OBOConfig) string { + return exchange.Target(cfg.Audience, cfg.Scopes) +} + +// oboSubjectToken resolves the OBO subject (assertion) token from the authenticated +// Identity. With an empty providerName it uses the inbound token the client +// presented (Identity.Token); with a providerName set it uses that upstream +// provider's token (Identity.UpstreamTokens[name]). +func oboSubjectToken(identity *auth.Identity, providerName string) (string, error) { + if providerName != "" { + token := identity.UpstreamTokens[providerName] // nil map read is safe + if token == "" { + return "", fmt.Errorf("obo: provider %q: %w", providerName, authtypes.ErrUpstreamTokenNotFound) + } + return token, nil + } + if identity.Token == "" { + return "", fmt.Errorf("obo: identity has no token") + } + return identity.Token, nil +} + +// oboExchangerCacheKey identifies the per-backend Exchanger by the fields that +// determine it and its cache: token URL, client ID, cache skew, and a fingerprint +// of the client secret. The secret is included as a SHA-256 hex digest — never +// raw — so two configs sharing a (URL, clientID) but differing in secret cannot +// silently share the first-cached Exchanger (a cross-config credential-confusion +// risk), and a rotated secret warms a fresh entry rather than reusing the stale +// one. Hashing (rather than embedding the secret) mirrors how obo/cache keys the +// sensitive user token. +func oboExchangerCacheKey(cfg *authtypes.OBOConfig, clientSecret string) string { + skew := int32(0) + if cfg.CacheSkewSeconds != nil { + skew = *cfg.CacheSkewSeconds + } + secretFP := sha256.Sum256([]byte(clientSecret)) + return fmt.Sprintf("%s\x00%s\x00%d\x00%s", cfg.TokenURL, cfg.ClientID, skew, hex.EncodeToString(secretFP[:])) +} diff --git a/pkg/vmcp/auth/strategies/obo_test.go b/pkg/vmcp/auth/strategies/obo_test.go new file mode 100644 index 0000000000..4dee7d2c38 --- /dev/null +++ b/pkg/vmcp/auth/strategies/obo_test.go @@ -0,0 +1,425 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package strategies + +import ( + "bytes" + "context" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive-core/env" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" + "github.com/stacklok/toolhive/pkg/auth/obo/exchange" + authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" + healthcontext "github.com/stacklok/toolhive/pkg/vmcp/health/context" +) + +const ( + oboTestTokenURL = "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token" + oboTestClientID = "client-123" + oboTestSubject = "user-123" + oboTestScope = "api://backend/.default" +) + +// oboStubExchanger is a configurable exchange.Exchanger test double recording the last +// call's arguments. +type oboStubExchanger struct { + token string + err error + calls int + lastUserToken string + lastAudience string +} + +var _ exchange.Exchanger = (*oboStubExchanger)(nil) + +func (s *oboStubExchanger) Exchange(_ context.Context, userToken, audience string) (string, error) { + s.calls++ + s.lastUserToken = userToken + s.lastAudience = audience + return s.token, s.err +} + +// oboMapEnv is a minimal env.Reader backed by a map. +type oboMapEnv map[string]string + +var _ env.Reader = oboMapEnv(nil) + +func (m oboMapEnv) Getenv(key string) string { return m[key] } + +func (m oboMapEnv) LookupEnv(key string) (string, bool) { + v, ok := m[key] + return v, ok +} + +// oboStrategyWithStub returns a Strategy whose Exchanger is always stub and whose +// audit records go to auditLogger (nil for the default). +func oboStrategyWithStub(stub *oboStubExchanger, auditLogger *slog.Logger) *OBOStrategy { + return newOBOStrategy(oboMapEnv{}, auditLogger, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { + return stub, nil + }) +} + +// validOBOStrategy returns a well-formed obo BackendAuthStrategy with the client +// secret already resolved (the discovered-auth state at request time). +func validOBOStrategy() *authtypes.BackendAuthStrategy { + return &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{ + TokenURL: oboTestTokenURL, + ClientID: oboTestClientID, + ClientSecret: "resolved-secret", + Scopes: []string{oboTestScope}, + }, + } +} + +// oboInboundIdentity returns an Identity carrying token as the inbound subject. +func oboInboundIdentity(token string) *auth.Identity { + return &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: oboTestSubject}, + Token: token, + } +} + +// oboServeAuthenticate runs Authenticate against a request carrying ctx and returns +// the request (for header inspection) and the error. +func oboServeAuthenticate( + ctx context.Context, t *testing.T, s *OBOStrategy, strat *authtypes.BackendAuthStrategy, +) (*http.Request, error) { + t.Helper() + // Authenticate runs on the outgoing backend-bound request (the vMCP client's + // round-tripper), which — like the real call path — carries no inbound client + // RemoteAddr; the audit source is therefore local to the component, not a + // network IP. + req := httptest.NewRequestWithContext(ctx, http.MethodPost, "http://backend.local/", nil) + return req, s.Authenticate(ctx, req, strat) +} + +func TestOBOStrategy_Name(t *testing.T) { + t.Parallel() + assert.Equal(t, authtypes.StrategyTypeOBO, (&OBOStrategy{}).Name()) +} + +// TestOBOAuthenticate_InboundSuccess exchanges the inbound token and injects the +// backend token, sending Entra the collapsed scope. +func TestOBOAuthenticate_InboundSuccess(t *testing.T) { + t.Parallel() + + stub := &oboStubExchanger{token: "backend-token"} + s := oboStrategyWithStub(stub, nil) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.NoError(t, err) + + assert.Equal(t, "Bearer backend-token", req.Header.Get("Authorization")) + assert.Equal(t, "user-token", stub.lastUserToken) + assert.Equal(t, oboTestScope, stub.lastAudience, "the exchange target is the collapsed scope") +} + +// TestOBOAuthenticate_UpstreamProviderSuccess uses a named upstream provider's token +// as the subject when SubjectTokenProviderName is set. +func TestOBOAuthenticate_UpstreamProviderSuccess(t *testing.T) { + t.Parallel() + + stub := &oboStubExchanger{token: "backend-token"} + s := oboStrategyWithStub(stub, nil) + + strat := validOBOStrategy() + strat.OBO.SubjectTokenProviderName = "entra" + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: oboTestSubject}, + Token: "session-token", // the proxy's own token, not the subject + UpstreamTokens: map[string]string{"entra": "upstream-token"}, + } + ctx := auth.WithIdentity(t.Context(), identity) + + req, err := oboServeAuthenticate(ctx, t, s, strat) + require.NoError(t, err) + assert.Equal(t, "Bearer backend-token", req.Header.Get("Authorization")) + assert.Equal(t, "upstream-token", stub.lastUserToken, "the named provider token is the subject") +} + +// TestOBOAuthenticate_SubjectErrors covers the missing-identity / missing-token +// failure modes: each returns an error and injects nothing. +func TestOBOAuthenticate_SubjectErrors(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + ctx func(t *testing.T) context.Context + strat func() *authtypes.BackendAuthStrategy + }{ + { + name: "no identity in context", + ctx: func(t *testing.T) context.Context { t.Helper(); return t.Context() }, + strat: validOBOStrategy, + }, + { + name: "identity has no inbound token", + ctx: func(t *testing.T) context.Context { + t.Helper() + return auth.WithIdentity(t.Context(), oboInboundIdentity("")) + }, + strat: validOBOStrategy, + }, + { + name: "named provider token absent", + ctx: func(t *testing.T) context.Context { + t.Helper() + return auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + }, + strat: func() *authtypes.BackendAuthStrategy { + s := validOBOStrategy() + s.OBO.SubjectTokenProviderName = "entra" + return s + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stub := &oboStubExchanger{token: "unused"} + s := oboStrategyWithStub(stub, nil) + + req, err := oboServeAuthenticate(tt.ctx(t), t, s, tt.strat()) + require.Error(t, err) + assert.Empty(t, req.Header.Get("Authorization"), "no token may be injected on failure") + assert.Zero(t, stub.calls, "no exchange should be attempted") + }) + } +} + +// TestOBOAuthenticate_HealthCheckSkips proves a health probe (no user identity) +// skips authentication rather than failing. +func TestOBOAuthenticate_HealthCheckSkips(t *testing.T) { + t.Parallel() + + stub := &oboStubExchanger{token: "unused"} + s := oboStrategyWithStub(stub, nil) + ctx := healthcontext.WithHealthCheckMarker(t.Context()) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.NoError(t, err) + assert.Empty(t, req.Header.Get("Authorization")) + assert.Zero(t, stub.calls) +} + +// TestOBOAuthenticate_ConditionalAccess_FailsFastWithAudit proves a conditional- +// access / claims challenge returns an error, injects nothing, and emits an +// audit record that names the denied subject but discloses neither the user +// token nor the raw claims challenge. +func TestOBOAuthenticate_ConditionalAccess_FailsFastWithAudit(t *testing.T) { + t.Parallel() + + const ( + userToken = "user-token-secret" + claims = `{"access_token":{"acrs":{"essential":true}}}` + ) + exErr := &entra.ExchangeError{ + Kind: entra.KindInteractionRequired, + OAuthError: "interaction_required", + Description: "AADSTS50076: MFA required", + Claims: claims, + HTTPStatus: http.StatusUnauthorized, + } + require.ErrorIs(t, exErr, entra.ErrInteractionRequired) + + var auditBuf bytes.Buffer + auditLogger := slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) + stub := &oboStubExchanger{err: exErr} + s := oboStrategyWithStub(stub, auditLogger) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity(userToken)) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.Error(t, err) + assert.ErrorIs(t, err, entra.ErrInteractionRequired) + assert.Empty(t, req.Header.Get("Authorization"), "fail-fast must not inject a token") + + out := auditBuf.String() + assert.NotEmpty(t, out, "a conditional-access denial must emit an audit record") + assert.Contains(t, out, obo.AuditEventType) + assert.Contains(t, out, "denied") + assert.Contains(t, out, "interaction_required") + assert.Contains(t, out, oboAuditComponent, "the audit source is local to this outgoing-auth component") + assert.Contains(t, out, oboTestSubject, "the audit record identifies the denied subject") + assert.NotContains(t, out, userToken, "the audit record must not contain the user token") + assert.NotContains(t, out, claims, "the audit record must not contain the raw claims challenge") +} + +// TestOBOAuthenticate_OtherExchangeError_NoAudit proves a non-CA exchange failure +// returns an error and injects nothing, without emitting a D1 audit record. +func TestOBOAuthenticate_OtherExchangeError_NoAudit(t *testing.T) { + t.Parallel() + + var auditBuf bytes.Buffer + auditLogger := slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) + stub := &oboStubExchanger{err: &entra.ExchangeError{Kind: entra.KindInvalidGrant, OAuthError: "invalid_grant"}} + s := oboStrategyWithStub(stub, auditLogger) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.Error(t, err) + assert.ErrorIs(t, err, entra.ErrInvalidGrant) + assert.Empty(t, req.Header.Get("Authorization")) + assert.Empty(t, auditBuf.String(), "only conditional-access denials emit the D1 audit record") +} + +// TestOBOAuthenticate_CachesExchangerPerConfig proves the per-backend Exchanger is +// built once and reused across requests, so the per-user token cache is shared. +func TestOBOAuthenticate_CachesExchangerPerConfig(t *testing.T) { + t.Parallel() + + builds := 0 + stub := &oboStubExchanger{token: "backend-token"} + s := newOBOStrategy(oboMapEnv{}, nil, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { + builds++ + return stub, nil + }) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + for range 3 { + _, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.NoError(t, err) + } + assert.Equal(t, 1, builds, "the exchanger must be built once and cached per backend config") +} + +// TestOBOAuthenticate_RealEntraExchange exercises the production path end-to-end: +// NewOBOStrategy (default buildExchanger) wires entra.NewFromTokenURL + cache.New / +// WithSkew, and Authenticate performs a real HTTP OBO exchange against an +// httptest server standing in for the Entra token endpoint (loopback http, which +// NewFromTokenURL permits). This is the only test that drives defaultBuildOBOExchanger +// rather than a stub, +// including the positive CacheSkewSeconds gate. +func TestOBOAuthenticate_RealEntraExchange(t *testing.T) { + t.Parallel() + + var gotAuthHeader, gotGrantType string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuthHeader = r.Header.Get("Authorization") + _ = r.ParseForm() + gotGrantType = r.Form.Get("grant_type") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"token_type":"Bearer","expires_in":3599,"access_token":"backend-abc"}`)) + })) + defer srv.Close() + + skew := int32(120) // exercise the CacheSkewSeconds > 0 gate in defaultBuildOBOExchanger + s := NewOBOStrategy(oboMapEnv{}) + strat := &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{ + TokenURL: srv.URL, // loopback http — accepted by NewFromTokenURL + ClientID: oboTestClientID, + ClientSecret: "resolved-secret", + Scopes: []string{oboTestScope}, + CacheSkewSeconds: &skew, + }, + } + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + req, err := oboServeAuthenticate(ctx, t, s, strat) + require.NoError(t, err) + assert.Equal(t, "Bearer backend-abc", req.Header.Get("Authorization"), + "the backend-scoped token from the real exchange must be injected") + assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", gotGrantType, + "the exchange must use the Entra on-behalf-of (jwt-bearer) grant") + assert.NotContains(t, gotAuthHeader, "user-token", + "the subject token must travel in the form body, not the request's Authorization header") +} + +func TestOBOValidate_Valid(t *testing.T) { + t.Parallel() + s := NewOBOStrategy(&env.OSReader{}) + require.NoError(t, s.Validate(validOBOStrategy())) +} + +// TestOBOValidate_Invalid rejects malformed strategy configurations. +func TestOBOValidate_Invalid(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + mutate func(*authtypes.BackendAuthStrategy) + wantMsg string + }{ + {name: "nil obo", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO = nil }, wantMsg: "OBO configuration is required"}, + {name: "missing token url", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.TokenURL = "" }, wantMsg: "tokenUrl is required"}, + {name: "missing client id", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientID = "" }, wantMsg: "clientId is required"}, + {name: "no audience or scopes", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.Scopes = nil; s.OBO.Audience = "" }, wantMsg: "one of audience or scopes is required"}, + {name: "both secret sources", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientSecretEnv = "ENV" }, wantMsg: "mutually exclusive"}, + {name: "no secret source", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientSecret = "" }, wantMsg: "a client secret is required"}, + {name: "negative cache skew", mutate: func(s *authtypes.BackendAuthStrategy) { + skew := int32(-1) + s.OBO.CacheSkewSeconds = &skew + }, wantMsg: "cacheSkewSeconds must not be negative"}, + } + + s := NewOBOStrategy(oboMapEnv{}) // empty env so ClientSecretEnv cannot resolve + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + strat := validOBOStrategy() + tt.mutate(strat) + err := s.Validate(strat) + require.Error(t, err) + assert.ErrorContains(t, err, tt.wantMsg, "the rejection must name the actual reason") + }) + } +} + +// TestOBOExchangeTarget_ParityWithSharedContract is the cross-path parity check: for +// a shared (audience, scopes) table, the value the vMCP strategy sends to Entra +// must equal obo.MiddlewareParameters.ExchangeTarget() — the single collapse +// implementation the proxy-runtime middleware also uses. Asserted both directly +// and behaviorally (the stub Exchanger records what Authenticate sent). +func TestOBOExchangeTarget_ParityWithSharedContract(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + audience string + scopes []string + }{ + {name: "scopes win over audience", audience: "api://backend", scopes: []string{"api://backend/.default"}}, + {name: "multiple scopes space-joined", audience: "", scopes: []string{"openid", "api://backend/.default"}}, + {name: "audience only", audience: "api://backend", scopes: nil}, + {name: "whitespace-only scope falls back to audience", audience: "api://backend", scopes: []string{" "}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := &authtypes.OBOConfig{Audience: tt.audience, Scopes: tt.scopes} + want := (&obo.MiddlewareParameters{Audience: tt.audience, Scopes: tt.scopes}).ExchangeTarget() + + // Direct parity: the strategy's collapse equals the shared contract's. + assert.Equal(t, want, oboExchangeTarget(cfg)) + + // Behavioral parity: Authenticate sends exactly that target to Entra. + stub := &oboStubExchanger{token: "backend-token"} + s := oboStrategyWithStub(stub, nil) + strat := validOBOStrategy() + strat.OBO.Audience = tt.audience + strat.OBO.Scopes = tt.scopes + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + _, err := oboServeAuthenticate(ctx, t, s, strat) + require.NoError(t, err) + assert.Equal(t, want, stub.lastAudience) + }) + } +} diff --git a/pkg/vmcp/auth/types/types.go b/pkg/vmcp/auth/types/types.go index 6c0d028b41..4d51aad383 100644 --- a/pkg/vmcp/auth/types/types.go +++ b/pkg/vmcp/auth/types/types.go @@ -44,10 +44,8 @@ const ( // and signs requests using SigV4. StrategyTypeAwsSts = "aws_sts" - // StrategyTypeOBO identifies the on-behalf-of (OBO) authentication strategy. - // The default upstream implementation returns ErrEnterpriseRequired from - // every method; an out-of-tree build registers a real OBO strategy executor - // via auth.RegisterOBOStrategy. + // StrategyTypeOBO identifies the Microsoft Entra on-behalf-of (OBO) + // authentication strategy. StrategyTypeOBO = "obo" // StrategyTypeXAA identifies the XAA (Cross-Application Access) strategy. @@ -86,8 +84,7 @@ type BackendAuthStrategy struct { AwsSts *AwsStsConfig `json:"awsSts,omitempty" yaml:"awsSts,omitempty"` // OBO contains configuration for on-behalf-of (OBO) auth strategy. - // Used when Type = "obo". The default upstream build returns ErrEnterpriseRequired; - // an out-of-tree build registers a real strategy via auth.RegisterOBOStrategy. + // Used when Type = "obo". OBO *OBOConfig `json:"obo,omitempty" yaml:"obo,omitempty"` // XAA contains configuration for XAA (Cross-Application Access) auth strategy. @@ -188,7 +185,7 @@ type RoleMapping struct { // This strategy uses the Entra jwt-bearer / on_behalf_of grant to exchange // the incoming user token for a backend-scoped token on behalf of the user. // -// Field names follow the OBO runtime contract (the enterprise obo.MiddlewareParameters), +// Field names follow the OBO runtime contract (obo.MiddlewareParameters), // not the RFC-8693 TokenExchangeConfig, because OBO uses a distinct Entra-specific grant. // +kubebuilder:object:generate=true // +gendoc @@ -219,12 +216,13 @@ type OBOConfig struct { // subject (assertion) token for the OBO exchange. When set, the token is looked // up from Identity.UpstreamTokens[SubjectTokenProviderName]; when omitted, the // inbound end-user token (Identity.Token) is used directly. - // Matches the operator CRD's SubjectTokenProviderName field; the enterprise OBO - // converter maps both to the runtime contract without renaming. + // Matches the operator CRD's SubjectTokenProviderName field; the OBO + // converter maps it to the runtime contract without renaming. SubjectTokenProviderName string `json:"subjectTokenProviderName,omitempty" yaml:"subjectTokenProviderName,omitempty"` // CacheSkewSeconds is the number of seconds to subtract from a cached token's - // expiry when deciding whether to refresh it. Defaults to zero (no skew). + // expiry when deciding whether to refresh it. When nil or zero the token + // cache's default skew (60 seconds) applies; negative values are rejected. // The operator CRD stores this as CacheSkew *metav1.Duration and converts it // to an integer-seconds value for the vMCP runtime contract. CacheSkewSeconds *int32 `json:"cacheSkewSeconds,omitempty" yaml:"cacheSkewSeconds,omitempty"` diff --git a/test/integration/vmcp/obo_integration_test.go b/test/integration/vmcp/obo_integration_test.go new file mode 100644 index 0000000000..a46f1326b5 --- /dev/null +++ b/test/integration/vmcp/obo_integration_test.go @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package vmcp_test + +// This file exercises the Entra on-behalf-of (OBO) outgoing-auth path end to +// end, across the seams the unit tests cover only in isolation: +// +// MCPExternalAuthConfig (CRD) +// -> converter (ConvertToStrategy / ResolveSecrets) +// -> outgoing-auth registry dispatch (GetStrategy "obo") +// -> OBOStrategy.Authenticate: real Entra exchange (mock endpoint) + inject +// -> backend receives Authorization: Bearer +// +// The Entra token endpoint and the backend are httptest servers, so the test +// is hermetic. Both wiring paths are covered: +// - discovered auth (MCPServer / MCPServerEntry backends discovered from a +// group): DiscoverAndResolveAuth resolves the secret from a Kubernetes +// Secret inline. +// - inline outgoingAuth: ConvertToStrategy runs alone and the operator points +// the strategy at a per-config env var, so two OBO backends in one vMCP pod +// each source their own secret. + +import ( + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" + authpkg "github.com/stacklok/toolhive/pkg/auth" + vmcpauth "github.com/stacklok/toolhive/pkg/vmcp/auth" + "github.com/stacklok/toolhive/pkg/vmcp/auth/converters" + authfactory "github.com/stacklok/toolhive/pkg/vmcp/auth/factory" + authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" +) + +const ( + oboTestTenant = "contoso.onmicrosoft.com" + oboTestClientID = "client-abc" + oboTestUserToken = "user-entra-token" + oboTestScope = "api://backend/.default" + oboTestNamespace = "default" + oboSecretKey = "client-secret" +) + +// TestOBOIntegration_DiscoveredAuthPath drives the discovered-auth wiring: +// DiscoverAndResolveAuth resolves the client secret from a Kubernetes Secret, +// then the registry-dispatched OBO strategy performs a real exchange and the +// backend receives the exchanged token. +func TestOBOIntegration_DiscoveredAuthPath(t *testing.T) { + t.Parallel() + + entra, entraCap := startMockEntra(t, "backend-token-discovered") + backend, backendCap := startMockBackend(t) + + cr := oboTestCR("obo-config", entra.URL, "obo-secret") + secret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-secret", Namespace: oboTestNamespace}, + Data: map[string][]byte{oboSecretKey: []byte("discovered-secret")}, + } + + strategy, err := converters.DiscoverAndResolveAuth( + t.Context(), &mcpv1beta1.ExternalAuthConfigRef{Name: cr.Name}, oboTestNamespace, newOBOFakeClient(t, cr, secret)) + require.NoError(t, err) + require.NotNil(t, strategy) + require.NotNil(t, strategy.OBO) + assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Type) + assert.Equal(t, "discovered-secret", strategy.OBO.ClientSecret, "the discovered path resolves the secret inline") + assert.Empty(t, strategy.OBO.ClientSecretEnv) + + registry, err := authfactory.NewOutgoingAuthRegistry(t.Context(), oboMapEnv{}) + require.NoError(t, err) + + exchangeThroughBackend(t, registry, strategy, backend, backendCap) + assertOBOExchange(t, entraCap, "discovered-secret") + assert.Equal(t, "Bearer backend-token-discovered", backendCap.authHeader()) +} + +// TestOBOIntegration_InlineTwoBackends drives the inline outgoingAuth wiring +// for two OBO backends in one vMCP: each strategy points at its own +// operator-mounted env var, and each exchange uses its own client secret. +func TestOBOIntegration_InlineTwoBackends(t *testing.T) { + t.Parallel() + + entraA, entraCapA := startMockEntra(t, "backend-token-a") + entraB, entraCapB := startMockEntra(t, "backend-token-b") + backendA, backendCapA := startMockBackend(t) + backendB, backendCapB := startMockBackend(t) + + strategyFor := func(name, authority string) *authtypes.BackendAuthStrategy { + strategy, err := converters.ConvertToStrategy(oboTestCR(name, authority, name+"-secret")) + require.NoError(t, err) + require.NotNil(t, strategy.OBO) + // The operator sets this when it renders the vMCP config (see + // convertExternalAuthConfigToStrategy) and mounts the secret under the + // same name (getExternalAuthConfigSecretEnvVars). + strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOEnvVarName(name) + return strategy + } + strategyA := strategyFor("obo-backend-a", entraA.URL) + strategyB := strategyFor("obo-backend-b", entraB.URL) + require.NotEqual(t, strategyA.OBO.ClientSecretEnv, strategyB.OBO.ClientSecretEnv) + + registry, err := authfactory.NewOutgoingAuthRegistry(t.Context(), oboMapEnv{ + strategyA.OBO.ClientSecretEnv: "secret-a", + strategyB.OBO.ClientSecretEnv: "secret-b", + }) + require.NoError(t, err) + + exchangeThroughBackend(t, registry, strategyA, backendA, backendCapA) + exchangeThroughBackend(t, registry, strategyB, backendB, backendCapB) + + assertOBOExchange(t, entraCapA, "secret-a") + assertOBOExchange(t, entraCapB, "secret-b") + assert.Equal(t, "Bearer backend-token-a", backendCapA.authHeader()) + assert.Equal(t, "Bearer backend-token-b", backendCapB.authHeader()) +} + +// exchangeThroughBackend resolves the OBO strategy from the registry, +// authenticates a backend-bound request as a signed-in user, sends it to the +// backend, and asserts the raw user token never reached the backend. +func exchangeThroughBackend( + t *testing.T, + registry vmcpauth.OutgoingAuthRegistry, + strategy *authtypes.BackendAuthStrategy, + backend *httptest.Server, + backendCap *oboCapture, +) { + t.Helper() + + exec, err := registry.GetStrategy(strategy.Type) + require.NoError(t, err, "the OBO strategy must be registered in the outgoing-auth registry") + + ctx := authpkg.WithIdentity(t.Context(), &authpkg.Identity{ + PrincipalInfo: authpkg.PrincipalInfo{Subject: "alice"}, + Token: oboTestUserToken, + }) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, backend.URL, nil) + require.NoError(t, err) + require.NoError(t, exec.Authenticate(ctx, req, strategy)) + + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + + assert.NotContains(t, backendCap.authHeader(), oboTestUserToken, + "the raw user token must never reach the backend") +} + +// assertOBOExchange asserts the mock Entra endpoint saw exactly one +// well-formed on-behalf-of exchange authenticated with clientSecret. +func assertOBOExchange(t *testing.T, entraCap *oboCapture, clientSecret string) { + t.Helper() + form := entraCap.form() + assert.Equal(t, 1, entraCap.count()) + assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", form.Get("grant_type")) + assert.Equal(t, "on_behalf_of", form.Get("requested_token_use")) + assert.Equal(t, oboTestClientID, form.Get("client_id")) + assert.Equal(t, clientSecret, form.Get("client_secret")) + assert.Equal(t, oboTestUserToken, form.Get("assertion"), "the user token is the OBO assertion") + assert.Equal(t, oboTestScope, form.Get("scope")) +} + +// oboTestCR builds an obo-typed MCPExternalAuthConfig whose token endpoint +// resolves to authorityURL (the mock Entra server; a loopback http authority +// is permitted for tests). +func oboTestCR(name, authorityURL, secretName string) *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: oboTestNamespace}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: oboTestTenant, + Authority: authorityURL, + ClientID: oboTestClientID, + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: secretName, Key: oboSecretKey}, + Scopes: []string{oboTestScope}, + }, + }, + } +} + +func newOBOFakeClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + scheme := runtime.NewScheme() + require.NoError(t, corev1.AddToScheme(scheme)) + require.NoError(t, mcpv1beta1.AddToScheme(scheme)) + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build() +} + +// startMockEntra starts an httptest server standing in for the Entra token +// endpoint. It records each request's form and issues accessToken. +func startMockEntra(t *testing.T, accessToken string) (*httptest.Server, *oboCapture) { + t.Helper() + c := &oboCapture{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + c.record(r) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"token_type":"Bearer","expires_in":3599,"access_token":"` + accessToken + `"}`)) + })) + t.Cleanup(srv.Close) + return srv, c +} + +// startMockBackend starts an httptest server standing in for the upstream MCP +// backend. It records the Authorization header it receives. +func startMockBackend(t *testing.T) (*httptest.Server, *oboCapture) { + t.Helper() + c := &oboCapture{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.record(r) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + return srv, c +} + +// oboCapture records request details from an httptest handler goroutine for +// the test goroutine to read after the exchange completes. +type oboCapture struct { + mu sync.Mutex + calls int + auth string + values url.Values +} + +func (c *oboCapture) record(r *http.Request) { + c.mu.Lock() + defer c.mu.Unlock() + c.calls++ + c.auth = r.Header.Get("Authorization") + c.values = r.Form +} + +func (c *oboCapture) authHeader() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.auth +} + +func (c *oboCapture) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls +} + +func (c *oboCapture) form() url.Values { + c.mu.Lock() + defer c.mu.Unlock() + return c.values +} + +// oboMapEnv is a minimal env.Reader backed by a map, standing in for the vMCP +// pod's environment (into which the operator mounts the OBO client secrets). +type oboMapEnv map[string]string + +func (m oboMapEnv) Getenv(key string) string { return m[key] } + +func (m oboMapEnv) LookupEnv(key string) (string, bool) { + v, ok := m[key] + return v, ok +} From d5c6ea2130c46a77786216971f6c99a3155d99bc Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 10:43:24 -0800 Subject: [PATCH 02/12] Return 502 when the Entra endpoint times out The HTTP client's own timeout matches context.DeadlineExceeded, so the exchanger reported it as caller cancellation and the OBO middleware wrote no response, giving a still-connected client an empty 200. Only treat a context error as cancellation when the caller's context is done; a token endpoint timeout is now a transient failure (502). Also rename the vMCP env var helper to GenerateUniqueOBOSecretEnvVarName, the name the issue specifies. Co-Authored-By: Claude Opus 5.5 --- .../virtualmcpserver_controller.go | 2 +- .../virtualmcpserver_externalauth_test.go | 4 +- .../pkg/controllerutil/externalauth.go | 4 +- cmd/thv-operator/pkg/controllerutil/obo.go | 4 +- .../pkg/controllerutil/obo_test.go | 2 +- cmd/thv-operator/pkg/vmcpconfig/converter.go | 2 +- .../pkg/vmcpconfig/converter_test.go | 4 +- pkg/auth/obo/entra/exchanger.go | 12 ++--- pkg/auth/obo/entra/exchanger_test.go | 32 ++++++++++++++ pkg/auth/obo/middleware.go | 6 ++- pkg/auth/obo/middleware_test.go | 44 +++++++++++++------ pkg/auth/obo/parameters.go | 2 +- pkg/vmcp/auth/converters/obo.go | 2 +- test/integration/vmcp/obo_integration_test.go | 2 +- 14 files changed, 87 insertions(+), 35 deletions(-) diff --git a/cmd/thv-operator/controllers/virtualmcpserver_controller.go b/cmd/thv-operator/controllers/virtualmcpserver_controller.go index a37393e81a..ff5e594af2 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_controller.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_controller.go @@ -2702,7 +2702,7 @@ func setUniqueSecretEnvNames( if strategy.OBO != nil && externalAuthConfig.Spec.OBO != nil && externalAuthConfig.Spec.OBO.ClientSecretRef != nil { - strategy.OBO.ClientSecretEnv = ctrlutil.GenerateUniqueOBOEnvVarName(externalAuthConfig.Name) + strategy.OBO.ClientSecretEnv = ctrlutil.GenerateUniqueOBOSecretEnvVarName(externalAuthConfig.Name) } if strategy.XAA != nil && externalAuthConfig.Spec.XAA != nil { if externalAuthConfig.Spec.XAA.IDPClientSecretRef != nil { diff --git a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go index 31a04b0a15..652a0608c7 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go @@ -2042,8 +2042,8 @@ func TestGetExternalAuthConfigSecretEnvVars_OBO(t *testing.T) { require.Len(t, envA, 1) require.Len(t, envB, 1) - assert.Equal(t, ctrlutil.GenerateUniqueOBOEnvVarName(backendA.Name), envA[0].Name) - assert.Equal(t, ctrlutil.GenerateUniqueOBOEnvVarName(backendB.Name), envB[0].Name) + assert.Equal(t, ctrlutil.GenerateUniqueOBOSecretEnvVarName(backendA.Name), envA[0].Name) + assert.Equal(t, ctrlutil.GenerateUniqueOBOSecretEnvVarName(backendB.Name), envB[0].Name) assert.NotEqual(t, envA[0].Name, envB[0].Name, "two OBO backends must get distinct env vars") assert.Equal(t, "secret-a", envA[0].ValueFrom.SecretKeyRef.Name) assert.Equal(t, "secret-b", envB[0].ValueFrom.SecretKeyRef.Name) diff --git a/cmd/thv-operator/pkg/controllerutil/externalauth.go b/cmd/thv-operator/pkg/controllerutil/externalauth.go index 56fe42a880..64f24d56d9 100644 --- a/cmd/thv-operator/pkg/controllerutil/externalauth.go +++ b/cmd/thv-operator/pkg/controllerutil/externalauth.go @@ -68,7 +68,7 @@ func GenerateUniqueXAATargetSecretEnvVarName(configName string) string { return fmt.Sprintf("TOOLHIVE_XAA_TARGET_CLIENT_SECRET_%s", sanitized) } -// GenerateUniqueOBOEnvVarName generates a unique environment variable name for +// GenerateUniqueOBOSecretEnvVarName generates a unique environment variable name for // an OBO client secret mounted into the vMCP pod, incorporating the // ExternalAuthConfig name so several OBO backends in one vMCP never collide. // Used by both the converter enrichment and the deployment controller for @@ -77,7 +77,7 @@ func GenerateUniqueXAATargetSecretEnvVarName(configName string) string { // // Example: For an ExternalAuthConfig named "my-auth-config", this returns: // "TOOLHIVE_OBO_CLIENT_SECRET_MY_AUTH_CONFIG" -func GenerateUniqueOBOEnvVarName(configName string) string { +func GenerateUniqueOBOSecretEnvVarName(configName string) string { sanitized := strings.ToUpper(strings.ReplaceAll(configName, "-", "_")) sanitized = envVarSanitizer.ReplaceAllString(sanitized, "_") return fmt.Sprintf("TOOLHIVE_OBO_CLIENT_SECRET_%s", sanitized) diff --git a/cmd/thv-operator/pkg/controllerutil/obo.go b/cmd/thv-operator/pkg/controllerutil/obo.go index 88969f5ca2..43b3ee4d0f 100644 --- a/cmd/thv-operator/pkg/controllerutil/obo.go +++ b/cmd/thv-operator/pkg/controllerutil/obo.go @@ -102,7 +102,7 @@ func OBOValidate(cfg *mcpv1beta1.MCPExternalAuthConfig) error { // OBOSecretEnvVars returns the env var that mounts the OBO client secret into // a proxyrunner pod (MCPServer or MCPRemoteProxy) under obo.ClientSecretEnvVar. -// The vMCP pod uses per-config names instead; see GenerateUniqueOBOEnvVarName. +// The vMCP pod uses per-config names instead; see GenerateUniqueOBOSecretEnvVarName. func OBOSecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { return currentOBOHandler().SecretEnvVars(cfg) } @@ -172,7 +172,7 @@ func OBOVMCPSecretEnvVar(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar if err := validateOBOSecretRef(cfg.Spec.OBO.ClientSecretRef); err != nil { return nil, err } - return []corev1.EnvVar{oboSecretEnvVar(GenerateUniqueOBOEnvVarName(cfg.Name), cfg.Spec.OBO.ClientSecretRef)}, nil + return []corev1.EnvVar{oboSecretEnvVar(GenerateUniqueOBOSecretEnvVarName(cfg.Name), cfg.Spec.OBO.ClientSecretRef)}, nil } // validateOBO is the built-in OBOHandler.Validate. diff --git a/cmd/thv-operator/pkg/controllerutil/obo_test.go b/cmd/thv-operator/pkg/controllerutil/obo_test.go index 4d779aabd6..26a7ec6e53 100644 --- a/cmd/thv-operator/pkg/controllerutil/obo_test.go +++ b/cmd/thv-operator/pkg/controllerutil/obo_test.go @@ -424,7 +424,7 @@ func TestOBOVMCPSecretEnvVar_UniquePerConfig(t *testing.T) { require.Len(t, second, 1) assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_A", first[0].Name) assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_B", second[0].Name) - assert.Equal(t, GenerateUniqueOBOEnvVarName("backend-a"), first[0].Name, + assert.Equal(t, GenerateUniqueOBOSecretEnvVarName("backend-a"), first[0].Name, "the deployment and the converter enrichment must agree on the name") _, err = OBOVMCPSecretEnvVar(oboCR("bad", mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }))) diff --git a/cmd/thv-operator/pkg/vmcpconfig/converter.go b/cmd/thv-operator/pkg/vmcpconfig/converter.go index 96b22b76e1..23ee2d61a2 100644 --- a/cmd/thv-operator/pkg/vmcpconfig/converter.go +++ b/cmd/thv-operator/pkg/vmcpconfig/converter.go @@ -805,7 +805,7 @@ func (*Converter) convertExternalAuthConfigToStrategy( if strategy.OBO != nil && externalAuthConfig.Spec.OBO != nil && externalAuthConfig.Spec.OBO.ClientSecretRef != nil { - strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOEnvVarName(externalAuthConfig.Name) + strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOSecretEnvVarName(externalAuthConfig.Name) } return strategy, nil diff --git a/cmd/thv-operator/pkg/vmcpconfig/converter_test.go b/cmd/thv-operator/pkg/vmcpconfig/converter_test.go index fc55a98257..95f68856b2 100644 --- a/cmd/thv-operator/pkg/vmcpconfig/converter_test.go +++ b/cmd/thv-operator/pkg/vmcpconfig/converter_test.go @@ -2440,8 +2440,8 @@ func TestConvertExternalAuthConfigToStrategy_OBOUsesPerConfigSecretEnv(t *testin require.NotNil(t, first.OBO) require.NotNil(t, second.OBO) - assert.Equal(t, controllerutil.GenerateUniqueOBOEnvVarName("obo-a"), first.OBO.ClientSecretEnv) - assert.Equal(t, controllerutil.GenerateUniqueOBOEnvVarName("obo-b"), second.OBO.ClientSecretEnv) + assert.Equal(t, controllerutil.GenerateUniqueOBOSecretEnvVarName("obo-a"), first.OBO.ClientSecretEnv) + assert.Equal(t, controllerutil.GenerateUniqueOBOSecretEnvVarName("obo-b"), second.OBO.ClientSecretEnv) assert.NotEqual(t, first.OBO.ClientSecretEnv, second.OBO.ClientSecretEnv) assert.Empty(t, first.OBO.ClientSecret) } diff --git a/pkg/auth/obo/entra/exchanger.go b/pkg/auth/obo/entra/exchanger.go index d8872bc310..a0ec9db5f2 100644 --- a/pkg/auth/obo/entra/exchanger.go +++ b/pkg/auth/obo/entra/exchanger.go @@ -6,7 +6,6 @@ package entra import ( "context" "encoding/json" - "errors" "fmt" "io" "net" @@ -309,10 +308,13 @@ func (e *Exchanger) ExchangeToken(ctx context.Context, userToken, audience strin resp, err := e.httpClient.Do(req) if err != nil { - // Surface caller-driven cancellation/timeout as-is so it is not - // misclassified as a retryable server failure. - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return exchange.Token{}, fmt.Errorf("entra obo: %w", err) + // Surface caller-driven cancellation or deadline as-is so it is not + // misclassified as a retryable server failure. Only when the caller's + // own context is done: the HTTP client's Timeout also produces an + // error matching context.DeadlineExceeded, and that is a slow or + // unreachable token endpoint, which is transient. + if ctx.Err() != nil { + return exchange.Token{}, fmt.Errorf("entra obo: %w", ctx.Err()) } // Transport-level failure (DNS, dial, TLS, read). The raw error is // dropped deliberately: it is not needed to classify the failure as diff --git a/pkg/auth/obo/entra/exchanger_test.go b/pkg/auth/obo/entra/exchanger_test.go index d360262bbe..0073494dfd 100644 --- a/pkg/auth/obo/entra/exchanger_test.go +++ b/pkg/auth/obo/entra/exchanger_test.go @@ -357,6 +357,38 @@ func TestExchanger_ExchangeToken_ContextCancelledPropagates(t *testing.T) { assert.NotErrorIs(t, err, entra.ErrTransient) } +// TestExchanger_ExchangeToken_ClientTimeoutIsTransient verifies that the HTTP +// client's own timeout (which net/http reports as matching +// context.DeadlineExceeded) is classified as a transient token endpoint failure +// rather than surfaced as caller cancellation, because the caller's context is +// still live. +func TestExchanger_ExchangeToken_ClientTimeoutIsTransient(t *testing.T) { + t.Parallel() + + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + <-release // slower than the client timeout + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + + ex, err := entra.New(entra.Config{ + TenantID: testTenant, + ClientID: testClientID, + ClientSecret: testClientSecret, + Authority: srv.URL, + HTTPClient: &http.Client{Timeout: 50 * time.Millisecond}, + }) + require.NoError(t, err) + + _, err = ex.ExchangeToken(t.Context(), testUserToken, testAudience) + + require.Error(t, err) + assert.ErrorIs(t, err, entra.ErrTransient) + assert.NotErrorIs(t, err, context.DeadlineExceeded, + "a token endpoint timeout must not look like caller cancellation") +} + func TestNew_EnforcesRedirectGuardOnInjectedClient(t *testing.T) { t.Parallel() diff --git a/pkg/auth/obo/middleware.go b/pkg/auth/obo/middleware.go index f8b030b92a..b7a4517963 100644 --- a/pkg/auth/obo/middleware.go +++ b/pkg/auth/obo/middleware.go @@ -262,10 +262,12 @@ func (m *middleware) writeExchangeError(w http.ResponseWriter, r *http.Request, slog.DebugContext(r.Context(), "obo: subject token rejected by identity provider") http.Error(w, unauthorizedMessage, http.StatusUnauthorized) - case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + case r.Context().Err() != nil && + (errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)): // The client (or its deadline) went away mid-exchange. Write no // response: a 502 would be a misleading 5xx for a request nobody is - // waiting on. + // waiting on. A context-shaped error on a request that is still live + // (e.g. a timeout reaching the token endpoint) falls through to 502. slog.DebugContext(r.Context(), "obo: token exchange cancelled before completion") default: diff --git a/pkg/auth/obo/middleware_test.go b/pkg/auth/obo/middleware_test.go index 8c773c45d8..b6f4b80055 100644 --- a/pkg/auth/obo/middleware_test.go +++ b/pkg/auth/obo/middleware_test.go @@ -561,20 +561,27 @@ func TestMiddleware_UnclassifiedError_NotLoggedToDefault(t *testing.T) { "an unclassified error's content must not reach the diagnostic log") } -// TestMiddleware_ClientCancellation_NoSpurious502 verifies that a client which -// disconnects mid-exchange does not produce a 502: context cancellation / -// deadline errors (including the entra-wrapped form) are treated as benign, with -// no error response written. -func TestMiddleware_ClientCancellation_NoSpurious502(t *testing.T) { +// TestMiddleware_ContextErrors verifies the handling of context-shaped +// exchange errors. When the client's own request context is done (it +// disconnected or its deadline passed), no response is written: a 502 would be +// a misleading 5xx for a request nobody is waiting on. When the request is +// still live, a context-shaped error (e.g. the HTTP client timing out against +// the token endpoint) is a backend failure and must be a 502, not an empty 200. +func TestMiddleware_ContextErrors(t *testing.T) { t.Parallel() tests := []struct { - name string - err error + name string + err error + cancelRequest bool + wantStatus int }{ - {name: "canceled", err: context.Canceled}, - {name: "deadline exceeded", err: context.DeadlineExceeded}, - {name: "entra-wrapped canceled", err: fmt.Errorf("entra obo: %w", context.Canceled)}, + {name: "canceled request", err: context.Canceled, cancelRequest: true, wantStatus: http.StatusOK}, + {name: "canceled request, entra-wrapped", err: fmt.Errorf("entra obo: %w", context.Canceled), + cancelRequest: true, wantStatus: http.StatusOK}, + {name: "deadline on a canceled request", err: context.DeadlineExceeded, cancelRequest: true, wantStatus: http.StatusOK}, + {name: "deadline on a live request is a 502", err: context.DeadlineExceeded, wantStatus: http.StatusBadGateway}, + {name: "canceled error on a live request is a 502", err: context.Canceled, wantStatus: http.StatusBadGateway}, } for _, tt := range tests { @@ -583,12 +590,21 @@ func TestMiddleware_ClientCancellation_NoSpurious502(t *testing.T) { stub := &stubExchanger{err: tt.err} mw := newMiddleware(stub, "", testTarget, nil) - rec, spy := serve(t, mw, request(t, inboundIdentity("user-token"))) + req := request(t, inboundIdentity("user-token")) + if tt.cancelRequest { + ctx, cancel := context.WithCancel(req.Context()) + cancel() + req = req.WithContext(ctx) + } + rec, spy := serve(t, mw, req) - assert.NotEqual(t, http.StatusBadGateway, rec.Code, "client cancellation must not be a 502") - assert.Empty(t, rec.Body.String(), "no error body is written for a cancelled request") + // httptest.ResponseRecorder reports 200 when nothing was written. + assert.Equal(t, tt.wantStatus, rec.Code) + if tt.cancelRequest { + assert.Empty(t, rec.Body.String(), "no error body is written for a cancelled request") + } assert.False(t, spy.called) - assert.Equal(t, 1, stub.calls, "the exchange was attempted before cancellation") + assert.Equal(t, 1, stub.calls) }) } } diff --git a/pkg/auth/obo/parameters.go b/pkg/auth/obo/parameters.go index 709733031c..47ebb44dcc 100644 --- a/pkg/auth/obo/parameters.go +++ b/pkg/auth/obo/parameters.go @@ -14,7 +14,7 @@ import ( // OBO confidential-client secret into for a proxyrunner pod (MCPServer and // MCPRemoteProxy). A proxy carries at most one OBO config, so a fixed name is // enough. The vMCP pod can carry several OBO backends and therefore uses a -// per-config name instead (see controllerutil.GenerateUniqueOBOEnvVarName). +// per-config name instead (see controllerutil.GenerateUniqueOBOSecretEnvVarName). // //nolint:gosec // G101: this is an environment-variable name, not a credential. const ClientSecretEnvVar = "TOOLHIVE_OBO_CLIENT_SECRET" diff --git a/pkg/vmcp/auth/converters/obo.go b/pkg/vmcp/auth/converters/obo.go index 6d06164012..b6f380139e 100644 --- a/pkg/vmcp/auth/converters/obo.go +++ b/pkg/vmcp/auth/converters/obo.go @@ -44,7 +44,7 @@ func (*OBOConverter) StrategyType() string { return authtypes.StrategyTypeOBO } // // Neither the client secret nor ClientSecretEnv is set here. In inline mode the // operator sets ClientSecretEnv to the per-config name it mounts the secret -// under (controllerutil.GenerateUniqueOBOEnvVarName), so several OBO backends in +// under (controllerutil.GenerateUniqueOBOSecretEnvVarName), so several OBO backends in // one vMCP pod never share an env var. In discovered mode ResolveSecrets sets // the resolved ClientSecret instead. func (*OBOConverter) ConvertToStrategy( diff --git a/test/integration/vmcp/obo_integration_test.go b/test/integration/vmcp/obo_integration_test.go index a46f1326b5..17eeed7e0d 100644 --- a/test/integration/vmcp/obo_integration_test.go +++ b/test/integration/vmcp/obo_integration_test.go @@ -105,7 +105,7 @@ func TestOBOIntegration_InlineTwoBackends(t *testing.T) { // The operator sets this when it renders the vMCP config (see // convertExternalAuthConfigToStrategy) and mounts the secret under the // same name (getExternalAuthConfigSecretEnvVars). - strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOEnvVarName(name) + strategy.OBO.ClientSecretEnv = controllerutil.GenerateUniqueOBOSecretEnvVarName(name) return strategy } strategyA := strategyFor("obo-backend-a", entraA.URL) From fd6774639c61bcc1e3b4241f70d9219ceffbf03f Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 10:50:55 -0800 Subject: [PATCH 03/12] Fix codespell findings in OBO code Co-Authored-By: Claude Opus 5.5 --- pkg/auth/obo/cache/cache_test.go | 16 +++++----- pkg/auth/obo/entra/exchanger.go | 2 +- pkg/vmcp/auth/strategies/obo_test.go | 46 ++++++++++++++-------------- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/pkg/auth/obo/cache/cache_test.go b/pkg/auth/obo/cache/cache_test.go index 60a6dad333..e613115aee 100644 --- a/pkg/auth/obo/cache/cache_test.go +++ b/pkg/auth/obo/cache/cache_test.go @@ -128,22 +128,22 @@ func TestCache_PartitionsByUserToken(t *testing.T) { }} c := New(fake, WithClock(clock.now)) - a, err := c.Exchange(t.Context(), "userA", "aud") + a, err := c.Exchange(t.Context(), "userAlice", "aud") require.NoError(t, err) - assert.Equal(t, "tok:userA", a) + assert.Equal(t, "tok:userAlice", a) - b, err := c.Exchange(t.Context(), "userB", "aud") + b, err := c.Exchange(t.Context(), "userBob", "aud") require.NoError(t, err) - assert.Equal(t, "tok:userB", b) + assert.Equal(t, "tok:userBob", b) assert.Equal(t, 2, fake.callCount(), "different user tokens must not share a cache entry") // Each user still reads its own cached token; no cross-contamination. - a2, err := c.Exchange(t.Context(), "userA", "aud") + a2, err := c.Exchange(t.Context(), "userAlice", "aud") require.NoError(t, err) - assert.Equal(t, "tok:userA", a2) - b2, err := c.Exchange(t.Context(), "userB", "aud") + assert.Equal(t, "tok:userAlice", a2) + b2, err := c.Exchange(t.Context(), "userBob", "aud") require.NoError(t, err) - assert.Equal(t, "tok:userB", b2) + assert.Equal(t, "tok:userBob", b2) assert.Equal(t, 2, fake.callCount()) } diff --git a/pkg/auth/obo/entra/exchanger.go b/pkg/auth/obo/entra/exchanger.go index a0ec9db5f2..a8b700c26c 100644 --- a/pkg/auth/obo/entra/exchanger.go +++ b/pkg/auth/obo/entra/exchanger.go @@ -380,7 +380,7 @@ type tokenResponse struct { func (*Exchanger) parseResponse(status int, body []byte) (exchange.Token, error) { var tr tokenResponse if err := json.Unmarshal(body, &tr); err != nil { - // Unparseable body: classify by status alone, without echoing the body. + // Unparsable body: classify by status alone, without echoing the body. kind := KindUnknown if status >= http.StatusInternalServerError { kind = KindTransient diff --git a/pkg/vmcp/auth/strategies/obo_test.go b/pkg/vmcp/auth/strategies/obo_test.go index 4dee7d2c38..05f885c4f0 100644 --- a/pkg/vmcp/auth/strategies/obo_test.go +++ b/pkg/vmcp/auth/strategies/obo_test.go @@ -94,7 +94,7 @@ func oboInboundIdentity(token string) *auth.Identity { // oboServeAuthenticate runs Authenticate against a request carrying ctx and returns // the request (for header inspection) and the error. func oboServeAuthenticate( - ctx context.Context, t *testing.T, s *OBOStrategy, strat *authtypes.BackendAuthStrategy, + ctx context.Context, t *testing.T, s *OBOStrategy, backendStrategy *authtypes.BackendAuthStrategy, ) (*http.Request, error) { t.Helper() // Authenticate runs on the outgoing backend-bound request (the vMCP client's @@ -102,7 +102,7 @@ func oboServeAuthenticate( // RemoteAddr; the audit source is therefore local to the component, not a // network IP. req := httptest.NewRequestWithContext(ctx, http.MethodPost, "http://backend.local/", nil) - return req, s.Authenticate(ctx, req, strat) + return req, s.Authenticate(ctx, req, backendStrategy) } func TestOBOStrategy_Name(t *testing.T) { @@ -135,8 +135,8 @@ func TestOBOAuthenticate_UpstreamProviderSuccess(t *testing.T) { stub := &oboStubExchanger{token: "backend-token"} s := oboStrategyWithStub(stub, nil) - strat := validOBOStrategy() - strat.OBO.SubjectTokenProviderName = "entra" + backendStrategy := validOBOStrategy() + backendStrategy.OBO.SubjectTokenProviderName = "entra" identity := &auth.Identity{ PrincipalInfo: auth.PrincipalInfo{Subject: oboTestSubject}, Token: "session-token", // the proxy's own token, not the subject @@ -144,7 +144,7 @@ func TestOBOAuthenticate_UpstreamProviderSuccess(t *testing.T) { } ctx := auth.WithIdentity(t.Context(), identity) - req, err := oboServeAuthenticate(ctx, t, s, strat) + req, err := oboServeAuthenticate(ctx, t, s, backendStrategy) require.NoError(t, err) assert.Equal(t, "Bearer backend-token", req.Header.Get("Authorization")) assert.Equal(t, "upstream-token", stub.lastUserToken, "the named provider token is the subject") @@ -156,14 +156,14 @@ func TestOBOAuthenticate_SubjectErrors(t *testing.T) { t.Parallel() tests := []struct { - name string - ctx func(t *testing.T) context.Context - strat func() *authtypes.BackendAuthStrategy + name string + ctx func(t *testing.T) context.Context + backendStrategy func() *authtypes.BackendAuthStrategy }{ { - name: "no identity in context", - ctx: func(t *testing.T) context.Context { t.Helper(); return t.Context() }, - strat: validOBOStrategy, + name: "no identity in context", + ctx: func(t *testing.T) context.Context { t.Helper(); return t.Context() }, + backendStrategy: validOBOStrategy, }, { name: "identity has no inbound token", @@ -171,7 +171,7 @@ func TestOBOAuthenticate_SubjectErrors(t *testing.T) { t.Helper() return auth.WithIdentity(t.Context(), oboInboundIdentity("")) }, - strat: validOBOStrategy, + backendStrategy: validOBOStrategy, }, { name: "named provider token absent", @@ -179,7 +179,7 @@ func TestOBOAuthenticate_SubjectErrors(t *testing.T) { t.Helper() return auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) }, - strat: func() *authtypes.BackendAuthStrategy { + backendStrategy: func() *authtypes.BackendAuthStrategy { s := validOBOStrategy() s.OBO.SubjectTokenProviderName = "entra" return s @@ -193,7 +193,7 @@ func TestOBOAuthenticate_SubjectErrors(t *testing.T) { stub := &oboStubExchanger{token: "unused"} s := oboStrategyWithStub(stub, nil) - req, err := oboServeAuthenticate(tt.ctx(t), t, s, tt.strat()) + req, err := oboServeAuthenticate(tt.ctx(t), t, s, tt.backendStrategy()) require.Error(t, err) assert.Empty(t, req.Header.Get("Authorization"), "no token may be injected on failure") assert.Zero(t, stub.calls, "no exchange should be attempted") @@ -318,7 +318,7 @@ func TestOBOAuthenticate_RealEntraExchange(t *testing.T) { skew := int32(120) // exercise the CacheSkewSeconds > 0 gate in defaultBuildOBOExchanger s := NewOBOStrategy(oboMapEnv{}) - strat := &authtypes.BackendAuthStrategy{ + backendStrategy := &authtypes.BackendAuthStrategy{ Type: authtypes.StrategyTypeOBO, OBO: &authtypes.OBOConfig{ TokenURL: srv.URL, // loopback http — accepted by NewFromTokenURL @@ -330,7 +330,7 @@ func TestOBOAuthenticate_RealEntraExchange(t *testing.T) { } ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) - req, err := oboServeAuthenticate(ctx, t, s, strat) + req, err := oboServeAuthenticate(ctx, t, s, backendStrategy) require.NoError(t, err) assert.Equal(t, "Bearer backend-abc", req.Header.Get("Authorization"), "the backend-scoped token from the real exchange must be injected") @@ -371,9 +371,9 @@ func TestOBOValidate_Invalid(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - strat := validOBOStrategy() - tt.mutate(strat) - err := s.Validate(strat) + backendStrategy := validOBOStrategy() + tt.mutate(backendStrategy) + err := s.Validate(backendStrategy) require.Error(t, err) assert.ErrorContains(t, err, tt.wantMsg, "the rejection must name the actual reason") }) @@ -412,12 +412,12 @@ func TestOBOExchangeTarget_ParityWithSharedContract(t *testing.T) { // Behavioral parity: Authenticate sends exactly that target to Entra. stub := &oboStubExchanger{token: "backend-token"} s := oboStrategyWithStub(stub, nil) - strat := validOBOStrategy() - strat.OBO.Audience = tt.audience - strat.OBO.Scopes = tt.scopes + backendStrategy := validOBOStrategy() + backendStrategy.OBO.Audience = tt.audience + backendStrategy.OBO.Scopes = tt.scopes ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) - _, err := oboServeAuthenticate(ctx, t, s, strat) + _, err := oboServeAuthenticate(ctx, t, s, backendStrategy) require.NoError(t, err) assert.Equal(t, want, stub.lastAudience) }) From 818864dc81ea767966bf4a90b5ebea2b5ae2cafe Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 11:08:37 -0800 Subject: [PATCH 04/12] Regenerate swagger and SDK for schema order Swag orders the awssts schemas differently once the OBO packages are in the import graph; the content is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/server/docs.go | 128 +++---- docs/server/swagger.json | 128 +++---- docs/server/swagger.yaml | 138 ++++---- sdk/go/client/oas_json_gen.go | 552 +++++++++++++++---------------- sdk/go/client/oas_schemas_gen.go | 390 +++++++++++----------- sdk/go/openapi.json | 116 +++---- sdk/go/openapi.yaml | 126 +++---- 7 files changed, 789 insertions(+), 789 deletions(-) diff --git a/docs/server/docs.go b/docs/server/docs.go index b4af426c0f..b2b72e339a 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -1048,6 +1048,69 @@ const docTemplate = `{ }, "type": "object" }, + "awssts.Config": { + "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", + "properties": { + "fallback_role_arn": { + "description": "FallbackRoleArn is the IAM role ARN to assume when no role mapping matches.", + "type": "string" + }, + "region": { + "description": "Region is the AWS region for STS and SigV4 signing.", + "type": "string" + }, + "role_claim": { + "description": "RoleClaim is the JWT claim to use for role mapping (default: \"groups\").", + "type": "string" + }, + "role_mappings": { + "description": "RoleMappings maps JWT claim values to IAM roles with priority.", + "items": { + "$ref": "#/components/schemas/awssts.RoleMapping" + }, + "type": "array", + "uniqueItems": false + }, + "service": { + "description": "Service is the AWS service name for SigV4 signing (default: \"aws-mcp\").", + "type": "string" + }, + "session_duration": { + "description": "SessionDuration is the duration in seconds for assumed role credentials (default: 3600).", + "type": "integer" + }, + "session_name_claim": { + "description": "SessionNameClaim is the JWT claim to use for role session name (default: \"sub\").", + "type": "string" + }, + "subject_provider_name": { + "description": "SubjectProviderName identifies which upstream provider's access token to use\nfor STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer\ntoken from the incoming HTTP request is used.", + "type": "string" + } + }, + "type": "object" + }, + "awssts.RoleMapping": { + "properties": { + "claim": { + "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", + "type": "string" + }, + "matcher": { + "description": "Matcher is a CEL expression for complex matching against JWT claims.\nThe expression has access to a \"claims\" variable containing all JWT claims.\nExamples:\n - \"admins\" in claims[\"groups\"]\n - claims[\"sub\"] == \"user123\" \u0026\u0026 !(\"act\" in claims)\nMutually exclusive with Claim.", + "type": "string" + }, + "priority": { + "description": "Priority determines selection order (lower number = higher priority).\nWhen multiple mappings match, the one with the lowest priority is selected.\nWhen nil (omitted), the mapping has the lowest possible priority, and\nconfiguration order acts as tie-breaker via stable sort.", + "type": "integer" + }, + "role_arn": { + "description": "RoleArn is the IAM role ARN to assume when this mapping matches.", + "type": "string" + } + }, + "type": "object" + }, "core.Workload": { "properties": { "created_at": { @@ -1135,69 +1198,6 @@ const docTemplate = `{ }, "type": "object" }, - "github_com_stacklok_toolhive_pkg_auth_awssts.Config": { - "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", - "properties": { - "fallback_role_arn": { - "description": "FallbackRoleArn is the IAM role ARN to assume when no role mapping matches.", - "type": "string" - }, - "region": { - "description": "Region is the AWS region for STS and SigV4 signing.", - "type": "string" - }, - "role_claim": { - "description": "RoleClaim is the JWT claim to use for role mapping (default: \"groups\").", - "type": "string" - }, - "role_mappings": { - "description": "RoleMappings maps JWT claim values to IAM roles with priority.", - "items": { - "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping" - }, - "type": "array", - "uniqueItems": false - }, - "service": { - "description": "Service is the AWS service name for SigV4 signing (default: \"aws-mcp\").", - "type": "string" - }, - "session_duration": { - "description": "SessionDuration is the duration in seconds for assumed role credentials (default: 3600).", - "type": "integer" - }, - "session_name_claim": { - "description": "SessionNameClaim is the JWT claim to use for role session name (default: \"sub\").", - "type": "string" - }, - "subject_provider_name": { - "description": "SubjectProviderName identifies which upstream provider's access token to use\nfor STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer\ntoken from the incoming HTTP request is used.", - "type": "string" - } - }, - "type": "object" - }, - "github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping": { - "properties": { - "claim": { - "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", - "type": "string" - }, - "matcher": { - "description": "Matcher is a CEL expression for complex matching against JWT claims.\nThe expression has access to a \"claims\" variable containing all JWT claims.\nExamples:\n - \"admins\" in claims[\"groups\"]\n - claims[\"sub\"] == \"user123\" \u0026\u0026 !(\"act\" in claims)\nMutually exclusive with Claim.", - "type": "string" - }, - "priority": { - "description": "Priority determines selection order (lower number = higher priority).\nWhen multiple mappings match, the one with the lowest priority is selected.\nWhen nil (omitted), the mapping has the lowest possible priority, and\nconfiguration order acts as tie-breaker via stable sort.", - "type": "integer" - }, - "role_arn": { - "description": "RoleArn is the IAM role ARN to assume when this mapping matches.", - "type": "string" - } - }, - "type": "object" - }, "github_com_stacklok_toolhive_pkg_auth_upstreamswap.Config": { "description": "UpstreamSwapConfig contains configuration for upstream token swap middleware.\nWhen set along with EmbeddedAuthServerConfig, this middleware exchanges ToolHive JWTs\nfor upstream IdP tokens before forwarding requests to the MCP server.", "properties": { @@ -1890,7 +1890,7 @@ const docTemplate = `{ "type": "string" }, "aws_sts_config": { - "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.Config" + "$ref": "#/components/schemas/awssts.Config" }, "base_name": { "description": "BaseName is the base name used for the container (without prefixes)", diff --git a/docs/server/swagger.json b/docs/server/swagger.json index e398fc00bc..17a2e47983 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -1041,6 +1041,69 @@ }, "type": "object" }, + "awssts.Config": { + "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", + "properties": { + "fallback_role_arn": { + "description": "FallbackRoleArn is the IAM role ARN to assume when no role mapping matches.", + "type": "string" + }, + "region": { + "description": "Region is the AWS region for STS and SigV4 signing.", + "type": "string" + }, + "role_claim": { + "description": "RoleClaim is the JWT claim to use for role mapping (default: \"groups\").", + "type": "string" + }, + "role_mappings": { + "description": "RoleMappings maps JWT claim values to IAM roles with priority.", + "items": { + "$ref": "#/components/schemas/awssts.RoleMapping" + }, + "type": "array", + "uniqueItems": false + }, + "service": { + "description": "Service is the AWS service name for SigV4 signing (default: \"aws-mcp\").", + "type": "string" + }, + "session_duration": { + "description": "SessionDuration is the duration in seconds for assumed role credentials (default: 3600).", + "type": "integer" + }, + "session_name_claim": { + "description": "SessionNameClaim is the JWT claim to use for role session name (default: \"sub\").", + "type": "string" + }, + "subject_provider_name": { + "description": "SubjectProviderName identifies which upstream provider's access token to use\nfor STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer\ntoken from the incoming HTTP request is used.", + "type": "string" + } + }, + "type": "object" + }, + "awssts.RoleMapping": { + "properties": { + "claim": { + "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", + "type": "string" + }, + "matcher": { + "description": "Matcher is a CEL expression for complex matching against JWT claims.\nThe expression has access to a \"claims\" variable containing all JWT claims.\nExamples:\n - \"admins\" in claims[\"groups\"]\n - claims[\"sub\"] == \"user123\" \u0026\u0026 !(\"act\" in claims)\nMutually exclusive with Claim.", + "type": "string" + }, + "priority": { + "description": "Priority determines selection order (lower number = higher priority).\nWhen multiple mappings match, the one with the lowest priority is selected.\nWhen nil (omitted), the mapping has the lowest possible priority, and\nconfiguration order acts as tie-breaker via stable sort.", + "type": "integer" + }, + "role_arn": { + "description": "RoleArn is the IAM role ARN to assume when this mapping matches.", + "type": "string" + } + }, + "type": "object" + }, "core.Workload": { "properties": { "created_at": { @@ -1128,69 +1191,6 @@ }, "type": "object" }, - "github_com_stacklok_toolhive_pkg_auth_awssts.Config": { - "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", - "properties": { - "fallback_role_arn": { - "description": "FallbackRoleArn is the IAM role ARN to assume when no role mapping matches.", - "type": "string" - }, - "region": { - "description": "Region is the AWS region for STS and SigV4 signing.", - "type": "string" - }, - "role_claim": { - "description": "RoleClaim is the JWT claim to use for role mapping (default: \"groups\").", - "type": "string" - }, - "role_mappings": { - "description": "RoleMappings maps JWT claim values to IAM roles with priority.", - "items": { - "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping" - }, - "type": "array", - "uniqueItems": false - }, - "service": { - "description": "Service is the AWS service name for SigV4 signing (default: \"aws-mcp\").", - "type": "string" - }, - "session_duration": { - "description": "SessionDuration is the duration in seconds for assumed role credentials (default: 3600).", - "type": "integer" - }, - "session_name_claim": { - "description": "SessionNameClaim is the JWT claim to use for role session name (default: \"sub\").", - "type": "string" - }, - "subject_provider_name": { - "description": "SubjectProviderName identifies which upstream provider's access token to use\nfor STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer\ntoken from the incoming HTTP request is used.", - "type": "string" - } - }, - "type": "object" - }, - "github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping": { - "properties": { - "claim": { - "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", - "type": "string" - }, - "matcher": { - "description": "Matcher is a CEL expression for complex matching against JWT claims.\nThe expression has access to a \"claims\" variable containing all JWT claims.\nExamples:\n - \"admins\" in claims[\"groups\"]\n - claims[\"sub\"] == \"user123\" \u0026\u0026 !(\"act\" in claims)\nMutually exclusive with Claim.", - "type": "string" - }, - "priority": { - "description": "Priority determines selection order (lower number = higher priority).\nWhen multiple mappings match, the one with the lowest priority is selected.\nWhen nil (omitted), the mapping has the lowest possible priority, and\nconfiguration order acts as tie-breaker via stable sort.", - "type": "integer" - }, - "role_arn": { - "description": "RoleArn is the IAM role ARN to assume when this mapping matches.", - "type": "string" - } - }, - "type": "object" - }, "github_com_stacklok_toolhive_pkg_auth_upstreamswap.Config": { "description": "UpstreamSwapConfig contains configuration for upstream token swap middleware.\nWhen set along with EmbeddedAuthServerConfig, this middleware exchanges ToolHive JWTs\nfor upstream IdP tokens before forwarding requests to the MCP server.", "properties": { @@ -1883,7 +1883,7 @@ "type": "string" }, "aws_sts_config": { - "$ref": "#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.Config" + "$ref": "#/components/schemas/awssts.Config" }, "base_name": { "description": "BaseName is the base name used for the container (without prefixes)", diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index ad31f13168..b480da1d69 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -1347,6 +1347,74 @@ components: If not specified, defaults to GET. type: string type: object + awssts.Config: + description: AWSStsConfig contains AWS STS token exchange configuration for + accessing AWS services + properties: + fallback_role_arn: + description: FallbackRoleArn is the IAM role ARN to assume when no role + mapping matches. + type: string + region: + description: Region is the AWS region for STS and SigV4 signing. + type: string + role_claim: + description: 'RoleClaim is the JWT claim to use for role mapping (default: + "groups").' + type: string + role_mappings: + description: RoleMappings maps JWT claim values to IAM roles with priority. + items: + $ref: '#/components/schemas/awssts.RoleMapping' + type: array + uniqueItems: false + service: + description: 'Service is the AWS service name for SigV4 signing (default: + "aws-mcp").' + type: string + session_duration: + description: 'SessionDuration is the duration in seconds for assumed role + credentials (default: 3600).' + type: integer + session_name_claim: + description: 'SessionNameClaim is the JWT claim to use for role session + name (default: "sub").' + type: string + subject_provider_name: + description: |- + SubjectProviderName identifies which upstream provider's access token to use + for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer + token from the incoming HTTP request is used. + type: string + type: object + awssts.RoleMapping: + properties: + claim: + description: |- + Claim is the simple claim value to match (e.g., group name). + Internally compiles to a CEL expression: "" in claims[""] + Mutually exclusive with Matcher. + type: string + matcher: + description: |- + Matcher is a CEL expression for complex matching against JWT claims. + The expression has access to a "claims" variable containing all JWT claims. + Examples: + - "admins" in claims["groups"] + - claims["sub"] == "user123" && !("act" in claims) + Mutually exclusive with Claim. + type: string + priority: + description: |- + Priority determines selection order (lower number = higher priority). + When multiple mappings match, the one with the lowest priority is selected. + When nil (omitted), the mapping has the lowest possible priority, and + configuration order acts as tie-breaker via stable sort. + type: integer + role_arn: + description: RoleArn is the IAM role ARN to assume when this mapping matches. + type: string + type: object core.Workload: properties: created_at: @@ -1428,74 +1496,6 @@ components: description: URL is the URL of the workload exposed by the ToolHive proxy. type: string type: object - github_com_stacklok_toolhive_pkg_auth_awssts.Config: - description: AWSStsConfig contains AWS STS token exchange configuration for - accessing AWS services - properties: - fallback_role_arn: - description: FallbackRoleArn is the IAM role ARN to assume when no role - mapping matches. - type: string - region: - description: Region is the AWS region for STS and SigV4 signing. - type: string - role_claim: - description: 'RoleClaim is the JWT claim to use for role mapping (default: - "groups").' - type: string - role_mappings: - description: RoleMappings maps JWT claim values to IAM roles with priority. - items: - $ref: '#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping' - type: array - uniqueItems: false - service: - description: 'Service is the AWS service name for SigV4 signing (default: - "aws-mcp").' - type: string - session_duration: - description: 'SessionDuration is the duration in seconds for assumed role - credentials (default: 3600).' - type: integer - session_name_claim: - description: 'SessionNameClaim is the JWT claim to use for role session - name (default: "sub").' - type: string - subject_provider_name: - description: |- - SubjectProviderName identifies which upstream provider's access token to use - for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer - token from the incoming HTTP request is used. - type: string - type: object - github_com_stacklok_toolhive_pkg_auth_awssts.RoleMapping: - properties: - claim: - description: |- - Claim is the simple claim value to match (e.g., group name). - Internally compiles to a CEL expression: "" in claims[""] - Mutually exclusive with Matcher. - type: string - matcher: - description: |- - Matcher is a CEL expression for complex matching against JWT claims. - The expression has access to a "claims" variable containing all JWT claims. - Examples: - - "admins" in claims["groups"] - - claims["sub"] == "user123" && !("act" in claims) - Mutually exclusive with Claim. - type: string - priority: - description: |- - Priority determines selection order (lower number = higher priority). - When multiple mappings match, the one with the lowest priority is selected. - When nil (omitted), the mapping has the lowest possible priority, and - configuration order acts as tie-breaker via stable sort. - type: integer - role_arn: - description: RoleArn is the IAM role ARN to assume when this mapping matches. - type: string - type: object github_com_stacklok_toolhive_pkg_auth_upstreamswap.Config: description: |- UpstreamSwapConfig contains configuration for upstream token swap middleware. @@ -2130,7 +2130,7 @@ components: AuthzConfigPath is the path to the authorization configuration file type: string aws_sts_config: - $ref: '#/components/schemas/github_com_stacklok_toolhive_pkg_auth_awssts.Config' + $ref: '#/components/schemas/awssts.Config' base_name: description: BaseName is the base name used for the container (without prefixes) type: string diff --git a/sdk/go/client/oas_json_gen.go b/sdk/go/client/oas_json_gen.go index 376d67596a..0b6667a1f2 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -13,256 +13,14 @@ import ( ) // Encode implements json.Marshaler. -func (s *AuditConfig) Encode(e *jx.Encoder) { +func (s *AWSSTSConfig) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } // encodeFields encodes fields. -func (s *AuditConfig) encodeFields(e *jx.Encoder) { - { - if s.Component.Set { - e.FieldStart("component") - s.Component.Encode(e) - } - } - { - if s.DetectApplicationErrors.Set { - e.FieldStart("detectApplicationErrors") - s.DetectApplicationErrors.Encode(e) - } - } - { - if s.Enabled.Set { - e.FieldStart("enabled") - s.Enabled.Encode(e) - } - } - { - if s.EventTypes != nil { - e.FieldStart("eventTypes") - e.ArrStart() - for _, elem := range s.EventTypes { - e.Str(elem) - } - e.ArrEnd() - } - } - { - if s.ExcludeEventTypes != nil { - e.FieldStart("excludeEventTypes") - e.ArrStart() - for _, elem := range s.ExcludeEventTypes { - e.Str(elem) - } - e.ArrEnd() - } - } - { - if s.IncludeRequestData.Set { - e.FieldStart("includeRequestData") - s.IncludeRequestData.Encode(e) - } - } - { - if s.IncludeResponseData.Set { - e.FieldStart("includeResponseData") - s.IncludeResponseData.Encode(e) - } - } - { - if s.LogFile.Set { - e.FieldStart("logFile") - s.LogFile.Encode(e) - } - } - { - if s.MaxDataSize.Set { - e.FieldStart("maxDataSize") - s.MaxDataSize.Encode(e) - } - } - { - if s.MaxDelegationDepth.Set { - e.FieldStart("maxDelegationDepth") - s.MaxDelegationDepth.Encode(e) - } - } -} - -var jsonFieldsNameOfAuditConfig = [10]string{ - 0: "component", - 1: "detectApplicationErrors", - 2: "enabled", - 3: "eventTypes", - 4: "excludeEventTypes", - 5: "includeRequestData", - 6: "includeResponseData", - 7: "logFile", - 8: "maxDataSize", - 9: "maxDelegationDepth", -} - -// Decode decodes AuditConfig from json. -func (s *AuditConfig) Decode(d *jx.Decoder) error { - if s == nil { - return errors.New("invalid: unable to decode AuditConfig to nil") - } - - if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { - switch string(k) { - case "component": - if err := func() error { - s.Component.Reset() - if err := s.Component.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"component\"") - } - case "detectApplicationErrors": - if err := func() error { - s.DetectApplicationErrors.Reset() - if err := s.DetectApplicationErrors.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"detectApplicationErrors\"") - } - case "enabled": - if err := func() error { - s.Enabled.Reset() - if err := s.Enabled.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"enabled\"") - } - case "eventTypes": - if err := func() error { - s.EventTypes = make([]string, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { - return err - } - s.EventTypes = append(s.EventTypes, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"eventTypes\"") - } - case "excludeEventTypes": - if err := func() error { - s.ExcludeEventTypes = make([]string, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { - return err - } - s.ExcludeEventTypes = append(s.ExcludeEventTypes, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"excludeEventTypes\"") - } - case "includeRequestData": - if err := func() error { - s.IncludeRequestData.Reset() - if err := s.IncludeRequestData.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"includeRequestData\"") - } - case "includeResponseData": - if err := func() error { - s.IncludeResponseData.Reset() - if err := s.IncludeResponseData.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"includeResponseData\"") - } - case "logFile": - if err := func() error { - s.LogFile.Reset() - if err := s.LogFile.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"logFile\"") - } - case "maxDataSize": - if err := func() error { - s.MaxDataSize.Reset() - if err := s.MaxDataSize.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"maxDataSize\"") - } - case "maxDelegationDepth": - if err := func() error { - s.MaxDelegationDepth.Reset() - if err := s.MaxDelegationDepth.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"maxDelegationDepth\"") - } - default: - return d.Skip() - } - return nil - }); err != nil { - return errors.Wrap(err, "decode AuditConfig") - } - - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s *AuditConfig) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AuditConfig) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - -// Encode implements json.Marshaler. -func (s *AuthAWSSTSConfig) Encode(e *jx.Encoder) { - e.ObjStart() - s.encodeFields(e) - e.ObjEnd() -} - -// encodeFields encodes fields. -func (s *AuthAWSSTSConfig) encodeFields(e *jx.Encoder) { +func (s *AWSSTSConfig) encodeFields(e *jx.Encoder) { { if s.FallbackRoleArn.Set { e.FieldStart("fallback_role_arn") @@ -317,7 +75,7 @@ func (s *AuthAWSSTSConfig) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAuthAWSSTSConfig = [8]string{ +var jsonFieldsNameOfAWSSTSConfig = [8]string{ 0: "fallback_role_arn", 1: "region", 2: "role_claim", @@ -328,10 +86,10 @@ var jsonFieldsNameOfAuthAWSSTSConfig = [8]string{ 7: "subject_provider_name", } -// Decode decodes AuthAWSSTSConfig from json. -func (s *AuthAWSSTSConfig) Decode(d *jx.Decoder) error { +// Decode decodes AWSSTSConfig from json. +func (s *AWSSTSConfig) Decode(d *jx.Decoder) error { if s == nil { - return errors.New("invalid: unable to decode AuthAWSSTSConfig to nil") + return errors.New("invalid: unable to decode AWSSTSConfig to nil") } if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { @@ -368,9 +126,9 @@ func (s *AuthAWSSTSConfig) Decode(d *jx.Decoder) error { } case "role_mappings": if err := func() error { - s.RoleMappings = make([]AuthAWSSTSRoleMapping, 0) + s.RoleMappings = make([]AWSSTSRoleMapping, 0) if err := d.Arr(func(d *jx.Decoder) error { - var elem AuthAWSSTSRoleMapping + var elem AWSSTSRoleMapping if err := elem.Decode(d); err != nil { return err } @@ -428,34 +186,34 @@ func (s *AuthAWSSTSConfig) Decode(d *jx.Decoder) error { } return nil }); err != nil { - return errors.Wrap(err, "decode AuthAWSSTSConfig") + return errors.Wrap(err, "decode AWSSTSConfig") } return nil } // MarshalJSON implements stdjson.Marshaler. -func (s *AuthAWSSTSConfig) MarshalJSON() ([]byte, error) { +func (s *AWSSTSConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AuthAWSSTSConfig) UnmarshalJSON(data []byte) error { +func (s *AWSSTSConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } // Encode implements json.Marshaler. -func (s *AuthAWSSTSRoleMapping) Encode(e *jx.Encoder) { +func (s *AWSSTSRoleMapping) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } // encodeFields encodes fields. -func (s *AuthAWSSTSRoleMapping) encodeFields(e *jx.Encoder) { +func (s *AWSSTSRoleMapping) encodeFields(e *jx.Encoder) { { if s.Claim.Set { e.FieldStart("claim") @@ -482,17 +240,17 @@ func (s *AuthAWSSTSRoleMapping) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAuthAWSSTSRoleMapping = [4]string{ +var jsonFieldsNameOfAWSSTSRoleMapping = [4]string{ 0: "claim", 1: "matcher", 2: "priority", 3: "role_arn", } -// Decode decodes AuthAWSSTSRoleMapping from json. -func (s *AuthAWSSTSRoleMapping) Decode(d *jx.Decoder) error { +// Decode decodes AWSSTSRoleMapping from json. +func (s *AWSSTSRoleMapping) Decode(d *jx.Decoder) error { if s == nil { - return errors.New("invalid: unable to decode AuthAWSSTSRoleMapping to nil") + return errors.New("invalid: unable to decode AWSSTSRoleMapping to nil") } if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { @@ -542,21 +300,263 @@ func (s *AuthAWSSTSRoleMapping) Decode(d *jx.Decoder) error { } return nil }); err != nil { - return errors.Wrap(err, "decode AuthAWSSTSRoleMapping") + return errors.Wrap(err, "decode AWSSTSRoleMapping") + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AWSSTSRoleMapping) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AWSSTSRoleMapping) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AuditConfig) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AuditConfig) encodeFields(e *jx.Encoder) { + { + if s.Component.Set { + e.FieldStart("component") + s.Component.Encode(e) + } + } + { + if s.DetectApplicationErrors.Set { + e.FieldStart("detectApplicationErrors") + s.DetectApplicationErrors.Encode(e) + } + } + { + if s.Enabled.Set { + e.FieldStart("enabled") + s.Enabled.Encode(e) + } + } + { + if s.EventTypes != nil { + e.FieldStart("eventTypes") + e.ArrStart() + for _, elem := range s.EventTypes { + e.Str(elem) + } + e.ArrEnd() + } + } + { + if s.ExcludeEventTypes != nil { + e.FieldStart("excludeEventTypes") + e.ArrStart() + for _, elem := range s.ExcludeEventTypes { + e.Str(elem) + } + e.ArrEnd() + } + } + { + if s.IncludeRequestData.Set { + e.FieldStart("includeRequestData") + s.IncludeRequestData.Encode(e) + } + } + { + if s.IncludeResponseData.Set { + e.FieldStart("includeResponseData") + s.IncludeResponseData.Encode(e) + } + } + { + if s.LogFile.Set { + e.FieldStart("logFile") + s.LogFile.Encode(e) + } + } + { + if s.MaxDataSize.Set { + e.FieldStart("maxDataSize") + s.MaxDataSize.Encode(e) + } + } + { + if s.MaxDelegationDepth.Set { + e.FieldStart("maxDelegationDepth") + s.MaxDelegationDepth.Encode(e) + } + } +} + +var jsonFieldsNameOfAuditConfig = [10]string{ + 0: "component", + 1: "detectApplicationErrors", + 2: "enabled", + 3: "eventTypes", + 4: "excludeEventTypes", + 5: "includeRequestData", + 6: "includeResponseData", + 7: "logFile", + 8: "maxDataSize", + 9: "maxDelegationDepth", +} + +// Decode decodes AuditConfig from json. +func (s *AuditConfig) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AuditConfig to nil") + } + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "component": + if err := func() error { + s.Component.Reset() + if err := s.Component.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"component\"") + } + case "detectApplicationErrors": + if err := func() error { + s.DetectApplicationErrors.Reset() + if err := s.DetectApplicationErrors.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detectApplicationErrors\"") + } + case "enabled": + if err := func() error { + s.Enabled.Reset() + if err := s.Enabled.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"enabled\"") + } + case "eventTypes": + if err := func() error { + s.EventTypes = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.EventTypes = append(s.EventTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"eventTypes\"") + } + case "excludeEventTypes": + if err := func() error { + s.ExcludeEventTypes = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.ExcludeEventTypes = append(s.ExcludeEventTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"excludeEventTypes\"") + } + case "includeRequestData": + if err := func() error { + s.IncludeRequestData.Reset() + if err := s.IncludeRequestData.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"includeRequestData\"") + } + case "includeResponseData": + if err := func() error { + s.IncludeResponseData.Reset() + if err := s.IncludeResponseData.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"includeResponseData\"") + } + case "logFile": + if err := func() error { + s.LogFile.Reset() + if err := s.LogFile.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"logFile\"") + } + case "maxDataSize": + if err := func() error { + s.MaxDataSize.Reset() + if err := s.MaxDataSize.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"maxDataSize\"") + } + case "maxDelegationDepth": + if err := func() error { + s.MaxDelegationDepth.Reset() + if err := s.MaxDelegationDepth.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"maxDelegationDepth\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AuditConfig") } return nil } // MarshalJSON implements stdjson.Marshaler. -func (s *AuthAWSSTSRoleMapping) MarshalJSON() ([]byte, error) { +func (s *AuditConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AuthAWSSTSRoleMapping) UnmarshalJSON(data []byte) error { +func (s *AuditConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } @@ -17492,18 +17492,18 @@ func (s *OidcOptions) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes AuditConfig as json. -func (o OptAuditConfig) Encode(e *jx.Encoder) { +// Encode encodes AWSSTSConfig as json. +func (o OptAWSSTSConfig) Encode(e *jx.Encoder) { if !o.Set { return } o.Value.Encode(e) } -// Decode decodes AuditConfig from json. -func (o *OptAuditConfig) Decode(d *jx.Decoder) error { +// Decode decodes AWSSTSConfig from json. +func (o *OptAWSSTSConfig) Decode(d *jx.Decoder) error { if o == nil { - return errors.New("invalid: unable to decode OptAuditConfig to nil") + return errors.New("invalid: unable to decode OptAWSSTSConfig to nil") } o.Set = true if err := o.Value.Decode(d); err != nil { @@ -17513,30 +17513,30 @@ func (o *OptAuditConfig) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s OptAuditConfig) MarshalJSON() ([]byte, error) { +func (s OptAWSSTSConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *OptAuditConfig) UnmarshalJSON(data []byte) error { +func (s *OptAWSSTSConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } -// Encode encodes AuthAWSSTSConfig as json. -func (o OptAuthAWSSTSConfig) Encode(e *jx.Encoder) { +// Encode encodes AuditConfig as json. +func (o OptAuditConfig) Encode(e *jx.Encoder) { if !o.Set { return } o.Value.Encode(e) } -// Decode decodes AuthAWSSTSConfig from json. -func (o *OptAuthAWSSTSConfig) Decode(d *jx.Decoder) error { +// Decode decodes AuditConfig from json. +func (o *OptAuditConfig) Decode(d *jx.Decoder) error { if o == nil { - return errors.New("invalid: unable to decode OptAuthAWSSTSConfig to nil") + return errors.New("invalid: unable to decode OptAuditConfig to nil") } o.Set = true if err := o.Value.Decode(d); err != nil { @@ -17546,14 +17546,14 @@ func (o *OptAuthAWSSTSConfig) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s OptAuthAWSSTSConfig) MarshalJSON() ([]byte, error) { +func (s OptAuditConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *OptAuthAWSSTSConfig) UnmarshalJSON(data []byte) error { +func (s *OptAuditConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index a6bc35df43..9b5ef01089 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -10,6 +10,171 @@ import ( "github.com/go-faster/jx" ) +// AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services. +// Ref: #/components/schemas/AWSSTSConfig +type AWSSTSConfig struct { + // FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. + FallbackRoleArn OptString `json:"fallback_role_arn"` + // Region is the AWS region for STS and SigV4 signing. + Region OptString `json:"region"` + // RoleClaim is the JWT claim to use for role mapping (default: "groups"). + RoleClaim OptString `json:"role_claim"` + // RoleMappings maps JWT claim values to IAM roles with priority. + RoleMappings []AWSSTSRoleMapping `json:"role_mappings"` + // Service is the AWS service name for SigV4 signing (default: "aws-mcp"). + Service OptString `json:"service"` + // SessionDuration is the duration in seconds for assumed role credentials (default: 3600). + SessionDuration OptInt `json:"session_duration"` + // SessionNameClaim is the JWT claim to use for role session name (default: "sub"). + SessionNameClaim OptString `json:"session_name_claim"` + // SubjectProviderName identifies which upstream provider's access token to use + // for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer + // token from the incoming HTTP request is used. + SubjectProviderName OptString `json:"subject_provider_name"` +} + +// GetFallbackRoleArn returns the value of FallbackRoleArn. +func (s *AWSSTSConfig) GetFallbackRoleArn() OptString { + return s.FallbackRoleArn +} + +// GetRegion returns the value of Region. +func (s *AWSSTSConfig) GetRegion() OptString { + return s.Region +} + +// GetRoleClaim returns the value of RoleClaim. +func (s *AWSSTSConfig) GetRoleClaim() OptString { + return s.RoleClaim +} + +// GetRoleMappings returns the value of RoleMappings. +func (s *AWSSTSConfig) GetRoleMappings() []AWSSTSRoleMapping { + return s.RoleMappings +} + +// GetService returns the value of Service. +func (s *AWSSTSConfig) GetService() OptString { + return s.Service +} + +// GetSessionDuration returns the value of SessionDuration. +func (s *AWSSTSConfig) GetSessionDuration() OptInt { + return s.SessionDuration +} + +// GetSessionNameClaim returns the value of SessionNameClaim. +func (s *AWSSTSConfig) GetSessionNameClaim() OptString { + return s.SessionNameClaim +} + +// GetSubjectProviderName returns the value of SubjectProviderName. +func (s *AWSSTSConfig) GetSubjectProviderName() OptString { + return s.SubjectProviderName +} + +// SetFallbackRoleArn sets the value of FallbackRoleArn. +func (s *AWSSTSConfig) SetFallbackRoleArn(val OptString) { + s.FallbackRoleArn = val +} + +// SetRegion sets the value of Region. +func (s *AWSSTSConfig) SetRegion(val OptString) { + s.Region = val +} + +// SetRoleClaim sets the value of RoleClaim. +func (s *AWSSTSConfig) SetRoleClaim(val OptString) { + s.RoleClaim = val +} + +// SetRoleMappings sets the value of RoleMappings. +func (s *AWSSTSConfig) SetRoleMappings(val []AWSSTSRoleMapping) { + s.RoleMappings = val +} + +// SetService sets the value of Service. +func (s *AWSSTSConfig) SetService(val OptString) { + s.Service = val +} + +// SetSessionDuration sets the value of SessionDuration. +func (s *AWSSTSConfig) SetSessionDuration(val OptInt) { + s.SessionDuration = val +} + +// SetSessionNameClaim sets the value of SessionNameClaim. +func (s *AWSSTSConfig) SetSessionNameClaim(val OptString) { + s.SessionNameClaim = val +} + +// SetSubjectProviderName sets the value of SubjectProviderName. +func (s *AWSSTSConfig) SetSubjectProviderName(val OptString) { + s.SubjectProviderName = val +} + +// Ref: #/components/schemas/AWSSTSRoleMapping +type AWSSTSRoleMapping struct { + // Claim is the simple claim value to match (e.g., group name). + // Internally compiles to a CEL expression: "" in claims[""] + // Mutually exclusive with Matcher. + Claim OptString `json:"claim"` + // Matcher is a CEL expression for complex matching against JWT claims. + // The expression has access to a "claims" variable containing all JWT claims. + // Examples: + // - "admins" in claims["groups"] + // - claims["sub"] == "user123" && !("act" in claims) + // Mutually exclusive with Claim. + Matcher OptString `json:"matcher"` + // Priority determines selection order (lower number = higher priority). + // When multiple mappings match, the one with the lowest priority is selected. + // When nil (omitted), the mapping has the lowest possible priority, and + // configuration order acts as tie-breaker via stable sort. + Priority OptInt `json:"priority"` + // RoleArn is the IAM role ARN to assume when this mapping matches. + RoleArn OptString `json:"role_arn"` +} + +// GetClaim returns the value of Claim. +func (s *AWSSTSRoleMapping) GetClaim() OptString { + return s.Claim +} + +// GetMatcher returns the value of Matcher. +func (s *AWSSTSRoleMapping) GetMatcher() OptString { + return s.Matcher +} + +// GetPriority returns the value of Priority. +func (s *AWSSTSRoleMapping) GetPriority() OptInt { + return s.Priority +} + +// GetRoleArn returns the value of RoleArn. +func (s *AWSSTSRoleMapping) GetRoleArn() OptString { + return s.RoleArn +} + +// SetClaim sets the value of Claim. +func (s *AWSSTSRoleMapping) SetClaim(val OptString) { + s.Claim = val +} + +// SetMatcher sets the value of Matcher. +func (s *AWSSTSRoleMapping) SetMatcher(val OptString) { + s.Matcher = val +} + +// SetPriority sets the value of Priority. +func (s *AWSSTSRoleMapping) SetPriority(val OptInt) { + s.Priority = val +} + +// SetRoleArn sets the value of RoleArn. +func (s *AWSSTSRoleMapping) SetRoleArn(val OptString) { + s.RoleArn = val +} + type AddRegistryNotImplemented struct { Data io.Reader } @@ -175,171 +340,6 @@ func (s *AuditConfig) SetMaxDelegationDepth(val OptInt) { s.MaxDelegationDepth = val } -// AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services. -// Ref: #/components/schemas/AuthAWSSTSConfig -type AuthAWSSTSConfig struct { - // FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. - FallbackRoleArn OptString `json:"fallback_role_arn"` - // Region is the AWS region for STS and SigV4 signing. - Region OptString `json:"region"` - // RoleClaim is the JWT claim to use for role mapping (default: "groups"). - RoleClaim OptString `json:"role_claim"` - // RoleMappings maps JWT claim values to IAM roles with priority. - RoleMappings []AuthAWSSTSRoleMapping `json:"role_mappings"` - // Service is the AWS service name for SigV4 signing (default: "aws-mcp"). - Service OptString `json:"service"` - // SessionDuration is the duration in seconds for assumed role credentials (default: 3600). - SessionDuration OptInt `json:"session_duration"` - // SessionNameClaim is the JWT claim to use for role session name (default: "sub"). - SessionNameClaim OptString `json:"session_name_claim"` - // SubjectProviderName identifies which upstream provider's access token to use - // for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer - // token from the incoming HTTP request is used. - SubjectProviderName OptString `json:"subject_provider_name"` -} - -// GetFallbackRoleArn returns the value of FallbackRoleArn. -func (s *AuthAWSSTSConfig) GetFallbackRoleArn() OptString { - return s.FallbackRoleArn -} - -// GetRegion returns the value of Region. -func (s *AuthAWSSTSConfig) GetRegion() OptString { - return s.Region -} - -// GetRoleClaim returns the value of RoleClaim. -func (s *AuthAWSSTSConfig) GetRoleClaim() OptString { - return s.RoleClaim -} - -// GetRoleMappings returns the value of RoleMappings. -func (s *AuthAWSSTSConfig) GetRoleMappings() []AuthAWSSTSRoleMapping { - return s.RoleMappings -} - -// GetService returns the value of Service. -func (s *AuthAWSSTSConfig) GetService() OptString { - return s.Service -} - -// GetSessionDuration returns the value of SessionDuration. -func (s *AuthAWSSTSConfig) GetSessionDuration() OptInt { - return s.SessionDuration -} - -// GetSessionNameClaim returns the value of SessionNameClaim. -func (s *AuthAWSSTSConfig) GetSessionNameClaim() OptString { - return s.SessionNameClaim -} - -// GetSubjectProviderName returns the value of SubjectProviderName. -func (s *AuthAWSSTSConfig) GetSubjectProviderName() OptString { - return s.SubjectProviderName -} - -// SetFallbackRoleArn sets the value of FallbackRoleArn. -func (s *AuthAWSSTSConfig) SetFallbackRoleArn(val OptString) { - s.FallbackRoleArn = val -} - -// SetRegion sets the value of Region. -func (s *AuthAWSSTSConfig) SetRegion(val OptString) { - s.Region = val -} - -// SetRoleClaim sets the value of RoleClaim. -func (s *AuthAWSSTSConfig) SetRoleClaim(val OptString) { - s.RoleClaim = val -} - -// SetRoleMappings sets the value of RoleMappings. -func (s *AuthAWSSTSConfig) SetRoleMappings(val []AuthAWSSTSRoleMapping) { - s.RoleMappings = val -} - -// SetService sets the value of Service. -func (s *AuthAWSSTSConfig) SetService(val OptString) { - s.Service = val -} - -// SetSessionDuration sets the value of SessionDuration. -func (s *AuthAWSSTSConfig) SetSessionDuration(val OptInt) { - s.SessionDuration = val -} - -// SetSessionNameClaim sets the value of SessionNameClaim. -func (s *AuthAWSSTSConfig) SetSessionNameClaim(val OptString) { - s.SessionNameClaim = val -} - -// SetSubjectProviderName sets the value of SubjectProviderName. -func (s *AuthAWSSTSConfig) SetSubjectProviderName(val OptString) { - s.SubjectProviderName = val -} - -// Ref: #/components/schemas/AuthAWSSTSRoleMapping -type AuthAWSSTSRoleMapping struct { - // Claim is the simple claim value to match (e.g., group name). - // Internally compiles to a CEL expression: "" in claims[""] - // Mutually exclusive with Matcher. - Claim OptString `json:"claim"` - // Matcher is a CEL expression for complex matching against JWT claims. - // The expression has access to a "claims" variable containing all JWT claims. - // Examples: - // - "admins" in claims["groups"] - // - claims["sub"] == "user123" && !("act" in claims) - // Mutually exclusive with Claim. - Matcher OptString `json:"matcher"` - // Priority determines selection order (lower number = higher priority). - // When multiple mappings match, the one with the lowest priority is selected. - // When nil (omitted), the mapping has the lowest possible priority, and - // configuration order acts as tie-breaker via stable sort. - Priority OptInt `json:"priority"` - // RoleArn is the IAM role ARN to assume when this mapping matches. - RoleArn OptString `json:"role_arn"` -} - -// GetClaim returns the value of Claim. -func (s *AuthAWSSTSRoleMapping) GetClaim() OptString { - return s.Claim -} - -// GetMatcher returns the value of Matcher. -func (s *AuthAWSSTSRoleMapping) GetMatcher() OptString { - return s.Matcher -} - -// GetPriority returns the value of Priority. -func (s *AuthAWSSTSRoleMapping) GetPriority() OptInt { - return s.Priority -} - -// GetRoleArn returns the value of RoleArn. -func (s *AuthAWSSTSRoleMapping) GetRoleArn() OptString { - return s.RoleArn -} - -// SetClaim sets the value of Claim. -func (s *AuthAWSSTSRoleMapping) SetClaim(val OptString) { - s.Claim = val -} - -// SetMatcher sets the value of Matcher. -func (s *AuthAWSSTSRoleMapping) SetMatcher(val OptString) { - s.Matcher = val -} - -// SetPriority sets the value of Priority. -func (s *AuthAWSSTSRoleMapping) SetPriority(val OptInt) { - s.Priority = val -} - -// SetRoleArn sets the value of RoleArn. -func (s *AuthAWSSTSRoleMapping) SetRoleArn(val OptString) { - s.RoleArn = val -} - // DEPRECATED: Middleware configuration. // OIDCConfig contains OIDC configuration. // Ref: #/components/schemas/AuthTokenValidatorConfig @@ -7014,38 +7014,38 @@ func (s *OidcOptions) SetScopes(val []string) { s.Scopes = val } -// NewOptAuditConfig returns new OptAuditConfig with value set to v. -func NewOptAuditConfig(v AuditConfig) OptAuditConfig { - return OptAuditConfig{ +// NewOptAWSSTSConfig returns new OptAWSSTSConfig with value set to v. +func NewOptAWSSTSConfig(v AWSSTSConfig) OptAWSSTSConfig { + return OptAWSSTSConfig{ Value: v, Set: true, } } -// OptAuditConfig is optional AuditConfig. -type OptAuditConfig struct { - Value AuditConfig +// OptAWSSTSConfig is optional AWSSTSConfig. +type OptAWSSTSConfig struct { + Value AWSSTSConfig Set bool } -// IsSet returns true if OptAuditConfig was set. -func (o OptAuditConfig) IsSet() bool { return o.Set } +// IsSet returns true if OptAWSSTSConfig was set. +func (o OptAWSSTSConfig) IsSet() bool { return o.Set } // Reset unsets value. -func (o *OptAuditConfig) Reset() { - var v AuditConfig +func (o *OptAWSSTSConfig) Reset() { + var v AWSSTSConfig o.Value = v o.Set = false } // SetTo sets value to v. -func (o *OptAuditConfig) SetTo(v AuditConfig) { +func (o *OptAWSSTSConfig) SetTo(v AWSSTSConfig) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. -func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { +func (o OptAWSSTSConfig) Get() (v AWSSTSConfig, ok bool) { if !o.Set { return v, false } @@ -7053,45 +7053,45 @@ func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { } // Or returns value if set, or given parameter if does not. -func (o OptAuditConfig) Or(d AuditConfig) AuditConfig { +func (o OptAWSSTSConfig) Or(d AWSSTSConfig) AWSSTSConfig { if v, ok := o.Get(); ok { return v } return d } -// NewOptAuthAWSSTSConfig returns new OptAuthAWSSTSConfig with value set to v. -func NewOptAuthAWSSTSConfig(v AuthAWSSTSConfig) OptAuthAWSSTSConfig { - return OptAuthAWSSTSConfig{ +// NewOptAuditConfig returns new OptAuditConfig with value set to v. +func NewOptAuditConfig(v AuditConfig) OptAuditConfig { + return OptAuditConfig{ Value: v, Set: true, } } -// OptAuthAWSSTSConfig is optional AuthAWSSTSConfig. -type OptAuthAWSSTSConfig struct { - Value AuthAWSSTSConfig +// OptAuditConfig is optional AuditConfig. +type OptAuditConfig struct { + Value AuditConfig Set bool } -// IsSet returns true if OptAuthAWSSTSConfig was set. -func (o OptAuthAWSSTSConfig) IsSet() bool { return o.Set } +// IsSet returns true if OptAuditConfig was set. +func (o OptAuditConfig) IsSet() bool { return o.Set } // Reset unsets value. -func (o *OptAuthAWSSTSConfig) Reset() { - var v AuthAWSSTSConfig +func (o *OptAuditConfig) Reset() { + var v AuditConfig o.Value = v o.Set = false } // SetTo sets value to v. -func (o *OptAuthAWSSTSConfig) SetTo(v AuthAWSSTSConfig) { +func (o *OptAuditConfig) SetTo(v AuditConfig) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. -func (o OptAuthAWSSTSConfig) Get() (v AuthAWSSTSConfig, ok bool) { +func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { if !o.Set { return v, false } @@ -7099,7 +7099,7 @@ func (o OptAuthAWSSTSConfig) Get() (v AuthAWSSTSConfig, ok bool) { } // Or returns value if set, or given parameter if does not. -func (o OptAuthAWSSTSConfig) Or(d AuthAWSSTSConfig) AuthAWSSTSConfig { +func (o OptAuditConfig) Or(d AuditConfig) AuditConfig { if v, ok := o.Get(); ok { return v } @@ -18278,8 +18278,8 @@ type RunnerRunConfig struct { AuthzConfig OptAuthorizationConfig `json:"authz_config"` // DEPRECATED: Middleware configuration. // AuthzConfigPath is the path to the authorization configuration file. - AuthzConfigPath OptString `json:"authz_config_path"` - AWSStsConfig OptAuthAWSSTSConfig `json:"aws_sts_config"` + AuthzConfigPath OptString `json:"authz_config_path"` + AWSStsConfig OptAWSSTSConfig `json:"aws_sts_config"` // BaseName is the base name used for the container (without prefixes). BaseName OptString `json:"base_name"` // CmdArgs are the arguments to pass to the container. @@ -18457,7 +18457,7 @@ func (s *RunnerRunConfig) GetAuthzConfigPath() OptString { } // GetAWSStsConfig returns the value of AWSStsConfig. -func (s *RunnerRunConfig) GetAWSStsConfig() OptAuthAWSSTSConfig { +func (s *RunnerRunConfig) GetAWSStsConfig() OptAWSSTSConfig { return s.AWSStsConfig } @@ -18772,7 +18772,7 @@ func (s *RunnerRunConfig) SetAuthzConfigPath(val OptString) { } // SetAWSStsConfig sets the value of AWSStsConfig. -func (s *RunnerRunConfig) SetAWSStsConfig(val OptAuthAWSSTSConfig) { +func (s *RunnerRunConfig) SetAWSStsConfig(val OptAWSSTSConfig) { s.AWSStsConfig = val } diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 67d9178d18..6286a5a7b3 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -1,61 +1,7 @@ { "components": { "schemas": { - "AuditConfig": { - "description": "DEPRECATED: Middleware configuration.\nAuditConfig contains the audit logging configuration", - "properties": { - "component": { - "description": "Component is the component name to use in audit events.\n+optional", - "type": "string" - }, - "detectApplicationErrors": { - "description": "DetectApplicationErrors controls whether the audit middleware inspects\nJSON-RPC response bodies for application-level errors when the HTTP\nstatus code indicates success (2xx). When enabled, a small prefix of\nthe response body is buffered to detect JSON-RPC error fields,\nindependent of the IncludeResponseData setting.\n+kubebuilder:default=true\n+optional", - "type": "boolean" - }, - "enabled": { - "description": "Enabled controls whether audit logging is enabled.\nWhen true, enables audit logging with the configured options.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "eventTypes": { - "description": "EventTypes specifies which event types to audit. If empty, all events are audited.\n+optional", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, - "excludeEventTypes": { - "description": "ExcludeEventTypes specifies which event types to exclude from auditing.\nThis takes precedence over EventTypes.\n+optional", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, - "includeRequestData": { - "description": "IncludeRequestData determines whether to include request data in audit logs.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "includeResponseData": { - "description": "IncludeResponseData determines whether to include response data in audit logs.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "logFile": { - "description": "LogFile specifies the file path for audit logs. If empty, logs to stdout.\n+optional", - "type": "string" - }, - "maxDataSize": { - "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", - "type": "integer" - }, - "maxDelegationDepth": { - "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", - "type": "integer" - } - }, - "type": "object" - }, - "AuthAWSSTSConfig": { + "AWSSTSConfig": { "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", "properties": { "fallback_role_arn": { @@ -73,7 +19,7 @@ "role_mappings": { "description": "RoleMappings maps JWT claim values to IAM roles with priority.", "items": { - "$ref": "#/components/schemas/AuthAWSSTSRoleMapping" + "$ref": "#/components/schemas/AWSSTSRoleMapping" }, "type": "array", "uniqueItems": false @@ -97,7 +43,7 @@ }, "type": "object" }, - "AuthAWSSTSRoleMapping": { + "AWSSTSRoleMapping": { "properties": { "claim": { "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", @@ -118,6 +64,60 @@ }, "type": "object" }, + "AuditConfig": { + "description": "DEPRECATED: Middleware configuration.\nAuditConfig contains the audit logging configuration", + "properties": { + "component": { + "description": "Component is the component name to use in audit events.\n+optional", + "type": "string" + }, + "detectApplicationErrors": { + "description": "DetectApplicationErrors controls whether the audit middleware inspects\nJSON-RPC response bodies for application-level errors when the HTTP\nstatus code indicates success (2xx). When enabled, a small prefix of\nthe response body is buffered to detect JSON-RPC error fields,\nindependent of the IncludeResponseData setting.\n+kubebuilder:default=true\n+optional", + "type": "boolean" + }, + "enabled": { + "description": "Enabled controls whether audit logging is enabled.\nWhen true, enables audit logging with the configured options.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "eventTypes": { + "description": "EventTypes specifies which event types to audit. If empty, all events are audited.\n+optional", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "excludeEventTypes": { + "description": "ExcludeEventTypes specifies which event types to exclude from auditing.\nThis takes precedence over EventTypes.\n+optional", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "includeRequestData": { + "description": "IncludeRequestData determines whether to include request data in audit logs.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "includeResponseData": { + "description": "IncludeResponseData determines whether to include response data in audit logs.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "logFile": { + "description": "LogFile specifies the file path for audit logs. If empty, logs to stdout.\n+optional", + "type": "string" + }, + "maxDataSize": { + "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", + "type": "integer" + }, + "maxDelegationDepth": { + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", + "type": "integer" + } + }, + "type": "object" + }, "AuthTokenValidatorConfig": { "description": "DEPRECATED: Middleware configuration.\nOIDCConfig contains OIDC configuration", "properties": { @@ -4040,7 +4040,7 @@ "type": "string" }, "aws_sts_config": { - "$ref": "#/components/schemas/AuthAWSSTSConfig" + "$ref": "#/components/schemas/AWSSTSConfig" }, "base_name": { "description": "BaseName is the base name used for the container (without prefixes)", diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 8075c91e15..fb980677a3 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -1,5 +1,67 @@ components: schemas: + AWSSTSConfig: + description: AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services + properties: + fallback_role_arn: + description: FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. + type: string + region: + description: Region is the AWS region for STS and SigV4 signing. + type: string + role_claim: + description: 'RoleClaim is the JWT claim to use for role mapping (default: "groups").' + type: string + role_mappings: + description: RoleMappings maps JWT claim values to IAM roles with priority. + items: + $ref: '#/components/schemas/AWSSTSRoleMapping' + type: array + uniqueItems: false + service: + description: 'Service is the AWS service name for SigV4 signing (default: "aws-mcp").' + type: string + session_duration: + description: 'SessionDuration is the duration in seconds for assumed role credentials (default: 3600).' + type: integer + session_name_claim: + description: 'SessionNameClaim is the JWT claim to use for role session name (default: "sub").' + type: string + subject_provider_name: + description: |- + SubjectProviderName identifies which upstream provider's access token to use + for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer + token from the incoming HTTP request is used. + type: string + type: object + AWSSTSRoleMapping: + properties: + claim: + description: |- + Claim is the simple claim value to match (e.g., group name). + Internally compiles to a CEL expression: "" in claims[""] + Mutually exclusive with Matcher. + type: string + matcher: + description: |- + Matcher is a CEL expression for complex matching against JWT claims. + The expression has access to a "claims" variable containing all JWT claims. + Examples: + - "admins" in claims["groups"] + - claims["sub"] == "user123" && !("act" in claims) + Mutually exclusive with Claim. + type: string + priority: + description: |- + Priority determines selection order (lower number = higher priority). + When multiple mappings match, the one with the lowest priority is selected. + When nil (omitted), the mapping has the lowest possible priority, and + configuration order acts as tie-breaker via stable sort. + type: integer + role_arn: + description: RoleArn is the IAM role ARN to assume when this mapping matches. + type: string + type: object AuditConfig: description: |- DEPRECATED: Middleware configuration. @@ -77,68 +139,6 @@ components: +optional type: integer type: object - AuthAWSSTSConfig: - description: AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services - properties: - fallback_role_arn: - description: FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. - type: string - region: - description: Region is the AWS region for STS and SigV4 signing. - type: string - role_claim: - description: 'RoleClaim is the JWT claim to use for role mapping (default: "groups").' - type: string - role_mappings: - description: RoleMappings maps JWT claim values to IAM roles with priority. - items: - $ref: '#/components/schemas/AuthAWSSTSRoleMapping' - type: array - uniqueItems: false - service: - description: 'Service is the AWS service name for SigV4 signing (default: "aws-mcp").' - type: string - session_duration: - description: 'SessionDuration is the duration in seconds for assumed role credentials (default: 3600).' - type: integer - session_name_claim: - description: 'SessionNameClaim is the JWT claim to use for role session name (default: "sub").' - type: string - subject_provider_name: - description: |- - SubjectProviderName identifies which upstream provider's access token to use - for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer - token from the incoming HTTP request is used. - type: string - type: object - AuthAWSSTSRoleMapping: - properties: - claim: - description: |- - Claim is the simple claim value to match (e.g., group name). - Internally compiles to a CEL expression: "" in claims[""] - Mutually exclusive with Matcher. - type: string - matcher: - description: |- - Matcher is a CEL expression for complex matching against JWT claims. - The expression has access to a "claims" variable containing all JWT claims. - Examples: - - "admins" in claims["groups"] - - claims["sub"] == "user123" && !("act" in claims) - Mutually exclusive with Claim. - type: string - priority: - description: |- - Priority determines selection order (lower number = higher priority). - When multiple mappings match, the one with the lowest priority is selected. - When nil (omitted), the mapping has the lowest possible priority, and - configuration order acts as tie-breaker via stable sort. - type: integer - role_arn: - description: RoleArn is the IAM role ARN to assume when this mapping matches. - type: string - type: object AuthTokenValidatorConfig: description: |- DEPRECATED: Middleware configuration. @@ -3884,7 +3884,7 @@ components: AuthzConfigPath is the path to the authorization configuration file type: string aws_sts_config: - $ref: '#/components/schemas/AuthAWSSTSConfig' + $ref: '#/components/schemas/AWSSTSConfig' base_name: description: BaseName is the base name used for the container (without prefixes) type: string From bead6e7efb18af705ad67335d43a1c4c6f1c4c35 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 12:16:18 -0800 Subject: [PATCH 05/12] Keep OBO clientSecretEnv unresolved at load The operator renders inline VirtualMCPServer OBO backends with only clientSecretEnv. The YAML loader copied the env value into clientSecret without clearing clientSecretEnv, so the validator and the OBO strategy rejected the backend as setting both, and vMCP failed at startup. The loader now only checks the variable is set, as it does for tokenExchange; the strategy reads it at request time. Addresses stacklok/toolhive#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 --- pkg/vmcp/config/yaml_loader.go | 9 ++- pkg/vmcp/config/yaml_loader_test.go | 31 +++++++++ test/integration/vmcp/obo_integration_test.go | 65 +++++++++++++++++++ 3 files changed, 102 insertions(+), 3 deletions(-) diff --git a/pkg/vmcp/config/yaml_loader.go b/pkg/vmcp/config/yaml_loader.go index 9bd9e59a75..8afc3555f2 100644 --- a/pkg/vmcp/config/yaml_loader.go +++ b/pkg/vmcp/config/yaml_loader.go @@ -161,11 +161,14 @@ func (l *YAMLLoader) processBackendAuthStrategy(name string, strategy *authtypes return fmt.Errorf("backend %s: only one of clientSecret or clientSecretEnv must be set", name) } if obo.ClientSecretEnv != "" { - resolvedSecret := l.envReader.Getenv(obo.ClientSecretEnv) - if resolvedSecret == "" { + // Only check the variable is set, as for tokenExchange: the OBO + // strategy reads ClientSecretEnv at request time and rejects a + // config that sets both ClientSecret and ClientSecretEnv, so + // copying the value into ClientSecret here would make the + // operator-generated inline config fail validation. + if l.envReader.Getenv(obo.ClientSecretEnv) == "" { return fmt.Errorf("backend %s: environment variable %s not set", name, obo.ClientSecretEnv) } - obo.ClientSecret = resolvedSecret } default: diff --git a/pkg/vmcp/config/yaml_loader_test.go b/pkg/vmcp/config/yaml_loader_test.go index ac6976492e..8f056639fd 100644 --- a/pkg/vmcp/config/yaml_loader_test.go +++ b/pkg/vmcp/config/yaml_loader_test.go @@ -739,6 +739,37 @@ aggregation: shouldPass: false, errMsg: "incomingAuth.type must be one of", }, + { + // The operator renders inline OBO backends with only + // clientSecretEnv and mounts the Secret under that name. + name: "obo backend with clientSecretEnv passes validation", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token + clientId: client-123 + clientSecretEnv: OBO_SECRET + scopes: + - api://backend/.default + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + envVars: map[string]string{"OBO_SECRET": "secret-value"}, + shouldPass: true, + }, } for _, tt := range tests { diff --git a/test/integration/vmcp/obo_integration_test.go b/test/integration/vmcp/obo_integration_test.go index 17eeed7e0d..3726211638 100644 --- a/test/integration/vmcp/obo_integration_test.go +++ b/test/integration/vmcp/obo_integration_test.go @@ -25,6 +25,8 @@ import ( "net/http" "net/http/httptest" "net/url" + "os" + "path/filepath" "sync" "testing" @@ -43,6 +45,7 @@ import ( "github.com/stacklok/toolhive/pkg/vmcp/auth/converters" authfactory "github.com/stacklok/toolhive/pkg/vmcp/auth/factory" authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types" + vmcpconfig "github.com/stacklok/toolhive/pkg/vmcp/config" ) const ( @@ -127,6 +130,68 @@ func TestOBOIntegration_InlineTwoBackends(t *testing.T) { assert.Equal(t, "Bearer backend-token-b", backendCapB.authHeader()) } +// TestOBOIntegration_InlineConfigFileLoad drives an operator-rendered inline +// OBO backend through the vMCP startup path: the YAML loader, the config +// validator, the strategy's own Validate, then a real exchange. The operator +// writes only clientSecretEnv and mounts the Secret under that name, so the +// loaded strategy must keep clientSecretEnv and leave clientSecret empty. +func TestOBOIntegration_InlineConfigFileLoad(t *testing.T) { + t.Parallel() + + entra, entraCap := startMockEntra(t, "backend-token-file") + backend, backendCap := startMockBackend(t) + + const secretEnv = "TOOLHIVE_OBO_CLIENT_SECRET_ENTRA_API" + envReader := oboMapEnv{secretEnv: "file-secret"} + + configYAML := ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: ` + entra.URL + ` + clientId: ` + oboTestClientID + ` + clientSecretEnv: ` + secretEnv + ` + scopes: + - ` + oboTestScope + ` + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +` + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(configYAML), 0o600)) + + cfg, err := vmcpconfig.NewYAMLLoader(path, envReader).Load() + require.NoError(t, err) + require.NoError(t, vmcpconfig.NewValidator().Validate(cfg)) + + strategy := cfg.OutgoingAuth.Backends["entra-api"] + require.NotNil(t, strategy) + require.NotNil(t, strategy.OBO) + assert.Equal(t, secretEnv, strategy.OBO.ClientSecretEnv) + assert.Empty(t, strategy.OBO.ClientSecret, "the loader must not copy the env value into clientSecret") + + registry, err := authfactory.NewOutgoingAuthRegistry(t.Context(), envReader) + require.NoError(t, err) + exec, err := registry.GetStrategy(strategy.Type) + require.NoError(t, err) + require.NoError(t, exec.Validate(strategy)) + + exchangeThroughBackend(t, registry, strategy, backend, backendCap) + assertOBOExchange(t, entraCap, "file-secret") + assert.Equal(t, "Bearer backend-token-file", backendCap.authHeader()) +} + // exchangeThroughBackend resolves the OBO strategy from the registry, // authenticates a backend-bound request as a signed-in user, sends it to the // backend, and asserts the raw user token never reached the backend. From 50bff0db8dcf106cba18649b47c9068871bcffa7 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 12:20:42 -0800 Subject: [PATCH 06/12] Pin SDK awssts names and fix middleware docs Swag emits the awssts schemas under their short name once the OBO packages are in the import graph, which renamed the exported SDK types (AuthAWSSTSConfig became AWSSTSConfig). The normalizer now maps the short form to the path form, so the SDK matches main again regardless of which name swag picks. docs/middleware.md: fix the audit anchor broken by the renumbering and list the OBO middleware in the chain overview and execution order. Addresses stacklok/toolhive#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 --- cmd/help/openapi-normalize/main.go | 16 + cmd/help/openapi-normalize/main_test.go | 2 + docs/middleware.md | 11 +- sdk/go/client/oas_json_gen.go | 552 ++++++++++++------------ sdk/go/client/oas_schemas_gen.go | 390 ++++++++--------- sdk/go/openapi.json | 116 ++--- sdk/go/openapi.yaml | 126 +++--- 7 files changed, 617 insertions(+), 596 deletions(-) diff --git a/cmd/help/openapi-normalize/main.go b/cmd/help/openapi-normalize/main.go index d0e48acbc3..b1e22ce017 100644 --- a/cmd/help/openapi-normalize/main.go +++ b/cmd/help/openapi-normalize/main.go @@ -154,6 +154,12 @@ func publicSchemaName(name string) string { } name = strings.TrimPrefix(name, "github_com_stacklok_toolhive_pkg_") + for short, full := range shortSchemaPackages { + if rest, ok := strings.CutPrefix(name, short); ok { + name = full + rest + break + } + } parts := strings.FieldsFunc(name, func(r rune) bool { return r == '.' || r == '_' }) var builder strings.Builder for _, part := range parts { @@ -169,6 +175,16 @@ func canonicalSchemaWord(value string) string { return exportName(value) } +// shortSchemaPackages maps a package-qualified schema prefix that swag may +// emit in short form ("awssts.Config") to the path form it emits when two +// parsed packages share a name ("github_com_stacklok_toolhive_pkg_auth_awssts.Config", +// already trimmed to "auth_awssts."). Swag picks between the two depending on +// which packages are in the import graph, so without this the public SDK type +// names would change whenever an unrelated import is added. +var shortSchemaPackages = map[string]string{ + "awssts.": "auth_awssts.", +} + var canonicalSchemaWords = map[string]string{ "api": "API", "authserver": "Authentication", diff --git a/cmd/help/openapi-normalize/main_test.go b/cmd/help/openapi-normalize/main_test.go index 1d59efb188..b5b65f0bc3 100644 --- a/cmd/help/openapi-normalize/main_test.go +++ b/cmd/help/openapi-normalize/main_test.go @@ -134,6 +134,8 @@ func TestSchemaNormalizationGuards(t *testing.T) { for source, want := range map[string]string{ "authserver.RunConfig": "AuthenticationRunConfig", "github_com_stacklok_toolhive_pkg_auth_awssts.Config": "AuthAWSSTSConfig", + "awssts.Config": "AuthAWSSTSConfig", + "awssts.RoleMapping": "AuthAWSSTSRoleMapping", "github_com_stacklok_toolhive_pkg_authserver_server_tokenexchange.JWTBearerSubjectBinding": "AuthenticationServerTokenExchangeJWTBearerSubjectBinding", "tokenexchange.JWTBearerGrantPolicy": "TokenExchangeJWTBearerGrantPolicy", "types.ToolRateLimitConfig": "ToolRateLimitConfig", diff --git a/docs/middleware.md b/docs/middleware.md index 68f9525cc7..57c970f716 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -20,7 +20,8 @@ The middleware chain consists of the following components: 8. **Telemetry Middleware**: Instruments requests with OpenTelemetry (optional) 9. **Authorization Middleware**: Evaluates Cedar policies to authorize requests (optional) 10. **Header Forward Middleware**: Injects custom headers into requests to remote MCP servers (optional) -11. **Recovery Middleware**: Catches panics and returns HTTP 500 errors (always present) +11. **On-Behalf-Of (OBO) Middleware**: Exchanges the user's token for a backend-scoped Microsoft Entra token and replaces `Authorization` (optional, operator-configured) +12. **Recovery Middleware**: Catches panics and returns HTTP 500 errors (always present) ## Dynamic webhook middleware @@ -47,7 +48,7 @@ Multiple webhook definitions of the same type run in configuration order. When m Configuration files may be written in YAML or JSON. Duration values such as `timeout` accept strings like `5s`, and omitted timeouts default to `10s`. -When the caller authenticated with an RFC 8693 delegated token, the request payload sent to webhook receivers includes a `delegation` field on the principal object, with the same shape as the `delegation` field documented under [Audit Middleware](#9-audit-middleware) below. +When the caller authenticated with an RFC 8693 delegated token, the request payload sent to webhook receivers includes a `delegation` field on the principal object, with the same shape as the `delegation` field documented under [Audit Middleware](#10-audit-middleware) below. Example: @@ -1244,7 +1245,8 @@ The middleware chain execution order is critical and controlled by the order in 12. **Usage Metrics Middleware** (if enabled) - Tracks tool call counts 13. **Authorization Middleware** (if enabled) - Cedar policy evaluation 14. **Header Forward Middleware** (if configured for remote servers) - Injects custom headers -15. **Recovery Middleware** (always present) - Catches panics +15. **On-Behalf-Of (OBO) Middleware** (if an `obo` external auth config is referenced) - Exchanges the user's token at Entra and replaces `Authorization`; spliced in from `AdditionalMiddlewareConfigs` +16. **Recovery Middleware** (always present) - Catches panics **Important Ordering Rules**: - Audit wraps the whole chain (directly inside the body-size limit): every request that passes the size cap produces an audit event no matter which middleware rejects it. It does not need to run inside auth or the parser — those publish the identity and parsed MCP data back to it via `auth.IdentityHolder` and `mcp.ParsedRequestHolder`. @@ -1259,9 +1261,10 @@ The middleware chain execution order is critical and controlled by the order in - Mutating webhooks must come before Validating webhooks and before Authorization, so policy evaluation sees the patched request - Middleware that rewrites the request body must republish the parsed request via `mcp.RepublishParsedMCPRequest` and refresh `r.ContentLength` — `ParsingMiddleware` deliberately parses only once, so downstream consumers read the refreshed context while outer audit and telemetry wrappers read the refreshed `mcp.ParsedRequestHolder` after the inner chain returns - Header Forward executes close to the backend handler (innermost position) +- OBO comes after Header Forward and before Recovery, so it has the final say on the outbound `Authorization` header; it needs the identity the Authentication Middleware publishes, which is why the operator requires `oidcConfigRef` alongside an `obo` config - Recovery is always last in config, making it the innermost wrapper (the chain wraps in reverse config order, so the first entry is the outermost and runs first) - Body-size limit and Origin validation stay OUTSIDE audit: oversized bodies must be rejected before audit buffers request data, and origin validation is a pre-auth DNS-rebind guard. The transparent proxy's `Connection` header check (see [Client `Connection` header](#client-connection-header)) runs before all of them. Their rejections (400/413/403) are the only ones not audited. -- The list above (steps 1-15) describes the operator/proxyrunner path (`PopulateMiddlewareConfigs` in `pkg/runner/middleware.go`). The CLI flag path (`WithMiddlewareFromFlags` in `pkg/runner/config_builder.go`) has no rate limiting at all, and orders Usage Metrics before the webhooks rather than after (see the comment at `pkg/runner/config_builder.go:700`) — both paths still run Mutating before Validating webhooks and both before Authorization. +- The list above (steps 1-16) describes the operator/proxyrunner path (`PopulateMiddlewareConfigs` in `pkg/runner/middleware.go`). The CLI flag path (`WithMiddlewareFromFlags` in `pkg/runner/config_builder.go`) has no rate limiting at all, and orders Usage Metrics before the webhooks rather than after (see the comment at `pkg/runner/config_builder.go:700`) — both paths still run Mutating before Validating webhooks and both before Authorization. ### Client `Connection` header diff --git a/sdk/go/client/oas_json_gen.go b/sdk/go/client/oas_json_gen.go index 0b6667a1f2..376d67596a 100644 --- a/sdk/go/client/oas_json_gen.go +++ b/sdk/go/client/oas_json_gen.go @@ -13,14 +13,256 @@ import ( ) // Encode implements json.Marshaler. -func (s *AWSSTSConfig) Encode(e *jx.Encoder) { +func (s *AuditConfig) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } // encodeFields encodes fields. -func (s *AWSSTSConfig) encodeFields(e *jx.Encoder) { +func (s *AuditConfig) encodeFields(e *jx.Encoder) { + { + if s.Component.Set { + e.FieldStart("component") + s.Component.Encode(e) + } + } + { + if s.DetectApplicationErrors.Set { + e.FieldStart("detectApplicationErrors") + s.DetectApplicationErrors.Encode(e) + } + } + { + if s.Enabled.Set { + e.FieldStart("enabled") + s.Enabled.Encode(e) + } + } + { + if s.EventTypes != nil { + e.FieldStart("eventTypes") + e.ArrStart() + for _, elem := range s.EventTypes { + e.Str(elem) + } + e.ArrEnd() + } + } + { + if s.ExcludeEventTypes != nil { + e.FieldStart("excludeEventTypes") + e.ArrStart() + for _, elem := range s.ExcludeEventTypes { + e.Str(elem) + } + e.ArrEnd() + } + } + { + if s.IncludeRequestData.Set { + e.FieldStart("includeRequestData") + s.IncludeRequestData.Encode(e) + } + } + { + if s.IncludeResponseData.Set { + e.FieldStart("includeResponseData") + s.IncludeResponseData.Encode(e) + } + } + { + if s.LogFile.Set { + e.FieldStart("logFile") + s.LogFile.Encode(e) + } + } + { + if s.MaxDataSize.Set { + e.FieldStart("maxDataSize") + s.MaxDataSize.Encode(e) + } + } + { + if s.MaxDelegationDepth.Set { + e.FieldStart("maxDelegationDepth") + s.MaxDelegationDepth.Encode(e) + } + } +} + +var jsonFieldsNameOfAuditConfig = [10]string{ + 0: "component", + 1: "detectApplicationErrors", + 2: "enabled", + 3: "eventTypes", + 4: "excludeEventTypes", + 5: "includeRequestData", + 6: "includeResponseData", + 7: "logFile", + 8: "maxDataSize", + 9: "maxDelegationDepth", +} + +// Decode decodes AuditConfig from json. +func (s *AuditConfig) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AuditConfig to nil") + } + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "component": + if err := func() error { + s.Component.Reset() + if err := s.Component.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"component\"") + } + case "detectApplicationErrors": + if err := func() error { + s.DetectApplicationErrors.Reset() + if err := s.DetectApplicationErrors.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detectApplicationErrors\"") + } + case "enabled": + if err := func() error { + s.Enabled.Reset() + if err := s.Enabled.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"enabled\"") + } + case "eventTypes": + if err := func() error { + s.EventTypes = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.EventTypes = append(s.EventTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"eventTypes\"") + } + case "excludeEventTypes": + if err := func() error { + s.ExcludeEventTypes = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.ExcludeEventTypes = append(s.ExcludeEventTypes, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"excludeEventTypes\"") + } + case "includeRequestData": + if err := func() error { + s.IncludeRequestData.Reset() + if err := s.IncludeRequestData.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"includeRequestData\"") + } + case "includeResponseData": + if err := func() error { + s.IncludeResponseData.Reset() + if err := s.IncludeResponseData.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"includeResponseData\"") + } + case "logFile": + if err := func() error { + s.LogFile.Reset() + if err := s.LogFile.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"logFile\"") + } + case "maxDataSize": + if err := func() error { + s.MaxDataSize.Reset() + if err := s.MaxDataSize.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"maxDataSize\"") + } + case "maxDelegationDepth": + if err := func() error { + s.MaxDelegationDepth.Reset() + if err := s.MaxDelegationDepth.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"maxDelegationDepth\"") + } + default: + return d.Skip() + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AuditConfig") + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AuditConfig) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AuditConfig) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AuthAWSSTSConfig) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AuthAWSSTSConfig) encodeFields(e *jx.Encoder) { { if s.FallbackRoleArn.Set { e.FieldStart("fallback_role_arn") @@ -75,7 +317,7 @@ func (s *AWSSTSConfig) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAWSSTSConfig = [8]string{ +var jsonFieldsNameOfAuthAWSSTSConfig = [8]string{ 0: "fallback_role_arn", 1: "region", 2: "role_claim", @@ -86,10 +328,10 @@ var jsonFieldsNameOfAWSSTSConfig = [8]string{ 7: "subject_provider_name", } -// Decode decodes AWSSTSConfig from json. -func (s *AWSSTSConfig) Decode(d *jx.Decoder) error { +// Decode decodes AuthAWSSTSConfig from json. +func (s *AuthAWSSTSConfig) Decode(d *jx.Decoder) error { if s == nil { - return errors.New("invalid: unable to decode AWSSTSConfig to nil") + return errors.New("invalid: unable to decode AuthAWSSTSConfig to nil") } if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { @@ -126,9 +368,9 @@ func (s *AWSSTSConfig) Decode(d *jx.Decoder) error { } case "role_mappings": if err := func() error { - s.RoleMappings = make([]AWSSTSRoleMapping, 0) + s.RoleMappings = make([]AuthAWSSTSRoleMapping, 0) if err := d.Arr(func(d *jx.Decoder) error { - var elem AWSSTSRoleMapping + var elem AuthAWSSTSRoleMapping if err := elem.Decode(d); err != nil { return err } @@ -186,34 +428,34 @@ func (s *AWSSTSConfig) Decode(d *jx.Decoder) error { } return nil }); err != nil { - return errors.Wrap(err, "decode AWSSTSConfig") + return errors.Wrap(err, "decode AuthAWSSTSConfig") } return nil } // MarshalJSON implements stdjson.Marshaler. -func (s *AWSSTSConfig) MarshalJSON() ([]byte, error) { +func (s *AuthAWSSTSConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AWSSTSConfig) UnmarshalJSON(data []byte) error { +func (s *AuthAWSSTSConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } // Encode implements json.Marshaler. -func (s *AWSSTSRoleMapping) Encode(e *jx.Encoder) { +func (s *AuthAWSSTSRoleMapping) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } // encodeFields encodes fields. -func (s *AWSSTSRoleMapping) encodeFields(e *jx.Encoder) { +func (s *AuthAWSSTSRoleMapping) encodeFields(e *jx.Encoder) { { if s.Claim.Set { e.FieldStart("claim") @@ -240,17 +482,17 @@ func (s *AWSSTSRoleMapping) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAWSSTSRoleMapping = [4]string{ +var jsonFieldsNameOfAuthAWSSTSRoleMapping = [4]string{ 0: "claim", 1: "matcher", 2: "priority", 3: "role_arn", } -// Decode decodes AWSSTSRoleMapping from json. -func (s *AWSSTSRoleMapping) Decode(d *jx.Decoder) error { +// Decode decodes AuthAWSSTSRoleMapping from json. +func (s *AuthAWSSTSRoleMapping) Decode(d *jx.Decoder) error { if s == nil { - return errors.New("invalid: unable to decode AWSSTSRoleMapping to nil") + return errors.New("invalid: unable to decode AuthAWSSTSRoleMapping to nil") } if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { @@ -300,263 +542,21 @@ func (s *AWSSTSRoleMapping) Decode(d *jx.Decoder) error { } return nil }); err != nil { - return errors.Wrap(err, "decode AWSSTSRoleMapping") - } - - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s *AWSSTSRoleMapping) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AWSSTSRoleMapping) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - -// Encode implements json.Marshaler. -func (s *AuditConfig) Encode(e *jx.Encoder) { - e.ObjStart() - s.encodeFields(e) - e.ObjEnd() -} - -// encodeFields encodes fields. -func (s *AuditConfig) encodeFields(e *jx.Encoder) { - { - if s.Component.Set { - e.FieldStart("component") - s.Component.Encode(e) - } - } - { - if s.DetectApplicationErrors.Set { - e.FieldStart("detectApplicationErrors") - s.DetectApplicationErrors.Encode(e) - } - } - { - if s.Enabled.Set { - e.FieldStart("enabled") - s.Enabled.Encode(e) - } - } - { - if s.EventTypes != nil { - e.FieldStart("eventTypes") - e.ArrStart() - for _, elem := range s.EventTypes { - e.Str(elem) - } - e.ArrEnd() - } - } - { - if s.ExcludeEventTypes != nil { - e.FieldStart("excludeEventTypes") - e.ArrStart() - for _, elem := range s.ExcludeEventTypes { - e.Str(elem) - } - e.ArrEnd() - } - } - { - if s.IncludeRequestData.Set { - e.FieldStart("includeRequestData") - s.IncludeRequestData.Encode(e) - } - } - { - if s.IncludeResponseData.Set { - e.FieldStart("includeResponseData") - s.IncludeResponseData.Encode(e) - } - } - { - if s.LogFile.Set { - e.FieldStart("logFile") - s.LogFile.Encode(e) - } - } - { - if s.MaxDataSize.Set { - e.FieldStart("maxDataSize") - s.MaxDataSize.Encode(e) - } - } - { - if s.MaxDelegationDepth.Set { - e.FieldStart("maxDelegationDepth") - s.MaxDelegationDepth.Encode(e) - } - } -} - -var jsonFieldsNameOfAuditConfig = [10]string{ - 0: "component", - 1: "detectApplicationErrors", - 2: "enabled", - 3: "eventTypes", - 4: "excludeEventTypes", - 5: "includeRequestData", - 6: "includeResponseData", - 7: "logFile", - 8: "maxDataSize", - 9: "maxDelegationDepth", -} - -// Decode decodes AuditConfig from json. -func (s *AuditConfig) Decode(d *jx.Decoder) error { - if s == nil { - return errors.New("invalid: unable to decode AuditConfig to nil") - } - - if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { - switch string(k) { - case "component": - if err := func() error { - s.Component.Reset() - if err := s.Component.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"component\"") - } - case "detectApplicationErrors": - if err := func() error { - s.DetectApplicationErrors.Reset() - if err := s.DetectApplicationErrors.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"detectApplicationErrors\"") - } - case "enabled": - if err := func() error { - s.Enabled.Reset() - if err := s.Enabled.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"enabled\"") - } - case "eventTypes": - if err := func() error { - s.EventTypes = make([]string, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { - return err - } - s.EventTypes = append(s.EventTypes, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"eventTypes\"") - } - case "excludeEventTypes": - if err := func() error { - s.ExcludeEventTypes = make([]string, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem string - v, err := d.Str() - elem = string(v) - if err != nil { - return err - } - s.ExcludeEventTypes = append(s.ExcludeEventTypes, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"excludeEventTypes\"") - } - case "includeRequestData": - if err := func() error { - s.IncludeRequestData.Reset() - if err := s.IncludeRequestData.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"includeRequestData\"") - } - case "includeResponseData": - if err := func() error { - s.IncludeResponseData.Reset() - if err := s.IncludeResponseData.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"includeResponseData\"") - } - case "logFile": - if err := func() error { - s.LogFile.Reset() - if err := s.LogFile.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"logFile\"") - } - case "maxDataSize": - if err := func() error { - s.MaxDataSize.Reset() - if err := s.MaxDataSize.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"maxDataSize\"") - } - case "maxDelegationDepth": - if err := func() error { - s.MaxDelegationDepth.Reset() - if err := s.MaxDelegationDepth.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"maxDelegationDepth\"") - } - default: - return d.Skip() - } - return nil - }); err != nil { - return errors.Wrap(err, "decode AuditConfig") + return errors.Wrap(err, "decode AuthAWSSTSRoleMapping") } return nil } // MarshalJSON implements stdjson.Marshaler. -func (s *AuditConfig) MarshalJSON() ([]byte, error) { +func (s *AuthAWSSTSRoleMapping) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AuditConfig) UnmarshalJSON(data []byte) error { +func (s *AuthAWSSTSRoleMapping) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } @@ -17492,18 +17492,18 @@ func (s *OidcOptions) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes AWSSTSConfig as json. -func (o OptAWSSTSConfig) Encode(e *jx.Encoder) { +// Encode encodes AuditConfig as json. +func (o OptAuditConfig) Encode(e *jx.Encoder) { if !o.Set { return } o.Value.Encode(e) } -// Decode decodes AWSSTSConfig from json. -func (o *OptAWSSTSConfig) Decode(d *jx.Decoder) error { +// Decode decodes AuditConfig from json. +func (o *OptAuditConfig) Decode(d *jx.Decoder) error { if o == nil { - return errors.New("invalid: unable to decode OptAWSSTSConfig to nil") + return errors.New("invalid: unable to decode OptAuditConfig to nil") } o.Set = true if err := o.Value.Decode(d); err != nil { @@ -17513,30 +17513,30 @@ func (o *OptAWSSTSConfig) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s OptAWSSTSConfig) MarshalJSON() ([]byte, error) { +func (s OptAuditConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *OptAWSSTSConfig) UnmarshalJSON(data []byte) error { +func (s *OptAuditConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } -// Encode encodes AuditConfig as json. -func (o OptAuditConfig) Encode(e *jx.Encoder) { +// Encode encodes AuthAWSSTSConfig as json. +func (o OptAuthAWSSTSConfig) Encode(e *jx.Encoder) { if !o.Set { return } o.Value.Encode(e) } -// Decode decodes AuditConfig from json. -func (o *OptAuditConfig) Decode(d *jx.Decoder) error { +// Decode decodes AuthAWSSTSConfig from json. +func (o *OptAuthAWSSTSConfig) Decode(d *jx.Decoder) error { if o == nil { - return errors.New("invalid: unable to decode OptAuditConfig to nil") + return errors.New("invalid: unable to decode OptAuthAWSSTSConfig to nil") } o.Set = true if err := o.Value.Decode(d); err != nil { @@ -17546,14 +17546,14 @@ func (o *OptAuditConfig) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s OptAuditConfig) MarshalJSON() ([]byte, error) { +func (s OptAuthAWSSTSConfig) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *OptAuditConfig) UnmarshalJSON(data []byte) error { +func (s *OptAuthAWSSTSConfig) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index 9b5ef01089..a6bc35df43 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -10,171 +10,6 @@ import ( "github.com/go-faster/jx" ) -// AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services. -// Ref: #/components/schemas/AWSSTSConfig -type AWSSTSConfig struct { - // FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. - FallbackRoleArn OptString `json:"fallback_role_arn"` - // Region is the AWS region for STS and SigV4 signing. - Region OptString `json:"region"` - // RoleClaim is the JWT claim to use for role mapping (default: "groups"). - RoleClaim OptString `json:"role_claim"` - // RoleMappings maps JWT claim values to IAM roles with priority. - RoleMappings []AWSSTSRoleMapping `json:"role_mappings"` - // Service is the AWS service name for SigV4 signing (default: "aws-mcp"). - Service OptString `json:"service"` - // SessionDuration is the duration in seconds for assumed role credentials (default: 3600). - SessionDuration OptInt `json:"session_duration"` - // SessionNameClaim is the JWT claim to use for role session name (default: "sub"). - SessionNameClaim OptString `json:"session_name_claim"` - // SubjectProviderName identifies which upstream provider's access token to use - // for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer - // token from the incoming HTTP request is used. - SubjectProviderName OptString `json:"subject_provider_name"` -} - -// GetFallbackRoleArn returns the value of FallbackRoleArn. -func (s *AWSSTSConfig) GetFallbackRoleArn() OptString { - return s.FallbackRoleArn -} - -// GetRegion returns the value of Region. -func (s *AWSSTSConfig) GetRegion() OptString { - return s.Region -} - -// GetRoleClaim returns the value of RoleClaim. -func (s *AWSSTSConfig) GetRoleClaim() OptString { - return s.RoleClaim -} - -// GetRoleMappings returns the value of RoleMappings. -func (s *AWSSTSConfig) GetRoleMappings() []AWSSTSRoleMapping { - return s.RoleMappings -} - -// GetService returns the value of Service. -func (s *AWSSTSConfig) GetService() OptString { - return s.Service -} - -// GetSessionDuration returns the value of SessionDuration. -func (s *AWSSTSConfig) GetSessionDuration() OptInt { - return s.SessionDuration -} - -// GetSessionNameClaim returns the value of SessionNameClaim. -func (s *AWSSTSConfig) GetSessionNameClaim() OptString { - return s.SessionNameClaim -} - -// GetSubjectProviderName returns the value of SubjectProviderName. -func (s *AWSSTSConfig) GetSubjectProviderName() OptString { - return s.SubjectProviderName -} - -// SetFallbackRoleArn sets the value of FallbackRoleArn. -func (s *AWSSTSConfig) SetFallbackRoleArn(val OptString) { - s.FallbackRoleArn = val -} - -// SetRegion sets the value of Region. -func (s *AWSSTSConfig) SetRegion(val OptString) { - s.Region = val -} - -// SetRoleClaim sets the value of RoleClaim. -func (s *AWSSTSConfig) SetRoleClaim(val OptString) { - s.RoleClaim = val -} - -// SetRoleMappings sets the value of RoleMappings. -func (s *AWSSTSConfig) SetRoleMappings(val []AWSSTSRoleMapping) { - s.RoleMappings = val -} - -// SetService sets the value of Service. -func (s *AWSSTSConfig) SetService(val OptString) { - s.Service = val -} - -// SetSessionDuration sets the value of SessionDuration. -func (s *AWSSTSConfig) SetSessionDuration(val OptInt) { - s.SessionDuration = val -} - -// SetSessionNameClaim sets the value of SessionNameClaim. -func (s *AWSSTSConfig) SetSessionNameClaim(val OptString) { - s.SessionNameClaim = val -} - -// SetSubjectProviderName sets the value of SubjectProviderName. -func (s *AWSSTSConfig) SetSubjectProviderName(val OptString) { - s.SubjectProviderName = val -} - -// Ref: #/components/schemas/AWSSTSRoleMapping -type AWSSTSRoleMapping struct { - // Claim is the simple claim value to match (e.g., group name). - // Internally compiles to a CEL expression: "" in claims[""] - // Mutually exclusive with Matcher. - Claim OptString `json:"claim"` - // Matcher is a CEL expression for complex matching against JWT claims. - // The expression has access to a "claims" variable containing all JWT claims. - // Examples: - // - "admins" in claims["groups"] - // - claims["sub"] == "user123" && !("act" in claims) - // Mutually exclusive with Claim. - Matcher OptString `json:"matcher"` - // Priority determines selection order (lower number = higher priority). - // When multiple mappings match, the one with the lowest priority is selected. - // When nil (omitted), the mapping has the lowest possible priority, and - // configuration order acts as tie-breaker via stable sort. - Priority OptInt `json:"priority"` - // RoleArn is the IAM role ARN to assume when this mapping matches. - RoleArn OptString `json:"role_arn"` -} - -// GetClaim returns the value of Claim. -func (s *AWSSTSRoleMapping) GetClaim() OptString { - return s.Claim -} - -// GetMatcher returns the value of Matcher. -func (s *AWSSTSRoleMapping) GetMatcher() OptString { - return s.Matcher -} - -// GetPriority returns the value of Priority. -func (s *AWSSTSRoleMapping) GetPriority() OptInt { - return s.Priority -} - -// GetRoleArn returns the value of RoleArn. -func (s *AWSSTSRoleMapping) GetRoleArn() OptString { - return s.RoleArn -} - -// SetClaim sets the value of Claim. -func (s *AWSSTSRoleMapping) SetClaim(val OptString) { - s.Claim = val -} - -// SetMatcher sets the value of Matcher. -func (s *AWSSTSRoleMapping) SetMatcher(val OptString) { - s.Matcher = val -} - -// SetPriority sets the value of Priority. -func (s *AWSSTSRoleMapping) SetPriority(val OptInt) { - s.Priority = val -} - -// SetRoleArn sets the value of RoleArn. -func (s *AWSSTSRoleMapping) SetRoleArn(val OptString) { - s.RoleArn = val -} - type AddRegistryNotImplemented struct { Data io.Reader } @@ -340,6 +175,171 @@ func (s *AuditConfig) SetMaxDelegationDepth(val OptInt) { s.MaxDelegationDepth = val } +// AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services. +// Ref: #/components/schemas/AuthAWSSTSConfig +type AuthAWSSTSConfig struct { + // FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. + FallbackRoleArn OptString `json:"fallback_role_arn"` + // Region is the AWS region for STS and SigV4 signing. + Region OptString `json:"region"` + // RoleClaim is the JWT claim to use for role mapping (default: "groups"). + RoleClaim OptString `json:"role_claim"` + // RoleMappings maps JWT claim values to IAM roles with priority. + RoleMappings []AuthAWSSTSRoleMapping `json:"role_mappings"` + // Service is the AWS service name for SigV4 signing (default: "aws-mcp"). + Service OptString `json:"service"` + // SessionDuration is the duration in seconds for assumed role credentials (default: 3600). + SessionDuration OptInt `json:"session_duration"` + // SessionNameClaim is the JWT claim to use for role session name (default: "sub"). + SessionNameClaim OptString `json:"session_name_claim"` + // SubjectProviderName identifies which upstream provider's access token to use + // for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer + // token from the incoming HTTP request is used. + SubjectProviderName OptString `json:"subject_provider_name"` +} + +// GetFallbackRoleArn returns the value of FallbackRoleArn. +func (s *AuthAWSSTSConfig) GetFallbackRoleArn() OptString { + return s.FallbackRoleArn +} + +// GetRegion returns the value of Region. +func (s *AuthAWSSTSConfig) GetRegion() OptString { + return s.Region +} + +// GetRoleClaim returns the value of RoleClaim. +func (s *AuthAWSSTSConfig) GetRoleClaim() OptString { + return s.RoleClaim +} + +// GetRoleMappings returns the value of RoleMappings. +func (s *AuthAWSSTSConfig) GetRoleMappings() []AuthAWSSTSRoleMapping { + return s.RoleMappings +} + +// GetService returns the value of Service. +func (s *AuthAWSSTSConfig) GetService() OptString { + return s.Service +} + +// GetSessionDuration returns the value of SessionDuration. +func (s *AuthAWSSTSConfig) GetSessionDuration() OptInt { + return s.SessionDuration +} + +// GetSessionNameClaim returns the value of SessionNameClaim. +func (s *AuthAWSSTSConfig) GetSessionNameClaim() OptString { + return s.SessionNameClaim +} + +// GetSubjectProviderName returns the value of SubjectProviderName. +func (s *AuthAWSSTSConfig) GetSubjectProviderName() OptString { + return s.SubjectProviderName +} + +// SetFallbackRoleArn sets the value of FallbackRoleArn. +func (s *AuthAWSSTSConfig) SetFallbackRoleArn(val OptString) { + s.FallbackRoleArn = val +} + +// SetRegion sets the value of Region. +func (s *AuthAWSSTSConfig) SetRegion(val OptString) { + s.Region = val +} + +// SetRoleClaim sets the value of RoleClaim. +func (s *AuthAWSSTSConfig) SetRoleClaim(val OptString) { + s.RoleClaim = val +} + +// SetRoleMappings sets the value of RoleMappings. +func (s *AuthAWSSTSConfig) SetRoleMappings(val []AuthAWSSTSRoleMapping) { + s.RoleMappings = val +} + +// SetService sets the value of Service. +func (s *AuthAWSSTSConfig) SetService(val OptString) { + s.Service = val +} + +// SetSessionDuration sets the value of SessionDuration. +func (s *AuthAWSSTSConfig) SetSessionDuration(val OptInt) { + s.SessionDuration = val +} + +// SetSessionNameClaim sets the value of SessionNameClaim. +func (s *AuthAWSSTSConfig) SetSessionNameClaim(val OptString) { + s.SessionNameClaim = val +} + +// SetSubjectProviderName sets the value of SubjectProviderName. +func (s *AuthAWSSTSConfig) SetSubjectProviderName(val OptString) { + s.SubjectProviderName = val +} + +// Ref: #/components/schemas/AuthAWSSTSRoleMapping +type AuthAWSSTSRoleMapping struct { + // Claim is the simple claim value to match (e.g., group name). + // Internally compiles to a CEL expression: "" in claims[""] + // Mutually exclusive with Matcher. + Claim OptString `json:"claim"` + // Matcher is a CEL expression for complex matching against JWT claims. + // The expression has access to a "claims" variable containing all JWT claims. + // Examples: + // - "admins" in claims["groups"] + // - claims["sub"] == "user123" && !("act" in claims) + // Mutually exclusive with Claim. + Matcher OptString `json:"matcher"` + // Priority determines selection order (lower number = higher priority). + // When multiple mappings match, the one with the lowest priority is selected. + // When nil (omitted), the mapping has the lowest possible priority, and + // configuration order acts as tie-breaker via stable sort. + Priority OptInt `json:"priority"` + // RoleArn is the IAM role ARN to assume when this mapping matches. + RoleArn OptString `json:"role_arn"` +} + +// GetClaim returns the value of Claim. +func (s *AuthAWSSTSRoleMapping) GetClaim() OptString { + return s.Claim +} + +// GetMatcher returns the value of Matcher. +func (s *AuthAWSSTSRoleMapping) GetMatcher() OptString { + return s.Matcher +} + +// GetPriority returns the value of Priority. +func (s *AuthAWSSTSRoleMapping) GetPriority() OptInt { + return s.Priority +} + +// GetRoleArn returns the value of RoleArn. +func (s *AuthAWSSTSRoleMapping) GetRoleArn() OptString { + return s.RoleArn +} + +// SetClaim sets the value of Claim. +func (s *AuthAWSSTSRoleMapping) SetClaim(val OptString) { + s.Claim = val +} + +// SetMatcher sets the value of Matcher. +func (s *AuthAWSSTSRoleMapping) SetMatcher(val OptString) { + s.Matcher = val +} + +// SetPriority sets the value of Priority. +func (s *AuthAWSSTSRoleMapping) SetPriority(val OptInt) { + s.Priority = val +} + +// SetRoleArn sets the value of RoleArn. +func (s *AuthAWSSTSRoleMapping) SetRoleArn(val OptString) { + s.RoleArn = val +} + // DEPRECATED: Middleware configuration. // OIDCConfig contains OIDC configuration. // Ref: #/components/schemas/AuthTokenValidatorConfig @@ -7014,38 +7014,38 @@ func (s *OidcOptions) SetScopes(val []string) { s.Scopes = val } -// NewOptAWSSTSConfig returns new OptAWSSTSConfig with value set to v. -func NewOptAWSSTSConfig(v AWSSTSConfig) OptAWSSTSConfig { - return OptAWSSTSConfig{ +// NewOptAuditConfig returns new OptAuditConfig with value set to v. +func NewOptAuditConfig(v AuditConfig) OptAuditConfig { + return OptAuditConfig{ Value: v, Set: true, } } -// OptAWSSTSConfig is optional AWSSTSConfig. -type OptAWSSTSConfig struct { - Value AWSSTSConfig +// OptAuditConfig is optional AuditConfig. +type OptAuditConfig struct { + Value AuditConfig Set bool } -// IsSet returns true if OptAWSSTSConfig was set. -func (o OptAWSSTSConfig) IsSet() bool { return o.Set } +// IsSet returns true if OptAuditConfig was set. +func (o OptAuditConfig) IsSet() bool { return o.Set } // Reset unsets value. -func (o *OptAWSSTSConfig) Reset() { - var v AWSSTSConfig +func (o *OptAuditConfig) Reset() { + var v AuditConfig o.Value = v o.Set = false } // SetTo sets value to v. -func (o *OptAWSSTSConfig) SetTo(v AWSSTSConfig) { +func (o *OptAuditConfig) SetTo(v AuditConfig) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. -func (o OptAWSSTSConfig) Get() (v AWSSTSConfig, ok bool) { +func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { if !o.Set { return v, false } @@ -7053,45 +7053,45 @@ func (o OptAWSSTSConfig) Get() (v AWSSTSConfig, ok bool) { } // Or returns value if set, or given parameter if does not. -func (o OptAWSSTSConfig) Or(d AWSSTSConfig) AWSSTSConfig { +func (o OptAuditConfig) Or(d AuditConfig) AuditConfig { if v, ok := o.Get(); ok { return v } return d } -// NewOptAuditConfig returns new OptAuditConfig with value set to v. -func NewOptAuditConfig(v AuditConfig) OptAuditConfig { - return OptAuditConfig{ +// NewOptAuthAWSSTSConfig returns new OptAuthAWSSTSConfig with value set to v. +func NewOptAuthAWSSTSConfig(v AuthAWSSTSConfig) OptAuthAWSSTSConfig { + return OptAuthAWSSTSConfig{ Value: v, Set: true, } } -// OptAuditConfig is optional AuditConfig. -type OptAuditConfig struct { - Value AuditConfig +// OptAuthAWSSTSConfig is optional AuthAWSSTSConfig. +type OptAuthAWSSTSConfig struct { + Value AuthAWSSTSConfig Set bool } -// IsSet returns true if OptAuditConfig was set. -func (o OptAuditConfig) IsSet() bool { return o.Set } +// IsSet returns true if OptAuthAWSSTSConfig was set. +func (o OptAuthAWSSTSConfig) IsSet() bool { return o.Set } // Reset unsets value. -func (o *OptAuditConfig) Reset() { - var v AuditConfig +func (o *OptAuthAWSSTSConfig) Reset() { + var v AuthAWSSTSConfig o.Value = v o.Set = false } // SetTo sets value to v. -func (o *OptAuditConfig) SetTo(v AuditConfig) { +func (o *OptAuthAWSSTSConfig) SetTo(v AuthAWSSTSConfig) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. -func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { +func (o OptAuthAWSSTSConfig) Get() (v AuthAWSSTSConfig, ok bool) { if !o.Set { return v, false } @@ -7099,7 +7099,7 @@ func (o OptAuditConfig) Get() (v AuditConfig, ok bool) { } // Or returns value if set, or given parameter if does not. -func (o OptAuditConfig) Or(d AuditConfig) AuditConfig { +func (o OptAuthAWSSTSConfig) Or(d AuthAWSSTSConfig) AuthAWSSTSConfig { if v, ok := o.Get(); ok { return v } @@ -18278,8 +18278,8 @@ type RunnerRunConfig struct { AuthzConfig OptAuthorizationConfig `json:"authz_config"` // DEPRECATED: Middleware configuration. // AuthzConfigPath is the path to the authorization configuration file. - AuthzConfigPath OptString `json:"authz_config_path"` - AWSStsConfig OptAWSSTSConfig `json:"aws_sts_config"` + AuthzConfigPath OptString `json:"authz_config_path"` + AWSStsConfig OptAuthAWSSTSConfig `json:"aws_sts_config"` // BaseName is the base name used for the container (without prefixes). BaseName OptString `json:"base_name"` // CmdArgs are the arguments to pass to the container. @@ -18457,7 +18457,7 @@ func (s *RunnerRunConfig) GetAuthzConfigPath() OptString { } // GetAWSStsConfig returns the value of AWSStsConfig. -func (s *RunnerRunConfig) GetAWSStsConfig() OptAWSSTSConfig { +func (s *RunnerRunConfig) GetAWSStsConfig() OptAuthAWSSTSConfig { return s.AWSStsConfig } @@ -18772,7 +18772,7 @@ func (s *RunnerRunConfig) SetAuthzConfigPath(val OptString) { } // SetAWSStsConfig sets the value of AWSStsConfig. -func (s *RunnerRunConfig) SetAWSStsConfig(val OptAWSSTSConfig) { +func (s *RunnerRunConfig) SetAWSStsConfig(val OptAuthAWSSTSConfig) { s.AWSStsConfig = val } diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 6286a5a7b3..67d9178d18 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -1,7 +1,61 @@ { "components": { "schemas": { - "AWSSTSConfig": { + "AuditConfig": { + "description": "DEPRECATED: Middleware configuration.\nAuditConfig contains the audit logging configuration", + "properties": { + "component": { + "description": "Component is the component name to use in audit events.\n+optional", + "type": "string" + }, + "detectApplicationErrors": { + "description": "DetectApplicationErrors controls whether the audit middleware inspects\nJSON-RPC response bodies for application-level errors when the HTTP\nstatus code indicates success (2xx). When enabled, a small prefix of\nthe response body is buffered to detect JSON-RPC error fields,\nindependent of the IncludeResponseData setting.\n+kubebuilder:default=true\n+optional", + "type": "boolean" + }, + "enabled": { + "description": "Enabled controls whether audit logging is enabled.\nWhen true, enables audit logging with the configured options.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "eventTypes": { + "description": "EventTypes specifies which event types to audit. If empty, all events are audited.\n+optional", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "excludeEventTypes": { + "description": "ExcludeEventTypes specifies which event types to exclude from auditing.\nThis takes precedence over EventTypes.\n+optional", + "items": { + "type": "string" + }, + "type": "array", + "uniqueItems": false + }, + "includeRequestData": { + "description": "IncludeRequestData determines whether to include request data in audit logs.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "includeResponseData": { + "description": "IncludeResponseData determines whether to include response data in audit logs.\n+kubebuilder:default=false\n+optional", + "type": "boolean" + }, + "logFile": { + "description": "LogFile specifies the file path for audit logs. If empty, logs to stdout.\n+optional", + "type": "string" + }, + "maxDataSize": { + "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", + "type": "integer" + }, + "maxDelegationDepth": { + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", + "type": "integer" + } + }, + "type": "object" + }, + "AuthAWSSTSConfig": { "description": "AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services", "properties": { "fallback_role_arn": { @@ -19,7 +73,7 @@ "role_mappings": { "description": "RoleMappings maps JWT claim values to IAM roles with priority.", "items": { - "$ref": "#/components/schemas/AWSSTSRoleMapping" + "$ref": "#/components/schemas/AuthAWSSTSRoleMapping" }, "type": "array", "uniqueItems": false @@ -43,7 +97,7 @@ }, "type": "object" }, - "AWSSTSRoleMapping": { + "AuthAWSSTSRoleMapping": { "properties": { "claim": { "description": "Claim is the simple claim value to match (e.g., group name).\nInternally compiles to a CEL expression: \"\u003cclaim_value\u003e\" in claims[\"\u003crole_claim\u003e\"]\nMutually exclusive with Matcher.", @@ -64,60 +118,6 @@ }, "type": "object" }, - "AuditConfig": { - "description": "DEPRECATED: Middleware configuration.\nAuditConfig contains the audit logging configuration", - "properties": { - "component": { - "description": "Component is the component name to use in audit events.\n+optional", - "type": "string" - }, - "detectApplicationErrors": { - "description": "DetectApplicationErrors controls whether the audit middleware inspects\nJSON-RPC response bodies for application-level errors when the HTTP\nstatus code indicates success (2xx). When enabled, a small prefix of\nthe response body is buffered to detect JSON-RPC error fields,\nindependent of the IncludeResponseData setting.\n+kubebuilder:default=true\n+optional", - "type": "boolean" - }, - "enabled": { - "description": "Enabled controls whether audit logging is enabled.\nWhen true, enables audit logging with the configured options.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "eventTypes": { - "description": "EventTypes specifies which event types to audit. If empty, all events are audited.\n+optional", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, - "excludeEventTypes": { - "description": "ExcludeEventTypes specifies which event types to exclude from auditing.\nThis takes precedence over EventTypes.\n+optional", - "items": { - "type": "string" - }, - "type": "array", - "uniqueItems": false - }, - "includeRequestData": { - "description": "IncludeRequestData determines whether to include request data in audit logs.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "includeResponseData": { - "description": "IncludeResponseData determines whether to include response data in audit logs.\n+kubebuilder:default=false\n+optional", - "type": "boolean" - }, - "logFile": { - "description": "LogFile specifies the file path for audit logs. If empty, logs to stdout.\n+optional", - "type": "string" - }, - "maxDataSize": { - "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", - "type": "integer" - }, - "maxDelegationDepth": { - "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", - "type": "integer" - } - }, - "type": "object" - }, "AuthTokenValidatorConfig": { "description": "DEPRECATED: Middleware configuration.\nOIDCConfig contains OIDC configuration", "properties": { @@ -4040,7 +4040,7 @@ "type": "string" }, "aws_sts_config": { - "$ref": "#/components/schemas/AWSSTSConfig" + "$ref": "#/components/schemas/AuthAWSSTSConfig" }, "base_name": { "description": "BaseName is the base name used for the container (without prefixes)", diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index fb980677a3..8075c91e15 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -1,67 +1,5 @@ components: schemas: - AWSSTSConfig: - description: AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services - properties: - fallback_role_arn: - description: FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. - type: string - region: - description: Region is the AWS region for STS and SigV4 signing. - type: string - role_claim: - description: 'RoleClaim is the JWT claim to use for role mapping (default: "groups").' - type: string - role_mappings: - description: RoleMappings maps JWT claim values to IAM roles with priority. - items: - $ref: '#/components/schemas/AWSSTSRoleMapping' - type: array - uniqueItems: false - service: - description: 'Service is the AWS service name for SigV4 signing (default: "aws-mcp").' - type: string - session_duration: - description: 'SessionDuration is the duration in seconds for assumed role credentials (default: 3600).' - type: integer - session_name_claim: - description: 'SessionNameClaim is the JWT claim to use for role session name (default: "sub").' - type: string - subject_provider_name: - description: |- - SubjectProviderName identifies which upstream provider's access token to use - for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer - token from the incoming HTTP request is used. - type: string - type: object - AWSSTSRoleMapping: - properties: - claim: - description: |- - Claim is the simple claim value to match (e.g., group name). - Internally compiles to a CEL expression: "" in claims[""] - Mutually exclusive with Matcher. - type: string - matcher: - description: |- - Matcher is a CEL expression for complex matching against JWT claims. - The expression has access to a "claims" variable containing all JWT claims. - Examples: - - "admins" in claims["groups"] - - claims["sub"] == "user123" && !("act" in claims) - Mutually exclusive with Claim. - type: string - priority: - description: |- - Priority determines selection order (lower number = higher priority). - When multiple mappings match, the one with the lowest priority is selected. - When nil (omitted), the mapping has the lowest possible priority, and - configuration order acts as tie-breaker via stable sort. - type: integer - role_arn: - description: RoleArn is the IAM role ARN to assume when this mapping matches. - type: string - type: object AuditConfig: description: |- DEPRECATED: Middleware configuration. @@ -139,6 +77,68 @@ components: +optional type: integer type: object + AuthAWSSTSConfig: + description: AWSStsConfig contains AWS STS token exchange configuration for accessing AWS services + properties: + fallback_role_arn: + description: FallbackRoleArn is the IAM role ARN to assume when no role mapping matches. + type: string + region: + description: Region is the AWS region for STS and SigV4 signing. + type: string + role_claim: + description: 'RoleClaim is the JWT claim to use for role mapping (default: "groups").' + type: string + role_mappings: + description: RoleMappings maps JWT claim values to IAM roles with priority. + items: + $ref: '#/components/schemas/AuthAWSSTSRoleMapping' + type: array + uniqueItems: false + service: + description: 'Service is the AWS service name for SigV4 signing (default: "aws-mcp").' + type: string + session_duration: + description: 'SessionDuration is the duration in seconds for assumed role credentials (default: 3600).' + type: integer + session_name_claim: + description: 'SessionNameClaim is the JWT claim to use for role session name (default: "sub").' + type: string + subject_provider_name: + description: |- + SubjectProviderName identifies which upstream provider's access token to use + for STS AssumeRoleWithWebIdentity. Used by vMCP only. When empty, the bearer + token from the incoming HTTP request is used. + type: string + type: object + AuthAWSSTSRoleMapping: + properties: + claim: + description: |- + Claim is the simple claim value to match (e.g., group name). + Internally compiles to a CEL expression: "" in claims[""] + Mutually exclusive with Matcher. + type: string + matcher: + description: |- + Matcher is a CEL expression for complex matching against JWT claims. + The expression has access to a "claims" variable containing all JWT claims. + Examples: + - "admins" in claims["groups"] + - claims["sub"] == "user123" && !("act" in claims) + Mutually exclusive with Claim. + type: string + priority: + description: |- + Priority determines selection order (lower number = higher priority). + When multiple mappings match, the one with the lowest priority is selected. + When nil (omitted), the mapping has the lowest possible priority, and + configuration order acts as tie-breaker via stable sort. + type: integer + role_arn: + description: RoleArn is the IAM role ARN to assume when this mapping matches. + type: string + type: object AuthTokenValidatorConfig: description: |- DEPRECATED: Middleware configuration. @@ -3884,7 +3884,7 @@ components: AuthzConfigPath is the path to the authorization configuration file type: string aws_sts_config: - $ref: '#/components/schemas/AWSSTSConfig' + $ref: '#/components/schemas/AuthAWSSTSConfig' base_name: description: BaseName is the base name used for the container (without prefixes) type: string From eae5487e5ecb15e42b449c8ffc484e65cab154d2 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 12:33:27 -0800 Subject: [PATCH 07/12] Address operator review findings for OBO Review findings on the OBO operator port (PR #7201): - #10: a mirrored Valid=False/InvalidConfig from a malformed obo source was mistaken for a locally-owned failure and stuck on MCPServer and MCPRemoteProxy after the source healed to the same spec. Mirrored condition messages now carry a fixed prefix, and the mirror clear and both same-hash guards skip conditions that carry it. - #9, #42: Reconcile-level tests for the terminal obo-without-OIDC path on MCPServer and MCPRemoteProxy; MCPRemoteProxy now retries when that rejection cannot be persisted instead of dropping it. - #40: split the MCPServer terminal branch into its own early return. - #41: table-test logOBOSecretEnvVarError redaction, and add an MCPRemoteProxy OBO env var error-path test. - #43, #44, #25, #26: fix stale or inconsistent comments, including the deprecation notes and the vMCP exception for registered handlers. - #37: rename OBOVMCPSecretEnvVar to OBOVMCPSecretEnvVars. - #36, #38: reject cacheSkew above MaxInt32 seconds as the vMCP converter does, and cover blank fields, truncation and Reason. - #39: append a hash of the raw config name to the vMCP OBO env var so names that sanitize alike no longer collide. - #45: two-OBO-backend cases for the vMCP secret discovery paths. Co-Authored-By: Claude Opus 5.5 --- .../v1beta1/mcpexternalauthconfig_types.go | 5 +- .../controllers/external_auth_mirror.go | 69 ++++-- .../controllers/external_auth_mirror_test.go | 217 ++++++++++++++++++ .../mcpexternalauthconfig_controller.go | 35 +-- .../mcpexternalauthconfig_controller_test.go | 41 +++- .../controllers/mcpremoteproxy_controller.go | 38 ++- .../mcpremoteproxy_controller_test.go | 98 +++++++- .../controllers/mcpremoteproxy_deployment.go | 7 +- .../mcpremoteproxy_deployment_test.go | 44 ++++ .../controllers/mcpserver_controller.go | 44 ++-- .../mcpserver_externalauth_test.go | 139 ++++++++++- .../virtualmcpserver_deployment.go | 5 +- .../virtualmcpserver_externalauth_test.go | 116 +++++++++- .../pkg/controllerutil/externalauth.go | 13 +- .../pkg/controllerutil/externalauth_test.go | 35 +++ cmd/thv-operator/pkg/controllerutil/obo.go | 43 +++- .../pkg/controllerutil/obo_test.go | 81 ++++++- .../mcp-external-auth/obo_reconcile_test.go | 4 +- docs/arch/09-operator-architecture.md | 2 +- docs/arch/10-virtual-mcp-architecture.md | 3 +- 20 files changed, 945 insertions(+), 94 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index c75e12043a..0ec04a1c71 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -2592,8 +2592,9 @@ const ( // ConditionReasonEnterpriseRequired was set on obo-typed configs before OBO // shipped in ToolHive itself. The operator no longer sets it. // - // Deprecated: OBO is built in. Kept for one release so out-of-tree code - // that references it keeps compiling; it will be removed. + // Deprecated: OBO is built in. Kept only so out-of-tree code that + // references it keeps compiling; it will be removed once out-of-tree users + // are gone, see stacklok/toolhive#7200. ConditionReasonEnterpriseRequired = "EnterpriseRequired" // ConditionReasonInvalidConfig: an obo-typed MCPExternalAuthConfig is diff --git a/cmd/thv-operator/controllers/external_auth_mirror.go b/cmd/thv-operator/controllers/external_auth_mirror.go index c3092c59d9..3eba787674 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror.go +++ b/cmd/thv-operator/controllers/external_auth_mirror.go @@ -6,6 +6,7 @@ package controllers import ( stderrors "errors" "fmt" + "strings" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -15,7 +16,8 @@ import ( // Status Condition Parity machinery for #5347. The probe reads a referenced // MCPExternalAuthConfig's Valid condition; the per-consumer mirror functions -// transcribe its reason+message onto the consumer CR's parallel condition. +// transcribe its reason and message (the latter behind mirroredMessagePrefix) +// onto the consumer CR's parallel condition. // Without this, an invalid MCPExternalAuthConfig (for example a malformed obo // config) surfaces its reason only on the referenced resource and the consumer // status reports only the generic dispatch failure. @@ -26,6 +28,14 @@ import ( // Reason verbatim without trapping the consumer in a noisy reconcile loop. const fallbackInvalidReason = "InvalidExternalAuthConfig" +// mirroredMessagePrefix starts the Message of every condition the mirror +// writes, marking it as mirrored rather than locally owned. A source can +// surface the same Reason a consumer uses for its own validation failures (a +// malformed obo config is Valid=False / InvalidConfig), so the Reason alone +// cannot tell the two owners apart. No local writer of InvalidConfig or +// InvalidCABundle starts its message with this prefix. +const mirroredMessagePrefix = "Referenced MCPExternalAuthConfig " + // mirroredInvalidExternalAuthConfigError signals that a referenced // MCPExternalAuthConfig had Status.Conditions[Valid]=False. Carries the // source's reason+message so callers can surface them on the consumer's @@ -73,25 +83,50 @@ func mirroredReasonFromError(err error) string { // ownedByLocalValidation reports whether conditions' entry for conditionType // (if any) was set by this operator's own validation rather than mirrored from -// the referenced MCPExternalAuthConfig. Two distinct owners qualify, each with -// a fixed Reason that an exact match identifies reliably regardless of the -// mirror's own (source-derived, unbounded) Reason values: +// the referenced MCPExternalAuthConfig. See isLocalValidationFailure. +func ownedByLocalValidation(conditions []metav1.Condition, conditionType string) bool { + return isLocalValidationFailure(meta.FindStatusCondition(conditions, conditionType)) +} + +// isLocalValidationFailure reports whether cond is a False condition written by +// this operator's own validation of the consumer. Two kinds of owner qualify, +// each with a fixed Reason: // -// - handleInvalidEmbeddedAuthServerConfig, ConditionReasonInvalidConfig, set +// - ConditionReasonInvalidConfig: handleInvalidEmbeddedAuthServerConfig, set // when the assembled RunConfig fails to build (e.g. delegate clients -// without an OIDC config). -// - the CA bundle check, ConditionReasonInvalidCABundle, set when a referenced -// bundle ConfigMap is missing its key or holds non-PEM content. +// without an OIDC config), and the obo incoming-auth check +// (ctrlutil.ValidateOBOIncomingAuth). +// - ConditionReasonInvalidCABundle: the CA bundle check, set when a +// referenced bundle ConfigMap is missing its key or holds non-PEM content. // -// Both re-derive the same condition a few lines after the mirror runs, so -// clearing it here would force a fresh LastTransitionTime on every reconcile. -func ownedByLocalValidation(conditions []metav1.Condition, conditionType string) bool { - existing := meta.FindStatusCondition(conditions, conditionType) - if existing == nil { +// These re-derive the same condition after the mirror runs, so clearing it in +// the mirror would force a fresh LastTransitionTime on every reconcile. +// +// A source can surface the same Reason (a malformed obo config is Valid=False / +// InvalidConfig), so a condition whose Message starts with +// mirroredMessagePrefix is the mirror's whatever its Reason. Treating it as +// local would hold it after the source heals back to an unchanged ConfigHash: +// the mirror would not clear it and the same-hash guard in the +// set*ExternalAuthConfigValidCondition writers would not overwrite it. +func isLocalValidationFailure(cond *metav1.Condition) bool { + if cond == nil || cond.Status != metav1.ConditionFalse { return false } - return existing.Reason == mcpv1beta1.ConditionReasonInvalidConfig || - existing.Reason == mcpv1beta1.ConditionReasonInvalidCABundle + if strings.HasPrefix(cond.Message, mirroredMessagePrefix) { + return false + } + return cond.Reason == mcpv1beta1.ConditionReasonInvalidConfig || + cond.Reason == mcpv1beta1.ConditionReasonInvalidCABundle +} + +// mirroredConditionMessage builds the consumer condition Message for the +// source sourceName whose Valid=False condition carries sourceMessage. Its +// mirroredMessagePrefix is what isLocalValidationFailure keys on. +func mirroredConditionMessage(sourceName, sourceMessage string) string { + if sourceMessage == "" { + return fmt.Sprintf("%s'%s' is invalid", mirroredMessagePrefix, sourceName) + } + return fmt.Sprintf("%s'%s' is invalid: %s", mirroredMessagePrefix, sourceName, sourceMessage) } // mirrorInvalidOnMCPServer mirrors the source's Valid=False condition onto the @@ -121,7 +156,7 @@ func mirrorInvalidOnMCPServer( Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, Status: metav1.ConditionFalse, Reason: mirrored.Reason, - Message: mirrored.Message, + Message: mirroredConditionMessage(externalAuthConfig.Name, mirrored.Message), ObservedGeneration: m.Generation, }) return true, fmt.Errorf("MCPExternalAuthConfig %s/%s: %w", m.Namespace, externalAuthConfig.Name, mirrored) @@ -155,7 +190,7 @@ func mirrorInvalidOnRemoteProxy( Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated, Status: metav1.ConditionFalse, Reason: mirrored.Reason, - Message: mirrored.Message, + Message: mirroredConditionMessage(externalAuthConfig.Name, mirrored.Message), ObservedGeneration: proxy.Generation, }) return true, fmt.Errorf("MCPExternalAuthConfig %s/%s: %w", proxy.Namespace, externalAuthConfig.Name, mirrored) diff --git a/cmd/thv-operator/controllers/external_auth_mirror_test.go b/cmd/thv-operator/controllers/external_auth_mirror_test.go index 067871be2e..a5b3c63d97 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror_test.go +++ b/cmd/thv-operator/controllers/external_auth_mirror_test.go @@ -3,6 +3,24 @@ package controllers +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" + "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" + "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" + "github.com/stacklok/toolhive/pkg/container/kubernetes" +) + // Arbitrary source Valid=False reason and message used by the Status Condition // Parity mirror tests. The mirror copies whatever reason the referenced // MCPExternalAuthConfig carries, so the tests use a value no controller sets @@ -11,3 +29,202 @@ const ( testSourceInvalidReason = "SourceRejected" testSourceInvalidMessage = "the referenced MCPExternalAuthConfig was rejected" ) + +// TestIsLocalValidationFailure pins which ExternalAuthConfigValidated +// conditions the mirror and the same-hash guards treat as locally owned. +func TestIsLocalValidationFailure(t *testing.T) { + t.Parallel() + + falseCond := func(reason, message string) *metav1.Condition { + return &metav1.Condition{Status: metav1.ConditionFalse, Reason: reason, Message: message} + } + + tests := []struct { + name string + cond *metav1.Condition + want bool + }{ + {name: "nil", cond: nil, want: false}, + { + name: "local InvalidConfig", + cond: falseCond(mcpv1beta1.ConditionReasonInvalidConfig, "obo external auth requires incoming authentication"), + want: true, + }, + { + name: "local InvalidCABundle", + cond: falseCond(mcpv1beta1.ConditionReasonInvalidCABundle, "invalid CA bundle: missing key"), + want: true, + }, + { + name: "mirrored InvalidConfig", + cond: falseCond(mcpv1beta1.ConditionReasonInvalidConfig, + mirroredConditionMessage("obo-config", "obo: clientId is required")), + want: false, + }, + { + name: "mirrored InvalidCABundle", + cond: falseCond(mcpv1beta1.ConditionReasonInvalidCABundle, mirroredConditionMessage("auth", "")), + want: false, + }, + {name: "other reason", cond: falseCond(testSourceInvalidReason, testSourceInvalidMessage), want: false}, + { + name: "True condition", + cond: &metav1.Condition{Status: metav1.ConditionTrue, Reason: mcpv1beta1.ConditionReasonInvalidConfig}, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, isLocalValidationFailure(tt.cond)) + }) + } +} + +// TestExternalAuthMirror_OBOSourceHealsToSameSpec drives a real obo +// MCPExternalAuthConfig through the MCPExternalAuthConfig reconciler from valid +// to malformed (Valid=False / InvalidConfig, the same reason the consumers use +// for their own validation failures) and back to the exact same valid spec, so +// the source's ConfigHash and the consumer's stored hash and generation never +// change. The consumer must end on ExternalAuthConfigValidated=True: the +// mirrored InvalidConfig must not be mistaken for a locally-owned failure and +// held by the same-hash guard. +func TestExternalAuthMirror_OBOSourceHealsToSameSpec(t *testing.T) { + t.Parallel() + + const ( + namespace = "default" + authName = "obo-config" + ) + + tests := []struct { + name string + // newConsumer returns the consumer object referencing authName. + newConsumer func() client.Object + // handle runs the consumer's handleExternalAuthConfig against obj. + handle func(ctx context.Context, c client.Client, obj client.Object) error + // condition returns the consumer's ExternalAuthConfigValidated condition. + condition func(obj client.Object) *metav1.Condition + wantReason string + }{ + { + name: "MCPServer", + newConsumer: func() client.Object { + return v1beta1test.NewMCPServer("server", namespace, + v1beta1test.WithImage("test-image"), + v1beta1test.WithExternalAuthConfigRef(authName), + v1beta1test.Mutate(func(m *mcpv1beta1.MCPServer) { + m.Generation = 4 + m.Spec.OIDCConfigRef = &mcpv1beta1.MCPOIDCConfigReference{Name: "oidc"} + }), + ) + }, + handle: func(ctx context.Context, c client.Client, obj client.Object) error { + r := newTestMCPServerReconciler(c, c.Scheme(), kubernetes.PlatformKubernetes) + return r.handleExternalAuthConfig(ctx, obj.(*mcpv1beta1.MCPServer)) + }, + condition: func(obj client.Object) *metav1.Condition { + return meta.FindStatusCondition(obj.(*mcpv1beta1.MCPServer).Status.Conditions, + mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + }, + wantReason: mcpv1beta1.ConditionReasonExternalAuthConfigValid, + }, + { + name: "MCPRemoteProxy", + newConsumer: func() client.Object { + return v1beta1test.NewMCPRemoteProxy("proxy", namespace, + v1beta1test.WithRemoteProxyExternalAuthConfigRef(authName), + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Generation = 4 + p.Spec.OIDCConfigRef = &mcpv1beta1.MCPOIDCConfigReference{Name: "oidc"} + }), + ) + }, + handle: func(ctx context.Context, c client.Client, obj client.Object) error { + r := &MCPRemoteProxyReconciler{Client: c, Scheme: c.Scheme()} + return r.handleExternalAuthConfig(ctx, obj.(*mcpv1beta1.MCPRemoteProxy)) + }, + condition: func(obj client.Object) *metav1.Condition { + return meta.FindStatusCondition(obj.(*mcpv1beta1.MCPRemoteProxy).Status.Conditions, + mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated) + }, + wantReason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigValid, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx := t.Context() + + source := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: authName, + Namespace: namespace, + Finalizers: []string{ExternalAuthConfigFinalizerName}, + }, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: validOBOSpec(), + }, + } + consumer := tt.newConsumer() + + scheme := testutil.NewScheme(t) + c := withExternalAuthConfigRefIndexes(fake.NewClientBuilder().WithScheme(scheme)). + WithObjects(source, consumer). + WithStatusSubresource( + &mcpv1beta1.MCPExternalAuthConfig{}, &mcpv1beta1.MCPServer{}, &mcpv1beta1.MCPRemoteProxy{}). + Build() + sourceReconciler := &MCPExternalAuthConfigReconciler{Client: c, Scheme: scheme} + sourceKey := client.ObjectKeyFromObject(source) + + // setSourceSpec writes the obo spec and reconciles the source. + setSourceSpec := func(spec *mcpv1beta1.OBOConfig) { + t.Helper() + live := &mcpv1beta1.MCPExternalAuthConfig{} + require.NoError(t, c.Get(ctx, sourceKey, live)) + live.Spec.OBO = spec + require.NoError(t, c.Update(ctx, live)) + _, err := sourceReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: sourceKey}) + require.NoError(t, err) + } + sourceHash := func() string { + t.Helper() + live := &mcpv1beta1.MCPExternalAuthConfig{} + require.NoError(t, c.Get(ctx, sourceKey, live)) + return live.Status.ConfigHash + } + + // 1. Valid source: the consumer records True and the source hash. + setSourceSpec(validOBOSpec()) + validHash := sourceHash() + require.NotEmpty(t, validHash) + require.NoError(t, tt.handle(ctx, c, consumer)) + require.Equal(t, metav1.ConditionTrue, tt.condition(consumer).Status) + + // 2. Malformed source: Valid=False / InvalidConfig, hash unchanged. + malformed := validOBOSpec() + malformed.ClientID = "" + setSourceSpec(malformed) + require.Equal(t, validHash, sourceHash(), "a rejected spec must not advance the source hash") + require.Error(t, tt.handle(ctx, c, consumer)) + mirrored := tt.condition(consumer) + require.NotNil(t, mirrored) + require.Equal(t, metav1.ConditionFalse, mirrored.Status) + require.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, mirrored.Reason) + + // 3. Revert to the exact last-valid spec: same hash, same consumer + // generation. The stale mirror must clear and True must be written. + setSourceSpec(validOBOSpec()) + require.Equal(t, validHash, sourceHash()) + require.NoError(t, tt.handle(ctx, c, consumer)) + healed := tt.condition(consumer) + require.NotNil(t, healed) + assert.Equal(t, metav1.ConditionTrue, healed.Status, + "a healed source must not leave a mirrored InvalidConfig on the consumer") + assert.Equal(t, tt.wantReason, healed.Reason) + }) + } +} diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go index 0a73a16b29..d5ea78f9cd 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go @@ -348,20 +348,12 @@ func (*MCPExternalAuthConfigReconciler) applyIdentitySynthesizedCondition( }) } -// triageOBOValidation runs the OBO validation and routes the result through -// the error contract documented on obo.ValidationError: -// -// - *obo.ValidationError → permanent, Reason=InvalidConfig (the typed -// error's Message is written verbatim into condition.Message) -// - anything else → transient; return the error wrapped so -// controller-runtime requeues with backoff and self-heals once the -// dependency recovers -// -// Returns handled=true to signal the caller to return immediately (with a -// zero ctrl.Result and the returned error). handled=false means Validate -// succeeded and the reconciler should continue with the Valid=True path. -// -// Extracted from Reconcile so the parent stays under the gocyclo threshold. +// triageOBOValidation runs ctrlutil.OBOValidate on cfg and hands the result to +// applyOBOValidationResult. The two are split only so tests can drive +// applyOBOValidationResult with an injected error (for example a transient, +// non-ValidationError one, which the built-in validator never returns but a +// handler registered through the deprecated ctrlutil.RegisterOBOHandler may); +// Reconcile always enters through this function. func (r *MCPExternalAuthConfigReconciler) triageOBOValidation( ctx context.Context, cfg *mcpv1beta1.MCPExternalAuthConfig, @@ -369,8 +361,19 @@ func (r *MCPExternalAuthConfigReconciler) triageOBOValidation( return r.applyOBOValidationResult(ctx, cfg, ctrlutil.OBOValidate(cfg)) } -// applyOBOValidationResult routes an OBO validation error into the matching -// bucket (see triageOBOValidation). A nil validateErr returns handled=false. +// applyOBOValidationResult routes an OBO validation result through the error +// contract documented on obo.ValidationError: +// +// - nil → handled=false; the reconciler continues with +// the Valid=True path +// - *obo.ValidationError → permanent, Reason=InvalidConfig (the typed +// error's Message is written verbatim into condition.Message) +// - anything else → transient; return the error wrapped so +// controller-runtime requeues with backoff and self-heals once the +// dependency recovers +// +// handled=true tells the caller to return immediately with a zero ctrl.Result +// and the returned error. func (r *MCPExternalAuthConfigReconciler) applyOBOValidationResult( ctx context.Context, cfg *mcpv1beta1.MCPExternalAuthConfig, diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go index 926412f77c..57c92451ce 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go @@ -7,6 +7,7 @@ import ( "context" stderrors "errors" "fmt" + "math" "testing" "time" @@ -1108,7 +1109,43 @@ func TestMCPExternalAuthConfigReconciler_OBO_Validation(t *testing.T) { wantReason string wantMessage string }{ - {name: "valid config", spec: validOBOSpec(), wantStatus: metav1.ConditionTrue}, + {name: "valid config", spec: validOBOSpec(), wantStatus: metav1.ConditionTrue, wantReason: "ValidationSucceeded"}, + { + name: "negative cache skew", + spec: func() *mcpv1beta1.OBOConfig { + c := validOBOSpec() + c.CacheSkew = &metav1.Duration{Duration: -time.Second} + return c + }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: cacheSkew must not be negative", + }, + { + name: "cache skew above MaxInt32 seconds", + spec: func() *mcpv1beta1.OBOConfig { + c := validOBOSpec() + c.CacheSkew = &metav1.Duration{Duration: (math.MaxInt32 + 1) * time.Second} + return c + }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "obo: cacheSkew is too large", + }, + { + name: "tenant neither guid nor domain", + spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.TenantID = "not a tenant"; return c }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "entra obo: TenantID must be a directory GUID or a domain name", + }, + { + name: "non-loopback http authority", + spec: func() *mcpv1beta1.OBOConfig { + c := validOBOSpec() + c.Authority = "http://login.microsoftonline.com" + return c + }(), + wantStatus: metav1.ConditionFalse, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, + wantMessage: "entra obo: Authority must use https (http allowed only for loopback)", + }, { name: "missing tenant", spec: func() *mcpv1beta1.OBOConfig { c := validOBOSpec(); c.TenantID = ""; return c }(), @@ -1170,8 +1207,8 @@ func TestMCPExternalAuthConfigReconciler_OBO_Validation(t *testing.T) { validCond := findCondition(updated.Status.Conditions, mcpv1beta1.ConditionTypeValid) require.NotNil(t, validCond, "Valid condition must be set for OBO-typed config") assert.Equal(t, tt.wantStatus, validCond.Status) + assert.Equal(t, tt.wantReason, validCond.Reason) if tt.wantStatus == metav1.ConditionFalse { - assert.Equal(t, tt.wantReason, validCond.Reason) assert.Equal(t, tt.wantMessage, validCond.Message) } }) diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index 33931042b8..6d3b2cb1af 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -278,11 +278,7 @@ func (r *MCPRemoteProxyReconciler) validateAndHandleConfigs(ctx context.Context, // Handle MCPExternalAuthConfig if err := r.handleExternalAuthConfig(ctx, proxy); err != nil { - ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") - if statusErr := r.markConfigHandlerFailed(ctx, proxy, "MCPExternalAuthConfig", err); statusErr != nil { - ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPExternalAuthConfig error") - } - return err + return r.markExternalAuthConfigFailed(ctx, proxy, err) } // Handle authServerRef config hash tracking @@ -345,6 +341,30 @@ func (r *MCPRemoteProxyReconciler) markConfigHandlerFailed( return r.Status().Update(ctx, proxy) } +// markExternalAuthConfigFailed records a handleExternalAuthConfig failure on +// status and returns the error validateAndHandleConfigs should propagate: +// normally err itself, but the status write error when err is a terminal +// *obo.ValidationError whose rejection could not be persisted. Reconcile does +// not requeue a ValidationError, so returning it then would drop the rejection. +func (r *MCPRemoteProxyReconciler) markExternalAuthConfigFailed( + ctx context.Context, + proxy *mcpv1beta1.MCPRemoteProxy, + err error, +) error { + ctxLogger := log.FromContext(ctx) + ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") + statusErr := r.markConfigHandlerFailed(ctx, proxy, "MCPExternalAuthConfig", err) + if statusErr == nil { + return err + } + ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPExternalAuthConfig error") + var validationErr *obo.ValidationError + if stderrors.As(err, &validationErr) { + return statusErr + } + return err +} + func (r *MCPRemoteProxyReconciler) validateSpecAndPodTemplate( ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy, @@ -1092,7 +1112,10 @@ func (r *MCPRemoteProxyReconciler) handleExternalAuthConfig(ctx context.Context, } // setMCPRemoteProxyExternalAuthConfigValidCondition preserves a terminal RunConfig validation failure -// until its referenced configuration or this resource generation changes. +// until its referenced configuration or this resource generation changes. An +// InvalidConfig mirrored from the referenced MCPExternalAuthConfig is not held +// (see isLocalValidationFailure): the source can heal back to an unchanged +// ConfigHash, and holding it would make the failure permanent. func setMCPRemoteProxyExternalAuthConfigValidCondition( proxy *mcpv1beta1.MCPRemoteProxy, configName, configHash string, @@ -1100,8 +1123,7 @@ func setMCPRemoteProxyExternalAuthConfigValidCondition( previousCondition := meta.FindStatusCondition( proxy.Status.Conditions, mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated, ) - if previousCondition != nil && - previousCondition.Status == metav1.ConditionFalse && + if isLocalValidationFailure(previousCondition) && previousCondition.Reason == mcpv1beta1.ConditionReasonInvalidConfig && previousCondition.ObservedGeneration == proxy.Generation && proxy.Status.ExternalAuthConfigHash == configHash { diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go index 72d83c58ee..01f79b2e8d 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller_test.go @@ -16,6 +16,7 @@ package controllers import ( "context" + stderrors "errors" "fmt" "testing" "time" @@ -38,6 +39,7 @@ import ( "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" + "github.com/stacklok/toolhive/pkg/auth/obo" ) // TestMCPRemoteProxyValidateSpec tests the spec validation logic @@ -416,6 +418,7 @@ func TestHandleExternalAuthConfig(t *testing.T) { externalAuth *mcpv1beta1.MCPExternalAuthConfig interceptorFuncs *interceptor.Funcs expectError bool + expectValidationErr bool // the error must be a terminal *obo.ValidationError errContains string expectCondition bool expectedCondStatus metav1.ConditionStatus @@ -562,7 +565,7 @@ func TestHandleExternalAuthConfig(t *testing.T) { expectCondition: true, expectedCondStatus: metav1.ConditionFalse, expectedCondReason: testSourceInvalidReason, - expectedCondMessage: testSourceInvalidMessage, + expectedCondMessage: mirroredConditionMessage("obo-config", testSourceInvalidMessage), }, { name: "obo config without incoming OIDC is rejected as InvalidConfig", @@ -576,6 +579,7 @@ func TestHandleExternalAuthConfig(t *testing.T) { }, }, expectError: true, + expectValidationErr: true, errContains: "requires incoming authentication", expectCondition: true, expectedCondStatus: metav1.ConditionFalse, @@ -660,6 +664,11 @@ func TestHandleExternalAuthConfig(t *testing.T) { if tt.errContains != "" { assert.Contains(t, err.Error(), tt.errContains) } + if tt.expectValidationErr { + var validationErr *obo.ValidationError + require.ErrorAs(t, err, &validationErr, + "the rejection must be terminal so Reconcile does not requeue") + } // Verify condition on in-memory object for error cases if tt.expectCondition { @@ -1456,6 +1465,93 @@ func TestMCPRemoteProxyReconciler_InvalidUpstreamCABundleIsTerminal(t *testing.T assert.Equal(t, mcpv1beta1.ConditionReasonInvalidCABundle, condition.Reason) } +// TestMCPRemoteProxyReconciler_OBOWithoutIncomingAuthIsTerminal drives +// Reconcile for an MCPRemoteProxy that references a valid obo config but has no +// oidcConfigRef. The rejection is a spec defect: Reconcile persists it on status +// and returns an empty result with no error instead of requeueing with backoff. +// Only a failure to persist that rejection is returned, so the write is retried. +func TestMCPRemoteProxyReconciler_OBOWithoutIncomingAuthIsTerminal(t *testing.T) { + t.Parallel() + + statusErr := stderrors.New("simulated status write failure") + // failRejectionWrite fails only the status write that records the obo + // rejection, so an unrelated earlier write cannot satisfy the assertion. + failRejectionWrite := interceptor.Funcs{ + SubResourceUpdate: func( + ctx context.Context, c client.Client, subResource string, obj client.Object, + opts ...client.SubResourceUpdateOption, + ) error { + if p, ok := obj.(*mcpv1beta1.MCPRemoteProxy); ok { + cond := meta.FindStatusCondition(p.Status.Conditions, + mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated) + if cond != nil && cond.Reason == mcpv1beta1.ConditionReasonInvalidConfig { + return statusErr + } + } + return c.SubResource(subResource).Update(ctx, obj, opts...) + }, + } + + tests := []struct { + name string + interceptor *interceptor.Funcs + wantErr error + }{ + {name: "rejection is persisted and not requeued"}, + {name: "failed status write is retried", interceptor: &failRejectionWrite, wantErr: statusErr}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + proxy := v1beta1test.NewMCPRemoteProxy("proxy", "default", + v1beta1test.WithRemoteProxyURL("https://remote.example.com"), + v1beta1test.WithRemoteProxyExternalAuthConfigRef("obo-config"), + ) + authConfig := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: validOBOSpec(), + }, + } + scheme := testutil.NewScheme(t) + builder := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(proxy, authConfig). + WithStatusSubresource(&mcpv1beta1.MCPRemoteProxy{}) + if tt.interceptor != nil { + builder = builder.WithInterceptorFuncs(*tt.interceptor) + } + fakeClient := builder.Build() + reconciler := &MCPRemoteProxyReconciler{ + Client: fakeClient, Scheme: scheme, PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } + + result, err := reconciler.Reconcile(t.Context(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(proxy)}) + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr, "an unpersisted rejection must be retried, not dropped") + return + } + require.NoError(t, err, "a spec defect must not be returned as an error (that requeues with backoff)") + assert.Equal(t, ctrl.Result{}, result) + + actual := &mcpv1beta1.MCPRemoteProxy{} + require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(proxy), actual)) + assert.Equal(t, mcpv1beta1.MCPRemoteProxyPhaseFailed, actual.Status.Phase) + ready := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeReady) + require.NotNil(t, ready) + assert.Equal(t, metav1.ConditionFalse, ready.Status) + condition := meta.FindStatusCondition(actual.Status.Conditions, + mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated) + require.NotNil(t, condition, "the rejection must be persisted, not only set in memory") + assert.Equal(t, metav1.ConditionFalse, condition.Status) + assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, condition.Reason) + assert.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, condition.Message) + }) + } +} + func TestGetExternalAuthConfigForMCPRemoteProxy(t *testing.T) { t.Parallel() diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go index 7b7558eae6..962fe607bc 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment.go @@ -308,10 +308,9 @@ func (r *MCPRemoteProxyReconciler) buildEnvVarsForProxy( env = append(env, bearerTokenEnvVars...) } - // Add OBO secret environment variables. Dispatched through the - // registered OBO handler; inert (no env vars) in builds without one. - // This function feeds both the deployment builder and containerNeedsUpdate, - // so builder/drift symmetry is automatic. + // Add OBO secret environment variables (none unless the referenced + // config is obo-typed). This function feeds both the deployment builder + // and containerNeedsUpdate, so builder/drift symmetry is automatic. oboEnvVars, err := ctrlutil.AddOBOSecretEnvVars( ctx, r.Client, diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go index d21b6450da..b089a8e3d7 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_deployment_test.go @@ -17,6 +17,8 @@ package controllers import ( "context" "fmt" + "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -1025,6 +1027,48 @@ func TestMCPRemoteProxyDeployment_OBOSecretEnvVars(t *testing.T) { "freshly built deployment with an OBO env var must not be seen as drifted") } +// TestMCPRemoteProxyDeployment_OBOSecretEnvVars_Error covers the MCPRemoteProxy +// path when the OBO secret env var cannot be produced (an obo config with no +// clientSecretRef): the builder logs the ValidationError and leaves the env var +// out. Unlike MCPServer, the builder and drift check share buildEnvVarsForProxy, +// so they agree and the Deployment is not reported as drifted. The +// MCPExternalAuthConfig reconciler surfaces the underlying InvalidConfig. +func TestMCPRemoteProxyDeployment_OBOSecretEnvVars_Error(t *testing.T) { + t.Parallel() + + scheme := testutil.NewScheme(t) + authConfig := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{}, + }, + } + proxy := v1beta1test.NewMCPRemoteProxy("test-proxy", "default", + v1beta1test.WithRemoteProxyExternalAuthConfigRef(authConfig.Name), + ) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(authConfig).Build() + reconciler := &MCPRemoteProxyReconciler{ + Client: fakeClient, + Scheme: scheme, + PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } + + ctx, lines := newLogCapturingContext(t) + deployment := reconciler.deploymentForMCPRemoteProxy(ctx, proxy, "test-checksum") + require.NotNil(t, deployment) + for _, ev := range deployment.Spec.Template.Spec.Containers[0].Env { + assert.NotEqual(t, obo.ClientSecretEnvVar, ev.Name) + } + assert.True(t, slices.ContainsFunc(*lines, func(line string) bool { + return strings.Contains(line, "Failed to generate OBO secret environment variables") && + strings.Contains(line, "obo: clientSecretRef must set both name and key") + }), "the builder must log the OBO validation failure; got %v", *lines) + + assert.False(t, reconciler.deploymentNeedsUpdate(t.Context(), deployment, proxy, "test-checksum"), + "builder and drift check share buildEnvVarsForProxy, so the OBO-env-less Deployment is not drifted") +} + func TestMCPRemoteProxyDeploymentNeedsUpdate_ImagePullSecretsDrift(t *testing.T) { t.Parallel() diff --git a/cmd/thv-operator/controllers/mcpserver_controller.go b/cmd/thv-operator/controllers/mcpserver_controller.go index 6fa7200be7..aefa56b9b1 100644 --- a/cmd/thv-operator/controllers/mcpserver_controller.go +++ b/cmd/thv-operator/controllers/mcpserver_controller.go @@ -269,6 +269,21 @@ func (r *MCPServerReconciler) handleInvalidCABundle( }) } +// markExternalAuthConfigFailed records a handleExternalAuthConfig failure as +// Phase=Failed / Ready=False, alongside the ExternalAuthConfigValidated +// condition the handler already set in memory. It keeps the full-object status +// Update the other MCPServer config handlers use, so the in-memory conditions +// are persisted with it. +func (r *MCPServerReconciler) markExternalAuthConfigFailed( + ctx context.Context, + mcpServer *mcpv1beta1.MCPServer, + err error, +) error { + mcpServer.Status.Phase = mcpv1beta1.MCPServerPhaseFailed + setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1beta1.ConditionReasonNotReady, err.Error()) + return r.Status().Update(ctx, mcpServer) +} + // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // @@ -387,24 +402,21 @@ func (r *MCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( } // A spec defect the user must fix (e.g. obo without incoming OIDC) is - // recorded on status and not requeued. + // recorded on status and not requeued; only a failed status write is + // retried. var validationErr *obo.ValidationError - terminal := stderrors.As(err, &validationErr) - if !terminal { - ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") - } - // Update status to reflect the error - mcpServer.Status.Phase = mcpv1beta1.MCPServerPhaseFailed - setReadyCondition(mcpServer, metav1.ConditionFalse, mcpv1beta1.ConditionReasonNotReady, err.Error()) - if statusErr := r.Status().Update(ctx, mcpServer); statusErr != nil { - ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPExternalAuthConfig error") - if terminal { + if stderrors.As(err, &validationErr) { + if statusErr := r.markExternalAuthConfigFailed(ctx, mcpServer, err); statusErr != nil { + ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPExternalAuthConfig error") return ctrl.Result{}, statusErr } - } - if terminal { return ctrl.Result{}, nil } + + ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig") + if statusErr := r.markExternalAuthConfigFailed(ctx, mcpServer, err); statusErr != nil { + ctxLogger.Error(statusErr, "Failed to update MCPServer status after MCPExternalAuthConfig error") + } return ctrl.Result{}, err } @@ -2552,6 +2564,9 @@ func (r *MCPServerReconciler) handleExternalAuthConfig(ctx context.Context, m *m // preserved here: its failing input is ConfigMap content, which neither // generation nor configHash tracks, and the check that records it re-runs // earlier in this same function. Holding it would make the failure permanent. +// Neither is an InvalidConfig mirrored from the referenced +// MCPExternalAuthConfig (see isLocalValidationFailure): the source can heal +// back to an unchanged ConfigHash, and holding it would then be permanent too. func setMCPServerExternalAuthConfigValidCondition( m *mcpv1beta1.MCPServer, configName, configHash string, @@ -2559,8 +2574,7 @@ func setMCPServerExternalAuthConfigValidCondition( previousCondition := meta.FindStatusCondition( m.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated, ) - if previousCondition != nil && - previousCondition.Status == metav1.ConditionFalse && + if isLocalValidationFailure(previousCondition) && previousCondition.Reason == mcpv1beta1.ConditionReasonInvalidConfig && previousCondition.ObservedGeneration == m.Generation && m.Status.ExternalAuthConfigHash == configHash { diff --git a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go index fd1bbd14dc..d163cc40cc 100644 --- a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go @@ -16,9 +16,11 @@ package controllers import ( "context" + "fmt" "testing" "time" + "github.com/go-logr/logr/funcr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" @@ -28,6 +30,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/log" mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" @@ -420,19 +423,37 @@ func TestMCPServerReconciler_handleExternalAuthConfig_MirrorsInvalidCondition(t }, wantMirrored: true, wantReason: reason, - wantMessage: message, + wantMessage: mirroredConditionMessage(authName, message), }, { - name: "source Valid=False/InvalidConfig is mirrored verbatim", + name: "source Valid=False/InvalidConfig keeps its reason behind the mirror marker", sourceValid: &metav1.Condition{ Type: mcpv1beta1.ConditionTypeValid, Status: metav1.ConditionFalse, Reason: mcpv1beta1.ConditionReasonInvalidConfig, - Message: "custom OBO handler rejected the spec", + Message: "obo: clientId is required", }, wantMirrored: true, wantReason: mcpv1beta1.ConditionReasonInvalidConfig, - wantMessage: "custom OBO handler rejected the spec", + wantMessage: "Referenced MCPExternalAuthConfig 'obo-config' is invalid: obo: clientId is required", + }, + { + // Regression guard for a stale mirror whose Reason collides with a + // locally-owned one: the marker, not the Reason, decides ownership. + name: "stale mirrored InvalidConfig is cleared when source has healed", + sourceValid: &metav1.Condition{ + Type: mcpv1beta1.ConditionTypeValid, + Status: metav1.ConditionTrue, + Reason: "ValidationSucceeded", + }, + preexisting: []metav1.Condition{{ + Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, + Status: metav1.ConditionFalse, + Reason: mcpv1beta1.ConditionReasonInvalidConfig, + Message: mirroredConditionMessage(authName, "obo: clientId is required"), + ObservedGeneration: 11, + }}, + wantMirrored: false, }, { name: "source Valid=True does not produce a mirror", @@ -905,6 +926,48 @@ func TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth(t } } +// TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal drives Reconcile for +// an MCPServer that references a valid obo config but has no oidcConfigRef. +// The rejection is a spec defect, so Reconcile records it on status and returns +// an empty result with no error rather than requeueing with backoff. +func TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal(t *testing.T) { + t.Parallel() + + server := v1beta1test.NewMCPServer("server", "default", + v1beta1test.WithImage("test"), + v1beta1test.WithExternalAuthConfigRef("obo-config"), + ) + authConfig := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: validOBOSpec(), + }, + } + scheme := testutil.NewScheme(t) + fakeClient := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(server, authConfig). + WithStatusSubresource(&mcpv1beta1.MCPServer{}). + Build() + reconciler := newTestMCPServerReconciler(fakeClient, scheme, kubernetes.PlatformKubernetes) + + result, err := reconciler.Reconcile(t.Context(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(server)}) + require.NoError(t, err, "a spec defect must not be returned as an error (that requeues with backoff)") + assert.Equal(t, ctrl.Result{}, result) + + actual := &mcpv1beta1.MCPServer{} + require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(server), actual)) + assert.Equal(t, mcpv1beta1.MCPServerPhaseFailed, actual.Status.Phase) + ready := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeReady) + require.NotNil(t, ready) + assert.Equal(t, metav1.ConditionFalse, ready.Status) + validated := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + require.NotNil(t, validated) + assert.Equal(t, metav1.ConditionFalse, validated.Status) + assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, validated.Reason) + assert.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, validated.Message) +} + // TestMCPServerDeployment_OBOSecretEnvVars verifies that an obo-typed // MCPExternalAuthConfig referenced from an MCPServer mounts the OBO client // secret into the proxy container under obo.ClientSecretEnvVar, and that the @@ -999,6 +1062,74 @@ func TestMCPServerDeployment_OBOSecretEnvVars_ErrorDivergence(t *testing.T) { "deploymentNeedsUpdate reports drift while the OBO env var cannot be produced") } +// newLogCapturingContext returns a context carrying a controller-runtime logger +// that records every rendered log line, and the slice it records into. +func newLogCapturingContext(t *testing.T) (context.Context, *[]string) { + t.Helper() + var lines []string + logger := funcr.New(func(prefix, args string) { + lines = append(lines, prefix+" "+args) + }, funcr.Options{}) + return log.IntoContext(t.Context(), logger), &lines +} + +// TestLogOBOSecretEnvVarError verifies that an OBO secret env var error is +// logged with its detail only when it is an *obo.ValidationError, whose message +// is safe to surface. Any other error may name a Secret, so it is logged +// generically with a pointer to the MCPExternalAuthConfig status. +func TestLogOBOSecretEnvVarError(t *testing.T) { + t.Parallel() + + const ( + validationMsg = "obo: clientSecretRef must set both name and key" + sensitiveText = "obo-secret/client-secret" + genericHint = "see the referenced MCPExternalAuthConfig status for details" + ) + + tests := []struct { + name string + err error + wantContain []string + wantAbsent []string + }{ + { + name: "ValidationError is logged with its message", + err: &obo.ValidationError{Message: validationMsg}, + wantContain: []string{validationMsg}, + wantAbsent: []string{genericHint}, + }, + { + name: "wrapped ValidationError is logged with its message", + err: fmt.Errorf("resolving obo env: %w", &obo.ValidationError{Message: validationMsg}), + wantContain: []string{validationMsg}, + wantAbsent: []string{genericHint}, + }, + { + name: "other error is redacted", + err: fmt.Errorf("secret %s not found", sensitiveText), + wantContain: []string{genericHint}, + wantAbsent: []string{sensitiveText}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx, lines := newLogCapturingContext(t) + logOBOSecretEnvVarError(ctx, tt.err) + + require.Len(t, *lines, 1, "the failure must be logged exactly once") + for _, want := range tt.wantContain { + assert.Contains(t, (*lines)[0], want) + } + for _, absent := range tt.wantAbsent { + assert.NotContains(t, (*lines)[0], absent) + } + }) + } +} + // TestMCPServerDeployment_TLSListenerKeepsHTTPProbes verifies that enabling the // auth server TLS listener leaves the proxy's health probes on plain HTTP: the // listener serves the auth server on its own port, not the MCP port. diff --git a/cmd/thv-operator/controllers/virtualmcpserver_deployment.go b/cmd/thv-operator/controllers/virtualmcpserver_deployment.go index cee7eff522..383b337e7d 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_deployment.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_deployment.go @@ -943,7 +943,10 @@ func (r *VirtualMCPServerReconciler) getExternalAuthConfigSecretEnvVars( case mcpv1beta1.ExternalAuthTypeOBO: // Per-config name (unlike the proxyrunner pod's fixed // obo.ClientSecretEnvVar): one vMCP can front several OBO backends. - return ctrlutil.OBOVMCPSecretEnvVar(externalAuthConfig) + // Deliberately bypasses a handler registered through the deprecated + // ctrlutil.RegisterOBOHandler: its SecretEnvVars yields one fixed name, + // which would collide across OBO backends in this pod. + return ctrlutil.OBOVMCPSecretEnvVars(externalAuthConfig) case mcpv1beta1.ExternalAuthTypeXAA: return xaaSecretEnvVars(externalAuthConfig, externalAuthConfigName), nil diff --git a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go index 652a0608c7..1d4d151721 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_externalauth_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -56,7 +57,7 @@ func TestConvertExternalAuthConfigToStrategy(t *testing.T) { assert.Equal(t, authtypes.StrategyTypeOBO, strategy.Type) assert.Equal(t, "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", strategy.OBO.TokenURL) - assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_OBO_BACKEND_A", strategy.OBO.ClientSecretEnv, + assert.Equal(t, ctrlutil.GenerateUniqueOBOSecretEnvVarName("obo-backend-a"), strategy.OBO.ClientSecretEnv, "must match the env var getExternalAuthConfigSecretEnvVars mounts") assert.Empty(t, strategy.OBO.ClientSecret, "the secret value must not be inlined in inline mode") }, @@ -1671,6 +1672,119 @@ func TestDiscoverInlineExternalAuthConfigSecrets_DeterministicOrdering(t *testin "env vars must be sorted alphabetically by Name to ensure deterministic reconcile behaviour") } +// TestDiscoverExternalAuthConfigSecrets_TwoOBOBackends verifies, for both +// discovered and inline outgoing auth, that two OBO backends put two distinct +// client secret env vars on the vMCP pod, and that each name is exactly the +// ClientSecretEnv convertExternalAuthConfigToStrategy writes into the vMCP +// config, so the runtime reads the env var the pod actually carries. The two +// config names sanitize to the same string ("obo.a" and "obo-a" both become +// OBO_A), so this also covers the hash suffix keeping them apart. +func TestDiscoverExternalAuthConfigSecrets_TwoOBOBackends(t *testing.T) { + t.Parallel() + + newOBOConfig := func(name, secretName string) *mcpv1beta1.MCPExternalAuthConfig { + return &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: &mcpv1beta1.OBOConfig{ + TenantID: "contoso.onmicrosoft.com", + ClientID: "client-id", + ClientSecretRef: &mcpv1beta1.SecretKeyRef{Name: secretName, Key: "client-secret"}, + Audience: "api://backend/.default", + }, + }, + } + } + configs := []*mcpv1beta1.MCPExternalAuthConfig{ + newOBOConfig("obo-a", "secret-dash"), + newOBOConfig("obo.a", "secret-dot"), + } + inlineRef := func(name string) mcpv1beta1.BackendAuthConfig { + return mcpv1beta1.BackendAuthConfig{ + Type: mcpv1beta1.BackendAuthTypeExternalAuthConfigRef, + ExternalAuthConfigRef: &mcpv1beta1.ExternalAuthConfigRef{Name: name}, + } + } + + tests := []struct { + name string + vmcp *mcpv1beta1.VirtualMCPServer + extra []client.Object + discover func(ctx context.Context, r *VirtualMCPServerReconciler, vmcp *mcpv1beta1.VirtualMCPServer) []corev1.EnvVar + }{ + { + name: "discovered", + vmcp: v1beta1test.NewVirtualMCPServer("vmcp", "default", + v1beta1test.WithVMCPOutgoingAuth(&mcpv1beta1.OutgoingAuthConfig{Source: "discovered"})), + extra: []client.Object{ + v1beta1test.NewMCPServer("server-dash", "default", v1beta1test.WithExternalAuthConfigRef("obo-a")), + v1beta1test.NewMCPServer("server-dot", "default", v1beta1test.WithExternalAuthConfigRef("obo.a")), + }, + discover: func(ctx context.Context, r *VirtualMCPServerReconciler, vmcp *mcpv1beta1.VirtualMCPServer) []corev1.EnvVar { + return r.discoverExternalAuthConfigSecrets(ctx, vmcp, []workloads.TypedWorkload{ + {Name: "server-dash", Type: workloads.WorkloadTypeMCPServer}, + {Name: "server-dot", Type: workloads.WorkloadTypeMCPServer}, + }) + }, + }, + { + name: "inline", + vmcp: v1beta1test.NewVirtualMCPServer("vmcp", "default", + v1beta1test.WithVMCPOutgoingAuth(&mcpv1beta1.OutgoingAuthConfig{ + Source: "inline", + Backends: map[string]mcpv1beta1.BackendAuthConfig{ + "backend-dash": inlineRef("obo-a"), + "backend-dot": inlineRef("obo.a"), + }, + })), + discover: func(ctx context.Context, r *VirtualMCPServerReconciler, vmcp *mcpv1beta1.VirtualMCPServer) []corev1.EnvVar { + return r.discoverInlineExternalAuthConfigSecrets(ctx, vmcp) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + scheme := testutil.NewScheme(t) + objects := []client.Object{tt.vmcp} + objects = append(objects, tt.extra...) + for _, cfg := range configs { + objects = append(objects, cfg.DeepCopy()) + } + r := &VirtualMCPServerReconciler{ + Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build(), + Scheme: scheme, + PlatformDetector: ctrlutil.NewSharedPlatformDetector(), + } + + envVars := tt.discover(t.Context(), r, tt.vmcp) + require.Len(t, envVars, 2, "each OBO backend must contribute its own env var") + assert.NotEqual(t, envVars[0].Name, envVars[1].Name) + + byName := make(map[string]corev1.EnvVar, len(envVars)) + for _, ev := range envVars { + byName[ev.Name] = ev + } + for _, cfg := range configs { + strategy, err := r.convertExternalAuthConfigToStrategy(cfg) + require.NoError(t, err) + require.NotNil(t, strategy.OBO) + + ev, ok := byName[strategy.OBO.ClientSecretEnv] + require.True(t, ok, "the pod must carry %q, the env var the vMCP config for %q names", + strategy.OBO.ClientSecretEnv, cfg.Name) + require.NotNil(t, ev.ValueFrom) + require.NotNil(t, ev.ValueFrom.SecretKeyRef) + assert.Equal(t, cfg.Spec.OBO.ClientSecretRef.Name, ev.ValueFrom.SecretKeyRef.Name) + assert.Equal(t, cfg.Spec.OBO.ClientSecretRef.Key, ev.ValueFrom.SecretKeyRef.Key) + } + }) + } +} + // TestBuildOutgoingAuthConfig_InlineBackendSubjectProviderInjection verifies that // SubjectProviderName is auto-populated for the inline Spec.OutgoingAuth.Backends path // (virtualmcpserver_controller.go:2007) when AuthServerConfig is set. diff --git a/cmd/thv-operator/pkg/controllerutil/externalauth.go b/cmd/thv-operator/pkg/controllerutil/externalauth.go index 64f24d56d9..a17ed70966 100644 --- a/cmd/thv-operator/pkg/controllerutil/externalauth.go +++ b/cmd/thv-operator/pkg/controllerutil/externalauth.go @@ -5,6 +5,8 @@ package controllerutil import ( + "crypto/sha256" + "encoding/hex" "fmt" "regexp" "strings" @@ -75,12 +77,19 @@ func GenerateUniqueXAATargetSecretEnvVarName(configName string) string { // consistent naming. (The proxyrunner pod carries at most one OBO config and // uses the fixed obo.ClientSecretEnvVar.) // +// The sanitized, upper-cased name keeps the env var readable, but sanitizing +// is lossy ("my-cfg" and "my.cfg" both become MY_CFG), so the first 8 hex +// characters (upper-cased) of the SHA-256 of the raw name are appended to keep +// distinct config names on distinct env vars. +// // Example: For an ExternalAuthConfig named "my-auth-config", this returns: -// "TOOLHIVE_OBO_CLIENT_SECRET_MY_AUTH_CONFIG" +// "TOOLHIVE_OBO_CLIENT_SECRET_MY_AUTH_CONFIG_EB7C1742" func GenerateUniqueOBOSecretEnvVarName(configName string) string { sanitized := strings.ToUpper(strings.ReplaceAll(configName, "-", "_")) sanitized = envVarSanitizer.ReplaceAllString(sanitized, "_") - return fmt.Sprintf("TOOLHIVE_OBO_CLIENT_SECRET_%s", sanitized) + sum := sha256.Sum256([]byte(configName)) + suffix := strings.ToUpper(hex.EncodeToString(sum[:4])) + return fmt.Sprintf("TOOLHIVE_OBO_CLIENT_SECRET_%s_%s", sanitized, suffix) } // Header-forward env-var helpers (constants + name generators + the shared diff --git a/cmd/thv-operator/pkg/controllerutil/externalauth_test.go b/cmd/thv-operator/pkg/controllerutil/externalauth_test.go index 638ba82dce..a46c9402e9 100644 --- a/cmd/thv-operator/pkg/controllerutil/externalauth_test.go +++ b/cmd/thv-operator/pkg/controllerutil/externalauth_test.go @@ -104,5 +104,40 @@ func TestGenerateUniqueHeaderInjectionEnvVarName(t *testing.T) { } } +// TestGenerateUniqueOBOSecretEnvVarName pins the OBO vMCP env var name format +// (readable sanitized name plus a hash of the raw name) and that names which +// sanitize identically still map to distinct env vars. +func TestGenerateUniqueOBOSecretEnvVarName(t *testing.T) { + t.Parallel() + + envVarPattern := regexp.MustCompile(`^[A-Z0-9_]+$`) + + tests := []struct { + name string + configName string + want string + }{ + // Suffixes are the first 8 hex characters of sha256(configName). + {name: "hyphenated name", configName: "my-auth-config", want: "TOOLHIVE_OBO_CLIENT_SECRET_MY_AUTH_CONFIG_EB7C1742"}, + {name: "a-b", configName: "a-b", want: "TOOLHIVE_OBO_CLIENT_SECRET_A_B_D44362D6"}, + {name: "a.b", configName: "a.b", want: "TOOLHIVE_OBO_CLIENT_SECRET_A_B_2E7336DC"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got := GenerateUniqueOBOSecretEnvVarName(tt.configName) + assert.Equal(t, tt.want, got) + assert.Regexp(t, envVarPattern, got, "result must be a valid environment variable name") + }) + } + + t.Run("names that sanitize identically do not collide", func(t *testing.T) { + t.Parallel() + assert.NotEqual(t, GenerateUniqueOBOSecretEnvVarName("a-b"), GenerateUniqueOBOSecretEnvVarName("a.b")) + assert.NotEqual(t, GenerateUniqueOBOSecretEnvVarName("my-cfg"), GenerateUniqueOBOSecretEnvVarName("my.cfg")) + }) +} + // Tests for the header-forward env var generators moved with the // implementation to pkg/vmcp/headerforward/wirefmt — see wirefmt_test.go. diff --git a/cmd/thv-operator/pkg/controllerutil/obo.go b/cmd/thv-operator/pkg/controllerutil/obo.go index 43b3ee4d0f..8ed657b02e 100644 --- a/cmd/thv-operator/pkg/controllerutil/obo.go +++ b/cmd/thv-operator/pkg/controllerutil/obo.go @@ -6,8 +6,10 @@ package controllerutil import ( "context" "fmt" + "math" "strings" "sync" + "time" corev1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -27,6 +29,7 @@ const ( //nolint:gosec // G101: validation message, not a credential. msgOBOClientSecretRef = "obo: clientSecretRef must set both name and key" msgOBOCacheSkew = "obo: cacheSkew must not be negative" + msgOBOCacheSkewTooBig = "obo: cacheSkew is too large" msgOBOAudienceOrScopes = "obo: at least one of audience or scopes is required" // MsgOBORequiresIncomingAuth is the condition message for an obo external @@ -40,7 +43,12 @@ const ( // // Deprecated: OBO is built in. OBOHandler and RegisterOBOHandler are kept only // so out-of-tree code that still registers a handler keeps compiling; they will -// be removed in a future release. +// be removed once out-of-tree users are gone, see stacklok/toolhive#7200. A +// registered handler applies to MCPServer and MCPRemoteProxy only. Its +// SecretEnvVars is deliberately not used for VirtualMCPServer, which always +// mounts each OBO client secret under the built-in per-config name +// (OBOVMCPSecretEnvVars) so that two OBO backends in one vMCP pod never +// collide on a single env var name. type OBOHandler struct { // Validate verifies an obo-typed MCPExternalAuthConfig is well-formed. Validate func(*mcpv1beta1.MCPExternalAuthConfig) error @@ -71,7 +79,9 @@ var oboHandler = OBOHandler{ // RegisterOBOHandler replaces the built-in OBO handler. Last-write-wins. // Panics if any of the three function fields is nil. // -// Deprecated: OBO is built in; see OBOHandler. +// Deprecated: OBO is built in; it will be removed once out-of-tree users are +// gone, see stacklok/toolhive#7200. As documented on OBOHandler, the +// registered SecretEnvVars does not apply to VirtualMCPServer. func RegisterOBOHandler(h OBOHandler) { switch { case h.Validate == nil: @@ -162,10 +172,12 @@ func AddOBOSecretEnvVars( return OBOSecretEnvVars(externalAuthConfig) } -// OBOVMCPSecretEnvVar returns the env var that mounts an OBO client secret into -// the vMCP pod. The name is unique per MCPExternalAuthConfig so several OBO -// backends in one vMCP never collide. -func OBOVMCPSecretEnvVar(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { +// OBOVMCPSecretEnvVars returns the env var that mounts an OBO client secret +// into the vMCP pod. The name is unique per MCPExternalAuthConfig +// (GenerateUniqueOBOSecretEnvVarName) so several OBO backends in one vMCP never +// collide. It never dispatches through a handler registered with the deprecated +// RegisterOBOHandler: a handler's SecretEnvVars returns a single fixed name. +func OBOVMCPSecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvVar, error) { if oboSpec(cfg) == nil { return nil, &obo.ValidationError{Message: msgOBOConfigRequired} } @@ -222,10 +234,12 @@ func oboProxySecretEnvVars(cfg *mcpv1beta1.MCPExternalAuthConfig) ([]corev1.EnvV } // buildOBOMiddlewareParameters maps an OBOConfig onto obo.MiddlewareParameters -// and validates what the CRD schema cannot express: clientId and -// clientSecretRef presence, a non-negative cacheSkew, a usable tenant and -// authority, and at least one of audience or scopes. Every rejection is an -// *obo.ValidationError. +// and validates what the CRD schema cannot express: a non-blank clientId, +// a clientSecretRef with a non-blank name and key, a cacheSkew between zero and +// math.MaxInt32 seconds, a usable tenant and authority, and at least one +// non-blank audience or scope. Every rejection is an *obo.ValidationError. The +// cacheSkew bounds match the vMCP OBO converter (cacheSkewToSeconds), so a +// config the vMCP would reject is InvalidConfig at reconcile time. func buildOBOMiddlewareParameters(oboCfg *mcpv1beta1.OBOConfig) (*obo.MiddlewareParameters, error) { if oboCfg == nil { return nil, &obo.ValidationError{Message: msgOBOConfigRequired} @@ -236,8 +250,13 @@ func buildOBOMiddlewareParameters(oboCfg *mcpv1beta1.OBOConfig) (*obo.Middleware if err := validateOBOSecretRef(oboCfg.ClientSecretRef); err != nil { return nil, err } - if oboCfg.CacheSkew != nil && oboCfg.CacheSkew.Duration < 0 { - return nil, &obo.ValidationError{Message: msgOBOCacheSkew} + if oboCfg.CacheSkew != nil { + if oboCfg.CacheSkew.Duration < 0 { + return nil, &obo.ValidationError{Message: msgOBOCacheSkew} + } + if int64(oboCfg.CacheSkew.Duration/time.Second) > math.MaxInt32 { + return nil, &obo.ValidationError{Message: msgOBOCacheSkewTooBig} + } } // entra.TokenURL is the single source of truth for the tenant/authority to diff --git a/cmd/thv-operator/pkg/controllerutil/obo_test.go b/cmd/thv-operator/pkg/controllerutil/obo_test.go index 26a7ec6e53..0d794d2214 100644 --- a/cmd/thv-operator/pkg/controllerutil/obo_test.go +++ b/cmd/thv-operator/pkg/controllerutil/obo_test.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "errors" + "math" "testing" "time" @@ -95,22 +96,60 @@ func TestOBOValidate(t *testing.T) { {name: "non-negative cache skew", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.CacheSkew = &metav1.Duration{Duration: 30 * time.Second} })}, + {name: "sub-second cache skew is accepted", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.CacheSkew = &metav1.Duration{Duration: 500 * time.Millisecond} + })}, + {name: "cache skew of MaxInt32 seconds is accepted", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.CacheSkew = &metav1.Duration{Duration: math.MaxInt32 * time.Second} + })}, {name: "nil obo config", cfg: nil, wantMsg: msgOBOConfigRequired}, { name: "missing client id", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientID = "" }), wantMsg: msgOBOClientIDRequired, }, + { + name: "whitespace-only client id", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientID = " \t " }), + wantMsg: msgOBOClientIDRequired, + }, { name: "nil client secret ref", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }), wantMsg: msgOBOClientSecretRef, }, + { + name: "client secret ref missing name", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef.Name = "" }), + wantMsg: msgOBOClientSecretRef, + }, + { + name: "client secret ref whitespace-only name", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef.Name = " " }), + wantMsg: msgOBOClientSecretRef, + }, { name: "client secret ref missing key", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef.Key = "" }), wantMsg: msgOBOClientSecretRef, }, + { + name: "client secret ref whitespace-only key", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef.Key = " " }), + wantMsg: msgOBOClientSecretRef, + }, + { + name: "whitespace-only audience and no scopes", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.Audience = " " }), + wantMsg: msgOBOAudienceOrScopes, + }, + { + name: "cache skew above MaxInt32 seconds", + cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.CacheSkew = &metav1.Duration{Duration: (math.MaxInt32 + 1) * time.Second} + }), + wantMsg: msgOBOCacheSkewTooBig, + }, { name: "no audience and only blank scopes", cfg: mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { @@ -157,6 +196,36 @@ func TestOBOValidate(t *testing.T) { } } +// TestBuildOBOMiddlewareParameters_CacheSkewSeconds pins the cacheSkew to +// CacheSkewSeconds conversion: whole seconds, truncated toward zero, so a +// sub-second skew becomes 0 (the runtime's "use the cache default"), the same +// as the vMCP OBO converter. +func TestBuildOBOMiddlewareParameters_CacheSkewSeconds(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + skew *metav1.Duration + want int + }{ + {name: "unset", skew: nil, want: 0}, + {name: "sub-second truncates to zero", skew: &metav1.Duration{Duration: 999 * time.Millisecond}, want: 0}, + {name: "fractional seconds truncate", skew: &metav1.Duration{Duration: 1500 * time.Millisecond}, want: 1}, + {name: "upper bound", skew: &metav1.Duration{Duration: math.MaxInt32 * time.Second}, want: math.MaxInt32}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + params, err := buildOBOMiddlewareParameters(mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { + c.CacheSkew = tt.skew + })) + require.NoError(t, err) + assert.Equal(t, tt.want, params.CacheSkewSeconds) + }) + } +} + func TestAddExternalAuthConfigOptions_OBO(t *testing.T) { t.Parallel() @@ -412,22 +481,22 @@ func TestAddOBOSecretEnvVars(t *testing.T) { } } -func TestOBOVMCPSecretEnvVar_UniquePerConfig(t *testing.T) { +func TestOBOVMCPSecretEnvVars_UniquePerConfig(t *testing.T) { t.Parallel() - first, err := OBOVMCPSecretEnvVar(oboCR("backend-a", validOBOConfig())) + first, err := OBOVMCPSecretEnvVars(oboCR("backend-a", validOBOConfig())) require.NoError(t, err) - second, err := OBOVMCPSecretEnvVar(oboCR("backend-b", validOBOConfig())) + second, err := OBOVMCPSecretEnvVars(oboCR("backend-b", validOBOConfig())) require.NoError(t, err) require.Len(t, first, 1) require.Len(t, second, 1) - assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_A", first[0].Name) - assert.Equal(t, "TOOLHIVE_OBO_CLIENT_SECRET_BACKEND_B", second[0].Name) + assert.NotEqual(t, first[0].Name, second[0].Name) assert.Equal(t, GenerateUniqueOBOSecretEnvVarName("backend-a"), first[0].Name, "the deployment and the converter enrichment must agree on the name") + assert.Equal(t, GenerateUniqueOBOSecretEnvVarName("backend-b"), second[0].Name) - _, err = OBOVMCPSecretEnvVar(oboCR("bad", mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }))) + _, err = OBOVMCPSecretEnvVars(oboCR("bad", mutatedOBOConfig(func(c *mcpv1beta1.OBOConfig) { c.ClientSecretRef = nil }))) var vErr *obo.ValidationError assert.ErrorAs(t, err, &vErr) } diff --git a/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go index 1d78991aab..41e5573db2 100644 --- a/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go +++ b/cmd/thv-operator/test-integration/mcp-external-auth/obo_reconcile_test.go @@ -60,7 +60,9 @@ var _ = Describe("MCPExternalAuthConfig OBO reconcile", Label("k8s", "obo"), fun createOBOConfig("obo-reconcile-valid", validOBO()) Eventually(validCondition("obo-reconcile-valid"), timeout, interval).Should( - And(Not(BeNil()), HaveField("Status", metav1.ConditionTrue))) + And(Not(BeNil()), + HaveField("Status", metav1.ConditionTrue), + HaveField("Reason", "ValidationSucceeded"))) }) DescribeTable("reconciles a malformed obo config to Valid=False / InvalidConfig", diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index 3884560e01..aa88160acf 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -236,7 +236,7 @@ MCPExternalAuthConfig resources can be referenced via two paths: **Referenced by MCPServer and MCPRemoteProxy** using `externalAuthConfigRef` or `authServerRef`. -**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 non-negative `cacheSkew`, 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_`) 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). +**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__`, where `` 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). **Controller**: `cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go` diff --git a/docs/arch/10-virtual-mcp-architecture.md b/docs/arch/10-virtual-mcp-architecture.md index c8d536f3d8..c3a0826b3e 100644 --- a/docs/arch/10-virtual-mcp-architecture.md +++ b/docs/arch/10-virtual-mcp-architecture.md @@ -1093,7 +1093,8 @@ Health-check probes carry no user and skip the exchange. A conditional-access or claims challenge fails the backend request and writes an `obo_token_exchange` audit event. OBO works for inline `outgoingAuth` backends, where the operator mounts each config's client secret under -`TOOLHIVE_OBO_CLIENT_SECRET_`, and for discovered backends +`TOOLHIVE_OBO_CLIENT_SECRET__` (a short hash of the +config name keeps names such as `my-cfg` and `my.cfg` distinct), and for discovered backends (MCPServer, MCPRemoteProxy, and MCPServerEntry in the group), where the converter reads the client secret from the referenced Secret. From b36366d3eec40811a44a5dd61d33bcd846a4c5b4 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 19 Nov 2026 12:37:02 -0800 Subject: [PATCH 08/12] Harden OBO tests and error handling Address review findings on the Entra OBO port so the tests fail when the behavior they cover breaks, and tighten a few error paths. Behavior changes: - #18 Classify HTTP 429, HTTP 408 and the OAuth error temporarily_unavailable as transient (the proxy answers 502). - #29 The vMCP strategy no longer returns Entra's error and error_description to MCP clients. It logs the detail server-side and returns a generic error that wraps only the entra sentinel. - #8 The vMCP converter rejects an empty client secret value when it resolves the secret. It also rejects a whitespace-only clientId, as the operator does. - #20 Remove the unused entra.Config and entra.New. Production code uses TokenURL with NewFromTokenURL; the tests now do too. Test hardening: - pkg/auth/obo: #2 provider-mode identities carry an inbound token that must not be used as a fallback; #15 DefaultFactory's skew wiring; #16 audit event table and port-stripped source; #17 test rename, t.Cleanup. - entra: #3 the body-cap test needs truncation to fail; #4 redirect refusal for default and injected clients, 307 and 308; #5 and #21 more classification rows (2xx with an error member, claims-only, AADSTS50079-only, 5xx precedence, lower-case bearer, body read failure, zero and negative expires_in). - cache: #6 timeouts on every blocking wait; #22 coalescing test proves followers join the flight; #23 coalesced error, the exact skew boundary, TTL shorter than skew, WithClock(nil). - pkg/runner: #24 RegisterFactory override reaches the runner, and assert instead of require in the handler. - pkg/vmcp/auth: #7 Authenticate error branches and pinned config-before-health-check order; #27 env.Reader reaches the registered factory; #28 comment fix; #31 and #35 real-builder caching per user and skew; #32 exchanger cache key table; #33 double-checked lock under contention; #34 unset ClientSecretEnv. Cleanup: #14 move NewInteractionRequiredAuditEvent to audit.go; #19 reword the validateTenant comment; #30a comment the strategy's mu and exchangers fields separately; #30b make parseResponse a plain function that takes the receive time. Co-Authored-By: Claude Opus 5.5 --- docs/arch/10-virtual-mcp-architecture.md | 4 +- docs/middleware.md | 2 +- pkg/auth/obo/audit.go | 48 +++ pkg/auth/obo/audit_test.go | 102 +++++ pkg/auth/obo/cache/cache_test.go | 303 ++++++++++--- pkg/auth/obo/cache/doc.go | 2 +- pkg/auth/obo/entra/config_test.go | 130 +++--- pkg/auth/obo/entra/doc.go | 8 +- pkg/auth/obo/entra/errors.go | 5 +- pkg/auth/obo/entra/exchanger.go | 142 +++---- pkg/auth/obo/entra/exchanger_test.go | 275 +++++++++--- pkg/auth/obo/errors.go | 4 +- pkg/auth/obo/middleware.go | 47 +- pkg/auth/obo/middleware_test.go | 128 +++++- pkg/runner/middleware_test.go | 27 +- pkg/vmcp/auth/converters/obo.go | 16 +- pkg/vmcp/auth/converters/obo_test.go | 94 ++++ pkg/vmcp/auth/factory/outgoing_test.go | 4 +- pkg/vmcp/auth/obo.go | 4 +- pkg/vmcp/auth/obo_test.go | 44 ++ pkg/vmcp/auth/strategies/obo.go | 56 ++- pkg/vmcp/auth/strategies/obo_test.go | 519 ++++++++++++++++++++--- 22 files changed, 1539 insertions(+), 425 deletions(-) create mode 100644 pkg/auth/obo/audit.go create mode 100644 pkg/auth/obo/audit_test.go diff --git a/docs/arch/10-virtual-mcp-architecture.md b/docs/arch/10-virtual-mcp-architecture.md index c3a0826b3e..4b217e7319 100644 --- a/docs/arch/10-virtual-mcp-architecture.md +++ b/docs/arch/10-virtual-mcp-architecture.md @@ -1091,7 +1091,9 @@ middleware (`pkg/auth/obo/entra`, `pkg/auth/obo/cache`), keeping one cached exchanger per (token URL, client ID, cache skew, client-secret fingerprint). Health-check probes carry no user and skip the exchange. A conditional-access or claims challenge fails the backend request and writes an -`obo_token_exchange` audit event. OBO works for inline `outgoingAuth` +`obo_token_exchange` audit event. The error returned to the MCP client names +only the failure class (denied, invalid grant, client authentication, or +transient); Entra's error code and description go to the vMCP log instead. OBO works for inline `outgoingAuth` backends, where the operator mounts each config's client secret under `TOOLHIVE_OBO_CLIENT_SECRET__` (a short hash of the config name keeps names such as `my-cfg` and `my.cfg` distinct), and for discovered backends diff --git a/docs/middleware.md b/docs/middleware.md index 57c970f716..9ef1d4e96e 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -526,7 +526,7 @@ body that does not disclose the provider error: | Named upstream provider token missing | 401 with `WWW-Authenticate: Bearer error="invalid_token"` | | Entra `invalid_grant` (subject token rejected) | 401 | | Conditional access, MFA, or claims challenge (`interaction_required`, a `claims` value, AADSTS50076/50079) | 403, plus an `obo_token_exchange` audit event with outcome `denied` | -| `invalid_client`, Entra 5xx or unreachable, or an unclassified failure | 502 | +| `invalid_client`, Entra 5xx, 429, 408 or `temporarily_unavailable` (throttling, classed as transient whatever the body says), unreachable, or an unclassified failure | 502 | | Client cancelled the request | no response | ### 10. Audit Middleware diff --git a/pkg/auth/obo/audit.go b/pkg/auth/obo/audit.go new file mode 100644 index 0000000000..3253a70b9b --- /dev/null +++ b/pkg/auth/obo/audit.go @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package obo + +import ( + "errors" + + "github.com/stacklok/toolhive/pkg/audit" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" +) + +// AuditEventType is the AuditEvent.Type for an OBO exchange decision. The proxy +// middleware and the vMCP strategy both emit it. +const AuditEventType = "obo_token_exchange" + +// NewInteractionRequiredAuditEvent builds the audit event for an OBO exchange +// that Entra refused with a conditional-access or claims challenge. It records +// the denied subject (an identifier, not a credential) and only the +// non-sensitive fields the entra error carries: OAuthError, Description, +// HTTPStatus, and whether a claims challenge was present. It never records the +// user token, the client secret, an issued token, or the raw claims challenge. +// +// Shared by the proxy middleware and the vMCP strategy so both surfaces emit +// the same record shape. identity may be nil. +func NewInteractionRequiredAuditEvent( + source audit.EventSource, component string, identity *auth.Identity, target string, err error, +) *audit.AuditEvent { + var subjects map[string]string + if identity != nil && identity.Subject != "" { + subjects = map[string]string{"sub": identity.Subject} + } + + event := audit.NewAuditEvent(AuditEventType, source, audit.OutcomeDenied, subjects, component). + WithTarget(map[string]string{"audience": target}) + + extra := map[string]any{"reason": "interaction_required"} + var exErr *entra.ExchangeError + if errors.As(err, &exErr) { + extra["oauth_error"] = exErr.OAuthError + extra["description"] = exErr.Description + extra["http_status"] = exErr.HTTPStatus + extra["claims_challenge_present"] = exErr.Claims != "" + } + event.Metadata.Extra = extra + return event +} diff --git a/pkg/auth/obo/audit_test.go b/pkg/auth/obo/audit_test.go new file mode 100644 index 0000000000..12d3081338 --- /dev/null +++ b/pkg/auth/obo/audit_test.go @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package obo + +import ( + "errors" + "fmt" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/stacklok/toolhive/pkg/audit" + "github.com/stacklok/toolhive/pkg/auth" + "github.com/stacklok/toolhive/pkg/auth/obo/entra" +) + +func TestNewInteractionRequiredAuditEvent(t *testing.T) { + t.Parallel() + + const component = "test-component" + source := audit.EventSource{Type: audit.SourceTypeNetwork, Value: "203.0.113.7"} + exErr := &entra.ExchangeError{ + Kind: entra.KindInteractionRequired, + OAuthError: "interaction_required", + Description: "AADSTS50079: proof-up required", + Claims: "CLAIMS-BLOB", + HTTPStatus: http.StatusBadRequest, + } + entraExtra := map[string]any{ + "reason": "interaction_required", + "oauth_error": "interaction_required", + "description": "AADSTS50079: proof-up required", + "http_status": http.StatusBadRequest, + "claims_challenge_present": true, + } + + tests := []struct { + name string + identity *auth.Identity + err error + wantSubjects map[string]string + wantExtra map[string]any + }{ + { + name: "entra error with identity", + identity: &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: "user-123"}}, + err: exErr, + wantSubjects: map[string]string{"sub": "user-123"}, + wantExtra: entraExtra, + }, + { + name: "wrapped entra error is still unwrapped", + identity: &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: "user-123"}}, + err: fmt.Errorf("strategy: %w", exErr), + wantExtra: entraExtra, + wantSubjects: map[string]string{ + "sub": "user-123", + }, + }, + { + name: "nil identity records no subject", + identity: nil, + err: exErr, + wantExtra: entraExtra, + }, + { + name: "identity without a subject records no subject", + identity: &auth.Identity{Token: "USER-TOKEN"}, + err: exErr, + wantExtra: entraExtra, + }, + { + name: "non-entra error records only the reason", + identity: &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: "user-123"}}, + err: errors.New("some other failure"), + wantSubjects: map[string]string{"sub": "user-123"}, + wantExtra: map[string]any{"reason": "interaction_required"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + event := NewInteractionRequiredAuditEvent(source, component, tt.identity, testTarget, tt.err) + + assert.Equal(t, AuditEventType, event.Type) + assert.Equal(t, audit.OutcomeDenied, event.Outcome) + assert.Equal(t, component, event.Component) + assert.Equal(t, source, event.Source) + assert.Equal(t, map[string]string{"audience": testTarget}, event.Target) + if tt.wantSubjects == nil { + assert.Empty(t, event.Subjects) + } else { + assert.Equal(t, tt.wantSubjects, event.Subjects) + } + assert.Equal(t, tt.wantExtra, event.Metadata.Extra) + }) + } +} diff --git a/pkg/auth/obo/cache/cache_test.go b/pkg/auth/obo/cache/cache_test.go index e613115aee..c14c72af45 100644 --- a/pkg/auth/obo/cache/cache_test.go +++ b/pkg/auth/obo/cache/cache_test.go @@ -7,6 +7,8 @@ import ( "context" "errors" "fmt" + "runtime" + "strings" "sync" "sync/atomic" "testing" @@ -66,6 +68,75 @@ func (f *fakeExchanger) callCount() int { return f.calls } +// testTimeout bounds every blocking wait in these tests so a synchronization +// regression fails fast instead of hanging until the global go test timeout. +const testTimeout = 5 * time.Second + +// recv receives one value from ch, failing the test if none arrives within +// testTimeout. Call it only from the test goroutine (it may call t.Fatal). +func recv[T any](t *testing.T, ch <-chan T, what string) T { + t.Helper() + select { + case v := <-ch: + return v + case <-time.After(testTimeout): + t.Fatalf("timed out waiting for %s", what) + var zero T + return zero + } +} + +// waitGroupWithTimeout waits for wg, failing the test if it does not finish +// within testTimeout. Call it only from the test goroutine. +func waitGroupWithTimeout(t *testing.T, wg *sync.WaitGroup) { + t.Helper() + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + recv(t, done, "goroutines to finish") +} + +// errBlockTimedOut is returned by a delegate whose test barrier was never +// released; it turns a hung test into a visible failure. +var errBlockTimedOut = errors.New("test barrier was never released") + +// awaitRelease blocks a delegate until release is closed, giving up after +// testTimeout. It runs on the cache's detached exchange goroutine, where t.Fatal +// is not allowed, so it reports the timeout as an error instead. +func awaitRelease(release <-chan struct{}) error { + select { + case <-release: + return nil + case <-time.After(testTimeout): + return errBlockTimedOut + } +} + +// goroutinesWaitingOnFlight counts goroutines parked in waitFor whose stack +// also names testName. Filtering by the test function keeps parallel tests in +// this package from inflating the count. It observes the scheduler rather than +// production internals, so no test hook is needed in Cache. +func goroutinesWaitingOnFlight(testName string) int { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + buf = buf[:n] + break + } + buf = make([]byte, 2*len(buf)) + } + count := 0 + for _, g := range strings.Split(string(buf), "\n\n") { + if strings.Contains(g, "cache.waitFor(") && strings.Contains(g, testName) { + count++ + } + } + return count +} + func TestCache_ServesCachedTokenWithinTTL(t *testing.T) { t.Parallel() @@ -86,37 +157,118 @@ func TestCache_ServesCachedTokenWithinTTL(t *testing.T) { assert.Equal(t, 1, fake.callCount(), "second call must be served from the cache") } -func TestCache_ReExchangesAfterExpiry(t *testing.T) { +// TestCache_FreshnessBoundary pins when a cached token stops being served: it +// is fresh strictly before expiry-skew and stale from that instant on. Each row +// exchanges once at base, advances the clock, and exchanges again. +func TestCache_FreshnessBoundary(t *testing.T) { t.Parallel() - clock := newFakeClock() - const ttl = 100 * time.Second - fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, call int) (exchange.Token, error) { - return exchange.Token{ - AccessToken: fmt.Sprintf("tok-%d", call), - Expiry: clock.now().Add(ttl), - }, nil - }} - c := New(fake, WithClock(clock.now)) // default 60s skew → stale at base+40s + tests := []struct { + name string + ttl time.Duration + opts []Option + advance time.Duration + wantCalls int + wantToken string + }{ + { + // Default 60s skew on a 100s token: stale from base+40s. + name: "default skew, just before the window", + ttl: 100 * time.Second, + advance: 39 * time.Second, + wantCalls: 1, + wantToken: "tok-1", + }, + { + name: "default skew, exactly at expiry minus skew", + ttl: 100 * time.Second, + advance: 40 * time.Second, + wantCalls: 2, + wantToken: "tok-2", + }, + { + name: "default skew, inside the window", + ttl: 100 * time.Second, + advance: 45 * time.Second, + wantCalls: 2, + wantToken: "tok-2", + }, + { + name: "custom skew, exactly at expiry minus skew", + ttl: 100 * time.Second, + opts: []Option{WithSkew(10 * time.Second)}, + advance: 90 * time.Second, + wantCalls: 2, + wantToken: "tok-2", + }, + { + name: "custom skew, just before expiry minus skew", + ttl: 100 * time.Second, + opts: []Option{WithSkew(10 * time.Second)}, + advance: 89 * time.Second, + wantCalls: 1, + wantToken: "tok-1", + }, + { + // A token whose whole lifetime is inside the skew is never served + // from the cache, even with no time passing. + name: "TTL shorter than skew is never reused", + ttl: 30 * time.Second, + advance: 0, + wantCalls: 2, + wantToken: "tok-2", + }, + { + name: "zero skew serves until expiry", + ttl: 100 * time.Second, + opts: []Option{WithSkew(0)}, + advance: 99 * time.Second, + wantCalls: 1, + wantToken: "tok-1", + }, + } - v, err := c.Exchange(t.Context(), "user", "aud") - require.NoError(t, err) - assert.Equal(t, "tok-1", v) - assert.Equal(t, 1, fake.callCount()) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + clock := newFakeClock() + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, call int) (exchange.Token, error) { + return exchange.Token{AccessToken: fmt.Sprintf("tok-%d", call), Expiry: clock.now().Add(tt.ttl)}, nil + }} + c := New(fake, append([]Option{WithClock(clock.now)}, tt.opts...)...) + + v, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok-1", v) + + clock.advance(tt.advance) + v, err = c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, tt.wantToken, v) + assert.Equal(t, tt.wantCalls, fake.callCount()) + }) + } +} - // Still fresh just before the skew window opens. - clock.advance(39 * time.Second) // now base+39s, threshold base+40s - v, err = c.Exchange(t.Context(), "user", "aud") - require.NoError(t, err) - assert.Equal(t, "tok-1", v) - assert.Equal(t, 1, fake.callCount()) +// TestWithClock_NilKeepsWallClock verifies a nil clock is ignored rather than +// installed (which would panic on the first lookup), and that the retained +// wall clock still drives caching. +func TestWithClock_NilKeepsWallClock(t *testing.T) { + t.Parallel() - // Inside the skew window the token is treated as stale and re-exchanged. - clock.advance(6 * time.Second) // now base+45s, past base+40s - v, err = c.Exchange(t.Context(), "user", "aud") - require.NoError(t, err) - assert.Equal(t, "tok-2", v) - assert.Equal(t, 2, fake.callCount()) + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + return exchange.Token{AccessToken: "tok", Expiry: time.Now().Add(time.Hour)}, nil + }} + c := New(fake, WithClock(nil)) + require.NotNil(t, c.now) + + for range 2 { + v, err := c.Exchange(t.Context(), "user", "aud") + require.NoError(t, err) + assert.Equal(t, "tok", v) + } + assert.Equal(t, 1, fake.callCount(), "the second call must be served from the cache") } func TestCache_PartitionsByUserToken(t *testing.T) { @@ -228,7 +380,7 @@ func TestCache_ConcurrentExchangesAreRaceFree(t *testing.T) { assert.Equal(t, "tok:"+user+":"+aud, got) }(i) } - wg.Wait() + waitGroupWithTimeout(t, &wg) } // TestCache_StarterCancellationDoesNotPoisonOthers verifies the detached-exchange @@ -244,7 +396,9 @@ func TestCache_StarterCancellationDoesNotPoisonOthers(t *testing.T) { proceed := make(chan struct{}) fake := &fakeExchanger{fn: func(ctx context.Context, _, _ string, _ int) (exchange.Token, error) { entered <- struct{}{} - <-proceed + if err := awaitRelease(proceed); err != nil { + return exchange.Token{}, err + } // The shared exchange must not inherit the starter's cancellation. if err := ctx.Err(); err != nil { return exchange.Token{}, err @@ -260,7 +414,7 @@ func TestCache_StarterCancellationDoesNotPoisonOthers(t *testing.T) { _, err := c.Exchange(starterCtx, "user", "aud") starterErr <- err }() - <-entered // the detached exchange has begun + recv(t, entered, "the detached exchange to begin") // A second caller with a healthy context coalesces onto the same exchange. followerTok := make(chan string, 1) @@ -272,57 +426,104 @@ func TestCache_StarterCancellationDoesNotPoisonOthers(t *testing.T) { // Cancelling the starter releases it promptly with its own error... cancelStarter() - assert.ErrorIs(t, <-starterErr, context.Canceled) + assert.ErrorIs(t, recv(t, starterErr, "the starter to return"), context.Canceled) // ...while the shared exchange completes and the follower still succeeds. close(proceed) - assert.Equal(t, "shared", <-followerTok) + assert.Equal(t, "shared", recv(t, followerTok, "the follower's token")) assert.Equal(t, 1, fake.callCount(), "the cancellation must not trigger a second exchange") } +// TestCache_CoalescesConcurrentMissesForSameKey proves followers join the +// leader's flight rather than racing past it: the delegate is held open until +// every caller is provably parked in waitFor, and only then released. Were the +// in-flight map removed, each parked caller would own a separate flight and the +// delegate would run once per caller. func TestCache_CoalescesConcurrentMissesForSameKey(t *testing.T) { t.Parallel() - const followers = 16 + const callers = 17 clock := newFakeClock() - // Buffered past the expected count so a (broken) extra exchange cannot - // deadlock on the signal — it would surface as a failed call-count assert. - entered := make(chan struct{}, followers+1) release := make(chan struct{}) var calls atomic.Int32 fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { calls.Add(1) - entered <- struct{}{} - <-release // hold the in-flight exchange open while followers pile up + // Hold the exchange open while the other callers pile up. + if err := awaitRelease(release); err != nil { + return exchange.Token{}, err + } return exchange.Token{AccessToken: "shared", Expiry: clock.now().Add(time.Hour)}, nil }} c := New(fake, WithClock(clock.now)) ctx := t.Context() - results := make(chan string, followers+1) - doExchange := func() { - v, err := c.Exchange(ctx, "user", "aud") - assert.NoError(t, err) - results <- v + results := make(chan string, callers) + for range callers { + go func() { + v, err := c.Exchange(ctx, "user", "aud") + assert.NoError(t, err) + results <- v + }() } - go doExchange() // leader - <-entered // leader is registered in-flight and inside the delegate - - for i := 0; i < followers; i++ { - go doExchange() // each joins the leader's in-flight exchange - } + // Every caller is parked on a flight before any flight can finish, so none + // of them can be served from a cache entry the leader wrote. + require.Eventually(t, func() bool { + return goroutinesWaitingOnFlight(t.Name()) == callers + }, testTimeout, 5*time.Millisecond, "all callers must be waiting on an in-flight exchange") - close(release) // let the single exchange complete; everyone shares its result + close(release) - for i := 0; i < followers+1; i++ { - assert.Equal(t, "shared", <-results) + for range callers { + assert.Equal(t, "shared", recv(t, results, "a caller's result")) } assert.Equal(t, int32(1), calls.Load(), "concurrent misses for one key must collapse to a single underlying exchange") } +// TestCache_CoalescedErrorReachesEveryCaller verifies a failed shared exchange +// hands its error to every coalesced caller and caches nothing. +func TestCache_CoalescedErrorReachesEveryCaller(t *testing.T) { + t.Parallel() + + const callers = 8 + sentinel := errors.New("delegate boom") + release := make(chan struct{}) + fake := &fakeExchanger{fn: func(_ context.Context, _, _ string, _ int) (exchange.Token, error) { + if err := awaitRelease(release); err != nil { + return exchange.Token{}, err + } + return exchange.Token{}, sentinel + }} + c := New(fake) + + ctx := t.Context() + errs := make(chan error, callers) + for range callers { + go func() { + _, err := c.Exchange(ctx, "user", "aud") + errs <- err + }() + } + + require.Eventually(t, func() bool { + return goroutinesWaitingOnFlight(t.Name()) == callers + }, testTimeout, 5*time.Millisecond, "all callers must be waiting on the in-flight exchange") + + close(release) + + for range callers { + assert.ErrorIs(t, recv(t, errs, "a caller's error"), sentinel) + } + assert.Equal(t, 1, fake.callCount(), "the failed exchange is shared, not repeated per caller") + + c.mu.Lock() + defer c.mu.Unlock() + assert.Empty(t, c.entries, "a failed exchange caches nothing") + assert.Empty(t, c.inflight, "the in-flight slot is freed after a failure") +} + // TestCache_JoinsExistingInflight deterministically exercises the single-flight // join path: a caller that finds an in-flight exchange for its key waits for and // shares that result instead of calling the delegate. It seeds the unexported diff --git a/pkg/auth/obo/cache/doc.go b/pkg/auth/obo/cache/doc.go index 42b5f7c42c..611eec21b0 100644 --- a/pkg/auth/obo/cache/doc.go +++ b/pkg/auth/obo/cache/doc.go @@ -13,7 +13,7 @@ // // Typical wiring: // -// exchanger, err := entra.New(cfg) +// exchanger, err := entra.NewFromTokenURL(tokenURL, clientID, clientSecret, nil) // if err != nil { ... } // var oboExchanger exchange.Exchanger = cache.New(exchanger) // diff --git a/pkg/auth/obo/entra/config_test.go b/pkg/auth/obo/entra/config_test.go index 8a4d784519..36f0ef4c4b 100644 --- a/pkg/auth/obo/entra/config_test.go +++ b/pkg/auth/obo/entra/config_test.go @@ -13,124 +13,102 @@ import ( "github.com/stacklok/toolhive/pkg/auth/obo/entra" ) -func TestNew_ValidConfigs(t *testing.T) { +func TestTokenURL_Valid(t *testing.T) { t.Parallel() tests := []struct { - name string - cfg entra.Config + name string + tenantID string + authority string + want string }{ { - name: "domain tenant with default authority", - cfg: entra.Config{TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret}, + name: "domain tenant with default authority", + tenantID: testTenant, + want: "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", }, { - name: "GUID tenant", - cfg: entra.Config{ - TenantID: "72f988bf-86f1-41af-91ab-2d7cd011db47", ClientID: testClientID, ClientSecret: testClientSecret, - }, + name: "GUID tenant", + tenantID: "72f988bf-86f1-41af-91ab-2d7cd011db47", + want: "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token", }, { - name: "explicit https authority", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "https://login.microsoftonline.us", - }, + name: "tenant is trimmed", + tenantID: " " + testTenant + " ", + want: "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", }, { - name: "loopback http authority permitted for tests", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "http://127.0.0.1:8080", - }, + name: "explicit https authority", + tenantID: testTenant, + authority: "https://login.microsoftonline.us", + want: "https://login.microsoftonline.us/contoso.onmicrosoft.com/oauth2/v2.0/token", + }, + { + name: "loopback http authority permitted for tests", + tenantID: testTenant, + authority: "http://127.0.0.1:8080", + want: "http://127.0.0.1:8080/contoso.onmicrosoft.com/oauth2/v2.0/token", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - ex, err := entra.New(tt.cfg) + got, err := entra.TokenURL(tt.tenantID, tt.authority) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + + // Every URL TokenURL derives must be accepted by NewFromTokenURL. + ex, err := entra.NewFromTokenURL(got, testClientID, testClientSecret, nil) require.NoError(t, err) assert.NotNil(t, ex) }) } } -func TestNew_InvalidConfigs(t *testing.T) { +func TestTokenURL_Invalid(t *testing.T) { t.Parallel() tests := []struct { - name string - cfg entra.Config + name string + tenantID string + authority string + wantErr string }{ + {name: "missing tenant", tenantID: "", wantErr: "TenantID is required"}, + {name: "whitespace tenant", tenantID: " ", wantErr: "TenantID is required"}, + {name: "tenant with path separator", tenantID: "tenant/../evil", wantErr: "GUID or a domain"}, + {name: "tenant that is neither GUID nor domain", tenantID: "not a real tenant", wantErr: "GUID or a domain"}, + {name: "single-label tenant", tenantID: "contoso", wantErr: "GUID or a domain"}, + {name: "tenant longer than the DNS limit", tenantID: strings.Repeat("a", 254), wantErr: "at most 253"}, { - name: "missing tenant", - cfg: entra.Config{ClientID: testClientID, ClientSecret: testClientSecret}, - }, - { - name: "missing client id", - cfg: entra.Config{TenantID: testTenant, ClientSecret: testClientSecret}, - }, - { - name: "missing client secret", - cfg: entra.Config{TenantID: testTenant, ClientID: testClientID}, - }, - { - name: "tenant with path separator", - cfg: entra.Config{TenantID: "tenant/../evil", ClientID: testClientID, ClientSecret: testClientSecret}, + name: "non-https authority scheme", tenantID: testTenant, + authority: "ftp://login.microsoftonline.com", wantErr: "Authority scheme must be https", }, { - name: "tenant that is neither GUID nor domain", - cfg: entra.Config{TenantID: "not a real tenant", ClientID: testClientID, ClientSecret: testClientSecret}, + name: "non-loopback http authority", tenantID: testTenant, + authority: "http://login.microsoftonline.com", wantErr: "http allowed only for loopback", }, { - name: "single-label tenant", - cfg: entra.Config{TenantID: "contoso", ClientID: testClientID, ClientSecret: testClientSecret}, + name: "authority with fragment", tenantID: testTenant, + authority: "https://login.microsoftonline.com/#frag", wantErr: "must not contain a fragment", }, { - name: "tenant longer than the DNS limit", - cfg: entra.Config{ - TenantID: strings.Repeat("a", 254), ClientID: testClientID, ClientSecret: testClientSecret, - }, + name: "authority with query string", tenantID: testTenant, + authority: "https://login.microsoftonline.com/?foo=bar", wantErr: "must not contain a query string", }, { - name: "non-https authority scheme", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "ftp://login.microsoftonline.com", - }, - }, - { - name: "non-loopback http authority", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "http://login.microsoftonline.com", - }, - }, - { - name: "authority with fragment", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "https://login.microsoftonline.com/#frag", - }, - }, - { - name: "authority with query string", - cfg: entra.Config{ - TenantID: testTenant, ClientID: testClientID, ClientSecret: testClientSecret, - Authority: "https://login.microsoftonline.com/?foo=bar", - }, + name: "authority without host", tenantID: testTenant, + authority: "https:///", wantErr: "Authority must include a host", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - ex, err := entra.New(tt.cfg) - require.Error(t, err) - assert.Nil(t, ex) - // Validation errors never echo the client secret. - assert.NotContains(t, err.Error(), testClientSecret) + got, err := entra.TokenURL(tt.tenantID, tt.authority) + require.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, got) }) } } diff --git a/pkg/auth/obo/entra/doc.go b/pkg/auth/obo/entra/doc.go index d7dc6bdb92..8a39145454 100644 --- a/pkg/auth/obo/entra/doc.go +++ b/pkg/auth/obo/entra/doc.go @@ -11,11 +11,9 @@ // wrap it in the sibling cache package to add session-partitioned token // caching: // -// exchanger, err := entra.New(entra.Config{ -// TenantID: "", -// ClientID: "", -// ClientSecret: "", -// }) +// tokenURL, err := entra.TokenURL("", "") // "" = public Entra authority +// if err != nil { ... } +// exchanger, err := entra.NewFromTokenURL(tokenURL, "", "", nil) // if err != nil { ... } // var oboExchanger exchange.Exchanger = cache.New(exchanger) // diff --git a/pkg/auth/obo/entra/errors.go b/pkg/auth/obo/entra/errors.go index a0c02434dd..0b74420127 100644 --- a/pkg/auth/obo/entra/errors.go +++ b/pkg/auth/obo/entra/errors.go @@ -37,8 +37,9 @@ var ( // permanent configuration error until the operator fixes the credentials. ErrInvalidClient = errors.New("entra obo: client authentication failed") - // ErrTransient indicates a retryable failure — a 5xx from the token endpoint - // or a transport-level error reaching it. Callers may retry with backoff. + // ErrTransient indicates a retryable failure — a 5xx, 429 or 408 from the + // token endpoint, an OAuth "temporarily_unavailable" error, or a + // transport-level error reaching it. Callers may retry with backoff. ErrTransient = errors.New("entra obo: transient token endpoint failure") ) diff --git a/pkg/auth/obo/entra/exchanger.go b/pkg/auth/obo/entra/exchanger.go index a8b700c26c..9a4b69f852 100644 --- a/pkg/auth/obo/entra/exchanger.go +++ b/pkg/auth/obo/entra/exchanger.go @@ -38,7 +38,7 @@ const ( const ( // defaultAuthority is the public Microsoft Entra (Azure AD) authority. It is - // overridable via Config.Authority for sovereign clouds and tests. + // overridable via TokenURL's authority argument for sovereign clouds and tests. defaultAuthority = "https://login.microsoftonline.com" // tokenEndpointPath is the v2.0 token endpoint path appended after the tenant. @@ -76,34 +76,6 @@ var caInteractionCodes = map[int]struct{}{ 50079: {}, // AADSTS50079: MFA enrolment required (proof-up). } -// Config is the Microsoft Entra confidential-client configuration for the OBO -// exchange. v1 supports client_secret authentication only; certificate and -// workload-identity client auth are planned fast-follows. -type Config struct { - // TenantID is the Entra tenant (directory) — a GUID or a verified domain. - // Required. - TenantID string - - // ClientID is the confidential client's application (client) ID. Required. - ClientID string - - // ClientSecret is the confidential client's secret. Required in v1. - ClientSecret string //nolint:gosec // G101: field name, not a hardcoded credential. - - // Authority overrides the Entra authority base URL. Defaults to - // https://login.microsoftonline.com. Must be https, except http is allowed - // for loopback hosts so tests can point at an httptest server. - Authority string - - // HTTPClient is the HTTP client used for the exchange. When nil, a client - // with a sane default timeout that refuses redirects is used. A - // caller-injected client SHOULD likewise refuse redirects: the request body - // carries client_secret and the user assertion, which Go replays on a - // 307/308 — including to a different host. A legitimate Entra token endpoint - // never redirects. - HTTPClient *http.Client -} - // Exchanger performs the Microsoft Entra on-behalf-of token exchange. It // implements both exchange.Exchanger (token string only) and exchange.TokenExchanger // (token plus expiry, consumed by the caching layer). @@ -125,33 +97,8 @@ var ( _ exchange.TokenExchanger = (*Exchanger)(nil) ) -// New validates cfg and returns an Exchanger. It fails loudly on missing -// required fields or a malformed authority rather than deferring the failure to -// the first exchange. Configuration errors are returned as plain errors, not as -// *ExchangeError (which classifies exchange-time failures only). -func New(cfg Config) (*Exchanger, error) { - tokenURL, err := TokenURL(cfg.TenantID, cfg.Authority) - if err != nil { - return nil, err - } - if strings.TrimSpace(cfg.ClientID) == "" { - return nil, fmt.Errorf("entra obo: ClientID is required") - } - if cfg.ClientSecret == "" { - return nil, fmt.Errorf("entra obo: ClientSecret is required") - } - - return &Exchanger{ - tokenURL: tokenURL, - clientID: cfg.ClientID, - clientSecret: cfg.ClientSecret, - httpClient: newHTTPClient(cfg.HTTPClient), - }, nil -} - // TokenURL builds and validates the Entra v2.0 on-behalf-of token endpoint for a -// tenant, applying exactly the rules New uses so the URL it returns is one -// NewFromTokenURL (the proxy-runtime constructor) will also accept. The operator's +// tenant. The URL it returns is one NewFromTokenURL will accept. The operator's // OBO validation calls this to derive the runtime contract's tokenUrl from the // CRD's tenantId (and optional authority) rather than re-spelling Entra's // authority/tenant/path structure — keeping that structure defined in one place. @@ -172,7 +119,7 @@ func TokenURL(tenantID, authority string) (string, error) { if authority == "" { authority = defaultAuthority } - if err := validateAuthority(authority); err != nil { + if err := validateHTTPSURL(authority, "Authority"); err != nil { return "", err } @@ -184,18 +131,21 @@ func TokenURL(tenantID, authority string) (string, error) { } // NewFromTokenURL returns an Exchanger that posts the OBO exchange to a -// fully-formed tenant token endpoint. It is the constructor for callers that -// already hold the complete token URL — notably the proxy-runtime middleware, -// which receives tokenURL verbatim from the obo.MiddlewareParameters -// contract and must not re-derive Entra's authority/tenant URL structure. -// Use New instead when the caller holds an authority + tenant pair. +// fully-formed tenant token endpoint. Callers that hold a tenant + authority pair +// derive the endpoint with TokenURL first; the proxy-runtime middleware receives +// tokenURL verbatim from the obo.MiddlewareParameters contract and must not +// re-derive Entra's authority/tenant URL structure. It fails loudly on missing +// required fields or a malformed URL rather than deferring the failure to the +// first exchange. // -// tokenURL is validated exactly as New validates its derived endpoint: an -// absolute https URL (http permitted only for loopback hosts, so tests can point -// at an httptest server), with a host and no query string or fragment. clientID -// and clientSecret are required. A nil httpClient gets the same redirect-refusing -// default New uses. Configuration errors are returned as plain errors, not as -// *ExchangeError (which classifies exchange-time failures only). +// tokenURL must be an absolute https URL (http permitted only for loopback +// hosts, so tests can point at an httptest server), with a host and no query +// string or fragment. clientID and clientSecret are required (v1 supports +// client_secret authentication only). A nil httpClient gets a default client +// with a bounded timeout; an injected client is used for its transport and +// timeout. Either way redirects are refused (see newHTTPClient). Configuration +// errors are returned as plain errors, not as *ExchangeError (which classifies +// exchange-time failures only). // // SECURITY: tokenURL is a trust boundary. The exchange POSTs the client secret // and the end-user assertion in the request body to tokenURL, so the caller must @@ -203,9 +153,9 @@ func TokenURL(tenantID, authority string) (string, error) { // from operator-controlled configuration (the obo.MiddlewareParameters contract), never // from end-user input, and the unconditional redirect guard (see newHTTPClient) // stops a 3xx from replaying that body to another host. This constructor -// intentionally does NOT allowlist hosts or enforce a path shape: New already -// trusts an operator-supplied Authority for arbitrary hosts (sovereign clouds), -// and a hard allowlist would reject legitimate sovereign / B2C / CIAM endpoints +// intentionally does NOT allowlist hosts or enforce a path shape: TokenURL +// already trusts an operator-supplied authority for arbitrary hosts (sovereign +// clouds), and a hard allowlist would reject legitimate sovereign / B2C / CIAM endpoints // (which use different hosts and token paths) while giving only false assurance. func NewFromTokenURL(tokenURL, clientID, clientSecret string, httpClient *http.Client) (*Exchanger, error) { if strings.TrimSpace(tokenURL) == "" { @@ -237,7 +187,8 @@ func NewFromTokenURL(tokenURL, clientID, clientSecret string, httpClient *http.C // // An injected client is shallow-copied so its Transport/Timeout/Jar are // preserved while CheckRedirect is overridden, and the caller's own *http.Client -// is never mutated (it may be shared). The copy is a snapshot taken at New time. +// is never mutated (it may be shared). The copy is a snapshot taken at +// construction time. func newHTTPClient(injected *http.Client) *http.Client { if injected == nil { return &http.Client{Timeout: defaultHTTPTimeout, CheckRedirect: refuseRedirects} @@ -255,8 +206,8 @@ func refuseRedirects(*http.Request, []*http.Request) error { // validateTenant accepts an Entra tenant identifier in the two forms the v2.0 // endpoint uses — a directory GUID or a verified domain — capped at the DNS name -// length. It rejects junk (including the path metacharacters the previous, -// looser check caught) at wiring time. +// length. Anything else, including path metacharacters such as "/" or "..", is +// rejected at wiring time. func validateTenant(tenant string) error { if len(tenant) > maxTenantLen { return fmt.Errorf("entra obo: TenantID must be at most %d characters", maxTenantLen) @@ -301,7 +252,7 @@ func (e *Exchanger) ExchangeToken(ctx context.Context, userToken, audience strin req, err := e.buildRequest(ctx, userToken, audience) if err != nil { - // Unreachable for a New-built Exchanger (the endpoint was validated), but + // Unreachable for a constructed Exchanger (the endpoint was validated), but // classified rather than panicked on if it ever happens. return exchange.Token{}, &ExchangeError{Kind: KindTransient, Description: "unable to build the token request"} } @@ -332,12 +283,12 @@ func (e *Exchanger) ExchangeToken(ctx context.Context, userToken, audience strin } } - return e.parseResponse(resp.StatusCode, body) + return parseResponse(resp.StatusCode, body, time.Now()) } // buildRequest assembles the Entra OBO POST. The subject token and client // secret travel in the form body only. It returns an error rather than papering -// over a request-build failure: New validated the endpoint, so this is +// over a request-build failure: the constructor validated the endpoint, so this is // unreachable in practice, but the caller classifies any failure instead of // risking a nil-pointer dereference. func (e *Exchanger) buildRequest(ctx context.Context, userToken, audience string) (*http.Request, error) { @@ -374,10 +325,10 @@ type tokenResponse struct { Claims string `json:"claims"` } -// parseResponse turns a decoded token endpoint reply into a Token or a typed -// error. It is a method only so the success path can stamp the expiry against -// the wall clock; it holds no per-request state. -func (*Exchanger) parseResponse(status int, body []byte) (exchange.Token, error) { +// parseResponse turns a token endpoint reply into a Token or a typed error. now +// is the instant the reply was received; a positive expires_in is added to it to +// stamp the token's expiry. +func parseResponse(status int, body []byte, now time.Time) (exchange.Token, error) { var tr tokenResponse if err := json.Unmarshal(body, &tr); err != nil { // Unparsable body: classify by status alone, without echoing the body. @@ -418,21 +369,24 @@ func (*Exchanger) parseResponse(status int, body []byte) (exchange.Token, error) var expiry time.Time if tr.ExpiresIn > 0 { - expiry = time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second) + expiry = now.Add(time.Duration(tr.ExpiresIn) * time.Second) } return exchange.Token{AccessToken: tr.AccessToken, Expiry: expiry}, nil } -// classifyHTTPError maps an Entra error reply onto an *ExchangeError. A 5xx is -// transient regardless of body; otherwise the OAuth error code and claims -// challenge drive the classification. +// classifyHTTPError maps an Entra error reply onto an *ExchangeError. A 5xx, a +// 429 (throttled) or a 408 (request timeout) is transient regardless of body; +// otherwise the OAuth error code and claims challenge drive the classification, +// with RFC 6749's "temporarily_unavailable" also treated as transient. func classifyHTTPError(status int, tr *tokenResponse) *ExchangeError { kind := func() ErrorKind { switch { - case status >= http.StatusInternalServerError: + case isTransientStatus(status): return KindTransient case isInteractionRequired(tr): return KindInteractionRequired + case tr.Error == "temporarily_unavailable": + return KindTransient case tr.Error == "invalid_grant": return KindInvalidGrant case tr.Error == "invalid_client" || tr.Error == "unauthorized_client": @@ -451,6 +405,14 @@ func classifyHTTPError(status int, tr *tokenResponse) *ExchangeError { } } +// isTransientStatus reports whether an HTTP status marks a retryable token +// endpoint failure: any 5xx, 429 Too Many Requests, or 408 Request Timeout. +func isTransientStatus(status int) bool { + return status >= http.StatusInternalServerError || + status == http.StatusTooManyRequests || + status == http.StatusRequestTimeout +} + // isInteractionRequired reports whether an Entra error reply is a // conditional-access / MFA / claims challenge. The canonical signals are the // "interaction_required" OAuth error and a non-empty claims challenge; the @@ -467,17 +429,11 @@ func isInteractionRequired(tr *tokenResponse) bool { return false } -// validateAuthority enforces that the authority is an absolute https URL (http -// permitted only for loopback hosts, so tests can use httptest), with a host and -// no fragment or query string. -func validateAuthority(raw string) error { - return validateHTTPSURL(raw, "Authority") -} - // validateHTTPSURL enforces that raw is an absolute https URL (http permitted // only for loopback hosts, so tests can use httptest), with a host and no // fragment or query string. label names the field in error messages so the same -// check serves both the authority (New) and the full token URL (NewFromTokenURL). +// check serves both the authority (TokenURL) and the full token URL +// (NewFromTokenURL). func validateHTTPSURL(raw, label string) error { u, err := url.Parse(raw) if err != nil { diff --git a/pkg/auth/obo/entra/exchanger_test.go b/pkg/auth/obo/entra/exchanger_test.go index 0073494dfd..cfc81a0e5a 100644 --- a/pkg/auth/obo/entra/exchanger_test.go +++ b/pkg/auth/obo/entra/exchanger_test.go @@ -34,15 +34,20 @@ const ( successResponseExpires = 3599 ) -// newTestExchanger returns an Exchanger pointed at authority (an httptest URL). +// newTestExchanger returns an Exchanger for testTenant at authority (an +// httptest URL), wired the way production wires it: TokenURL derives the +// endpoint and NewFromTokenURL builds the exchanger. func newTestExchanger(t *testing.T, authority string) *entra.Exchanger { t.Helper() - ex, err := entra.New(entra.Config{ - TenantID: testTenant, - ClientID: testClientID, - ClientSecret: testClientSecret, - Authority: authority, - }) + return newTestExchangerWithClient(t, authority, nil) +} + +// newTestExchangerWithClient is newTestExchanger with an injected HTTP client. +func newTestExchangerWithClient(t *testing.T, authority string, client *http.Client) *entra.Exchanger { + t.Helper() + tokenURL, err := entra.TokenURL(testTenant, authority) + require.NoError(t, err) + ex, err := entra.NewFromTokenURL(tokenURL, testClientID, testClientSecret, client) require.NoError(t, err) return ex } @@ -134,20 +139,59 @@ func TestExchanger_Exchange_PropagatesError(t *testing.T) { assert.ErrorIs(t, err, entra.ErrInvalidGrant) } -func TestExchanger_ExchangeToken_NoExpiryWhenExpiresInAbsent(t *testing.T) { +// TestExchanger_ExchangeToken_SuccessVariants pins how the success path treats +// expires_in values that do not yield a usable expiry, and the case-insensitive +// token_type check. +func TestExchanger_ExchangeToken_SuccessVariants(t *testing.T) { t.Parallel() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"token_type":"Bearer","access_token":"`+testAccessToken+`"}`) - })) - t.Cleanup(srv.Close) + tests := []struct { + name string + body string + wantZeroExpiry bool + }{ + { + name: "missing expires_in yields a zero expiry", + body: `{"token_type":"Bearer","access_token":"` + testAccessToken + `"}`, + wantZeroExpiry: true, + }, + { + name: "zero expires_in yields a zero expiry", + body: `{"token_type":"Bearer","expires_in":0,"access_token":"` + testAccessToken + `"}`, + wantZeroExpiry: true, + }, + { + name: "negative expires_in yields a zero expiry", + body: `{"token_type":"Bearer","expires_in":-30,"access_token":"` + testAccessToken + `"}`, + wantZeroExpiry: true, + }, + { + name: "lower-case bearer token_type is accepted", + body: `{"token_type":"bearer","expires_in":3599,"access_token":"` + testAccessToken + `"}`, + }, + } - ex := newTestExchanger(t, srv.URL) - tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) - require.NoError(t, err) - assert.Equal(t, testAccessToken, tok.AccessToken) - assert.True(t, tok.Expiry.IsZero(), "missing expires_in yields a zero (non-cacheable) expiry") + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, tt.body) + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + require.NoError(t, err) + assert.Equal(t, testAccessToken, tok.AccessToken) + if tt.wantZeroExpiry { + assert.True(t, tok.Expiry.IsZero(), "a non-positive or absent expires_in yields a zero (non-cacheable) expiry") + } else { + assert.WithinDuration(t, time.Now().Add(3599*time.Second), tok.Expiry, 5*time.Second) + } + }) + } } func TestExchanger_ExchangeToken_Failures(t *testing.T) { @@ -239,6 +283,72 @@ func TestExchanger_ExchangeToken_Failures(t *testing.T) { wantKind: entra.KindUnknown, wantSentinel: nil, }, + { + name: "interaction required via claims challenge alone", + status: http.StatusBadRequest, + body: `{"claims":"{\"access_token\":{\"acrs\":{\"essential\":true}}}"}`, + wantKind: entra.KindInteractionRequired, + wantSentinel: entra.ErrInteractionRequired, + wantClaims: `{"access_token":{"acrs":{"essential":true}}}`, + }, + { + name: "interaction required via AADSTS50079 alone", + status: http.StatusBadRequest, + body: `{"error_codes":[50079]}`, + wantKind: entra.KindInteractionRequired, + wantSentinel: entra.ErrInteractionRequired, + }, + { + name: "5xx takes precedence over an interaction_required body", + status: http.StatusServiceUnavailable, + body: `{"error":"interaction_required","claims":"c"}`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + wantClaims: "c", + }, + { + name: "429 throttling is transient even with an invalid_grant body", + status: http.StatusTooManyRequests, + body: `{"error":"invalid_grant","error_description":"AADSTS50196: loop detected"}`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "408 request timeout is transient", + status: http.StatusRequestTimeout, + body: `{"error":"invalid_client"}`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "temporarily_unavailable on a 4xx is transient", + status: http.StatusBadRequest, + body: `{"error":"temporarily_unavailable","error_description":"AADSTS90033: transient"}`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "2xx with interaction_required error and claims", + status: http.StatusOK, + body: `{"error":"interaction_required","claims":"c"}`, + wantKind: entra.KindInteractionRequired, + wantSentinel: entra.ErrInteractionRequired, + wantClaims: "c", + }, + { + name: "2xx with invalid_grant error", + status: http.StatusOK, + body: `{"error":"invalid_grant","error_description":"AADSTS50013"}`, + wantKind: entra.KindInvalidGrant, + wantSentinel: entra.ErrInvalidGrant, + }, + { + name: "2xx with an error field and an access_token is still a failure", + status: http.StatusOK, + body: `{"error":"invalid_client","token_type":"Bearer","expires_in":3599,"access_token":"` + testAccessToken + `"}`, + wantKind: entra.KindInvalidClient, + wantSentinel: entra.ErrInvalidClient, + }, { name: "malformed 2xx JSON body", status: http.StatusOK, @@ -294,13 +404,13 @@ func TestExchanger_ExchangeToken_Failures(t *testing.T) { func TestExchanger_ExchangeToken_CapsResponseBody(t *testing.T) { t.Parallel() - // A >1 MiB body whose valid-JSON prefix is followed by megabytes of padding. - // The 1 MiB LimitReader truncates it mid-stream, so the decode fails and the - // result is classified as a malformed (unknown) response rather than hanging - // or exhausting memory. + // A >1 MiB body that, read in full, is a valid success response: the prefix + // carries a Bearer token and the padding is one long string member. Only the + // 1 MiB LimitReader truncating it mid-stream makes the decode fail, so the + // malformed (unknown) classification proves the cap is applied. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"access_token":"`+testAccessToken+`","expires_in":3599,"pad":"`) + _, _ = io.WriteString(w, `{"token_type":"Bearer","access_token":"`+testAccessToken+`","expires_in":3599,"pad":"`) pad := make([]byte, 2<<20) // 2 MiB, past the 1 MiB cap for i := range pad { pad[i] = 'A' @@ -311,15 +421,48 @@ func TestExchanger_ExchangeToken_CapsResponseBody(t *testing.T) { t.Cleanup(srv.Close) ex := newTestExchanger(t, srv.URL) - _, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) require.Error(t, err) + assert.Empty(t, tok.AccessToken) var exErr *entra.ExchangeError require.ErrorAs(t, err, &exErr) assert.Equal(t, entra.KindUnknown, exErr.Kind, "a truncated body is a malformed response") assert.NotContains(t, err.Error(), testAccessToken) } +// TestExchanger_ExchangeToken_BodyReadFailureIsTransient covers a connection +// that drops mid-body: the status line arrived but the body cannot be read in +// full, which is a transient failure rather than a malformed response. +func TestExchanger_ExchangeToken_BodyReadFailureIsTransient(t *testing.T) { + t.Parallel() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hj, ok := w.(http.Hijacker) + if !assert.True(t, ok, "test server must support hijacking") { + return + } + conn, buf, err := hj.Hijack() + if !assert.NoError(t, err) { + return + } + // Promise 1000 bytes, deliver a few, then drop the connection. + _, _ = buf.WriteString("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 1000\r\n\r\n{\"access") + _ = buf.Flush() + _ = conn.Close() + })) + t.Cleanup(srv.Close) + + ex := newTestExchanger(t, srv.URL) + _, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + + var exErr *entra.ExchangeError + require.ErrorAs(t, err, &exErr) + assert.Equal(t, entra.KindTransient, exErr.Kind) + assert.Equal(t, http.StatusOK, exErr.HTTPStatus) + assert.ErrorIs(t, err, entra.ErrTransient) +} + func TestExchanger_ExchangeToken_TransientOnTransportFailure(t *testing.T) { t.Parallel() @@ -372,16 +515,9 @@ func TestExchanger_ExchangeToken_ClientTimeoutIsTransient(t *testing.T) { t.Cleanup(srv.Close) t.Cleanup(func() { close(release) }) - ex, err := entra.New(entra.Config{ - TenantID: testTenant, - ClientID: testClientID, - ClientSecret: testClientSecret, - Authority: srv.URL, - HTTPClient: &http.Client{Timeout: 50 * time.Millisecond}, - }) - require.NoError(t, err) + ex := newTestExchangerWithClient(t, srv.URL, &http.Client{Timeout: 50 * time.Millisecond}) - _, err = ex.ExchangeToken(t.Context(), testUserToken, testAudience) + _, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) require.Error(t, err) assert.ErrorIs(t, err, entra.ErrTransient) @@ -389,37 +525,52 @@ func TestExchanger_ExchangeToken_ClientTimeoutIsTransient(t *testing.T) { "a token endpoint timeout must not look like caller cancellation") } -func TestNew_EnforcesRedirectGuardOnInjectedClient(t *testing.T) { +// TestNewFromTokenURL_RefusesRedirects proves the redirect guard holds for both +// the default client and a caller-injected one (which, left alone, would follow +// redirects), for both body-preserving redirect codes. Following either would +// replay the client_secret and user assertion to the redirect target. +func TestNewFromTokenURL_RefusesRedirects(t *testing.T) { t.Parallel() - var redirectFollowed atomic.Bool - mux := http.NewServeMux() - mux.HandleFunc("/leaked", func(w http.ResponseWriter, _ *http.Request) { - // Reached only if the 307 was followed, replaying the secret-bearing body. - redirectFollowed.Store(true) - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"access_token":"leaked","token_type":"Bearer","expires_in":3599}`) - }) - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "/leaked", http.StatusTemporaryRedirect) // 307 preserves the POST body - }) - srv := httptest.NewServer(mux) - t.Cleanup(srv.Close) - - // Inject a client that, left alone, would follow redirects (nil CheckRedirect). - ex, err := entra.New(entra.Config{ - TenantID: testTenant, - ClientID: testClientID, - ClientSecret: testClientSecret, - Authority: srv.URL, - HTTPClient: &http.Client{}, - }) - require.NoError(t, err) - - _, err = ex.ExchangeToken(t.Context(), testUserToken, testAudience) - require.Error(t, err) // the 307 itself is not a usable token response - assert.False(t, redirectFollowed.Load(), - "New must enforce the no-redirect guard even on a caller-injected client") + clients := []struct { + name string + client func() *http.Client + }{ + {name: "default client", client: func() *http.Client { return nil }}, + {name: "injected client", client: func() *http.Client { return &http.Client{} }}, + } + codes := []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} + + for _, c := range clients { + for _, code := range codes { + t.Run(fmt.Sprintf("%s/%d", c.name, code), func(t *testing.T) { + t.Parallel() + + var redirectFollowed atomic.Bool + mux := http.NewServeMux() + mux.HandleFunc("/leaked", func(w http.ResponseWriter, _ *http.Request) { + // Reached only if the redirect was followed, replaying the + // secret-bearing body. + redirectFollowed.Store(true) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"leaked","token_type":"Bearer","expires_in":3599}`) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/leaked", code) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + ex, err := entra.NewFromTokenURL(srv.URL+"/token", testClientID, testClientSecret, c.client()) + require.NoError(t, err) + + tok, err := ex.ExchangeToken(t.Context(), testUserToken, testAudience) + require.Error(t, err) // the redirect itself is not a usable token response + assert.Empty(t, tok.AccessToken) + assert.False(t, redirectFollowed.Load(), "the redirect target must never be contacted") + }) + } + } } func TestExchanger_ExchangeToken_RejectsEmptyArguments(t *testing.T) { diff --git a/pkg/auth/obo/errors.go b/pkg/auth/obo/errors.go index 5041405a32..e161f73c05 100644 --- a/pkg/auth/obo/errors.go +++ b/pkg/auth/obo/errors.go @@ -9,8 +9,8 @@ import "errors" // shipped in ToolHive itself. No code path in this module returns it any more. // // Deprecated: OBO is built in. The sentinel is kept only so out-of-tree code -// that still references it keeps compiling; it will be removed in a future -// release. +// that still references it keeps compiling; it will be removed once +// out-of-tree users are gone (see stacklok/toolhive#7200). var ErrEnterpriseRequired = errors.New( "on-behalf-of (OBO) external auth type requires an enterprise build") diff --git a/pkg/auth/obo/middleware.go b/pkg/auth/obo/middleware.go index b7a4517963..979adc3810 100644 --- a/pkg/auth/obo/middleware.go +++ b/pkg/auth/obo/middleware.go @@ -73,15 +73,9 @@ const ( badGatewayMessage = "OBO token exchange unavailable" ) -const ( - // AuditEventType is the AuditEvent.Type for an OBO exchange decision. The - // proxy middleware and the vMCP strategy both emit it. - AuditEventType = "obo_token_exchange" - - // auditComponent identifies the OBO proxy middleware as the source - // component of the audit record. - auditComponent = "toolhive-obo" -) +// auditComponent identifies the OBO proxy middleware as the source component +// of the audit record. +const auditComponent = "toolhive-obo" // factoryMu guards reads and writes of currentFactory. var factoryMu sync.RWMutex @@ -106,7 +100,8 @@ func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRun // // Deprecated: OBO is built in and DefaultFactory is the implementation. // RegisterFactory is kept only so out-of-tree code that still calls it keeps -// compiling; it will be removed in a future release. +// compiling; it will be removed once out-of-tree users are gone (see +// stacklok/toolhive#7200). func RegisterFactory(f types.MiddlewareFactory) { if f == nil { panic("obo.RegisterFactory: factory is nil") @@ -295,38 +290,6 @@ func (m *middleware) auditInteractionRequired(r *http.Request, err error) { event.LogTo(r.Context(), m.auditLogger, audit.LevelAudit) } -// NewInteractionRequiredAuditEvent builds the audit event for an OBO exchange -// that Entra refused with a conditional-access or claims challenge. It records -// the denied subject (an identifier, not a credential) and only the -// non-sensitive fields the entra error carries: OAuthError, Description, -// HTTPStatus, and whether a claims challenge was present. It never records the -// user token, the client secret, an issued token, or the raw claims challenge. -// -// Shared by the proxy middleware and the vMCP strategy so both surfaces emit -// the same record shape. identity may be nil. -func NewInteractionRequiredAuditEvent( - source audit.EventSource, component string, identity *auth.Identity, target string, err error, -) *audit.AuditEvent { - var subjects map[string]string - if identity != nil && identity.Subject != "" { - subjects = map[string]string{"sub": identity.Subject} - } - - event := audit.NewAuditEvent(AuditEventType, source, audit.OutcomeDenied, subjects, component). - WithTarget(map[string]string{"audience": target}) - - extra := map[string]any{"reason": "interaction_required"} - var exErr *entra.ExchangeError - if errors.As(err, &exErr) { - extra["oauth_error"] = exErr.OAuthError - extra["description"] = exErr.Description - extra["http_status"] = exErr.HTTPStatus - extra["claims_challenge_present"] = exErr.Claims != "" - } - event.Metadata.Extra = extra - return event -} - // clientAddr returns the client's IP for the audit source, stripping the port // from RemoteAddr when present. func clientAddr(r *http.Request) string { diff --git a/pkg/auth/obo/middleware_test.go b/pkg/auth/obo/middleware_test.go index b6f4b80055..b3ca50d156 100644 --- a/pkg/auth/obo/middleware_test.go +++ b/pkg/auth/obo/middleware_test.go @@ -13,6 +13,7 @@ import ( "net/http" "net/http/httptest" "sync" + "sync/atomic" "testing" "time" @@ -117,11 +118,19 @@ func inboundIdentity(token string) *auth.Identity { } } +// testInboundToken is the inbound token every upstream-provider-mode identity +// also carries. Provider mode must never fall back to it, so tests assert it is +// never exchanged. +const testInboundToken = "INBOUND-TOKEN-NOT-THE-SUBJECT" + // upstreamIdentity returns an Identity carrying token under the given upstream -// provider name — the upstream-provider-mode subject source. +// provider name — the upstream-provider-mode subject source. It also carries a +// non-empty inbound token, as a real authenticated identity would, so a +// fallback to Identity.Token is observable. func upstreamIdentity(provider, token string) *auth.Identity { return &auth.Identity{ PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}, + Token: testInboundToken, UpstreamTokens: map[string]string{provider: token}, } } @@ -196,7 +205,7 @@ func TestCreateMiddleware_InstallsOBOMiddleware(t *testing.T) { // TestCreateMiddleware_InstallsUpstreamProviderMode verifies the factory wires the // configured subjectTokenProviderName onto the installed middleware. -func TestRegisterFactory_InstallsUpstreamProviderMode(t *testing.T) { +func TestCreateMiddleware_InstallsUpstreamProviderMode(t *testing.T) { t.Setenv("TEST_OBO_SECRET_PROVIDER", "the-client-secret") ctrl := gomock.NewController(t) @@ -331,6 +340,93 @@ func TestDefaultFactory_BadTokenURL(t *testing.T) { assert.NotContains(t, err.Error(), "the-client-secret") } +// TestDefaultFactory_WiresCacheSkew drives DefaultFactory against a stub Entra +// token endpoint issuing 30s tokens and counts exchanges for two requests from +// one session. The default 60s skew exceeds the token lifetime, so every +// request re-exchanges; only a configured skew shorter than the lifetime lets +// the second request hit the cache, which proves the factory passes +// cacheSkewSeconds to the cache and that zero keeps the default. +func TestDefaultFactory_WiresCacheSkew(t *testing.T) { + tests := []struct { + name string + skew *int + wantCalls int32 + }{ + {name: "unset skew uses the 60s default", skew: nil, wantCalls: 2}, + {name: "zero skew uses the 60s default", skew: ptrTo(0), wantCalls: 2}, + {name: "skew shorter than the token lifetime caches", skew: ptrTo(10), wantCalls: 1}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("TEST_OBO_SECRET_SKEW", "the-client-secret") + + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"token_type":"Bearer","expires_in":30,"access_token":"backend-token"}`)) + })) + t.Cleanup(srv.Close) + + params := map[string]any{ + "tokenUrl": srv.URL + "/tenant/oauth2/v2.0/token", + "clientId": "client-id", + "scopes": []string{testTarget}, + "clientSecretEnvVar": "TEST_OBO_SECRET_SKEW", + } + if tt.skew != nil { + params["cacheSkewSeconds"] = *tt.skew + } + cfg, err := types.NewMiddlewareConfig(MiddlewareType, params) + require.NoError(t, err) + + var captured types.Middleware + mockRunner := mocks.NewMockMiddlewareRunner(gomock.NewController(t)) + mockRunner.EXPECT(). + AddMiddleware(MiddlewareType, gomock.Any()). + Do(func(_ string, mw types.Middleware) { captured = mw }). + Times(1) + require.NoError(t, DefaultFactory(cfg, mockRunner)) + installed, ok := captured.(*middleware) + require.True(t, ok) + + for range 2 { + rec, spy := serve(t, installed, request(t, inboundIdentity("same-user-token"))) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "Bearer backend-token", spy.authHeader) + } + assert.Equal(t, tt.wantCalls, hits.Load()) + }) + } +} + +func ptrTo[T any](v T) *T { return &v } + +// TestClientAddr verifies the audit source strips the port from RemoteAddr and +// passes through a RemoteAddr that has none. +func TestClientAddr(t *testing.T) { + t.Parallel() + + tests := []struct { + remoteAddr string + want string + }{ + {remoteAddr: "203.0.113.7:54321", want: "203.0.113.7"}, + {remoteAddr: "[2001:db8::1]:443", want: "2001:db8::1"}, + {remoteAddr: "203.0.113.7", want: "203.0.113.7"}, + {remoteAddr: "", want: ""}, + } + for _, tt := range tests { + t.Run(tt.remoteAddr, func(t *testing.T) { + t.Parallel() + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.RemoteAddr = tt.remoteAddr + assert.Equal(t, tt.want, clientAddr(r)) + }) + } +} + // TestMiddleware_Success_Inbound verifies the inbound path: the Identity.Token is // exchanged and the upstream request carries Authorization: Bearer , and the downstream handler runs. @@ -367,8 +463,10 @@ func TestMiddleware_Success_UpstreamProvider(t *testing.T) { assert.Equal(t, http.StatusOK, rec.Code) assert.True(t, spy.called) assert.Equal(t, "Bearer backend-token", spy.authHeader) + assert.Equal(t, 1, stub.calls) assert.Equal(t, "upstream-entra-token", stub.lastUserToken, "the named upstream provider token is the subject, not the inbound token") + assert.NotEqual(t, testInboundToken, stub.lastUserToken) } // TestMiddleware_NoIdentity_401 verifies both modes reject a request without an @@ -408,7 +506,8 @@ func TestMiddleware_InboundIdentityWithoutToken_401(t *testing.T) { // TestMiddleware_UpstreamProviderTokenMissing_401Challenge verifies the // upstream-provider path returns 401 with a re-auth challenge when the configured -// provider has no usable token, mirroring upstreamswap. +// provider has no usable token, mirroring upstreamswap. Every identity carries a +// non-empty inbound token, so a fallback to it would show up as an exchange. func TestMiddleware_UpstreamProviderTokenMissing_401Challenge(t *testing.T) { t.Parallel() @@ -416,7 +515,10 @@ func TestMiddleware_UpstreamProviderTokenMissing_401Challenge(t *testing.T) { name string identity *auth.Identity }{ - {name: "provider absent", identity: &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}}}, + {name: "provider absent", identity: &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: testSubject}, + Token: testInboundToken, + }}, {name: "provider present but empty", identity: upstreamIdentity(testProvider, "")}, {name: "different provider", identity: upstreamIdentity("other", "tok")}, } @@ -461,12 +563,26 @@ func TestMiddleware_InteractionRequired_403AndAudit(t *testing.T) { stub := &stubExchanger{err: exErr} mw := newMiddleware(stub, "", testTarget, slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug}))) - rec, spy := serve(t, mw, request(t, inboundIdentity(userToken))) + req := request(t, inboundIdentity(userToken)) + req.RemoteAddr = "203.0.113.7:54321" + rec, spy := serve(t, mw, req) assert.Equal(t, http.StatusForbidden, rec.Code) assert.False(t, spy.called, "downstream must not be called on a claims challenge") assert.Contains(t, rec.Body.String(), forbiddenMessage) + // The audit source is the client IP with the port stripped. + var record struct { + Source struct { + Type string `json:"type"` + Value string `json:"value"` + } `json:"source"` + Target map[string]string `json:"target"` + } + require.NoError(t, json.Unmarshal(auditBuf.Bytes(), &record)) + assert.Equal(t, "203.0.113.7", record.Source.Value) + assert.Equal(t, testTarget, record.Target["audience"]) + // Non-disclosure: neither the response body nor the audit record may leak // the user token or the raw claims challenge. assert.NotContains(t, rec.Body.String(), userToken) @@ -669,7 +785,7 @@ func TestMiddleware_RealEntra_InteractionRequired_NonDisclosure(t *testing.T) { `"error_description":"AADSTS50079: due to a configuration change made by your administrator",` + `"claims":"` + claimsBlob + `"}`)) })) - defer srv.Close() + t.Cleanup(srv.Close) ex, err := entra.NewFromTokenURL(srv.URL+"/tenant/oauth2/v2.0/token", "client-id", clientSecret, nil) require.NoError(t, err) diff --git a/pkg/runner/middleware_test.go b/pkg/runner/middleware_test.go index 91f6b351b4..4a8774235b 100644 --- a/pkg/runner/middleware_test.go +++ b/pkg/runner/middleware_test.go @@ -6,6 +6,7 @@ package runner import ( "bytes" "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -618,6 +619,26 @@ func TestGetSupportedMiddlewareFactories(t *testing.T) { } } +// TestOBOFactoryHonorsRegisterFactory verifies the runner's factory map +// dispatches obo.MiddlewareType through obo.CreateMiddleware rather than +// binding obo.DefaultFactory directly, so a replacement installed with the +// deprecated obo.RegisterFactory is still honored. +// +//nolint:paralleltest // Replaces the package-level OBO factory; must not overlap other tests. +func TestOBOFactoryHonorsRegisterFactory(t *testing.T) { + sentinel := errors.New("replacement obo factory") + //nolint:staticcheck // SA1019: exercising the deprecated override path is the point of this test. + obo.RegisterFactory(func(*types.MiddlewareConfig, types.MiddlewareRunner) error { return sentinel }) + t.Cleanup(func() { + obo.RegisterFactory(obo.DefaultFactory) //nolint:staticcheck // SA1019: restores the default. + }) + + factory, ok := GetSupportedMiddlewareFactories()[obo.MiddlewareType] + require.True(t, ok) + err := factory(&types.MiddlewareConfig{Type: obo.MiddlewareType}, nil) + require.ErrorIs(t, err, sentinel, "the runner must dispatch through obo.CreateMiddleware") +} + // TestOBORegistration exercises the proxyrunner path for an operator-injected // obo middleware: the RunConfig round-trips through JSON, the runner's factory // map builds the built-in OBO middleware, and a request through it has its @@ -627,7 +648,11 @@ func TestGetSupportedMiddlewareFactories(t *testing.T) { //nolint:paralleltest // Uses t.Setenv for the client secret the factory reads. func TestOBORegistration(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - require.NoError(t, r.ParseForm()) + // assert, not require: this runs on the server's goroutine. + if !assert.NoError(t, r.ParseForm()) { + http.Error(w, "bad form", http.StatusBadRequest) + return + } assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", r.Form.Get("grant_type")) assert.Equal(t, "on_behalf_of", r.Form.Get("requested_token_use")) assert.Equal(t, "user-token", r.Form.Get("assertion")) diff --git a/pkg/vmcp/auth/converters/obo.go b/pkg/vmcp/auth/converters/obo.go index b6f380139e..cf8e520fcb 100644 --- a/pkg/vmcp/auth/converters/obo.go +++ b/pkg/vmcp/auth/converters/obo.go @@ -56,8 +56,10 @@ func (*OBOConverter) ConvertToStrategy( } // Check the simple required credentials first, so a config missing a client - // credential reports that rather than a downstream tenant-format error. - if cfg.ClientID == "" { + // credential reports that rather than a downstream tenant-format error. A + // whitespace-only clientId is rejected like an empty one, as the operator's + // OBO validation does. + if strings.TrimSpace(cfg.ClientID) == "" { return nil, fmt.Errorf("vMCP OBO converter: %s", msgClientID) } // OBO is a confidential-client shared-secret flow: clientSecretRef must be @@ -105,7 +107,8 @@ func (*OBOConverter) ConvertToStrategy( // mode, where secrets cannot be mounted as pod env vars because the vMCP pod does // not know about backend auth configs at creation time). It clears ClientSecretEnv // so the resolved value is the single secret source, and returns the strategy -// unchanged when no secret reference is configured. +// unchanged when no secret reference is configured. A missing secret, a missing +// key, or an empty value is an error. // // The secret value is never logged and never written to the strategy's // non-secret fields, so it does not leak into logs or CR status; error messages @@ -144,6 +147,13 @@ func (*OBOConverter) ResolveSecrets( return nil, fmt.Errorf("vMCP OBO converter: secret %s/%s has no key %s", namespace, cfg.ClientSecretRef.Name, cfg.ClientSecretRef.Key) } + // Reject an empty value here, where the secret and key can be named, rather + // than resolving to no secret and failing later with a generic + // "client secret is required". + if len(value) == 0 { + return nil, fmt.Errorf("vMCP OBO converter: secret %s/%s key %s is empty", + namespace, cfg.ClientSecretRef.Name, cfg.ClientSecretRef.Key) + } strategy.OBO.ClientSecretEnv = "" strategy.OBO.ClientSecret = string(value) diff --git a/pkg/vmcp/auth/converters/obo_test.go b/pkg/vmcp/auth/converters/obo_test.go index 3ba93f495f..167c6c2d07 100644 --- a/pkg/vmcp/auth/converters/obo_test.go +++ b/pkg/vmcp/auth/converters/obo_test.go @@ -156,6 +156,8 @@ func TestOBOConvertToStrategy_Malformed(t *testing.T) { }{ {name: "nil obo", nilOBO: true, wantMsg: msgOBONil}, {name: "missing client id", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientID = "" }, wantMsg: msgClientID}, + {name: "whitespace-only client id", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientID = " \t " }, wantMsg: msgClientID}, + {name: "whitespace-only secret ref key", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef.Key = " " }, wantMsg: msgClientSecretRef}, {name: "missing client secret ref", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef = nil }, wantMsg: msgClientSecretRef}, {name: "empty secret ref name", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef.Name = " " }, wantMsg: msgClientSecretRef}, {name: "empty secret ref key", mutate: func(o *mcpv1beta1.OBOConfig) { o.ClientSecretRef.Key = "" }, wantMsg: msgClientSecretRef}, @@ -203,6 +205,9 @@ func TestOBOResolveSecrets_PopulatesFromK8s(t *testing.T) { cr := validOBOCR() strategy, err := ConvertToStrategy(cr) require.NoError(t, err) + // A stale env-var reference (the inline-mode secret source) must give way to + // the resolved value. + strategy.OBO.ClientSecretEnv = "STALE_OBO_SECRET_ENV" k8sClient := fakeClientWithSecret(t, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: testSecretName, Namespace: testNamespace}, @@ -253,6 +258,95 @@ func TestOBOResolveSecrets_Errors(t *testing.T) { assert.NotContains(t, err.Error(), testSecretValue, "the error must not echo the secret value") assert.Empty(t, strategy.OBO.ClientSecret, "a failed resolve must not set the secret") }) + + t.Run("empty secret value", func(t *testing.T) { + t.Parallel() + cr := validOBOCR() + strategy, err := ConvertToStrategy(cr) + require.NoError(t, err) + + client := fakeClientWithSecret(t, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: testSecretName, Namespace: testNamespace}, + Data: map[string][]byte{testSecretKey: {}}, + }) + _, err = ResolveSecretsForStrategy(t.Context(), cr, client, testNamespace, strategy) + require.ErrorContains(t, err, "is empty") + assert.ErrorContains(t, err, testSecretName) + assert.ErrorContains(t, err, testSecretKey) + assert.Empty(t, strategy.OBO.ClientSecret) + }) +} + +// TestOBOResolveSecrets_Guards covers the inputs ResolveSecrets rejects or +// passes through without contacting Kubernetes. The fake client holds no +// secrets, so any lookup would fail the passthrough row. +func TestOBOResolveSecrets_Guards(t *testing.T) { + t.Parallel() + + withSecretEnv := func() *authtypes.BackendAuthStrategy { + return &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{TokenURL: testTokenURL, ClientID: testClientID, ClientSecretEnv: "OBO_SECRET_ENV"}, + } + } + + tests := []struct { + name string + cr func() *mcpv1beta1.MCPExternalAuthConfig + strategy func() *authtypes.BackendAuthStrategy + wantErrContains string + }{ + { + name: "nil strategy", + cr: validOBOCR, + strategy: func() *authtypes.BackendAuthStrategy { return nil }, + wantErrContains: msgStrategyNil, + }, + { + name: "strategy without OBO", + cr: validOBOCR, + strategy: func() *authtypes.BackendAuthStrategy { + return &authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO} + }, + wantErrContains: msgStrategyNil, + }, + { + name: "external auth config without OBO", + cr: func() *mcpv1beta1.MCPExternalAuthConfig { + cr := validOBOCR() + cr.Spec.OBO = nil + return cr + }, + strategy: withSecretEnv, + wantErrContains: msgOBONil, + }, + { + name: "no client secret reference passes the strategy through", + cr: func() *mcpv1beta1.MCPExternalAuthConfig { + cr := validOBOCR() + cr.Spec.OBO.ClientSecretRef = nil + return cr + }, + strategy: withSecretEnv, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + in := tt.strategy() + got, err := (&OBOConverter{}).ResolveSecrets(t.Context(), tt.cr(), fakeClientWithSecret(t), testNamespace, in) + if tt.wantErrContains != "" { + require.ErrorContains(t, err, tt.wantErrContains) + assert.Nil(t, got) + return + } + require.NoError(t, err) + assert.Same(t, in, got) + assert.Equal(t, withSecretEnv(), got, "the strategy must be returned unchanged") + }) + } } // fakeClientWithSecret builds a controller-runtime fake client seeded with the diff --git a/pkg/vmcp/auth/factory/outgoing_test.go b/pkg/vmcp/auth/factory/outgoing_test.go index 33bbcfffa6..4be0e692aa 100644 --- a/pkg/vmcp/auth/factory/outgoing_test.go +++ b/pkg/vmcp/auth/factory/outgoing_test.go @@ -158,8 +158,8 @@ func TestNewOutgoingAuthRegistry(t *testing.T) { require.NoError(t, err, "obo strategy should be registered") assert.IsType(t, &strategies.OBOStrategy{}, strategy) - // A config with no token URL is rejected by the real validator, not by a - // licensing stub. + // A strategy with no OBO block at all is rejected by the real validator, + // not by a licensing stub. err = strategy.Validate(&authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO}) require.Error(t, err) assert.ErrorContains(t, err, "OBO configuration is required") diff --git a/pkg/vmcp/auth/obo.go b/pkg/vmcp/auth/obo.go index 6e616237ab..8948d42de5 100644 --- a/pkg/vmcp/auth/obo.go +++ b/pkg/vmcp/auth/obo.go @@ -22,8 +22,8 @@ var oboStrategyOverride func(env.Reader) Strategy // // Deprecated: OBO is built in; NewOBOStrategy returns the Entra OBO strategy // from pkg/vmcp/auth/strategies. RegisterOBOStrategy is kept only so -// out-of-tree code that still calls it keeps compiling; it will be removed in -// a future release. +// out-of-tree code that still calls it keeps compiling; it will be removed +// once out-of-tree users are gone (see stacklok/toolhive#7200). func RegisterOBOStrategy(f func(env.Reader) Strategy) { if f == nil { panic("auth.RegisterOBOStrategy: factory is nil") diff --git a/pkg/vmcp/auth/obo_test.go b/pkg/vmcp/auth/obo_test.go index 7e3aa8416d..8a1026c1f4 100644 --- a/pkg/vmcp/auth/obo_test.go +++ b/pkg/vmcp/auth/obo_test.go @@ -64,6 +64,50 @@ func TestRegisterOBOStrategy_OverridesBuiltIn(t *testing.T) { assert.Equal(t, "second", err.Error(), "the last registered factory must win") } +// staticEnv is a map-backed env.Reader, so tests can identify the reader a +// strategy was given by what it resolves. +type staticEnv map[string]string + +func (e staticEnv) Getenv(key string) string { return e[key] } + +func (e staticEnv) LookupEnv(key string) (string, bool) { + v, ok := e[key] + return v, ok +} + +//nolint:paralleltest // Mutates package-level oboStrategyOverride; must not race other tests. +func TestNewOBOStrategy_PassesEnvReader(t *testing.T) { + withNoOBOOverride(t) + + reader := staticEnv{"OBO_TEST_CLIENT_SECRET": "from-the-injected-reader"} + + t.Run("built-in strategy resolves secrets through the reader", func(t *testing.T) { + strategy := &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{ + TokenURL: "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token", + ClientID: "client-id", + ClientSecretEnv: "OBO_TEST_CLIENT_SECRET", + Scopes: []string{"api://backend/.default"}, + }, + } + assert.NoError(t, NewOBOStrategy(reader).Validate(strategy), + "the secret is only resolvable through the reader passed to NewOBOStrategy") + assert.Error(t, NewOBOStrategy(staticEnv{}).Validate(strategy)) + }) + + t.Run("registered factory receives the reader", func(t *testing.T) { + var got env.Reader + RegisterOBOStrategy(func(r env.Reader) Strategy { + got = r + return &namedStrategy{tag: "override"} + }) + + NewOBOStrategy(reader) + assert.Equal(t, reader, got, "the factory must receive the env.Reader passed to NewOBOStrategy") + }) +} + func TestRegisterOBOStrategy_PanicsOnNil(t *testing.T) { t.Parallel() diff --git a/pkg/vmcp/auth/strategies/obo.go b/pkg/vmcp/auth/strategies/obo.go index 15ce2cdd72..cfd0f52400 100644 --- a/pkg/vmcp/auth/strategies/obo.go +++ b/pkg/vmcp/auth/strategies/obo.go @@ -56,10 +56,12 @@ type OBOStrategy struct { // production uses defaultBuildOBOExchanger. buildExchanger func(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) - // exchangers caches the per-backend Exchanger keyed by oboExchangerCacheKey. Each - // is shared across all users of that backend (the cache partitions per user - // internally). - mu sync.RWMutex + // mu guards exchangers. + mu sync.RWMutex + + // exchangers caches the per-backend Exchanger keyed by oboExchangerCacheKey. + // Each is shared across all users of that backend (the cache partitions per + // user internally). exchangers map[string]exchange.Exchanger } @@ -104,6 +106,9 @@ func (*OBOStrategy) Name() string { return authtypes.StrategyTypeOBO } func (s *OBOStrategy) Authenticate( ctx context.Context, req *http.Request, strategy *authtypes.BackendAuthStrategy, ) error { + // The config is validated before the health-check skip, as the token-exchange + // strategy does: a misconfigured backend fails its health probe instead of + // being probed unauthenticated and reported healthy. cfg, clientSecret, err := s.resolveConfig(strategy) if err != nil { return fmt.Errorf("obo: invalid strategy configuration: %w", err) @@ -211,22 +216,53 @@ func (s *OBOStrategy) getOrCreateExchanger(cfg *authtypes.OBOConfig, clientSecre } // mapExchangeError translates an exchange failure into the error the Strategy -// returns, without disclosing token or secret material (the Entra error already -// composes only non-sensitive fields). A conditional-access / claims challenge -// fails fast with an audit record; a cancelled context propagates -// as-is so it is not misreported as a backend failure. +// returns. The returned error wraps only the matching entra sentinel (so +// errors.Is keeps working) behind a generic message: it reaches MCP clients via +// the tool error, so it must not carry Entra's error_description or any other +// provider detail. That detail is recorded server-side instead — in the audit +// record for a conditional-access / claims challenge, and in the diagnostic log +// otherwise. A cancelled context propagates as-is so it is not misreported as a +// backend failure. func (s *OBOStrategy) mapExchangeError( ctx context.Context, identity *auth.Identity, target string, err error, ) error { switch { case errors.Is(err, entra.ErrInteractionRequired): + // The audit record is built from the original error so it keeps the + // ExchangeError's safe-to-log fields. s.auditInteractionRequired(ctx, identity, target, err) - return fmt.Errorf("obo: token exchange denied: %w", err) + return fmt.Errorf("obo: token exchange denied: %w", entra.ErrInteractionRequired) case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): return err + case errors.Is(err, entra.ErrInvalidGrant): + // The end-user token was rejected (expired, malformed, or not consented): + // a per-caller condition, so it is logged at DEBUG only. + logExchangeFailure(ctx, slog.LevelDebug, err) + return fmt.Errorf("obo: token exchange failed: %w", entra.ErrInvalidGrant) default: - return fmt.Errorf("obo: token exchange failed: %w", err) + // invalid_client, a transient IdP failure, or an unclassified error. + logExchangeFailure(ctx, slog.LevelWarn, err) + for _, sentinel := range []error{entra.ErrInvalidClient, entra.ErrTransient} { + if errors.Is(err, sentinel) { + return fmt.Errorf("obo: token exchange failed: %w", sentinel) + } + } + return errors.New("obo: token exchange failed") + } +} + +// logExchangeFailure records an exchange failure in the diagnostic log. Only +// *entra.ExchangeError detail is logged: its Error() composes solely +// non-sensitive fields. Any other error is logged without its message so no +// Exchanger implementation can leak credential material here, matching the +// proxy middleware. +func logExchangeFailure(ctx context.Context, level slog.Level, err error) { + var exErr *entra.ExchangeError + if errors.As(err, &exErr) { + slog.Log(ctx, level, "obo: token exchange failed", "error", exErr.Error()) + return } + slog.Log(ctx, level, "obo: token exchange failed with an unclassified error") } // auditInteractionRequired emits the audit record for a fail-fast diff --git a/pkg/vmcp/auth/strategies/obo_test.go b/pkg/vmcp/auth/strategies/obo_test.go index 05f885c4f0..57d360ebf4 100644 --- a/pkg/vmcp/auth/strategies/obo_test.go +++ b/pkg/vmcp/auth/strategies/obo_test.go @@ -6,10 +6,17 @@ package strategies import ( "bytes" "context" + "errors" + "fmt" "log/slog" "net/http" "net/http/httptest" + "runtime" + "strings" + "sync" + "sync/atomic" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -155,35 +162,47 @@ func TestOBOAuthenticate_UpstreamProviderSuccess(t *testing.T) { func TestOBOAuthenticate_SubjectErrors(t *testing.T) { t.Parallel() + withProvider := func() *authtypes.BackendAuthStrategy { + s := validOBOStrategy() + s.OBO.SubjectTokenProviderName = "entra" + return s + } + tests := []struct { name string - ctx func(t *testing.T) context.Context + identity *auth.Identity // nil means no identity in the context backendStrategy func() *authtypes.BackendAuthStrategy + wantErrIs error + wantErrContains string }{ { name: "no identity in context", - ctx: func(t *testing.T) context.Context { t.Helper(); return t.Context() }, backendStrategy: validOBOStrategy, + wantErrContains: "no identity found in context", }, { - name: "identity has no inbound token", - ctx: func(t *testing.T) context.Context { - t.Helper() - return auth.WithIdentity(t.Context(), oboInboundIdentity("")) - }, + name: "identity has no inbound token", + identity: oboInboundIdentity(""), backendStrategy: validOBOStrategy, + wantErrContains: "identity has no token", }, { - name: "named provider token absent", - ctx: func(t *testing.T) context.Context { - t.Helper() - return auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) - }, - backendStrategy: func() *authtypes.BackendAuthStrategy { - s := validOBOStrategy() - s.OBO.SubjectTokenProviderName = "entra" - return s + // The inbound token is present but must not be used as a fallback. + name: "named provider token absent", + identity: oboInboundIdentity("user-token"), + backendStrategy: withProvider, + wantErrIs: authtypes.ErrUpstreamTokenNotFound, + wantErrContains: `provider "entra"`, + }, + { + name: "named provider token empty", + identity: &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{Subject: oboTestSubject}, + Token: "user-token", + UpstreamTokens: map[string]string{"entra": ""}, }, + backendStrategy: withProvider, + wantErrIs: authtypes.ErrUpstreamTokenNotFound, }, } @@ -193,14 +212,131 @@ func TestOBOAuthenticate_SubjectErrors(t *testing.T) { stub := &oboStubExchanger{token: "unused"} s := oboStrategyWithStub(stub, nil) - req, err := oboServeAuthenticate(tt.ctx(t), t, s, tt.backendStrategy()) + ctx := t.Context() + if tt.identity != nil { + ctx = auth.WithIdentity(ctx, tt.identity) + } + req, err := oboServeAuthenticate(ctx, t, s, tt.backendStrategy()) require.Error(t, err) + if tt.wantErrIs != nil { + assert.ErrorIs(t, err, tt.wantErrIs) + } + if tt.wantErrContains != "" { + assert.ErrorContains(t, err, tt.wantErrContains) + } assert.Empty(t, req.Header.Get("Authorization"), "no token may be injected on failure") assert.Zero(t, stub.calls, "no exchange should be attempted") }) } } +// TestOBOAuthenticate_ConfigAndBuildErrors covers the failures that occur before +// any exchange: an invalid configuration (also under a health-check context, +// because the config is validated before the health-check skip), a +// ClientSecretEnv naming an unset variable, and an Exchanger that fails to build. +func TestOBOAuthenticate_ConfigAndBuildErrors(t *testing.T) { + t.Parallel() + + buildErr := errors.New("exchanger build failed") + withSecretEnv := func() *authtypes.BackendAuthStrategy { + s := validOBOStrategy() + s.OBO.ClientSecret = "" + s.OBO.ClientSecretEnv = "OBO_TEST_SECRET_NOT_SET" + return s + } + nilOBO := func() *authtypes.BackendAuthStrategy { + return &authtypes.BackendAuthStrategy{Type: authtypes.StrategyTypeOBO} + } + + tests := []struct { + name string + healthCheck bool + backendStrategy func() *authtypes.BackendAuthStrategy + buildErr error + wantErrIs error + wantErrContains []string + wantBuilds int32 + }{ + { + name: "invalid configuration", + backendStrategy: nilOBO, + wantErrContains: []string{"obo: invalid strategy configuration", "OBO configuration is required"}, + }, + { + name: "invalid configuration fails a health check too", + healthCheck: true, + backendStrategy: nilOBO, + wantErrContains: []string{"obo: invalid strategy configuration", "OBO configuration is required"}, + }, + { + name: "client secret env var absent from the environment", + backendStrategy: withSecretEnv, + wantErrContains: []string{"obo: invalid strategy configuration", "OBO_TEST_SECRET_NOT_SET"}, + }, + { + name: "exchanger build fails", + backendStrategy: validOBOStrategy, + buildErr: buildErr, + wantErrIs: buildErr, + wantErrContains: []string{"obo: build exchanger"}, + wantBuilds: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + stub := &oboStubExchanger{token: "unused"} + var builds atomic.Int32 + s := newOBOStrategy(oboMapEnv{}, nil, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { + builds.Add(1) + if tt.buildErr != nil { + return nil, tt.buildErr + } + return stub, nil + }) + + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + if tt.healthCheck { + ctx = healthcontext.WithHealthCheckMarker(ctx) + } + req, err := oboServeAuthenticate(ctx, t, s, tt.backendStrategy()) + require.Error(t, err) + if tt.wantErrIs != nil { + assert.ErrorIs(t, err, tt.wantErrIs) + } + for _, want := range tt.wantErrContains { + assert.ErrorContains(t, err, want) + } + assert.Empty(t, req.Header.Get("Authorization")) + assert.Equal(t, tt.wantBuilds, builds.Load()) + assert.Zero(t, stub.calls, "no exchange may be attempted") + }) + } +} + +// TestOBOAuthenticate_ContextErrorsPassThrough verifies a cancelled or expired +// caller context surfaces as itself, not as a token exchange failure. +func TestOBOAuthenticate_ContextErrorsPassThrough(t *testing.T) { + t.Parallel() + + for _, ctxErr := range []error{context.Canceled, context.DeadlineExceeded} { + t.Run(ctxErr.Error(), func(t *testing.T) { + t.Parallel() + + stub := &oboStubExchanger{err: fmt.Errorf("entra obo: %w", ctxErr)} + s := oboStrategyWithStub(stub, nil) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.ErrorIs(t, err, ctxErr) + assert.NotContains(t, err.Error(), "token exchange failed") + assert.Empty(t, req.Header.Get("Authorization")) + }) + } +} + // TestOBOAuthenticate_HealthCheckSkips proves a health probe (no user identity) // skips authentication rather than failing. func TestOBOAuthenticate_HealthCheckSkips(t *testing.T) { @@ -258,22 +394,74 @@ func TestOBOAuthenticate_ConditionalAccess_FailsFastWithAudit(t *testing.T) { assert.NotContains(t, out, claims, "the audit record must not contain the raw claims challenge") } -// TestOBOAuthenticate_OtherExchangeError_NoAudit proves a non-CA exchange failure -// returns an error and injects nothing, without emitting a D1 audit record. -func TestOBOAuthenticate_OtherExchangeError_NoAudit(t *testing.T) { +// TestOBOAuthenticate_ExchangeErrorMapping proves every exchange failure +// returns an error that still matches its entra sentinel but carries none of +// Entra's provider detail (the error reaches MCP clients via the tool error), +// injects nothing, and that only a conditional-access denial emits the audit +// record — which keeps the detail server-side. +func TestOBOAuthenticate_ExchangeErrorMapping(t *testing.T) { t.Parallel() - var auditBuf bytes.Buffer - auditLogger := slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) - stub := &oboStubExchanger{err: &entra.ExchangeError{Kind: entra.KindInvalidGrant, OAuthError: "invalid_grant"}} - s := oboStrategyWithStub(stub, auditLogger) - ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + const ( + description = "AADSTS7000215: PROVIDER-DIAGNOSTIC-DETAIL" + oauthError = "provider_error_code_detail" + ) + exErr := func(kind entra.ErrorKind) error { + return &entra.ExchangeError{Kind: kind, OAuthError: oauthError, Description: description, HTTPStatus: 400} + } - req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) - require.Error(t, err) - assert.ErrorIs(t, err, entra.ErrInvalidGrant) - assert.Empty(t, req.Header.Get("Authorization")) - assert.Empty(t, auditBuf.String(), "only conditional-access denials emit the D1 audit record") + tests := []struct { + name string + err error + wantSentinel error // nil: matches none of the entra sentinels + wantAudit bool + }{ + {name: "interaction required", err: exErr(entra.KindInteractionRequired), + wantSentinel: entra.ErrInteractionRequired, wantAudit: true}, + {name: "invalid grant", err: exErr(entra.KindInvalidGrant), wantSentinel: entra.ErrInvalidGrant}, + {name: "invalid client", err: exErr(entra.KindInvalidClient), wantSentinel: entra.ErrInvalidClient}, + {name: "transient", err: exErr(entra.KindTransient), wantSentinel: entra.ErrTransient}, + {name: "unknown kind", err: exErr(entra.KindUnknown)}, + {name: "wrapped exchange error", err: fmt.Errorf("cache: %w", exErr(entra.KindInvalidClient)), + wantSentinel: entra.ErrInvalidClient}, + {name: "non-entra error", err: errors.New("unexpected failure " + description)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var auditBuf bytes.Buffer + auditLogger := slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) + stub := &oboStubExchanger{err: tt.err} + s := oboStrategyWithStub(stub, auditLogger) + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) + + req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) + require.Error(t, err) + assert.Empty(t, req.Header.Get("Authorization")) + + assert.NotContains(t, err.Error(), description, "Entra's error_description must not reach the client") + assert.NotContains(t, err.Error(), oauthError, "Entra's error code must not reach the client") + var leaked *entra.ExchangeError + assert.NotErrorAs(t, err, &leaked, "the returned error must not wrap the ExchangeError") + + sentinels := []error{entra.ErrInteractionRequired, entra.ErrInvalidGrant, entra.ErrInvalidClient, entra.ErrTransient} + for _, sentinel := range sentinels { + if sentinel == tt.wantSentinel { + assert.ErrorIs(t, err, sentinel) + } else { + assert.NotErrorIs(t, err, sentinel) + } + } + + if tt.wantAudit { + assert.Contains(t, auditBuf.String(), description, "the audit record keeps the provider detail server-side") + } else { + assert.Empty(t, auditBuf.String(), "only conditional-access denials emit the audit record") + } + }) + } } // TestOBOAuthenticate_CachesExchangerPerConfig proves the per-backend Exchanger is @@ -298,46 +486,247 @@ func TestOBOAuthenticate_CachesExchangerPerConfig(t *testing.T) { // TestOBOAuthenticate_RealEntraExchange exercises the production path end-to-end: // NewOBOStrategy (default buildExchanger) wires entra.NewFromTokenURL + cache.New / -// WithSkew, and Authenticate performs a real HTTP OBO exchange against an -// httptest server standing in for the Entra token endpoint (loopback http, which -// NewFromTokenURL permits). This is the only test that drives defaultBuildOBOExchanger -// rather than a stub, -// including the positive CacheSkewSeconds gate. +// WithSkew, and Authenticate performs real HTTP OBO exchanges against an httptest +// server standing in for the Entra token endpoint (loopback http, which +// NewFromTokenURL permits). The server mints a token per assertion and counts +// hits, so each row pins how many exchanges a sequence of requests costs: the +// per-user cache is shared across requests and partitioned by user, and the +// configured CacheSkewSeconds reaches the cache (zero and unset keep the 60s +// default). func TestOBOAuthenticate_RealEntraExchange(t *testing.T) { t.Parallel() - var gotAuthHeader, gotGrantType string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuthHeader = r.Header.Get("Authorization") - _ = r.ParseForm() - gotGrantType = r.Form.Get("grant_type") - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"token_type":"Bearer","expires_in":3599,"access_token":"backend-abc"}`)) - })) - defer srv.Close() - - skew := int32(120) // exercise the CacheSkewSeconds > 0 gate in defaultBuildOBOExchanger - s := NewOBOStrategy(oboMapEnv{}) - backendStrategy := &authtypes.BackendAuthStrategy{ - Type: authtypes.StrategyTypeOBO, - OBO: &authtypes.OBOConfig{ - TokenURL: srv.URL, // loopback http — accepted by NewFromTokenURL - ClientID: oboTestClientID, - ClientSecret: "resolved-secret", - Scopes: []string{oboTestScope}, - CacheSkewSeconds: &skew, - }, + tests := []struct { + name string + skew *int32 + expiresIn int + users []string + wantHits int32 + }{ + {name: "unset skew, long-lived token is cached", expiresIn: 3599, + users: []string{"alice", "alice"}, wantHits: 1}, + {name: "zero skew, long-lived token is cached", skew: ptrInt32(0), expiresIn: 3599, + users: []string{"alice", "alice"}, wantHits: 1}, + {name: "zero skew keeps the 60s default", skew: ptrInt32(0), expiresIn: 30, + users: []string{"alice", "alice"}, wantHits: 2}, + {name: "token lifetime shorter than the skew is re-exchanged", skew: ptrInt32(120), expiresIn: 90, + users: []string{"alice", "alice"}, wantHits: 2}, + {name: "skew shorter than the token lifetime caches", skew: ptrInt32(10), expiresIn: 30, + users: []string{"alice", "alice"}, wantHits: 1}, + {name: "a second user gets its own exchange", expiresIn: 3599, + users: []string{"alice", "alice", "bob", "bob"}, wantHits: 2}, } - ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) - req, err := oboServeAuthenticate(ctx, t, s, backendStrategy) - require.NoError(t, err) - assert.Equal(t, "Bearer backend-abc", req.Header.Get("Authorization"), - "the backend-scoped token from the real exchange must be injected") - assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", gotGrantType, - "the exchange must use the Entra on-behalf-of (jwt-bearer) grant") - assert.NotContains(t, gotAuthHeader, "user-token", - "the subject token must travel in the form body, not the request's Authorization header") + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + // assert, not require: this runs on the server's goroutine. + if !assert.NoError(t, r.ParseForm()) { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + assert.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", r.Form.Get("grant_type"), + "the exchange must use the Entra on-behalf-of (jwt-bearer) grant") + assert.Empty(t, r.Header.Get("Authorization"), + "the subject token must travel in the form body, not an Authorization header") + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"token_type":"Bearer","expires_in":%d,"access_token":"backend-for-%s"}`, + tt.expiresIn, r.Form.Get("assertion")) + })) + t.Cleanup(srv.Close) + + s := NewOBOStrategy(oboMapEnv{}) + backendStrategy := &authtypes.BackendAuthStrategy{ + Type: authtypes.StrategyTypeOBO, + OBO: &authtypes.OBOConfig{ + TokenURL: srv.URL, // loopback http — accepted by NewFromTokenURL + ClientID: oboTestClientID, + ClientSecret: "resolved-secret", + Scopes: []string{oboTestScope}, + CacheSkewSeconds: tt.skew, + }, + } + + for _, user := range tt.users { + ctx := auth.WithIdentity(t.Context(), oboInboundIdentity(user)) + req, err := oboServeAuthenticate(ctx, t, s, backendStrategy) + require.NoError(t, err) + assert.Equal(t, "Bearer backend-for-"+user, req.Header.Get("Authorization"), + "each user must receive the token exchanged for their own assertion") + } + assert.Equal(t, tt.wantHits, hits.Load()) + }) + } +} + +func ptrInt32(v int32) *int32 { return &v } + +// TestOBOExchangerCacheKey verifies every field that determines the Exchanger +// partitions the per-backend cache, and that the raw client secret never +// appears in the key. +func TestOBOExchangerCacheKey(t *testing.T) { + t.Parallel() + + const secret = "client-secret-RAW-VALUE" + base := func() *authtypes.OBOConfig { + return &authtypes.OBOConfig{TokenURL: oboTestTokenURL, ClientID: oboTestClientID, CacheSkewSeconds: ptrInt32(30)} + } + baseKey := oboExchangerCacheKey(base(), secret) + assert.NotContains(t, baseKey, secret, "the raw client secret must not appear in the key") + assert.Equal(t, baseKey, oboExchangerCacheKey(base(), secret), "the key must be deterministic") + + tests := []struct { + name string + mutate func(*authtypes.OBOConfig) + secret string + }{ + {name: "token URL", mutate: func(c *authtypes.OBOConfig) { c.TokenURL = "https://login.microsoftonline.us/t/oauth2/v2.0/token" }}, + {name: "client ID", mutate: func(c *authtypes.OBOConfig) { c.ClientID = "other-client" }}, + {name: "cache skew", mutate: func(c *authtypes.OBOConfig) { c.CacheSkewSeconds = ptrInt32(31) }}, + {name: "client secret", secret: "rotated-secret-RAW-VALUE"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + cfg := base() + if tt.mutate != nil { + tt.mutate(cfg) + } + sec := secret + if tt.secret != "" { + sec = tt.secret + } + key := oboExchangerCacheKey(cfg, sec) + assert.NotEqual(t, baseKey, key, "changing the %s must select a different Exchanger", tt.name) + assert.NotContains(t, key, sec, "the raw client secret must not appear in the key") + }) + } +} + +// TestOBOGetOrCreateExchanger_BuildsOnceUnderContention exercises the +// double-checked lock: callers released together all miss on the read-locked +// check, and the builder holds the write lock until every other caller is +// parked on the mutex. Callers that queued on the write lock must find the +// Exchanger on the second check rather than building another one. +// +// A caller that reached the read lock only after the build began never needs the +// second check, so an attempt where no caller was parked on the write lock +// proves nothing; such attempts are retried. Callers busy-wait on a gate rather +// than block on a channel, so each is already running on its own P when +// released and their read checks overlap. One P is left free for the test +// goroutine to open the gate. +func TestOBOGetOrCreateExchanger_BuildsOnceUnderContention(t *testing.T) { + t.Parallel() + + procs := runtime.GOMAXPROCS(0) + if procs < 3 { + t.Skip("needs GOMAXPROCS >= 3 for callers to overlap on the read-locked check") + } + callers := int32(min(procs-1, 8)) + const maxAttempts = 200 + cfg := validOBOStrategy().OBO + + for range maxAttempts { + var builds, writeWaiters atomic.Int32 + s := newOBOStrategy(oboMapEnv{}, nil, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { + if builds.Add(1) == 1 { + writeWaiters.Store(int32(awaitParkedOnMutex( + "TestOBOGetOrCreateExchanger_BuildsOnceUnderContention", int(callers)-1))) + } + return &oboStubExchanger{}, nil + }) + + var ready atomic.Int32 + var gate atomic.Bool + var wg sync.WaitGroup + for range callers { + wg.Add(1) + go func() { + defer wg.Done() + ready.Add(1) + for !gate.Load() { + // Busy-wait deliberately: the caller stays on its P, so it + // starts the instant the gate opens. + } + ex, err := s.getOrCreateExchanger(cfg, "resolved-secret") + assert.NoError(t, err) + assert.NotNil(t, ex) + }() + } + require.Eventually(t, func() bool { return ready.Load() == callers }, + 5*time.Second, time.Millisecond, "callers must reach the gate") + gate.Store(true) + waitGroupWithTimeout(t, &wg) + + if writeWaiters.Load() == 0 { + continue // the second check was not exercised; try again + } + assert.Equal(t, int32(1), builds.Load(), + "callers queued on the write lock must reuse the Exchanger built by the first") + return + } + t.Fatalf("no attempt in %d had a caller parked on the write lock", maxAttempts) +} + +// awaitParkedOnMutex polls goroutine stacks until want goroutines created by +// testName are blocked on an RWMutex inside getOrCreateExchanger, or a timeout +// passes. It returns how many of them were waiting on the write lock (Lock) +// rather than the read lock. It runs inside the builder, on a caller's +// goroutine, so it reports rather than failing the test. +func awaitParkedOnMutex(testName string, want int) int { + deadline := time.Now().Add(5 * time.Second) + for { + parked, writers := 0, 0 + for _, g := range goroutineStacks() { + if !strings.Contains(g, testName) || !strings.Contains(g, "getOrCreateExchanger") { + continue + } + switch { + case strings.Contains(g, "(*RWMutex).Lock("): + parked++ + writers++ + case strings.Contains(g, "(*RWMutex).RLock("): + parked++ + } + } + if parked >= want || time.Now().After(deadline) { + return writers + } + time.Sleep(time.Millisecond) + } +} + +// goroutineStacks returns the stack trace of every goroutine, one per element. +func goroutineStacks() []string { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + return strings.Split(string(buf[:n]), "\n\n") + } + buf = make([]byte, 2*len(buf)) + } +} + +// waitGroupWithTimeout waits for wg, failing the test if it does not finish in +// time. Call it only from the test goroutine. +func waitGroupWithTimeout(t *testing.T, wg *sync.WaitGroup) { + t.Helper() + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for goroutines to finish") + } } func TestOBOValidate_Valid(t *testing.T) { From 41bc9e50c466a60e073e2205c90a767e4de270af Mon Sep 17 00:00:00 2001 From: Trey Date: Sun, 22 Nov 2026 18:54:43 -0800 Subject: [PATCH 09/12] Clear stale OBO incoming-auth rejection on revert The same-hash guard held the local obo-without-OIDC InvalidConfig after the referenced config reverted from obo to its earlier spec, because the rejection returns before the stored hash advances. The guard no longer holds that condition; it is re-derived on every reconcile. Addresses stacklok/toolhive#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 --- .../controllers/external_auth_mirror.go | 3 +- .../controllers/external_auth_mirror_test.go | 157 ++++++++++++++++++ .../controllers/mcpremoteproxy_controller.go | 7 +- .../controllers/mcpserver_controller.go | 5 + .../mcpserver_externalauth_test.go | 112 +++++++++---- docs/arch/09-operator-architecture.md | 2 + 6 files changed, 254 insertions(+), 32 deletions(-) diff --git a/cmd/thv-operator/controllers/external_auth_mirror.go b/cmd/thv-operator/controllers/external_auth_mirror.go index 3eba787674..a44ec7ff52 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror.go +++ b/cmd/thv-operator/controllers/external_auth_mirror.go @@ -33,7 +33,8 @@ const fallbackInvalidReason = "InvalidExternalAuthConfig" // surface the same Reason a consumer uses for its own validation failures (a // malformed obo config is Valid=False / InvalidConfig), so the Reason alone // cannot tell the two owners apart. No local writer of InvalidConfig or -// InvalidCABundle starts its message with this prefix. +// InvalidCABundle may start its message with this prefix; +// TestMirroredMessagePrefix_NotUsedByLocalMessages checks the fixed ones. const mirroredMessagePrefix = "Referenced MCPExternalAuthConfig " // mirroredInvalidExternalAuthConfigError signals that a referenced diff --git a/cmd/thv-operator/controllers/external_auth_mirror_test.go b/cmd/thv-operator/controllers/external_auth_mirror_test.go index a5b3c63d97..d4fac0ef74 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror_test.go +++ b/cmd/thv-operator/controllers/external_auth_mirror_test.go @@ -5,6 +5,9 @@ package controllers import ( "context" + "errors" + "fmt" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -18,6 +21,7 @@ import ( mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1/v1beta1test" "github.com/stacklok/toolhive/cmd/thv-operator/internal/testutil" + ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil" "github.com/stacklok/toolhive/pkg/container/kubernetes" ) @@ -228,3 +232,156 @@ func TestExternalAuthMirror_OBOSourceHealsToSameSpec(t *testing.T) { }) } } + +// TestExternalAuthMirror_OBOIncomingAuthRejectionClearsOnRevert covers the +// consumer's own obo incoming-auth rejection rather than a mirrored one. A +// consumer without oidcConfigRef references a valid non-obo config and stores +// its hash. The source switches to obo, so the consumer records InvalidConfig +// while its stored hash stays at the old value. The source then reverts to the +// original spec and hash: the consumer must end on True, because the rejection +// no longer applies, even though its generation and stored hash are unchanged. +func TestExternalAuthMirror_OBOIncomingAuthRejectionClearsOnRevert(t *testing.T) { + t.Parallel() + + const ( + namespace = "default" + authName = "auth-config" + ) + + tests := []struct { + name string + newConsumer func() client.Object + handle func(ctx context.Context, c client.Client, obj client.Object) error + condition func(obj client.Object) *metav1.Condition + wantReason string + }{ + { + name: "MCPServer", + newConsumer: func() client.Object { + return v1beta1test.NewMCPServer("server", namespace, + v1beta1test.WithImage("test-image"), + v1beta1test.WithExternalAuthConfigRef(authName), + v1beta1test.Mutate(func(m *mcpv1beta1.MCPServer) { m.Generation = 4 }), + ) + }, + handle: func(ctx context.Context, c client.Client, obj client.Object) error { + r := newTestMCPServerReconciler(c, c.Scheme(), kubernetes.PlatformKubernetes) + return r.handleExternalAuthConfig(ctx, obj.(*mcpv1beta1.MCPServer)) + }, + condition: func(obj client.Object) *metav1.Condition { + return meta.FindStatusCondition(obj.(*mcpv1beta1.MCPServer).Status.Conditions, + mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + }, + wantReason: mcpv1beta1.ConditionReasonExternalAuthConfigValid, + }, + { + name: "MCPRemoteProxy", + newConsumer: func() client.Object { + return v1beta1test.NewMCPRemoteProxy("proxy", namespace, + v1beta1test.WithRemoteProxyExternalAuthConfigRef(authName), + v1beta1test.MutateRemoteProxy(func(p *mcpv1beta1.MCPRemoteProxy) { + p.Generation = 4 + p.Spec.OIDCConfigRef = nil + }), + ) + }, + handle: func(ctx context.Context, c client.Client, obj client.Object) error { + r := &MCPRemoteProxyReconciler{Client: c, Scheme: c.Scheme()} + return r.handleExternalAuthConfig(ctx, obj.(*mcpv1beta1.MCPRemoteProxy)) + }, + condition: func(obj client.Object) *metav1.Condition { + return meta.FindStatusCondition(obj.(*mcpv1beta1.MCPRemoteProxy).Status.Conditions, + mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated) + }, + wantReason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigValid, + }, + } + + unauthenticated := mcpv1beta1.MCPExternalAuthConfigSpec{Type: mcpv1beta1.ExternalAuthTypeUnauthenticated} + oboSpec := mcpv1beta1.MCPExternalAuthConfigSpec{Type: mcpv1beta1.ExternalAuthTypeOBO, OBO: validOBOSpec()} + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx := t.Context() + + source := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: authName, + Namespace: namespace, + Finalizers: []string{ExternalAuthConfigFinalizerName}, + }, + Spec: unauthenticated, + } + consumer := tt.newConsumer() + + scheme := testutil.NewScheme(t) + c := withExternalAuthConfigRefIndexes(fake.NewClientBuilder().WithScheme(scheme)). + WithObjects(source, consumer). + WithStatusSubresource( + &mcpv1beta1.MCPExternalAuthConfig{}, &mcpv1beta1.MCPServer{}, &mcpv1beta1.MCPRemoteProxy{}). + Build() + sourceReconciler := &MCPExternalAuthConfigReconciler{Client: c, Scheme: scheme} + sourceKey := client.ObjectKeyFromObject(source) + + // setSourceSpec writes spec, reconciles the source and returns its hash. + setSourceSpec := func(spec mcpv1beta1.MCPExternalAuthConfigSpec) string { + t.Helper() + live := &mcpv1beta1.MCPExternalAuthConfig{} + require.NoError(t, c.Get(ctx, sourceKey, live)) + live.Spec = spec + require.NoError(t, c.Update(ctx, live)) + _, err := sourceReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: sourceKey}) + require.NoError(t, err) + require.NoError(t, c.Get(ctx, sourceKey, live)) + return live.Status.ConfigHash + } + + // 1. Non-obo source: True, and the consumer stores its hash. + originalHash := setSourceSpec(unauthenticated) + require.NotEmpty(t, originalHash) + require.NoError(t, tt.handle(ctx, c, consumer)) + require.Equal(t, metav1.ConditionTrue, tt.condition(consumer).Status) + + // 2. obo source: the consumer has no incoming OIDC and rejects it. + require.NotEqual(t, originalHash, setSourceSpec(oboSpec)) + require.Error(t, tt.handle(ctx, c, consumer)) + rejected := tt.condition(consumer) + require.NotNil(t, rejected) + require.Equal(t, metav1.ConditionFalse, rejected.Status) + require.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, rejected.Message) + + // 3. Revert to the original spec: same hash as the consumer stored. + require.Equal(t, originalHash, setSourceSpec(unauthenticated)) + require.NoError(t, tt.handle(ctx, c, consumer)) + healed := tt.condition(consumer) + require.NotNil(t, healed) + assert.Equal(t, metav1.ConditionTrue, healed.Status, + "the obo incoming-auth rejection must clear once the source is no longer obo") + assert.Equal(t, tt.wantReason, healed.Reason) + }) + } +} + +// TestMirroredMessagePrefix_NotUsedByLocalMessages pins the invariant +// isLocalValidationFailure relies on: no locally written InvalidConfig or +// InvalidCABundle message starts with mirroredMessagePrefix, or the condition +// would be mistaken for a mirrored one and cleared by the mirror on every +// reconcile. The embedded-auth RunConfig build failure carries a dynamic error +// message and is not listed; its errors come from RunConfig validation and do +// not name a referenced MCPExternalAuthConfig. +func TestMirroredMessagePrefix_NotUsedByLocalMessages(t *testing.T) { + t.Parallel() + + localMessages := map[string]string{ + "obo incoming auth": ctrlutil.MsgOBORequiresIncomingAuth, + "CA bundle": fmt.Sprintf("invalid CA bundle: %v", errors.New("missing key")), + } + for name, msg := range localMessages { + assert.False(t, strings.HasPrefix(msg, mirroredMessagePrefix), + "%s message %q must not start with the mirrored prefix", name, msg) + assert.True(t, isLocalValidationFailure(&metav1.Condition{ + Status: metav1.ConditionFalse, Reason: mcpv1beta1.ConditionReasonInvalidConfig, Message: msg, + }), "%s message must be treated as locally owned", name) + } +} diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index 6d3b2cb1af..d7f67a6137 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -1115,7 +1115,11 @@ func (r *MCPRemoteProxyReconciler) handleExternalAuthConfig(ctx context.Context, // until its referenced configuration or this resource generation changes. An // InvalidConfig mirrored from the referenced MCPExternalAuthConfig is not held // (see isLocalValidationFailure): the source can heal back to an unchanged -// ConfigHash, and holding it would make the failure permanent. +// ConfigHash, and holding it would make the failure permanent. Nor is the obo +// incoming-auth rejection (ctrlutil.MsgOBORequiresIncomingAuth): it re-runs +// earlier in handleExternalAuthConfig and returns before the stored hash +// advances, so a source that reverts from obo to its earlier spec matches the +// stored hash, and holding it would keep a stale False. func setMCPRemoteProxyExternalAuthConfigValidCondition( proxy *mcpv1beta1.MCPRemoteProxy, configName, configHash string, @@ -1125,6 +1129,7 @@ func setMCPRemoteProxyExternalAuthConfigValidCondition( ) if isLocalValidationFailure(previousCondition) && previousCondition.Reason == mcpv1beta1.ConditionReasonInvalidConfig && + previousCondition.Message != ctrlutil.MsgOBORequiresIncomingAuth && previousCondition.ObservedGeneration == proxy.Generation && proxy.Status.ExternalAuthConfigHash == configHash { return diff --git a/cmd/thv-operator/controllers/mcpserver_controller.go b/cmd/thv-operator/controllers/mcpserver_controller.go index aefa56b9b1..e67b3e9326 100644 --- a/cmd/thv-operator/controllers/mcpserver_controller.go +++ b/cmd/thv-operator/controllers/mcpserver_controller.go @@ -2567,6 +2567,10 @@ func (r *MCPServerReconciler) handleExternalAuthConfig(ctx context.Context, m *m // Neither is an InvalidConfig mirrored from the referenced // 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 +// stored hash advances, so a source that reverts from obo to its earlier spec +// matches the stored hash, and holding it would keep a stale False. func setMCPServerExternalAuthConfigValidCondition( m *mcpv1beta1.MCPServer, configName, configHash string, @@ -2576,6 +2580,7 @@ func setMCPServerExternalAuthConfigValidCondition( ) if isLocalValidationFailure(previousCondition) && previousCondition.Reason == mcpv1beta1.ConditionReasonInvalidConfig && + previousCondition.Message != ctrlutil.MsgOBORequiresIncomingAuth && previousCondition.ObservedGeneration == m.Generation && m.Status.ExternalAuthConfigHash == configHash { return diff --git a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go index d163cc40cc..7b5a3b79e9 100644 --- a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go @@ -16,6 +16,7 @@ package controllers import ( "context" + stderrors "errors" "fmt" "testing" "time" @@ -30,6 +31,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" "sigs.k8s.io/controller-runtime/pkg/log" mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" @@ -929,43 +931,93 @@ func TestMCPServerReconciler_handleExternalAuthConfig_OBORequiresIncomingAuth(t // TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal drives Reconcile for // an MCPServer that references a valid obo config but has no oidcConfigRef. // The rejection is a spec defect, so Reconcile records it on status and returns -// an empty result with no error rather than requeueing with backoff. +// an empty result with no error rather than requeueing with backoff. Only a +// failure to persist that rejection is returned, so the write is retried. A +// non-validation error (a missing referenced config) is returned and requeued. func TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal(t *testing.T) { t.Parallel() - server := v1beta1test.NewMCPServer("server", "default", - v1beta1test.WithImage("test"), - v1beta1test.WithExternalAuthConfigRef("obo-config"), - ) - authConfig := &mcpv1beta1.MCPExternalAuthConfig{ - ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, - Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ - Type: mcpv1beta1.ExternalAuthTypeOBO, - OBO: validOBOSpec(), + statusErr := stderrors.New("simulated status write failure") + // failRejectionWrite fails only the status write that records the obo + // rejection, so an unrelated earlier write cannot satisfy the assertion. + failRejectionWrite := interceptor.Funcs{ + SubResourceUpdate: func( + ctx context.Context, c client.Client, subResource string, obj client.Object, + opts ...client.SubResourceUpdateOption, + ) error { + if m, ok := obj.(*mcpv1beta1.MCPServer); ok { + cond := meta.FindStatusCondition(m.Status.Conditions, + mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + if cond != nil && cond.Reason == mcpv1beta1.ConditionReasonInvalidConfig { + return statusErr + } + } + return c.SubResource(subResource).Update(ctx, obj, opts...) }, } - scheme := testutil.NewScheme(t) - fakeClient := fake.NewClientBuilder().WithScheme(scheme). - WithObjects(server, authConfig). - WithStatusSubresource(&mcpv1beta1.MCPServer{}). - Build() - reconciler := newTestMCPServerReconciler(fakeClient, scheme, kubernetes.PlatformKubernetes) - result, err := reconciler.Reconcile(t.Context(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(server)}) - require.NoError(t, err, "a spec defect must not be returned as an error (that requeues with backoff)") - assert.Equal(t, ctrl.Result{}, result) + tests := []struct { + name string + authRef string + interceptor *interceptor.Funcs + wantErr error + wantAnyErr bool + }{ + {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}, + } - actual := &mcpv1beta1.MCPServer{} - require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(server), actual)) - assert.Equal(t, mcpv1beta1.MCPServerPhaseFailed, actual.Status.Phase) - ready := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeReady) - require.NotNil(t, ready) - assert.Equal(t, metav1.ConditionFalse, ready.Status) - validated := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) - require.NotNil(t, validated) - assert.Equal(t, metav1.ConditionFalse, validated.Status) - assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, validated.Reason) - assert.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, validated.Message) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + server := v1beta1test.NewMCPServer("server", "default", + v1beta1test.WithImage("test"), + v1beta1test.WithExternalAuthConfigRef(tt.authRef), + ) + authConfig := &mcpv1beta1.MCPExternalAuthConfig{ + ObjectMeta: metav1.ObjectMeta{Name: "obo-config", Namespace: "default"}, + Spec: mcpv1beta1.MCPExternalAuthConfigSpec{ + Type: mcpv1beta1.ExternalAuthTypeOBO, + OBO: validOBOSpec(), + }, + } + scheme := testutil.NewScheme(t) + builder := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(server, authConfig). + WithStatusSubresource(&mcpv1beta1.MCPServer{}) + if tt.interceptor != nil { + builder = builder.WithInterceptorFuncs(*tt.interceptor) + } + fakeClient := builder.Build() + reconciler := newTestMCPServerReconciler(fakeClient, scheme, kubernetes.PlatformKubernetes) + + result, err := reconciler.Reconcile(t.Context(), ctrl.Request{NamespacedName: client.ObjectKeyFromObject(server)}) + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr, "an unpersisted rejection must be retried, not dropped") + return + } + if tt.wantAnyErr { + require.Error(t, err, "a non-validation error must be returned so it requeues") + return + } + require.NoError(t, err, "a spec defect must not be returned as an error (that requeues with backoff)") + assert.Equal(t, ctrl.Result{}, result) + + actual := &mcpv1beta1.MCPServer{} + require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(server), actual)) + assert.Equal(t, mcpv1beta1.MCPServerPhaseFailed, actual.Status.Phase) + ready := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeReady) + require.NotNil(t, ready) + assert.Equal(t, metav1.ConditionFalse, ready.Status) + validated := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + require.NotNil(t, validated) + assert.Equal(t, metav1.ConditionFalse, validated.Status) + assert.Equal(t, mcpv1beta1.ConditionReasonInvalidConfig, validated.Reason) + assert.Equal(t, ctrlutil.MsgOBORequiresIncomingAuth, validated.Message) + }) + } } // TestMCPServerDeployment_OBOSecretEnvVars verifies that an obo-typed diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index aa88160acf..2eee585edc 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -238,6 +238,8 @@ MCPExternalAuthConfig resources can be referenced via two paths: **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__`, where `` 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 '' is invalid: ` (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. + **Controller**: `cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go` `EmbeddedAuthServerConfig` can carry top-level SPIFFE trust-domain declarations in `spiffeTrustDomains` and canonical client associations in `inboundGrants.spiffeClientAuth` (`cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go`). The operator converts these CRD fields into runtime config via `buildSPIFFETrustDomainRunConfigs`/`buildSPIFFEClientAuthRunConfigs` in `cmd/thv-operator/pkg/controllerutil/authserver.go`, and projects file-source ConfigMap data read-only. `newServer` constructs the configured bundle source and passes its X.509 and JWT views to the authorization server. `RunConfig.Validate()` accepts only the `file` bundle source, so a `bundle_endpoint` or `workload_api` source passes the CRD schema but is rejected by the MCPExternalAuthConfig validation and by the VirtualMCPServer inline `authServerConfig` validation (both through `EmbeddedAuthServerConfig.ValidateSPIFFEBundleSourceTypes`, which calls `authserver.ValidateRuntimeSPIFFEBundleSourceType`), and again by `BuildAuthServerRunConfig` when a referencing workload reconciles. With a `file` source, JWT-SVID and X.509-SVID client authentication are enforced. The proxy runner and vMCP can start the auth-server TLS listener on fixed port 8443. The operator's `embeddedAuthServer.tlsListener` field, its validation and the pod rollout rules are described in the [Operator configuration](18-spiffe-association-declarations.md#operator-configuration) section of that document. When the listener is enabled, the operator adds an `https-auth` container port and Service port 8443 (with `appProtocol: https`) alongside the existing `http` port. X.509 client authentication needs TLS passed through to the listener, because a proxy or Ingress that terminates TLS drops the client certificate. See [SPIFFE Association Declarations](18-spiffe-association-declarations.md) for current scope. From 2f1213532bfdc51d86f4f87fcdc031ecad6e2888 Mon Sep 17 00:00:00 2001 From: Trey Date: Sun, 22 Nov 2026 18:54:43 -0800 Subject: [PATCH 10/12] Tighten OBO vMCP errors, validation and tests A rejected client credential now reads as a generic exchange failure to MCP clients, a whitespace clientId fails strategy validation, and a 429 or 408 with an unparsable body is transient like one with a JSON body. Addresses stacklok/toolhive#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 --- docs/arch/10-virtual-mcp-architecture.md | 6 +- docs/middleware.md | 8 +- pkg/auth/obo/entra/exchanger.go | 2 +- pkg/auth/obo/entra/exchanger_test.go | 21 +++ pkg/vmcp/auth/strategies/obo.go | 60 ++++++-- pkg/vmcp/auth/strategies/obo_test.go | 188 +++++++++-------------- pkg/vmcp/config/yaml_loader_test.go | 156 +++++++++++++++++++ 7 files changed, 312 insertions(+), 129 deletions(-) diff --git a/docs/arch/10-virtual-mcp-architecture.md b/docs/arch/10-virtual-mcp-architecture.md index 4b217e7319..c2b0b09e4e 100644 --- a/docs/arch/10-virtual-mcp-architecture.md +++ b/docs/arch/10-virtual-mcp-architecture.md @@ -1092,8 +1092,10 @@ exchanger per (token URL, client ID, cache skew, client-secret fingerprint). Health-check probes carry no user and skip the exchange. A conditional-access or claims challenge fails the backend request and writes an `obo_token_exchange` audit event. The error returned to the MCP client names -only the failure class (denied, invalid grant, client authentication, or -transient); Entra's error code and description go to the vMCP log instead. OBO works for inline `outgoingAuth` +at most the failure class (denied, invalid grant, or transient); a rejected +client credential reads as a plain "token exchange failed", since it is the +operator's problem. Entra's error code and description go to the vMCP log +instead. OBO works for inline `outgoingAuth` backends, where the operator mounts each config's client secret under `TOOLHIVE_OBO_CLIENT_SECRET__` (a short hash of the config name keeps names such as `my-cfg` and `my.cfg` distinct), and for discovered backends diff --git a/docs/middleware.md b/docs/middleware.md index 9ef1d4e96e..795565d7d2 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -526,9 +526,15 @@ body that does not disclose the provider error: | Named upstream provider token missing | 401 with `WWW-Authenticate: Bearer error="invalid_token"` | | Entra `invalid_grant` (subject token rejected) | 401 | | Conditional access, MFA, or claims challenge (`interaction_required`, a `claims` value, AADSTS50076/50079) | 403, plus an `obo_token_exchange` audit event with outcome `denied` | -| `invalid_client`, Entra 5xx, 429, 408 or `temporarily_unavailable` (throttling, classed as transient whatever the body says), unreachable, or an unclassified failure | 502 | +| Entra HTTP 5xx, 429 or 408, whatever the body says (transient) | 502 | +| Entra `temporarily_unavailable` on another status, unless the reply is also a claims challenge (transient) | 502 | +| Token endpoint unreachable or timed out (transient) | 502 | +| Entra `invalid_client` (the proxy's client credential was rejected), or an unclassified failure | 502 | | Client cancelled the request | no response | +Throttling is reported as a plain 502: Entra's `Retry-After` header is not +forwarded to the client. + ### 10. Audit Middleware **Purpose**: Logs request events for compliance, monitoring, and debugging. diff --git a/pkg/auth/obo/entra/exchanger.go b/pkg/auth/obo/entra/exchanger.go index 9a4b69f852..0cfeba9416 100644 --- a/pkg/auth/obo/entra/exchanger.go +++ b/pkg/auth/obo/entra/exchanger.go @@ -333,7 +333,7 @@ func parseResponse(status int, body []byte, now time.Time) (exchange.Token, erro if err := json.Unmarshal(body, &tr); err != nil { // Unparsable body: classify by status alone, without echoing the body. kind := KindUnknown - if status >= http.StatusInternalServerError { + if isTransientStatus(status) { kind = KindTransient } return exchange.Token{}, &ExchangeError{ diff --git a/pkg/auth/obo/entra/exchanger_test.go b/pkg/auth/obo/entra/exchanger_test.go index cfc81a0e5a..3fb6abfba3 100644 --- a/pkg/auth/obo/entra/exchanger_test.go +++ b/pkg/auth/obo/entra/exchanger_test.go @@ -356,6 +356,27 @@ func TestExchanger_ExchangeToken_Failures(t *testing.T) { wantKind: entra.KindUnknown, wantSentinel: nil, }, + { + name: "429 with an HTML body is transient", + status: http.StatusTooManyRequests, + body: `Too Many Requests`, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "408 with an empty body is transient", + status: http.StatusRequestTimeout, + body: ``, + wantKind: entra.KindTransient, + wantSentinel: entra.ErrTransient, + }, + { + name: "malformed 4xx body stays unclassified", + status: http.StatusBadRequest, + body: `bad request`, + wantKind: entra.KindUnknown, + wantSentinel: nil, + }, } for _, tt := range tests { diff --git a/pkg/vmcp/auth/strategies/obo.go b/pkg/vmcp/auth/strategies/obo.go index cfd0f52400..c20c5377d4 100644 --- a/pkg/vmcp/auth/strategies/obo.go +++ b/pkg/vmcp/auth/strategies/obo.go @@ -11,6 +11,7 @@ import ( "fmt" "log/slog" "net/http" + "strings" "sync" "time" @@ -51,11 +52,20 @@ type OBOStrategy struct { envReader env.Reader auditLogger *slog.Logger + // logger receives the diagnostic log of exchange failures. nil means + // slog.Default(), read at log time; tests set it to capture the output. + logger *slog.Logger + // buildExchanger constructs the cached Exchanger for a config. It is a field // so tests can inject a stub Exchanger instead of a real Entra HTTP client; // production uses defaultBuildOBOExchanger. buildExchanger func(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) + // 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() + // mu guards exchangers. mu sync.RWMutex @@ -201,6 +211,10 @@ func (s *OBOStrategy) getOrCreateExchanger(cfg *authtypes.OBOConfig, clientSecre } s.mu.RUnlock() + if s.afterReadMiss != nil { + s.afterReadMiss() + } + s.mu.Lock() defer s.mu.Unlock() if ex, ok := s.exchangers[key]; ok { @@ -237,32 +251,52 @@ func (s *OBOStrategy) mapExchangeError( case errors.Is(err, entra.ErrInvalidGrant): // The end-user token was rejected (expired, malformed, or not consented): // a per-caller condition, so it is logged at DEBUG only. - logExchangeFailure(ctx, slog.LevelDebug, err) + s.logExchangeFailure(ctx, slog.LevelDebug, err) return fmt.Errorf("obo: token exchange failed: %w", entra.ErrInvalidGrant) + case errors.Is(err, entra.ErrInvalidClient): + // A rejected client credential is the operator's problem, not the + // caller's, so the message does not say so; the proxy middleware hides + // it behind an opaque 502 for the same reason. errors.Is still matches. + s.logExchangeFailure(ctx, slog.LevelWarn, err) + return &opaqueExchangeError{sentinel: entra.ErrInvalidClient} + case errors.Is(err, entra.ErrTransient): + s.logExchangeFailure(ctx, slog.LevelWarn, err) + return fmt.Errorf("obo: token exchange failed: %w", entra.ErrTransient) default: - // invalid_client, a transient IdP failure, or an unclassified error. - logExchangeFailure(ctx, slog.LevelWarn, err) - for _, sentinel := range []error{entra.ErrInvalidClient, entra.ErrTransient} { - if errors.Is(err, sentinel) { - return fmt.Errorf("obo: token exchange failed: %w", sentinel) - } - } - return errors.New("obo: token exchange failed") + s.logExchangeFailure(ctx, slog.LevelWarn, err) + return errors.New(oboExchangeFailedMessage) } } +// oboExchangeFailedMessage is the generic client-facing exchange failure text. +const oboExchangeFailedMessage = "obo: token exchange failed" + +// opaqueExchangeError reports a generic exchange failure to the client while +// still matching sentinel with errors.Is. +type opaqueExchangeError struct { + sentinel error +} + +func (*opaqueExchangeError) Error() string { return oboExchangeFailedMessage } + +func (e *opaqueExchangeError) Unwrap() error { return e.sentinel } + // logExchangeFailure records an exchange failure in the diagnostic log. Only // *entra.ExchangeError detail is logged: its Error() composes solely // non-sensitive fields. Any other error is logged without its message so no // Exchanger implementation can leak credential material here, matching the // proxy middleware. -func logExchangeFailure(ctx context.Context, level slog.Level, err error) { +func (s *OBOStrategy) logExchangeFailure(ctx context.Context, level slog.Level, err error) { + logger := s.logger + if logger == nil { + logger = slog.Default() + } var exErr *entra.ExchangeError if errors.As(err, &exErr) { - slog.Log(ctx, level, "obo: token exchange failed", "error", exErr.Error()) + logger.Log(ctx, level, "obo: token exchange failed", "error", exErr.Error()) return } - slog.Log(ctx, level, "obo: token exchange failed with an unclassified error") + logger.Log(ctx, level, "obo: token exchange failed with an unclassified error") } // auditInteractionRequired emits the audit record for a fail-fast @@ -317,7 +351,7 @@ func parseOBOConfig(strategy *authtypes.BackendAuthStrategy) (*authtypes.OBOConf if cfg.TokenURL == "" { return nil, fmt.Errorf("tokenUrl is required") } - if cfg.ClientID == "" { + if strings.TrimSpace(cfg.ClientID) == "" { return nil, fmt.Errorf("clientId is required") } if cfg.ClientSecret != "" && cfg.ClientSecretEnv != "" { diff --git a/pkg/vmcp/auth/strategies/obo_test.go b/pkg/vmcp/auth/strategies/obo_test.go index 57d360ebf4..bce56f26d9 100644 --- a/pkg/vmcp/auth/strategies/obo_test.go +++ b/pkg/vmcp/auth/strategies/obo_test.go @@ -11,9 +11,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "runtime" - "strings" - "sync" "sync/atomic" "testing" "time" @@ -398,7 +395,9 @@ func TestOBOAuthenticate_ConditionalAccess_FailsFastWithAudit(t *testing.T) { // returns an error that still matches its entra sentinel but carries none of // Entra's provider detail (the error reaches MCP clients via the tool error), // injects nothing, and that only a conditional-access denial emits the audit -// record — which keeps the detail server-side. +// record — which keeps the detail server-side. Every other failure keeps it in +// the diagnostic log instead, at DEBUG for invalid_grant and WARN otherwise; a +// non-entra error is logged without its message. func TestOBOAuthenticate_ExchangeErrorMapping(t *testing.T) { t.Parallel() @@ -415,16 +414,28 @@ func TestOBOAuthenticate_ExchangeErrorMapping(t *testing.T) { err error wantSentinel error // nil: matches none of the entra sentinels wantAudit bool + // wantLogLevel is the diagnostic log level; "" means no diagnostic log. + wantLogLevel string + // wantLogDetail is whether the diagnostic log carries Entra's detail. + wantLogDetail bool + // wantMessage, when set, is the exact client-facing error text. + wantMessage string }{ {name: "interaction required", err: exErr(entra.KindInteractionRequired), wantSentinel: entra.ErrInteractionRequired, wantAudit: true}, - {name: "invalid grant", err: exErr(entra.KindInvalidGrant), wantSentinel: entra.ErrInvalidGrant}, - {name: "invalid client", err: exErr(entra.KindInvalidClient), wantSentinel: entra.ErrInvalidClient}, - {name: "transient", err: exErr(entra.KindTransient), wantSentinel: entra.ErrTransient}, - {name: "unknown kind", err: exErr(entra.KindUnknown)}, + {name: "invalid grant", err: exErr(entra.KindInvalidGrant), wantSentinel: entra.ErrInvalidGrant, + wantLogLevel: "DEBUG", wantLogDetail: true}, + {name: "invalid client", err: exErr(entra.KindInvalidClient), wantSentinel: entra.ErrInvalidClient, + wantLogLevel: "WARN", wantLogDetail: true, wantMessage: "obo: token exchange failed"}, + {name: "transient", err: exErr(entra.KindTransient), wantSentinel: entra.ErrTransient, + wantLogLevel: "WARN", wantLogDetail: true}, + {name: "unknown kind", err: exErr(entra.KindUnknown), + wantLogLevel: "WARN", wantLogDetail: true, wantMessage: "obo: token exchange failed"}, {name: "wrapped exchange error", err: fmt.Errorf("cache: %w", exErr(entra.KindInvalidClient)), - wantSentinel: entra.ErrInvalidClient}, - {name: "non-entra error", err: errors.New("unexpected failure " + description)}, + wantSentinel: entra.ErrInvalidClient, wantLogLevel: "WARN", wantLogDetail: true, + wantMessage: "obo: token exchange failed"}, + {name: "non-entra error", err: errors.New("unexpected failure " + description), + wantLogLevel: "WARN", wantMessage: "obo: token exchange failed"}, } for _, tt := range tests { @@ -433,13 +444,32 @@ func TestOBOAuthenticate_ExchangeErrorMapping(t *testing.T) { var auditBuf bytes.Buffer auditLogger := slog.New(slog.NewJSONHandler(&auditBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) + var logBuf bytes.Buffer stub := &oboStubExchanger{err: tt.err} s := oboStrategyWithStub(stub, auditLogger) + s.logger = slog.New(slog.NewJSONHandler(&logBuf, &slog.HandlerOptions{Level: slog.LevelDebug})) ctx := auth.WithIdentity(t.Context(), oboInboundIdentity("user-token")) req, err := oboServeAuthenticate(ctx, t, s, validOBOStrategy()) require.Error(t, err) assert.Empty(t, req.Header.Get("Authorization")) + if tt.wantMessage != "" { + assert.Equal(t, tt.wantMessage, err.Error()) + } + + logOut := logBuf.String() + if tt.wantLogLevel == "" { + assert.Empty(t, logOut, "this failure is recorded in the audit log, not the diagnostic log") + } else { + assert.Contains(t, logOut, `"level":"`+tt.wantLogLevel+`"`) + if tt.wantLogDetail { + assert.Contains(t, logOut, description, "the diagnostic log keeps Entra's description") + assert.Contains(t, logOut, oauthError, "the diagnostic log keeps Entra's error code") + } else { + assert.Contains(t, logOut, "unclassified error") + assert.NotContains(t, logOut, description, "a non-entra error's text must not be logged") + } + } assert.NotContains(t, err.Error(), description, "Entra's error_description must not reach the client") assert.NotContains(t, err.Error(), oauthError, "Entra's error code must not reach the client") @@ -609,124 +639,57 @@ func TestOBOExchangerCacheKey(t *testing.T) { } // TestOBOGetOrCreateExchanger_BuildsOnceUnderContention exercises the -// double-checked lock: callers released together all miss on the read-locked -// check, and the builder holds the write lock until every other caller is -// parked on the mutex. Callers that queued on the write lock must find the +// double-checked lock deterministically: the afterReadMiss hook holds every +// caller after its read-locked miss until all of them have missed, so they all +// then queue on the write lock. Every caller after the first must find the // Exchanger on the second check rather than building another one. -// -// A caller that reached the read lock only after the build began never needs the -// second check, so an attempt where no caller was parked on the write lock -// proves nothing; such attempts are retried. Callers busy-wait on a gate rather -// than block on a channel, so each is already running on its own P when -// released and their read checks overlap. One P is left free for the test -// goroutine to open the gate. func TestOBOGetOrCreateExchanger_BuildsOnceUnderContention(t *testing.T) { t.Parallel() - procs := runtime.GOMAXPROCS(0) - if procs < 3 { - t.Skip("needs GOMAXPROCS >= 3 for callers to overlap on the read-locked check") - } - callers := int32(min(procs-1, 8)) - const maxAttempts = 200 + const callers = 8 cfg := validOBOStrategy().OBO - for range maxAttempts { - var builds, writeWaiters atomic.Int32 - s := newOBOStrategy(oboMapEnv{}, nil, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { - if builds.Add(1) == 1 { - writeWaiters.Store(int32(awaitParkedOnMutex( - "TestOBOGetOrCreateExchanger_BuildsOnceUnderContention", int(callers)-1))) - } - return &oboStubExchanger{}, nil - }) + var builds atomic.Int32 + s := newOBOStrategy(oboMapEnv{}, nil, func(_ *authtypes.OBOConfig, _ string) (exchange.Exchanger, error) { + builds.Add(1) + return &oboStubExchanger{}, nil + }) - var ready atomic.Int32 - var gate atomic.Bool - var wg sync.WaitGroup - for range callers { - wg.Add(1) - go func() { - defer wg.Done() - ready.Add(1) - for !gate.Load() { - // Busy-wait deliberately: the caller stays on its P, so it - // starts the instant the gate opens. - } - ex, err := s.getOrCreateExchanger(cfg, "resolved-secret") - assert.NoError(t, err) - assert.NotNil(t, ex) - }() + var missed atomic.Int32 + allMissed := make(chan struct{}) + s.afterReadMiss = func() { + if missed.Add(1) == callers { + close(allMissed) } - require.Eventually(t, func() bool { return ready.Load() == callers }, - 5*time.Second, time.Millisecond, "callers must reach the gate") - gate.Store(true) - waitGroupWithTimeout(t, &wg) - - if writeWaiters.Load() == 0 { - continue // the second check was not exercised; try again + select { + case <-allMissed: + case <-time.After(5 * time.Second): + // Fall through: the build count assertion reports the failure. } - assert.Equal(t, int32(1), builds.Load(), - "callers queued on the write lock must reuse the Exchanger built by the first") - return } - t.Fatalf("no attempt in %d had a caller parked on the write lock", maxAttempts) -} -// awaitParkedOnMutex polls goroutine stacks until want goroutines created by -// testName are blocked on an RWMutex inside getOrCreateExchanger, or a timeout -// passes. It returns how many of them were waiting on the write lock (Lock) -// rather than the read lock. It runs inside the builder, on a caller's -// goroutine, so it reports rather than failing the test. -func awaitParkedOnMutex(testName string, want int) int { - deadline := time.Now().Add(5 * time.Second) - for { - parked, writers := 0, 0 - for _, g := range goroutineStacks() { - if !strings.Contains(g, testName) || !strings.Contains(g, "getOrCreateExchanger") { - continue - } - switch { - case strings.Contains(g, "(*RWMutex).Lock("): - parked++ - writers++ - case strings.Contains(g, "(*RWMutex).RLock("): - parked++ + results := make(chan error, callers) + for range callers { + go func() { + ex, err := s.getOrCreateExchanger(cfg, "resolved-secret") + if err == nil && ex == nil { + err = errors.New("nil exchanger") } - } - if parked >= want || time.Now().After(deadline) { - return writers - } - time.Sleep(time.Millisecond) + results <- err + }() } -} - -// goroutineStacks returns the stack trace of every goroutine, one per element. -func goroutineStacks() []string { - buf := make([]byte, 1<<20) - for { - n := runtime.Stack(buf, true) - if n < len(buf) { - return strings.Split(string(buf[:n]), "\n\n") + for range callers { + select { + case err := <-results: + require.NoError(t, err) + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for getOrCreateExchanger callers") } - buf = make([]byte, 2*len(buf)) } -} -// waitGroupWithTimeout waits for wg, failing the test if it does not finish in -// time. Call it only from the test goroutine. -func waitGroupWithTimeout(t *testing.T, wg *sync.WaitGroup) { - t.Helper() - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("timed out waiting for goroutines to finish") - } + require.Equal(t, int32(callers), missed.Load(), "every caller must miss on the read-locked check") + assert.Equal(t, int32(1), builds.Load(), + "callers queued on the write lock must reuse the Exchanger built by the first") } func TestOBOValidate_Valid(t *testing.T) { @@ -747,6 +710,7 @@ func TestOBOValidate_Invalid(t *testing.T) { {name: "nil obo", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO = nil }, wantMsg: "OBO configuration is required"}, {name: "missing token url", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.TokenURL = "" }, wantMsg: "tokenUrl is required"}, {name: "missing client id", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientID = "" }, wantMsg: "clientId is required"}, + {name: "whitespace client id", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientID = " " }, wantMsg: "clientId is required"}, {name: "no audience or scopes", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.Scopes = nil; s.OBO.Audience = "" }, wantMsg: "one of audience or scopes is required"}, {name: "both secret sources", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientSecretEnv = "ENV" }, wantMsg: "mutually exclusive"}, {name: "no secret source", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientSecret = "" }, wantMsg: "a client secret is required"}, diff --git a/pkg/vmcp/config/yaml_loader_test.go b/pkg/vmcp/config/yaml_loader_test.go index 8f056639fd..e98e7ec615 100644 --- a/pkg/vmcp/config/yaml_loader_test.go +++ b/pkg/vmcp/config/yaml_loader_test.go @@ -550,6 +550,162 @@ aggregation: wantErr: true, errMsg: "environment variable EMPTY_TOKEN not set or empty", }, + { + // The secret stays behind clientSecretEnv: the OBO strategy reads it + // at request time and rejects a config that sets both fields. + name: "obo clientSecretEnv is checked but not resolved", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token + clientId: client-123 + clientSecretEnv: OBO_SECRET + scopes: + - api://backend/.default + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + envVars: map[string]string{"OBO_SECRET": "secret-value"}, + want: func(t *testing.T, cfg *Config) { + t.Helper() + backend, ok := cfg.OutgoingAuth.Backends["entra-api"] + if !ok || backend.OBO == nil { + t.Fatal("entra-api obo backend not found") + } + if backend.OBO.ClientSecretEnv != "OBO_SECRET" { + t.Errorf("OBO.ClientSecretEnv = %v, want OBO_SECRET", backend.OBO.ClientSecretEnv) + } + if backend.OBO.ClientSecret != "" { + t.Errorf("OBO.ClientSecret = %q, want empty (the env var must not be resolved at load)", backend.OBO.ClientSecret) + } + }, + }, + { + name: "obo fails when clientSecretEnv is unset", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token + clientId: client-123 + clientSecretEnv: OBO_SECRET + scopes: + - api://backend/.default + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + wantErr: true, + errMsg: "environment variable OBO_SECRET not set", + }, + { + name: "obo fails when clientSecretEnv is empty", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token + clientId: client-123 + clientSecretEnv: OBO_SECRET + scopes: + - api://backend/.default + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + envVars: map[string]string{"OBO_SECRET": ""}, + wantErr: true, + errMsg: "environment variable OBO_SECRET not set", + }, + { + name: "obo fails when both clientSecret and clientSecretEnv are set", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + obo: + tokenUrl: https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token + clientId: client-123 + clientSecret: literal-secret + clientSecretEnv: OBO_SECRET + scopes: + - api://backend/.default + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + envVars: map[string]string{"OBO_SECRET": "secret-value"}, + wantErr: true, + errMsg: "only one of clientSecret or clientSecretEnv must be set", + }, + { + name: "obo fails without an obo block", + yaml: ` +name: test-vmcp +groupRef: test-group + +incomingAuth: + type: anonymous + +outgoingAuth: + source: inline + backends: + entra-api: + type: obo + +aggregation: + conflictResolution: prefix + conflictResolutionConfig: + prefixFormat: "{workload}_" +`, + wantErr: true, + errMsg: "backend entra-api: obo configuration is required", + }, { name: "valid audit configuration", yaml: ` From 065a7700d70e817f672e1350ce1bd0c8ce5e02ee Mon Sep 17 00:00:00 2001 From: Trey Date: Sun, 22 Nov 2026 20:58:34 -0800 Subject: [PATCH 11/12] Share CA bundle message and tighten operator tests Addresses stacklok/toolhive#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 --- .../controllers/external_auth_mirror.go | 4 +++- .../controllers/external_auth_mirror_test.go | 18 +++++++++-------- .../controllers/mcpremoteproxy_controller.go | 6 +++--- .../controllers/mcpserver_controller.go | 10 +++++----- .../mcpserver_externalauth_test.go | 20 ++++++++++++++----- .../virtualmcpserver_controller.go | 2 +- .../pkg/controllerutil/ca_bundle.go | 8 ++++++++ docs/arch/09-operator-architecture.md | 2 +- 8 files changed, 46 insertions(+), 24 deletions(-) diff --git a/cmd/thv-operator/controllers/external_auth_mirror.go b/cmd/thv-operator/controllers/external_auth_mirror.go index a44ec7ff52..4b34b81ce4 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror.go +++ b/cmd/thv-operator/controllers/external_auth_mirror.go @@ -34,7 +34,9 @@ const fallbackInvalidReason = "InvalidExternalAuthConfig" // malformed obo config is Valid=False / InvalidConfig), so the Reason alone // cannot tell the two owners apart. No local writer of InvalidConfig or // InvalidCABundle may start its message with this prefix; -// TestMirroredMessagePrefix_NotUsedByLocalMessages checks the fixed ones. +// TestMirroredMessagePrefix_NotUsedByLocalMessages checks the obo +// incoming-auth message and the shared CA bundle format +// (ctrlutil.InvalidCABundleMessage). const mirroredMessagePrefix = "Referenced MCPExternalAuthConfig " // mirroredInvalidExternalAuthConfigError signals that a referenced diff --git a/cmd/thv-operator/controllers/external_auth_mirror_test.go b/cmd/thv-operator/controllers/external_auth_mirror_test.go index d4fac0ef74..3f0adfb343 100644 --- a/cmd/thv-operator/controllers/external_auth_mirror_test.go +++ b/cmd/thv-operator/controllers/external_auth_mirror_test.go @@ -6,7 +6,6 @@ package controllers import ( "context" "errors" - "fmt" "strings" "testing" @@ -373,15 +372,18 @@ func TestExternalAuthMirror_OBOIncomingAuthRejectionClearsOnRevert(t *testing.T) func TestMirroredMessagePrefix_NotUsedByLocalMessages(t *testing.T) { t.Parallel() - localMessages := map[string]string{ - "obo incoming auth": ctrlutil.MsgOBORequiresIncomingAuth, - "CA bundle": fmt.Sprintf("invalid CA bundle: %v", errors.New("missing key")), + localConditions := map[string]struct{ reason, message string }{ + "obo incoming auth": {mcpv1beta1.ConditionReasonInvalidConfig, ctrlutil.MsgOBORequiresIncomingAuth}, + "CA bundle": { + mcpv1beta1.ConditionReasonInvalidCABundle, + ctrlutil.InvalidCABundleMessage(errors.New("missing key")), + }, } - for name, msg := range localMessages { - assert.False(t, strings.HasPrefix(msg, mirroredMessagePrefix), - "%s message %q must not start with the mirrored prefix", name, msg) + for name, c := range localConditions { + assert.False(t, strings.HasPrefix(c.message, mirroredMessagePrefix), + "%s message %q must not start with the mirrored prefix", name, c.message) assert.True(t, isLocalValidationFailure(&metav1.Condition{ - Status: metav1.ConditionFalse, Reason: mcpv1beta1.ConditionReasonInvalidConfig, Message: msg, + Status: metav1.ConditionFalse, Reason: c.reason, Message: c.message, }), "%s message must be treated as locally owned", name) } } diff --git a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go index d7f67a6137..01b957a6bd 100644 --- a/cmd/thv-operator/controllers/mcpremoteproxy_controller.go +++ b/cmd/thv-operator/controllers/mcpremoteproxy_controller.go @@ -150,7 +150,7 @@ func (r *MCPRemoteProxyReconciler) handleInvalidCABundle( Status: metav1.ConditionFalse, ObservedGeneration: remoteProxy.Generation, Reason: mcpv1beta1.ConditionReasonInvalidCABundle, - Message: fmt.Sprintf("invalid CA bundle: %v", err), + Message: ctrlutil.InvalidCABundleMessage(err), }) }) } @@ -1069,7 +1069,7 @@ func (r *MCPRemoteProxyReconciler) handleExternalAuthConfig(ctx context.Context, } meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{ Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonInvalidCABundle, Message: fmt.Sprintf("invalid CA bundle: %v", err), + Reason: mcpv1beta1.ConditionReasonInvalidCABundle, Message: ctrlutil.InvalidCABundleMessage(err), ObservedGeneration: proxy.Generation, }) return err @@ -1245,7 +1245,7 @@ func (r *MCPRemoteProxyReconciler) handleAuthServerRef(ctx context.Context, prox Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated, Status: metav1.ConditionFalse, Reason: mcpv1beta1.ConditionReasonInvalidCABundle, - Message: fmt.Sprintf("invalid CA bundle: %v", err), + Message: ctrlutil.InvalidCABundleMessage(err), ObservedGeneration: proxy.Generation, }) return err diff --git a/cmd/thv-operator/controllers/mcpserver_controller.go b/cmd/thv-operator/controllers/mcpserver_controller.go index e67b3e9326..83490b84fa 100644 --- a/cmd/thv-operator/controllers/mcpserver_controller.go +++ b/cmd/thv-operator/controllers/mcpserver_controller.go @@ -264,7 +264,7 @@ func (r *MCPServerReconciler) handleInvalidCABundle( Status: metav1.ConditionFalse, ObservedGeneration: server.Generation, Reason: mcpv1beta1.ConditionReasonInvalidCABundle, - Message: fmt.Sprintf("invalid CA bundle: %v", err), + Message: ctrlutil.InvalidCABundleMessage(err), }) }) } @@ -2508,7 +2508,7 @@ func (r *MCPServerReconciler) handleExternalAuthConfig(ctx context.Context, m *m } meta.SetStatusCondition(&m.Status.Conditions, metav1.Condition{ Type: mcpv1beta1.ConditionTypeExternalAuthConfigValidated, Status: metav1.ConditionFalse, - Reason: mcpv1beta1.ConditionReasonInvalidCABundle, Message: fmt.Sprintf("invalid CA bundle: %v", err), + Reason: mcpv1beta1.ConditionReasonInvalidCABundle, Message: ctrlutil.InvalidCABundleMessage(err), ObservedGeneration: m.Generation, }) return err @@ -2563,12 +2563,12 @@ func (r *MCPServerReconciler) handleExternalAuthConfig(ctx context.Context, m *m // A CA bundle failure (ConditionReasonInvalidCABundle) is deliberately not // preserved here: its failing input is ConfigMap content, which neither // generation nor configHash tracks, and the check that records it re-runs -// earlier in this same function. Holding it would make the failure permanent. +// earlier in handleExternalAuthConfig. Holding it would make the failure permanent. // Neither is an InvalidConfig mirrored from the referenced // 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 +// held either: it re-runs earlier in handleExternalAuthConfig and returns before the // stored hash advances, so a source that reverts from obo to its earlier spec // matches the stored hash, and holding it would keep a stale False. func setMCPServerExternalAuthConfigValidCondition( @@ -2695,7 +2695,7 @@ func (r *MCPServerReconciler) handleAuthServerRef(ctx context.Context, m *mcpv1b Type: mcpv1beta1.ConditionTypeAuthServerRefValidated, Status: metav1.ConditionFalse, Reason: mcpv1beta1.ConditionReasonInvalidCABundle, - Message: fmt.Sprintf("invalid CA bundle: %v", err), + Message: ctrlutil.InvalidCABundleMessage(err), ObservedGeneration: m.Generation, }) return err diff --git a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go index 7b5a3b79e9..3e5e507068 100644 --- a/cmd/thv-operator/controllers/mcpserver_externalauth_test.go +++ b/cmd/thv-operator/controllers/mcpserver_externalauth_test.go @@ -961,11 +961,13 @@ func TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal(t *testing.T) { authRef string interceptor *interceptor.Funcs wantErr error - wantAnyErr bool + // wantNotFound expects the lookup of the referenced config to fail + // as not found, which must requeue and never record the obo rejection. + wantNotFound bool }{ {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}, + {name: "missing referenced config is requeued", authRef: "missing-config", wantNotFound: true}, } for _, tt := range tests { @@ -998,14 +1000,22 @@ func TestMCPServerReconciler_OBOWithoutIncomingAuthIsTerminal(t *testing.T) { require.ErrorIs(t, err, tt.wantErr, "an unpersisted rejection must be retried, not dropped") return } - if tt.wantAnyErr { - require.Error(t, err, "a non-validation error must be returned so it requeues") + + actual := &mcpv1beta1.MCPServer{} + if tt.wantNotFound { + require.Error(t, err, "a missing referenced config must be returned so it requeues") + assert.EqualError(t, err, "MCPExternalAuthConfig missing-config not found in namespace default") + require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(server), actual)) + validated := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeExternalAuthConfigValidated) + if validated != nil { + assert.NotEqual(t, ctrlutil.MsgOBORequiresIncomingAuth, validated.Message, + "a lookup failure must not be recorded as the obo rejection") + } return } require.NoError(t, err, "a spec defect must not be returned as an error (that requeues with backoff)") assert.Equal(t, ctrl.Result{}, result) - actual := &mcpv1beta1.MCPServer{} require.NoError(t, fakeClient.Get(t.Context(), client.ObjectKeyFromObject(server), actual)) assert.Equal(t, mcpv1beta1.MCPServerPhaseFailed, actual.Status.Phase) ready := meta.FindStatusCondition(actual.Status.Conditions, mcpv1beta1.ConditionTypeReady) diff --git a/cmd/thv-operator/controllers/virtualmcpserver_controller.go b/cmd/thv-operator/controllers/virtualmcpserver_controller.go index ff5e594af2..56b69cec2e 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_controller.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_controller.go @@ -644,7 +644,7 @@ func (r *VirtualMCPServerReconciler) validateAuthServerConfigCABundles( if !stderrors.As(err, &invalidCABundleErr) { return false, err } - message := fmt.Sprintf("invalid CA bundle: %v", err) + message := ctrlutil.InvalidCABundleMessage(err) statusManager.SetPhase(mcpv1beta1.VirtualMCPServerPhaseFailed) statusManager.SetMessage(message) statusManager.SetAuthServerConfigValidatedCondition( diff --git a/cmd/thv-operator/pkg/controllerutil/ca_bundle.go b/cmd/thv-operator/pkg/controllerutil/ca_bundle.go index b083334a4f..8f5fbedc07 100644 --- a/cmd/thv-operator/pkg/controllerutil/ca_bundle.go +++ b/cmd/thv-operator/pkg/controllerutil/ca_bundle.go @@ -35,6 +35,14 @@ func invalidCABundleError(err error) error { return &InvalidCABundleError{err: err} } +// InvalidCABundleMessage is the condition Message the workload controllers +// write for a CA bundle failure. Controllers and tests share it so the message +// format cannot drift from what TestMirroredMessagePrefix_NotUsedByLocalMessages +// checks. +func InvalidCABundleMessage(err error) string { + return fmt.Sprintf("invalid CA bundle: %v", err) +} + // ResolveCABundle reads and validates a CA bundle referenced by a workload. // ConfigMapKeySelector is deliberately resolved here rather than left to pod // admission: an optional or malformed reference must never result in a diff --git a/docs/arch/09-operator-architecture.md b/docs/arch/09-operator-architecture.md index 2eee585edc..162e2efeb8 100644 --- a/docs/arch/09-operator-architecture.md +++ b/docs/arch/09-operator-architecture.md @@ -238,7 +238,7 @@ MCPExternalAuthConfig resources can be referenced via two paths: **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__`, where `` 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 '' is invalid: ` (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. +**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 '' is invalid: `, or without the `: ` suffix when the source message is empty. 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. **Controller**: `cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go` From 5027c70a187a121d9268bc08ef6debe19fec0230 Mon Sep 17 00:00:00 2001 From: Trey Date: Sun, 22 Nov 2026 20:58:34 -0800 Subject: [PATCH 12/12] Replace OBO test hook with a store seam Addresses stacklok/toolhive#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 --- pkg/vmcp/auth/strategies/obo.go | 83 +++++++++++++++++----------- pkg/vmcp/auth/strategies/obo_test.go | 51 ++++++++++++----- 2 files changed, 87 insertions(+), 47 deletions(-) diff --git a/pkg/vmcp/auth/strategies/obo.go b/pkg/vmcp/auth/strategies/obo.go index c20c5377d4..4ef4925aa3 100644 --- a/pkg/vmcp/auth/strategies/obo.go +++ b/pkg/vmcp/auth/strategies/obo.go @@ -61,18 +61,54 @@ type OBOStrategy struct { // production uses defaultBuildOBOExchanger. buildExchanger func(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) - // 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() + // exchangers caches the per-backend Exchanger keyed by oboExchangerCacheKey. + // Each is shared across all users of that backend (the cache partitions per + // user internally). It is an interface so tests can wrap the store to + // control the interleaving of concurrent callers. + exchangers oboExchangerStore +} - // mu guards exchangers. +// oboExchangerStore holds the per-backend Exchangers. lookup is the fast +// read-only path; lookupOrStore re-checks under exclusive access and builds +// only when the key is still absent, so concurrent callers that all missed in +// lookup share a single build. +type oboExchangerStore interface { + lookup(key string) (exchange.Exchanger, bool) + lookupOrStore(key string, build func() (exchange.Exchanger, error)) (exchange.Exchanger, error) +} + +// rwExchangerStore is the production oboExchangerStore: a map behind a +// read-write mutex with a double-checked build. +type rwExchangerStore struct { mu sync.RWMutex + m map[string]exchange.Exchanger +} - // exchangers caches the per-backend Exchanger keyed by oboExchangerCacheKey. - // Each is shared across all users of that backend (the cache partitions per - // user internally). - exchangers map[string]exchange.Exchanger +func newRWExchangerStore() *rwExchangerStore { + return &rwExchangerStore{m: make(map[string]exchange.Exchanger)} +} + +func (r *rwExchangerStore) lookup(key string) (exchange.Exchanger, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + ex, ok := r.m[key] + return ex, ok +} + +func (r *rwExchangerStore) lookupOrStore( + key string, build func() (exchange.Exchanger, error), +) (exchange.Exchanger, error) { + r.mu.Lock() + defer r.mu.Unlock() + if ex, ok := r.m[key]; ok { + return ex, nil + } + ex, err := build() + if err != nil { + return nil, err + } + r.m[key] = ex + return ex, nil } // NewOBOStrategy returns a Strategy using the default Entra+cache Exchanger builder @@ -100,7 +136,7 @@ func newOBOStrategy( envReader: envReader, auditLogger: auditLogger, buildExchanger: build, - exchangers: make(map[string]exchange.Exchanger), + exchangers: newRWExchangerStore(), } } @@ -204,29 +240,12 @@ func (s *OBOStrategy) resolveClientSecret(cfg *authtypes.OBOConfig) (string, err func (s *OBOStrategy) getOrCreateExchanger(cfg *authtypes.OBOConfig, clientSecret string) (exchange.Exchanger, error) { key := oboExchangerCacheKey(cfg, clientSecret) - s.mu.RLock() - if ex, ok := s.exchangers[key]; ok { - s.mu.RUnlock() - return ex, nil - } - s.mu.RUnlock() - - if s.afterReadMiss != nil { - s.afterReadMiss() - } - - s.mu.Lock() - defer s.mu.Unlock() - if ex, ok := s.exchangers[key]; ok { + if ex, ok := s.exchangers.lookup(key); ok { return ex, nil } - - ex, err := s.buildExchanger(cfg, clientSecret) - if err != nil { - return nil, err - } - s.exchangers[key] = ex - return ex, nil + return s.exchangers.lookupOrStore(key, func() (exchange.Exchanger, error) { + return s.buildExchanger(cfg, clientSecret) + }) } // mapExchangeError translates an exchange failure into the error the Strategy @@ -348,7 +367,7 @@ func parseOBOConfig(strategy *authtypes.BackendAuthStrategy) (*authtypes.OBOConf } cfg := strategy.OBO - if cfg.TokenURL == "" { + if strings.TrimSpace(cfg.TokenURL) == "" { return nil, fmt.Errorf("tokenUrl is required") } if strings.TrimSpace(cfg.ClientID) == "" { diff --git a/pkg/vmcp/auth/strategies/obo_test.go b/pkg/vmcp/auth/strategies/obo_test.go index bce56f26d9..40f4b89629 100644 --- a/pkg/vmcp/auth/strategies/obo_test.go +++ b/pkg/vmcp/auth/strategies/obo_test.go @@ -638,10 +638,36 @@ func TestOBOExchangerCacheKey(t *testing.T) { } } +// barrierExchangerStore wraps an oboExchangerStore and holds every caller +// after a lookup miss until wantMisses callers have missed (or the timeout +// passes), so they all reach lookupOrStore together. +type barrierExchangerStore struct { + oboExchangerStore + wantMisses int32 + missed atomic.Int32 + allMissed chan struct{} +} + +func (b *barrierExchangerStore) lookup(key string) (exchange.Exchanger, bool) { + ex, ok := b.oboExchangerStore.lookup(key) + if ok { + return ex, ok + } + if b.missed.Add(1) == b.wantMisses { + close(b.allMissed) + } + select { + case <-b.allMissed: + case <-time.After(5 * time.Second): + // Fall through: the build count assertion reports the failure. + } + return nil, false +} + // TestOBOGetOrCreateExchanger_BuildsOnceUnderContention exercises the -// double-checked lock deterministically: the afterReadMiss hook holds every -// caller after its read-locked miss until all of them have missed, so they all -// then queue on the write lock. Every caller after the first must find the +// double-checked build deterministically: a wrapping store holds every caller +// after its lookup miss until all of them have missed, so they all then +// contend in lookupOrStore. Every caller after the first must find the // Exchanger on the second check rather than building another one. func TestOBOGetOrCreateExchanger_BuildsOnceUnderContention(t *testing.T) { t.Parallel() @@ -655,18 +681,12 @@ func TestOBOGetOrCreateExchanger_BuildsOnceUnderContention(t *testing.T) { return &oboStubExchanger{}, nil }) - var missed atomic.Int32 - allMissed := make(chan struct{}) - s.afterReadMiss = func() { - if missed.Add(1) == callers { - close(allMissed) - } - select { - case <-allMissed: - case <-time.After(5 * time.Second): - // Fall through: the build count assertion reports the failure. - } + store := &barrierExchangerStore{ + oboExchangerStore: s.exchangers, + wantMisses: callers, + allMissed: make(chan struct{}), } + s.exchangers = store results := make(chan error, callers) for range callers { @@ -687,7 +707,7 @@ func TestOBOGetOrCreateExchanger_BuildsOnceUnderContention(t *testing.T) { } } - require.Equal(t, int32(callers), missed.Load(), "every caller must miss on the read-locked check") + require.Equal(t, int32(callers), store.missed.Load(), "every caller must miss on the read-locked check") assert.Equal(t, int32(1), builds.Load(), "callers queued on the write lock must reuse the Exchanger built by the first") } @@ -709,6 +729,7 @@ func TestOBOValidate_Invalid(t *testing.T) { }{ {name: "nil obo", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO = nil }, wantMsg: "OBO configuration is required"}, {name: "missing token url", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.TokenURL = "" }, wantMsg: "tokenUrl is required"}, + {name: "whitespace token url", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.TokenURL = " \t " }, wantMsg: "tokenUrl is required"}, {name: "missing client id", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientID = "" }, wantMsg: "clientId is required"}, {name: "whitespace client id", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.ClientID = " " }, wantMsg: "clientId is required"}, {name: "no audience or scopes", mutate: func(s *authtypes.BackendAuthStrategy) { s.OBO.Scopes = nil; s.OBO.Audience = "" }, wantMsg: "one of audience or scopes is required"},