Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions cmd/help/openapi-normalize/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions cmd/help/openapi-normalize/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
88 changes: 37 additions & 51 deletions cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"`
Expand Down Expand Up @@ -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"`
Expand All @@ -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/<tenantId>/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
Expand All @@ -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
Expand All @@ -179,7 +168,7 @@ type OBOConfig struct {
// interpolates it into the token endpoint
// (<authority>/<tenantId>/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,})$`
Expand Down Expand Up @@ -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"`
}
Expand Down Expand Up @@ -2602,16 +2589,19 @@ 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
Comment thread
tgrunnagle marked this conversation as resolved.
Resolved
// shipped in ToolHive itself. The operator no longer sets it.
//
// 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
// 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
Expand Down Expand Up @@ -2797,15 +2787,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
Expand Down
76 changes: 57 additions & 19 deletions cmd/thv-operator/controllers/external_auth_mirror.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -15,9 +16,10 @@ 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
// 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.

// fallbackInvalidReason is substituted when a source surfaces Valid=False with
Expand All @@ -26,6 +28,17 @@ 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 may start its message with this prefix;
// TestMirroredMessagePrefix_NotUsedByLocalMessages checks the obo
// incoming-auth message and the shared CA bundle format
// (ctrlutil.InvalidCABundleMessage).
const mirroredMessagePrefix = "Referenced MCPExternalAuthConfig "
Comment thread
tgrunnagle marked this conversation as resolved.
Resolved

// 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
Expand Down Expand Up @@ -73,25 +86,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
Expand Down Expand Up @@ -121,7 +159,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)
Expand Down Expand Up @@ -155,7 +193,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)
Expand Down
Loading
Loading