diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index 513a28157a..78bf127ecb 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -273,6 +273,21 @@ const ( ) // UpstreamProviderConfig defines configuration for an upstream Identity Provider. +// +// Exactly one of OIDCConfig or OAuth2Config must be set and must match the +// declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers +// set OAuth2Config. The CEL rule below enforces the pairing at admission; the +// matching Go-level check in validateUpstreamProvider provides defense-in-depth +// for stored objects. +// +// The rule is structured as a chain of equality checks ending in an explicit +// `false`, so adding a new UpstreamProviderType value without extending this +// rule fails admission instead of silently demanding the OAuth2 shape. When +// adding a new type, extend both this rule and validateUpstreamProvider. +// +// +kubebuilder:validation:XValidation:rule="self.type == 'oidc' ? (has(self.oidcConfig) && !has(self.oauth2Config)) : self.type == 'oauth2' ? (has(self.oauth2Config) && !has(self.oidcConfig)) : false",message="type must be 'oidc' or 'oauth2'; oidcConfig must be set when type is 'oidc' and oauth2Config must be set when type is 'oauth2' (and the other must not be set)" +// +//nolint:lll // CEL validation rules exceed line length limit type UpstreamProviderConfig struct { // Name uniquely identifies this upstream provider. // Used for routing decisions and session binding in multi-upstream scenarios. @@ -354,6 +369,14 @@ type OIDCUpstreamConfig struct { // OAuth2UpstreamConfig contains configuration for pure OAuth 2.0 providers. // OAuth 2.0 providers require explicit endpoint configuration. +// +// Exactly one of ClientID or DCRConfig must be set: ClientID is used when the +// client is pre-provisioned out of band, DCRConfig enables RFC 7591 Dynamic +// Client Registration at runtime. +// +// +kubebuilder:validation:XValidation:rule="(has(self.clientId) && size(self.clientId) > 0) ? !has(self.dcrConfig) : has(self.dcrConfig)",message="exactly one of clientId or dcrConfig must be set" +// +//nolint:lll // CEL validation rules exceed line length limit type OAuth2UpstreamConfig struct { // AuthorizationEndpoint is the URL for the OAuth authorization endpoint. // +kubebuilder:validation:Required @@ -374,8 +397,10 @@ type OAuth2UpstreamConfig struct { UserInfo *UserInfoConfig `json:"userInfo,omitempty"` // ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. - // +kubebuilder:validation:Required - ClientID string `json:"clientId"` + // Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + // at runtime via RFC 7591 Dynamic Client Registration and must be left empty. + // +optional + ClientID string `json:"clientId,omitempty"` // ClientSecretRef references a Kubernetes Secret containing the OAuth 2.0 client secret. // Optional for public clients using PKCE instead of client secret. @@ -410,6 +435,81 @@ type OAuth2UpstreamConfig struct { // +kubebuilder:validation:MaxProperties=16 // +optional AdditionalAuthorizationParams map[string]string `json:"additionalAuthorizationParams,omitempty"` + + // DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + // authorization server. When set, the client credentials are obtained at + // runtime rather than being pre-provisioned, and ClientID must be left empty. + // Mutually exclusive with ClientID. + // +optional + DCRConfig *DCRUpstreamConfig `json:"dcrConfig,omitempty"` +} + +// DCRUpstreamConfig configures RFC 7591 Dynamic Client Registration for an +// OAuth 2.0 upstream. When present on an OAuth2 upstream, the authserver +// performs registration at runtime to obtain client credentials, replacing +// the need to pre-provision a ClientID. +// +// Exactly one of DiscoveryURL or RegistrationEndpoint must be set. DiscoveryURL +// points at an RFC 8414 / OIDC Discovery document from which the registration +// endpoint is resolved; RegistrationEndpoint is used directly when the upstream +// does not publish discovery metadata. +// +// The XOR rule uses has() alone (not has() + size() > 0) to keep the rule's +// estimated CEL cost under the apiserver's per-rule static budget. With +// `omitempty` on both fields, an unset field is absent on the wire and has() +// returns false; the explicit-empty-string edge case is rejected at reconcile +// time by ValidateOAuth2DCRConfig. +// +// +kubebuilder:validation:XValidation:rule="has(self.discoveryUrl) != has(self.registrationEndpoint)",message="exactly one of discoveryUrl or registrationEndpoint must be set" +// +//nolint:lll // CEL validation rules exceed line length limit +type DCRUpstreamConfig struct { + // DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + // issues a single GET against this URL (no well-known-path fallback) and + // reads registration_endpoint, authorization_endpoint, token_endpoint, + // token_endpoint_auth_methods_supported, and scopes_supported from the + // response. + // Mutually exclusive with RegistrationEndpoint. + // MaxLength bounds CEL cost estimation on the parent struct's + // XValidation rule and matches the conventional URL length cap. + // +optional + // +kubebuilder:validation:Pattern=`^https?://.*$` + // +kubebuilder:validation:MaxLength=2048 + DiscoveryURL string `json:"discoveryUrl,omitempty"` + + // RegistrationEndpoint is the RFC 7591 registration endpoint URL used + // directly, bypassing discovery. When using this field, the caller is + // expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + // explicit Scopes list on the parent OAuth2UpstreamConfig. + // Mutually exclusive with DiscoveryURL. + // MaxLength bounds CEL cost estimation on the parent struct's + // XValidation rule and matches the conventional URL length cap. + // +optional + // +kubebuilder:validation:Pattern=`^https?://.*$` + // +kubebuilder:validation:MaxLength=2048 + RegistrationEndpoint string `json:"registrationEndpoint,omitempty"` + + // InitialAccessTokenRef is an optional reference to a Kubernetes Secret + // carrying an RFC 7591 §3 initial access token. When set, the resolver + // presents the token value as a Bearer credential on the registration + // request. Mirrors the ClientSecretRef pattern. + // +optional + InitialAccessTokenRef *SecretKeyRef `json:"initialAccessTokenRef,omitempty"` + + // SoftwareID is the RFC 7591 "software_id" registration metadata value, + // identifying the client software independent of any particular + // registration instance. Typically a UUID or short identifier. + // +optional + // +kubebuilder:validation:MaxLength=255 + SoftwareID string `json:"softwareId,omitempty"` + + // SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + // metadata about the client software, signed by a party the authorization + // server trusts. Bounded to 4096 characters to prevent unbounded + // user input from inflating the CR beyond etcd object limits. + // +optional + // +kubebuilder:validation:MaxLength=4096 + SoftwareStatement string `json:"softwareStatement,omitempty"` } // TokenResponseMapping maps non-standard token response fields to standard OAuth 2.0 fields @@ -956,10 +1056,62 @@ func (*MCPExternalAuthConfig) validateUpstreamProvider(index int, provider *Upst return fmt.Errorf("%s: unsupported provider type: %s", prefix, provider.Type) } + // Validate OAuth2-specific DCR / ClientID constraints (defense-in-depth with CEL). + if provider.Type == UpstreamProviderTypeOAuth2 && provider.OAuth2Config != nil { + if err := ValidateOAuth2DCRConfig(prefix, provider.OAuth2Config); err != nil { + return err + } + } + // Validate additionalAuthorizationParams does not contain reserved keys return ValidateAdditionalAuthorizationParams(prefix, provider.AdditionalAuthorizationParams()) } +// ValidateOAuth2DCRConfig enforces the mutual exclusivity between ClientID and +// DCRConfig and, when DCRConfig is present, between DiscoveryURL and +// RegistrationEndpoint. These rules mirror the CEL validation on +// OAuth2UpstreamConfig and DCRUpstreamConfig and provide defense-in-depth for +// stored objects (e.g., objects stored before CEL rules were added or +// validated through code paths that bypass admission). +// +// The prefix is embedded in error messages to identify the offending upstream +// (e.g., "upstreamProviders[i]"). Pass an empty string when the caller already +// wraps the error with the upstream identifier, to avoid duplicating it. +// Exported so the controllerutil conversion layer can reuse the same +// invariants when building runtime configs, rejecting malformed objects at +// reconcile time rather than waiting until the authserver process parses them. +func ValidateOAuth2DCRConfig(prefix string, cfg *OAuth2UpstreamConfig) error { + hasClientID := cfg.ClientID != "" + hasDCR := cfg.DCRConfig != nil + + scoped := scopedFieldPath(prefix, "oauth2Config") + if hasClientID == hasDCR { + return fmt.Errorf("%s: exactly one of clientId or dcrConfig must be set", scoped) + } + + if !hasDCR { + return nil + } + + hasDiscoveryURL := cfg.DCRConfig.DiscoveryURL != "" + hasRegistrationEndpoint := cfg.DCRConfig.RegistrationEndpoint != "" + if hasDiscoveryURL == hasRegistrationEndpoint { + return fmt.Errorf("%s.dcrConfig: exactly one of discoveryUrl or registrationEndpoint must be set", scoped) + } + return nil +} + +// scopedFieldPath joins a non-empty prefix to a field name with a dot. When +// the prefix is empty, it returns just the field name so callers that already +// supply their own scope (e.g., a wrapping `fmt.Errorf("upstream %q: %w", ...)`) +// don't end up with a leading dot. +func scopedFieldPath(prefix, field string) string { + if prefix == "" { + return field + } + return prefix + "." + field +} + // AdditionalAuthorizationParams returns the additional authorization parameters // from whichever upstream config is set, or nil if none. func (p *UpstreamProviderConfig) AdditionalAuthorizationParams() map[string]string { diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index 235d74a826..09e92438fc 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -571,6 +571,125 @@ func TestMCPExternalAuthConfig_validateUpstreamProvider(t *testing.T) { }, expectErr: false, }, + { + name: "OAuth2 provider with valid DCRConfig (discoveryUrl only)", + provider: UpstreamProviderConfig{ + Name: "dcr-discovery", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + }, + }, + }, + expectErr: false, + }, + { + name: "OAuth2 provider with valid DCRConfig (registrationEndpoint only)", + provider: UpstreamProviderConfig{ + Name: "dcr-endpoint", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + Scopes: []string{"openid"}, + DCRConfig: &DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + }, + }, + }, + expectErr: false, + }, + { + name: "OAuth2 provider with DCRConfig and non-empty ClientID", + provider: UpstreamProviderConfig{ + Name: "dcr-with-clientid", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + ClientID: "pre-provisioned-id", + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + }, + }, + }, + expectErr: true, + errMsg: "exactly one of clientId or dcrConfig must be set", + }, + { + name: "OAuth2 provider with DCRConfig specifying both endpoints", + provider: UpstreamProviderConfig{ + Name: "dcr-both-endpoints", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + RegistrationEndpoint: "https://idp.example.com/register", + }, + }, + }, + expectErr: true, + errMsg: "exactly one of discoveryUrl or registrationEndpoint must be set", + }, + { + name: "OAuth2 provider with DCRConfig specifying neither endpoint", + provider: UpstreamProviderConfig{ + Name: "dcr-neither-endpoint", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{}, + }, + }, + expectErr: true, + errMsg: "exactly one of discoveryUrl or registrationEndpoint must be set", + }, + { + name: "OAuth2 provider with neither ClientID nor DCRConfig", + provider: UpstreamProviderConfig{ + Name: "oauth2-missing-auth", + Type: UpstreamProviderTypeOAuth2, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + }, + }, + expectErr: true, + // Pin the scoped prefix so a rename of the oauth2Config label surfaces as a test failure. + errMsg: "oauth2Config: exactly one of clientId or dcrConfig must be set", + }, + { + // Regression guard: conversion only maps DCRConfig in the OAuth2 + // branch, so an OIDC-typed provider carrying OAuth2Config/DCRConfig + // must be rejected at validate time rather than silently dropped. + name: "OIDC provider with OAuth2Config carrying DCRConfig is rejected", + provider: UpstreamProviderConfig{ + Name: "mismatched-oidc", + Type: UpstreamProviderTypeOIDC, + OAuth2Config: &OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + }, + }, + }, + expectErr: true, + errMsg: "oidcConfig must be set when type is 'oidc' and must not be set otherwise", + }, } for _, tt := range tests { diff --git a/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go b/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go index 04da44756d..830ccb44f9 100644 --- a/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go +++ b/cmd/thv-operator/api/v1beta1/zz_generated.deepcopy.go @@ -204,6 +204,26 @@ func (in *ConfigMapAuthzRef) DeepCopy() *ConfigMapAuthzRef { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DCRUpstreamConfig) DeepCopyInto(out *DCRUpstreamConfig) { + *out = *in + if in.InitialAccessTokenRef != nil { + in, out := &in.InitialAccessTokenRef, &out.InitialAccessTokenRef + *out = new(SecretKeyRef) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DCRUpstreamConfig. +func (in *DCRUpstreamConfig) DeepCopy() *DCRUpstreamConfig { + if in == nil { + return nil + } + out := new(DCRUpstreamConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EmbeddedAuthServerConfig) DeepCopyInto(out *EmbeddedAuthServerConfig) { *out = *in @@ -1969,6 +1989,11 @@ func (in *OAuth2UpstreamConfig) DeepCopyInto(out *OAuth2UpstreamConfig) { (*out)[key] = val } } + if in.DCRConfig != nil { + in, out := &in.DCRConfig, &out.DCRConfig + *out = new(DCRUpstreamConfig) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuth2UpstreamConfig. diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index 486b7cb4a2..b45386fed5 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -55,27 +55,38 @@ const ( // UpstreamClientSecretEnvVar is the prefix for upstream client secret environment variables. // Actual names are TOOLHIVE_UPSTREAM_CLIENT_SECRET_ where PROVIDER is the - // upstream name uppercased with hyphens replaced by underscores. + // upstream name uppercased with hyphens replaced by underscores (e.g., + // "acme-idp" -> TOOLHIVE_UPSTREAM_CLIENT_SECRET_ACME_IDP). // #nosec G101 -- This is an environment variable name, not a hardcoded credential UpstreamClientSecretEnvVar = "TOOLHIVE_UPSTREAM_CLIENT_SECRET" + // UpstreamDCRInitialAccessTokenEnvVarPrefix is the prefix for RFC 7591 + // initial access token environment variables used with Dynamic Client + // Registration. Actual env var names are constructed as + // _ where PROVIDER is the upstream name uppercased + // with hyphens replaced by underscores (e.g., "acme-idp" -> + // TOOLHIVE_UPSTREAM_DCR_INITIAL_ACCESS_TOKEN_ACME_IDP). + // #nosec G101 -- This is an environment variable name, not a hardcoded credential + UpstreamDCRInitialAccessTokenEnvVarPrefix = "TOOLHIVE_UPSTREAM_DCR_INITIAL_ACCESS_TOKEN" + // DefaultSentinelPort is the default Redis Sentinel port DefaultSentinelPort = 26379 ) -// upstreamSecretBinding binds an upstream provider to its env var name for the -// client secret. Both GenerateAuthServerEnvVars (Pod env) and -// buildUpstreamRunConfig (runtime config) MUST use these bindings so the -// env var names stay consistent. +// upstreamSecretBinding binds an upstream provider to the env var names for +// the secrets it owns (client secret and, optionally, the DCR initial access +// token). Both GenerateAuthServerEnvVars (Pod env) and buildUpstreamRunConfig +// (runtime config) MUST use these bindings so the env var names stay consistent. type upstreamSecretBinding struct { - Provider *mcpv1beta1.UpstreamProviderConfig - EnvVarName string + Provider *mcpv1beta1.UpstreamProviderConfig + EnvVarName string + DCRInitialAccessTokenEnvVar string } -// buildUpstreamSecretBindings computes the canonical env var name for each -// upstream provider's client secret. The env var name is derived from the -// provider's Name field (uppercased, hyphens replaced with underscores) to -// keep bindings stable across provider reordering in the CRD. +// buildUpstreamSecretBindings computes the canonical env var names for each +// upstream provider's secrets. Names are derived from the provider's Name +// field (uppercased, hyphens replaced with underscores) to keep bindings +// stable across provider reordering in the CRD. func buildUpstreamSecretBindings( providers []mcpv1beta1.UpstreamProviderConfig, ) []upstreamSecretBinding { @@ -83,13 +94,83 @@ func buildUpstreamSecretBindings( for i := range providers { suffix := strings.ToUpper(strings.ReplaceAll(providers[i].Name, "-", "_")) bindings[i] = upstreamSecretBinding{ - Provider: &providers[i], - EnvVarName: fmt.Sprintf("%s_%s", UpstreamClientSecretEnvVar, suffix), + Provider: &providers[i], + EnvVarName: fmt.Sprintf("%s_%s", UpstreamClientSecretEnvVar, suffix), + DCRInitialAccessTokenEnvVar: fmt.Sprintf("%s_%s", UpstreamDCRInitialAccessTokenEnvVarPrefix, suffix), } } return bindings } +// buildUpstreamSecretEnvVars returns the Pod env vars that expose the +// client-secret and, when DCR is configured, the initial access token for a +// single upstream provider. Returns nil if the provider has no relevant +// secret references. +func buildUpstreamSecretEnvVars(b *upstreamSecretBinding) []corev1.EnvVar { + clientSecretRef, initialAccessTokenRef := extractUpstreamSecretRefs(b.Provider) + + var envVars []corev1.EnvVar + if clientSecretRef != nil { + envVars = append(envVars, envVarFromSecretRef(b.EnvVarName, clientSecretRef)) + } + if initialAccessTokenRef != nil { + envVars = append(envVars, envVarFromSecretRef(b.DCRInitialAccessTokenEnvVar, initialAccessTokenRef)) + } + return envVars +} + +// extractUpstreamSecretRefs returns the client-secret and DCR initial-access-token +// secret references for an upstream provider. +// +// What can be returned, given the admission-time invariants on +// UpstreamProviderConfig (see the kubebuilder XValidation rule on the type and +// the matching Go-level check in validateUpstreamProvider, which together +// enforce that exactly one of OIDCConfig / OAuth2Config is set and that it +// matches Type): +// - OIDC providers: only `clientSecretRef` is ever non-nil. +// `initialAccessTokenRef` is always nil because DCR is OAuth2-only and +// OAuth2Config must be nil for OIDC-typed providers. +// - OAuth2 providers: `clientSecretRef` and `initialAccessTokenRef` are +// independent — either, both, or neither may be non-nil. +// - Any other (currently unreachable) Type value: both are nil. +// +// Callers must not rely on the third bullet to mask an admission-bypassing +// object — `BuildAuthServerRunConfig` is the reconcile-time backstop for that. +func extractUpstreamSecretRefs( + provider *mcpv1beta1.UpstreamProviderConfig, +) (clientSecretRef, initialAccessTokenRef *mcpv1beta1.SecretKeyRef) { + switch provider.Type { + case mcpv1beta1.UpstreamProviderTypeOIDC: + if provider.OIDCConfig != nil { + clientSecretRef = provider.OIDCConfig.ClientSecretRef + } + case mcpv1beta1.UpstreamProviderTypeOAuth2: + if provider.OAuth2Config != nil { + clientSecretRef = provider.OAuth2Config.ClientSecretRef + if provider.OAuth2Config.DCRConfig != nil { + initialAccessTokenRef = provider.OAuth2Config.DCRConfig.InitialAccessTokenRef + } + } + } + return clientSecretRef, initialAccessTokenRef +} + +// envVarFromSecretRef builds a corev1.EnvVar that sources its value from the +// given SecretKeyRef. +func envVarFromSecretRef(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, + }, + }, + } +} + // EmbeddedAuthServerConfigName returns the config name that should be used for // embedded auth server volume/env generation, or empty string if neither ref applies. // AuthServerRef takes precedence; externalAuthConfigRef is used as a fallback. @@ -282,33 +363,7 @@ func GenerateAuthServerEnvVars( // Generate env vars for upstream client secrets using shared bindings for _, b := range buildUpstreamSecretBindings(authConfig.UpstreamProviders) { - // Extract client secret reference based on provider type - var clientSecretRef *mcpv1beta1.SecretKeyRef - - switch b.Provider.Type { - case mcpv1beta1.UpstreamProviderTypeOIDC: - if b.Provider.OIDCConfig != nil { - clientSecretRef = b.Provider.OIDCConfig.ClientSecretRef - } - case mcpv1beta1.UpstreamProviderTypeOAuth2: - if b.Provider.OAuth2Config != nil { - clientSecretRef = b.Provider.OAuth2Config.ClientSecretRef - } - } - - if clientSecretRef != nil { - envVars = append(envVars, corev1.EnvVar{ - Name: b.EnvVarName, - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: clientSecretRef.Name, - }, - Key: clientSecretRef.Key, - }, - }, - }) - } + envVars = append(envVars, buildUpstreamSecretEnvVars(&b)...) } // Generate env vars for Redis ACL credentials if configured @@ -511,7 +566,11 @@ func BuildAuthServerRunConfig( bindings := buildUpstreamSecretBindings(authConfig.UpstreamProviders) config.Upstreams = make([]authserver.UpstreamRunConfig, 0, len(bindings)) for _, b := range bindings { - config.Upstreams = append(config.Upstreams, *buildUpstreamRunConfig(b.Provider, b.EnvVarName, resourceURL)) + upstream, err := buildUpstreamRunConfig(&b, resourceURL) + if err != nil { + return nil, fmt.Errorf("upstream %q: %w", b.Provider.Name, err) + } + config.Upstreams = append(config.Upstreams, *upstream) } // Build storage configuration @@ -645,14 +704,20 @@ func defaultRedirectURI(resourceURL string) string { } // buildUpstreamRunConfig converts CRD UpstreamProviderConfig to authserver.UpstreamRunConfig. -// The envVarName is computed by buildUpstreamSecretBindings to keep Pod env -// and runtime config in sync. When a provider's RedirectURI is empty, it is -// defaulted to {resourceURL}/oauth/callback. +// The binding carries the provider and the env var names computed by +// buildUpstreamSecretBindings so Pod env and runtime config stay in sync. +// When a provider's RedirectURI is empty, it is defaulted to +// {resourceURL}/oauth/callback. +// +// Returns an error when the OAuth2 provider's ClientID and DCRConfig +// combination is invalid (the same XOR enforced at admission by CEL). +// Failing at reconcile time — rather than at authserver startup — matches +// the project convention of rejecting malformed objects as early as possible. func buildUpstreamRunConfig( - provider *mcpv1beta1.UpstreamProviderConfig, - envVarName string, + b *upstreamSecretBinding, resourceURL string, -) *authserver.UpstreamRunConfig { +) (*authserver.UpstreamRunConfig, error) { + provider := b.Provider config := &authserver.UpstreamRunConfig{ Name: provider.Name, Type: authserver.UpstreamProviderType(provider.Type), @@ -661,59 +726,121 @@ func buildUpstreamRunConfig( switch provider.Type { case mcpv1beta1.UpstreamProviderTypeOIDC: if provider.OIDCConfig != nil { - redirectURI := provider.OIDCConfig.RedirectURI - if redirectURI == "" && resourceURL != "" { - redirectURI = defaultRedirectURI(resourceURL) - } - config.OIDCConfig = &authserver.OIDCUpstreamRunConfig{ - IssuerURL: provider.OIDCConfig.IssuerURL, - ClientID: provider.OIDCConfig.ClientID, - RedirectURI: redirectURI, - Scopes: provider.OIDCConfig.Scopes, - AdditionalAuthorizationParams: provider.OIDCConfig.AdditionalAuthorizationParams, - } - // If client secret is configured, reference it via env var - if provider.OIDCConfig.ClientSecretRef != nil { - config.OIDCConfig.ClientSecretEnvVar = envVarName - } - if provider.OIDCConfig.UserInfoOverride != nil { - config.OIDCConfig.UserInfoOverride = buildUserInfoRunConfig(provider.OIDCConfig.UserInfoOverride) - } + config.OIDCConfig = buildOIDCUpstreamRunConfig(provider.OIDCConfig, b.EnvVarName, resourceURL) } case mcpv1beta1.UpstreamProviderTypeOAuth2: if provider.OAuth2Config != nil { - redirectURI := provider.OAuth2Config.RedirectURI - if redirectURI == "" && resourceURL != "" { - redirectURI = defaultRedirectURI(resourceURL) - } - config.OAuth2Config = &authserver.OAuth2UpstreamRunConfig{ - AuthorizationEndpoint: provider.OAuth2Config.AuthorizationEndpoint, - TokenEndpoint: provider.OAuth2Config.TokenEndpoint, - ClientID: provider.OAuth2Config.ClientID, - RedirectURI: redirectURI, - Scopes: provider.OAuth2Config.Scopes, - AdditionalAuthorizationParams: provider.OAuth2Config.AdditionalAuthorizationParams, - } - // If client secret is configured, reference it via env var - if provider.OAuth2Config.ClientSecretRef != nil { - config.OAuth2Config.ClientSecretEnvVar = envVarName - } - if provider.OAuth2Config.UserInfo != nil { - config.OAuth2Config.UserInfo = buildUserInfoRunConfig(provider.OAuth2Config.UserInfo) - } - if provider.OAuth2Config.TokenResponseMapping != nil { - m := provider.OAuth2Config.TokenResponseMapping - config.OAuth2Config.TokenResponseMapping = &authserver.TokenResponseMappingRunConfig{ - AccessTokenPath: m.AccessTokenPath, - ScopePath: m.ScopePath, - RefreshTokenPath: m.RefreshTokenPath, - ExpiresInPath: m.ExpiresInPath, - } + oauth2, err := buildOAuth2UpstreamRunConfig(provider, b, resourceURL) + if err != nil { + return nil, err } + config.OAuth2Config = oauth2 } } - return config + return config, nil +} + +// buildOIDCUpstreamRunConfig converts a CRD OIDCUpstreamConfig to the +// runtime representation. `clientSecretEnvVar` is the resolved env var name +// used when ClientSecretRef is configured. +func buildOIDCUpstreamRunConfig( + cfg *mcpv1beta1.OIDCUpstreamConfig, + clientSecretEnvVar string, + resourceURL string, +) *authserver.OIDCUpstreamRunConfig { + redirectURI := cfg.RedirectURI + if redirectURI == "" && resourceURL != "" { + redirectURI = defaultRedirectURI(resourceURL) + } + runConfig := &authserver.OIDCUpstreamRunConfig{ + IssuerURL: cfg.IssuerURL, + ClientID: cfg.ClientID, + RedirectURI: redirectURI, + Scopes: cfg.Scopes, + AdditionalAuthorizationParams: cfg.AdditionalAuthorizationParams, + } + if cfg.ClientSecretRef != nil { + runConfig.ClientSecretEnvVar = clientSecretEnvVar + } + if cfg.UserInfoOverride != nil { + runConfig.UserInfoOverride = buildUserInfoRunConfig(cfg.UserInfoOverride) + } + return runConfig +} + +// buildOAuth2UpstreamRunConfig converts a CRD OAuth2UpstreamConfig to the +// runtime representation. It rejects malformed ClientID/DCRConfig pairs +// before producing a RunConfig — mirroring the CEL XValidation rules on +// OAuth2UpstreamConfig / DCRUpstreamConfig — so objects that reached etcd +// without passing admission (stored-before-CEL, apiserver patches, test +// fixtures bypassing validation) fail at reconcile time rather than at +// authserver startup. +func buildOAuth2UpstreamRunConfig( + provider *mcpv1beta1.UpstreamProviderConfig, + b *upstreamSecretBinding, + resourceURL string, +) (*authserver.OAuth2UpstreamRunConfig, error) { + cfg := provider.OAuth2Config + // Pass an empty prefix so the upstream name appears once — supplied by the + // outer wrap in BuildAuthServerRunConfig — instead of duplicating it on + // both the inner and outer error messages. + if err := mcpv1beta1.ValidateOAuth2DCRConfig("", cfg); err != nil { + return nil, err + } + + redirectURI := cfg.RedirectURI + if redirectURI == "" && resourceURL != "" { + redirectURI = defaultRedirectURI(resourceURL) + } + runConfig := &authserver.OAuth2UpstreamRunConfig{ + AuthorizationEndpoint: cfg.AuthorizationEndpoint, + TokenEndpoint: cfg.TokenEndpoint, + ClientID: cfg.ClientID, + RedirectURI: redirectURI, + Scopes: cfg.Scopes, + AdditionalAuthorizationParams: cfg.AdditionalAuthorizationParams, + } + if cfg.ClientSecretRef != nil { + runConfig.ClientSecretEnvVar = b.EnvVarName + } + if cfg.UserInfo != nil { + runConfig.UserInfo = buildUserInfoRunConfig(cfg.UserInfo) + } + if cfg.TokenResponseMapping != nil { + m := cfg.TokenResponseMapping + runConfig.TokenResponseMapping = &authserver.TokenResponseMappingRunConfig{ + AccessTokenPath: m.AccessTokenPath, + ScopePath: m.ScopePath, + RefreshTokenPath: m.RefreshTokenPath, + ExpiresInPath: m.ExpiresInPath, + } + } + if cfg.DCRConfig != nil { + runConfig.DCRConfig = buildDCRUpstreamRunConfig(cfg.DCRConfig, b.DCRInitialAccessTokenEnvVar) + } + return runConfig, nil +} + +// buildDCRUpstreamRunConfig converts CRD DCRUpstreamConfig to +// authserver.DCRUpstreamConfig. When an InitialAccessTokenRef is present on +// the CRD, the resolver reads the token value from the supplied env var +// (populated from the secret ref by GenerateAuthServerEnvVars), mirroring the +// ClientSecretRef → env-var pattern. +func buildDCRUpstreamRunConfig( + dcr *mcpv1beta1.DCRUpstreamConfig, + initialAccessTokenEnvVar string, +) *authserver.DCRUpstreamConfig { + rc := &authserver.DCRUpstreamConfig{ + DiscoveryURL: dcr.DiscoveryURL, + RegistrationEndpoint: dcr.RegistrationEndpoint, + SoftwareID: dcr.SoftwareID, + SoftwareStatement: dcr.SoftwareStatement, + } + if dcr.InitialAccessTokenRef != nil { + rc.InitialAccessTokenEnvVar = initialAccessTokenEnvVar + } + return rc } // buildUserInfoRunConfig converts CRD UserInfoConfig to authserver.UserInfoRunConfig. diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_test.go index 3c3f1ac443..19c6a9f5c3 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_test.go @@ -6,6 +6,7 @@ package controllerutil import ( "context" "fmt" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -497,6 +498,86 @@ func TestGenerateAuthServerEnvVars(t *testing.T) { }, wantSecretNames: []string{"okta-secret", "github-secret"}, }, + { + name: "OAuth2 provider with DCR initial access token ref emits separate env var", + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "acme-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + InitialAccessTokenRef: &mcpv1beta1.SecretKeyRef{ + Name: "acme-dcr-token", + Key: "token", + }, + }, + }, + }, + }, + }, + wantEnvNames: []string{UpstreamDCRInitialAccessTokenEnvVarPrefix + "_ACME_IDP"}, + wantSecretNames: []string{"acme-dcr-token"}, + }, + { + name: "OAuth2 provider with DCR and client secret emits both env vars", + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "acme-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + ClientSecretRef: &mcpv1beta1.SecretKeyRef{ + Name: "acme-secret", + Key: "client-secret", + }, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + InitialAccessTokenRef: &mcpv1beta1.SecretKeyRef{ + Name: "acme-dcr-token", + Key: "token", + }, + }, + }, + }, + }, + }, + wantEnvNames: []string{ + UpstreamClientSecretEnvVar + "_ACME_IDP", + UpstreamDCRInitialAccessTokenEnvVarPrefix + "_ACME_IDP", + }, + wantSecretNames: []string{"acme-secret", "acme-dcr-token"}, + }, + { + name: "OAuth2 provider with DCR but no initial access token ref emits no DCR env var", + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "public-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + }, + }, + }, + }, + }, + wantEnvNames: nil, + }, } for _, tt := range tests { @@ -1175,6 +1256,142 @@ func TestBuildAuthServerRunConfig(t *testing.T) { assert.Equal(t, "https://mcp.example.com/oauth/callback", config.Upstreams[0].OIDCConfig.RedirectURI) }, }, + { + name: "with OAuth2 upstream using DCR (discoveryUrl)", + resourceURL: defaultResourceURL, + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + SigningKeySecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "signing-key", Key: "private.pem"}, + }, + HMACSecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "hmac-secret", Key: "hmac"}, + }, + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "acme-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + SoftwareID: "toolhive", + SoftwareStatement: "jwt-statement", + InitialAccessTokenRef: &mcpv1beta1.SecretKeyRef{ + Name: "acme-dcr-token", + Key: "token", + }, + }, + }, + }, + }, + }, + allowedAudiences: defaultAudiences, + scopesSupported: defaultScopes, + checkFunc: func(t *testing.T, config *authserver.RunConfig) { + t.Helper() + require.Len(t, config.Upstreams, 1) + upstream := config.Upstreams[0] + require.NotNil(t, upstream.OAuth2Config) + assert.Empty(t, upstream.OAuth2Config.ClientID, + "ClientID should be empty when DCRConfig is used") + require.NotNil(t, upstream.OAuth2Config.DCRConfig) + assert.Equal(t, + "https://idp.example.com/.well-known/openid-configuration", + upstream.OAuth2Config.DCRConfig.DiscoveryURL) + assert.Empty(t, upstream.OAuth2Config.DCRConfig.RegistrationEndpoint) + assert.Equal(t, "toolhive", upstream.OAuth2Config.DCRConfig.SoftwareID) + assert.Equal(t, "jwt-statement", upstream.OAuth2Config.DCRConfig.SoftwareStatement) + assert.Equal(t, + UpstreamDCRInitialAccessTokenEnvVarPrefix+"_ACME_IDP", + upstream.OAuth2Config.DCRConfig.InitialAccessTokenEnvVar) + assert.Empty(t, upstream.OAuth2Config.DCRConfig.InitialAccessTokenFile) + }, + }, + { + name: "with OAuth2 upstream using DCR (registrationEndpoint)", + resourceURL: defaultResourceURL, + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + SigningKeySecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "signing-key", Key: "private.pem"}, + }, + HMACSecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "hmac-secret", Key: "hmac"}, + }, + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "acme-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + Scopes: []string{"openid"}, + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + RegistrationEndpoint: "https://idp.example.com/register", + }, + }, + }, + }, + }, + allowedAudiences: defaultAudiences, + scopesSupported: defaultScopes, + checkFunc: func(t *testing.T, config *authserver.RunConfig) { + t.Helper() + require.Len(t, config.Upstreams, 1) + upstream := config.Upstreams[0] + require.NotNil(t, upstream.OAuth2Config) + require.NotNil(t, upstream.OAuth2Config.DCRConfig) + assert.Equal(t, "https://idp.example.com/register", + upstream.OAuth2Config.DCRConfig.RegistrationEndpoint) + assert.Empty(t, upstream.OAuth2Config.DCRConfig.DiscoveryURL) + // No InitialAccessTokenRef set: env var name should stay empty. + assert.Empty(t, upstream.OAuth2Config.DCRConfig.InitialAccessTokenEnvVar) + }, + }, + { + // Regression guard: the non-DCR OAuth2 path must leave DCRConfig + // nil and carry ClientID through untouched. Without this case, + // refactors of buildUpstreamRunConfig could populate DCRConfig + // (or drop ClientID) silently. + name: "with OAuth2 upstream using ClientID only (no DCRConfig)", + resourceURL: defaultResourceURL, + authConfig: &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + SigningKeySecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "signing-key", Key: "private.pem"}, + }, + HMACSecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "hmac-secret", Key: "hmac"}, + }, + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "github", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://github.com/login/oauth/authorize", + TokenEndpoint: "https://github.com/login/oauth/access_token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://api.github.com/user"}, + ClientID: "pre-provisioned-id", + }, + }, + }, + }, + allowedAudiences: defaultAudiences, + scopesSupported: defaultScopes, + checkFunc: func(t *testing.T, config *authserver.RunConfig) { + t.Helper() + require.Len(t, config.Upstreams, 1) + upstream := config.Upstreams[0] + require.NotNil(t, upstream.OAuth2Config) + assert.Equal(t, "pre-provisioned-id", upstream.OAuth2Config.ClientID) + assert.Nil(t, upstream.OAuth2Config.DCRConfig, + "DCRConfig should remain nil when only ClientID is set") + }, + }, } for _, tt := range tests { @@ -1190,6 +1407,109 @@ func TestBuildAuthServerRunConfig(t *testing.T) { } } +// TestBuildAuthServerRunConfig_InvalidDCR verifies that BuildAuthServerRunConfig +// rejects OAuth2 upstreams whose ClientID / DCRConfig pairing violates the +// mutual-exclusivity invariants (matching the CEL XValidation rules on +// OAuth2UpstreamConfig and DCRUpstreamConfig). This is the reconcile-time +// defense-in-depth against stored objects that bypassed admission. +func TestBuildAuthServerRunConfig_InvalidDCR(t *testing.T) { + t.Parallel() + + defaultAudiences := []string{"http://test-server.default.svc.cluster.local:8080"} + defaultScopes := []string{"openid", "offline_access"} + + tests := []struct { + name string + oauth2Cfg *mcpv1beta1.OAuth2UpstreamConfig + wantErr string + }{ + { + name: "both ClientID and DCRConfig set", + oauth2Cfg: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + ClientID: "pre-provisioned-id", + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + }, + }, + wantErr: "exactly one of clientId or dcrConfig must be set", + }, + { + name: "neither ClientID nor DCRConfig set", + oauth2Cfg: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + }, + wantErr: "exactly one of clientId or dcrConfig must be set", + }, + { + name: "DCRConfig with both endpoints set", + oauth2Cfg: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{ + DiscoveryURL: "https://idp.example.com/.well-known/openid-configuration", + RegistrationEndpoint: "https://idp.example.com/register", + }, + }, + wantErr: "exactly one of discoveryUrl or registrationEndpoint must be set", + }, + { + name: "DCRConfig with neither endpoint set", + oauth2Cfg: &mcpv1beta1.OAuth2UpstreamConfig{ + AuthorizationEndpoint: "https://idp.example.com/authorize", + TokenEndpoint: "https://idp.example.com/token", + UserInfo: &mcpv1beta1.UserInfoConfig{EndpointURL: "https://idp.example.com/userinfo"}, + DCRConfig: &mcpv1beta1.DCRUpstreamConfig{}, + }, + wantErr: "exactly one of discoveryUrl or registrationEndpoint must be set", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + authConfig := &mcpv1beta1.EmbeddedAuthServerConfig{ + Issuer: "https://auth.example.com", + SigningKeySecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "signing-key", Key: "private.pem"}, + }, + HMACSecretRefs: []mcpv1beta1.SecretKeyRef{ + {Name: "hmac-secret", Key: "hmac"}, + }, + UpstreamProviders: []mcpv1beta1.UpstreamProviderConfig{ + { + Name: "acme-idp", + Type: mcpv1beta1.UpstreamProviderTypeOAuth2, + OAuth2Config: tt.oauth2Cfg, + }, + }, + } + + config, err := BuildAuthServerRunConfig( + "default", "test-server", authConfig, + defaultAudiences, defaultScopes, + "http://test-server.default.svc.cluster.local:8080", + ) + + require.Error(t, err, "expected BuildAuthServerRunConfig to fail on invalid DCR pairing") + assert.Nil(t, config) + assert.Contains(t, err.Error(), tt.wantErr, + "error should surface the mutual-exclusivity violation") + // The upstream name must appear exactly once: the outer wrap in + // BuildAuthServerRunConfig supplies it, and the inner validator is + // invoked with an empty prefix so it doesn't duplicate the name. + assert.Equal(t, 1, strings.Count(err.Error(), "acme-idp"), + "upstream name should appear exactly once in error: %q", err.Error()) + }) + } +} + func TestAddEmbeddedAuthServerConfigOptions_Validation(t *testing.T) { t.Parallel() 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 fe2312bd70..d911fbd701 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 @@ -475,8 +475,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -510,8 +521,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -528,6 +541,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -644,9 +726,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -786,6 +872,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: @@ -1510,8 +1603,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -1545,8 +1649,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -1563,6 +1669,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -1679,9 +1854,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -1821,6 +2000,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: 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 0e7212a060..be695bb191 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 @@ -348,8 +348,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -383,8 +394,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -401,6 +414,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -517,9 +599,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -659,6 +745,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: @@ -2831,8 +2924,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -2866,8 +2970,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -2884,6 +2990,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -3000,9 +3175,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -3142,6 +3321,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: 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 116e7dc41c..b31aac8506 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -478,8 +478,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -513,8 +524,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -531,6 +544,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -647,9 +729,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -789,6 +875,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: @@ -1513,8 +1606,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -1548,8 +1652,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -1566,6 +1672,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -1682,9 +1857,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -1824,6 +2003,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: 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 47b0e3e2cf..eae9f15158 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -351,8 +351,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -386,8 +397,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -404,6 +417,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -520,9 +602,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -662,6 +748,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: @@ -2834,8 +2927,19 @@ spec: The embedded auth server delegates authentication to these providers. MCPServer and MCPRemoteProxy support a single upstream; VirtualMCPServer supports multiple. items: - description: UpstreamProviderConfig defines configuration for - an upstream Identity Provider. + description: |- + UpstreamProviderConfig defines configuration for an upstream Identity Provider. + + Exactly one of OIDCConfig or OAuth2Config must be set and must match the + declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers + set OAuth2Config. The CEL rule below enforces the pairing at admission; the + matching Go-level check in validateUpstreamProvider provides defense-in-depth + for stored objects. + + The rule is structured as a chain of equality checks ending in an explicit + `false`, so adding a new UpstreamProviderType value without extending this + rule fails admission instead of silently demanding the OAuth2 shape. When + adding a new type, extend both this rule and validateUpstreamProvider. properties: name: description: |- @@ -2869,8 +2973,10 @@ spec: pattern: ^https?://.*$ type: string clientId: - description: ClientID is the OAuth 2.0 client identifier - registered with the upstream IDP. + description: |- + ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. + Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained + at runtime via RFC 7591 Dynamic Client Registration and must be left empty. type: string clientSecretRef: description: |- @@ -2887,6 +2993,75 @@ spec: - key - name type: object + dcrConfig: + description: |- + DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream + authorization server. When set, the client credentials are obtained at + runtime rather than being pre-provisioned, and ClientID must be left empty. + Mutually exclusive with ClientID. + properties: + discoveryUrl: + description: |- + DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver + issues a single GET against this URL (no well-known-path fallback) and + reads registration_endpoint, authorization_endpoint, token_endpoint, + token_endpoint_auth_methods_supported, and scopes_supported from the + response. + Mutually exclusive with RegistrationEndpoint. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + initialAccessTokenRef: + description: |- + InitialAccessTokenRef is an optional reference to a Kubernetes Secret + carrying an RFC 7591 §3 initial access token. When set, the resolver + presents the token value as a Bearer credential on the registration + request. Mirrors the ClientSecretRef pattern. + properties: + key: + description: Key is the key within the secret + type: string + name: + description: Name is the name of the secret + type: string + required: + - key + - name + type: object + registrationEndpoint: + description: |- + RegistrationEndpoint is the RFC 7591 registration endpoint URL used + directly, bypassing discovery. When using this field, the caller is + expected to also supply AuthorizationEndpoint, TokenEndpoint, and an + explicit Scopes list on the parent OAuth2UpstreamConfig. + Mutually exclusive with DiscoveryURL. + MaxLength bounds CEL cost estimation on the parent struct's + XValidation rule and matches the conventional URL length cap. + maxLength: 2048 + pattern: ^https?://.*$ + type: string + softwareId: + description: |- + SoftwareID is the RFC 7591 "software_id" registration metadata value, + identifying the client software independent of any particular + registration instance. Typically a UUID or short identifier. + maxLength: 255 + type: string + softwareStatement: + description: |- + SoftwareStatement is the RFC 7591 "software_statement" JWT asserting + metadata about the client software, signed by a party the authorization + server trusts. Bounded to 4096 characters to prevent unbounded + user input from inflating the CR beyond etcd object limits. + maxLength: 4096 + type: string + type: object + x-kubernetes-validations: + - message: exactly one of discoveryUrl or registrationEndpoint + must be set + rule: has(self.discoveryUrl) != has(self.registrationEndpoint) redirectUri: description: |- RedirectURI is the callback URL where the upstream IDP will redirect after authentication. @@ -3003,9 +3178,13 @@ spec: type: object required: - authorizationEndpoint - - clientId - tokenEndpoint type: object + x-kubernetes-validations: + - message: exactly one of clientId or dcrConfig must be + set + rule: '(has(self.clientId) && size(self.clientId) > 0) + ? !has(self.dcrConfig) : has(self.dcrConfig)' oidcConfig: description: |- OIDCConfig contains OIDC-specific configuration. @@ -3145,6 +3324,13 @@ spec: - name - type type: object + x-kubernetes-validations: + - message: type must be 'oidc' or 'oauth2'; oidcConfig must + be set when type is 'oidc' and oauth2Config must be set + when type is 'oauth2' (and the other must not be set) + rule: 'self.type == ''oidc'' ? (has(self.oidcConfig) && !has(self.oauth2Config)) + : self.type == ''oauth2'' ? (has(self.oauth2Config) && !has(self.oidcConfig)) + : false' minItems: 1 type: array x-kubernetes-list-map-keys: diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index e256896797..304fbd6101 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -1071,6 +1071,40 @@ _Appears in:_ | `key` _string_ | Key is the key in the ConfigMap that contains the authorization configuration | authz.json | Optional: \{\}
| +#### api.v1beta1.DCRUpstreamConfig + + + +DCRUpstreamConfig configures RFC 7591 Dynamic Client Registration for an +OAuth 2.0 upstream. When present on an OAuth2 upstream, the authserver +performs registration at runtime to obtain client credentials, replacing +the need to pre-provision a ClientID. + +Exactly one of DiscoveryURL or RegistrationEndpoint must be set. DiscoveryURL +points at an RFC 8414 / OIDC Discovery document from which the registration +endpoint is resolved; RegistrationEndpoint is used directly when the upstream +does not publish discovery metadata. + +The XOR rule uses has() alone (not has() + size() > 0) to keep the rule's +estimated CEL cost under the apiserver's per-rule static budget. With +`omitempty` on both fields, an unset field is absent on the wire and has() +returns false; the explicit-empty-string edge case is rejected at reconcile +time by ValidateOAuth2DCRConfig. + + + +_Appears in:_ +- [api.v1beta1.OAuth2UpstreamConfig](#apiv1beta1oauth2upstreamconfig) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `discoveryUrl` _string_ | DiscoveryURL is the RFC 8414 / OIDC Discovery document URL. The resolver
issues a single GET against this URL (no well-known-path fallback) and
reads registration_endpoint, authorization_endpoint, token_endpoint,
token_endpoint_auth_methods_supported, and scopes_supported from the
response.
Mutually exclusive with RegistrationEndpoint.
MaxLength bounds CEL cost estimation on the parent struct's
XValidation rule and matches the conventional URL length cap. | | MaxLength: 2048
Pattern: `^https?://.*$`
Optional: \{\}
| +| `registrationEndpoint` _string_ | RegistrationEndpoint is the RFC 7591 registration endpoint URL used
directly, bypassing discovery. When using this field, the caller is
expected to also supply AuthorizationEndpoint, TokenEndpoint, and an
explicit Scopes list on the parent OAuth2UpstreamConfig.
Mutually exclusive with DiscoveryURL.
MaxLength bounds CEL cost estimation on the parent struct's
XValidation rule and matches the conventional URL length cap. | | MaxLength: 2048
Pattern: `^https?://.*$`
Optional: \{\}
| +| `initialAccessTokenRef` _[api.v1beta1.SecretKeyRef](#apiv1beta1secretkeyref)_ | InitialAccessTokenRef is an optional reference to a Kubernetes Secret
carrying an RFC 7591 §3 initial access token. When set, the resolver
presents the token value as a Bearer credential on the registration
request. Mirrors the ClientSecretRef pattern. | | Optional: \{\}
| +| `softwareId` _string_ | SoftwareID is the RFC 7591 "software_id" registration metadata value,
identifying the client software independent of any particular
registration instance. Typically a UUID or short identifier. | | MaxLength: 255
Optional: \{\}
| +| `softwareStatement` _string_ | SoftwareStatement is the RFC 7591 "software_statement" JWT asserting
metadata about the client software, signed by a party the authorization
server trusts. Bounded to 4096 characters to prevent unbounded
user input from inflating the CR beyond etcd object limits. | | MaxLength: 4096
Optional: \{\}
| + + #### api.v1beta1.EmbeddedAuthServerConfig @@ -2516,6 +2550,10 @@ _Appears in:_ OAuth2UpstreamConfig contains configuration for pure OAuth 2.0 providers. OAuth 2.0 providers require explicit endpoint configuration. +Exactly one of ClientID or DCRConfig must be set: ClientID is used when the +client is pre-provisioned out of band, DCRConfig enables RFC 7591 Dynamic +Client Registration at runtime. + _Appears in:_ @@ -2526,12 +2564,13 @@ _Appears in:_ | `authorizationEndpoint` _string_ | AuthorizationEndpoint is the URL for the OAuth authorization endpoint. | | Pattern: `^https?://.*$`
Required: \{\}
| | `tokenEndpoint` _string_ | TokenEndpoint is the URL for the OAuth token endpoint. | | Pattern: `^https?://.*$`
Required: \{\}
| | `userInfo` _[api.v1beta1.UserInfoConfig](#apiv1beta1userinfoconfig)_ | UserInfo contains configuration for fetching user information from the upstream provider.
When omitted, the embedded auth server runs in synthesis mode for this
upstream: a non-PII subject derived from the access token, no Name/Email.
Use this shape for upstreams with no userinfo surface (e.g., MCP
authorization servers per the MCP spec). | | Optional: \{\}
| -| `clientId` _string_ | ClientID is the OAuth 2.0 client identifier registered with the upstream IDP. | | Required: \{\}
| +| `clientId` _string_ | ClientID is the OAuth 2.0 client identifier registered with the upstream IDP.
Mutually exclusive with DCRConfig: when DCRConfig is set, ClientID is obtained
at runtime via RFC 7591 Dynamic Client Registration and must be left empty. | | Optional: \{\}
| | `clientSecretRef` _[api.v1beta1.SecretKeyRef](#apiv1beta1secretkeyref)_ | ClientSecretRef references a Kubernetes Secret containing the OAuth 2.0 client secret.
Optional for public clients using PKCE instead of client secret. | | Optional: \{\}
| | `redirectUri` _string_ | RedirectURI is the callback URL where the upstream IDP will redirect after authentication.
When not specified, defaults to `\{resourceUrl\}/oauth/callback` where `resourceUrl` is the
URL associated with the resource (e.g., MCPServer or vMCP) using this config. | | Optional: \{\}
| | `scopes` _string array_ | Scopes are the OAuth scopes to request from the upstream IDP. | | Optional: \{\}
| | `tokenResponseMapping` _[api.v1beta1.TokenResponseMapping](#apiv1beta1tokenresponsemapping)_ | TokenResponseMapping configures custom field extraction from non-standard token responses.
Some OAuth providers (e.g., GovSlack) nest token fields under non-standard paths
instead of returning them at the top level. When set, ToolHive performs the token
exchange HTTP call directly and extracts fields using the configured dot-notation paths.
If nil, standard OAuth 2.0 token response parsing is used. | | Optional: \{\}
| | `additionalAuthorizationParams` _object (keys:string, values:string)_ | AdditionalAuthorizationParams are extra query parameters to include in
authorization requests sent to the upstream provider.
This is useful for providers that require custom parameters, such as
Google's access_type=offline for obtaining refresh tokens.
Framework-managed parameters (response_type, client_id, redirect_uri,
scope, state, code_challenge, code_challenge_method, nonce) are not allowed. | | MaxProperties: 16
Optional: \{\}
| +| `dcrConfig` _[api.v1beta1.DCRUpstreamConfig](#apiv1beta1dcrupstreamconfig)_ | DCRConfig enables RFC 7591 Dynamic Client Registration against the upstream
authorization server. When set, the client credentials are obtained at
runtime rather than being pre-provisioned, and ClientID must be left empty.
Mutually exclusive with ClientID. | | Optional: \{\}
| #### api.v1beta1.OIDCUpstreamConfig @@ -2903,6 +2942,7 @@ SecretKeyRef is a reference to a key within a Secret _Appears in:_ - [api.v1beta1.BearerTokenConfig](#apiv1beta1bearertokenconfig) +- [api.v1beta1.DCRUpstreamConfig](#apiv1beta1dcrupstreamconfig) - [api.v1beta1.EmbeddedAuthServerConfig](#apiv1beta1embeddedauthserverconfig) - [api.v1beta1.EmbeddingServerSpec](#apiv1beta1embeddingserverspec) - [api.v1beta1.HeaderFromSecret](#apiv1beta1headerfromsecret) @@ -3167,6 +3207,17 @@ _Appears in:_ UpstreamProviderConfig defines configuration for an upstream Identity Provider. +Exactly one of OIDCConfig or OAuth2Config must be set and must match the +declared Type: oidc-typed providers set OIDCConfig, oauth2-typed providers +set OAuth2Config. The CEL rule below enforces the pairing at admission; the +matching Go-level check in validateUpstreamProvider provides defense-in-depth +for stored objects. + +The rule is structured as a chain of equality checks ending in an explicit +`false`, so adding a new UpstreamProviderType value without extending this +rule fails admission instead of silently demanding the OAuth2 shape. When +adding a new type, extend both this rule and validateUpstreamProvider. + _Appears in:_