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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 43 additions & 15 deletions cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ type SPIFFETrustDomainConfig struct {
// always supplies it instead of letting it be configured.
//
// +kubebuilder:validation:XValidation:rule="self.principalPattern.split('/').all(segment, segment != '.' && segment != '..')",message="principalPattern path must not contain . or .. segments"
// +kubebuilder:validation:XValidation:rule="has(self.resources) && size(self.resources) > 0",message="resources is required"
//
//nolint:lll // CEL validation rule exceeds line length limit
type SPIFFEClientConfig struct {
Expand Down Expand Up @@ -787,25 +788,29 @@ type SPIFFEClientConfig struct {
// which is derived at reconcile time and not available on this CRD, so
// allowlist membership is validated at reconcile time, not admission.
// Shape (a well-formed absolute HTTP(S) URI) is independent of that
// derived allowlist and is validated here. Distinct from Audiences: a
// resource permission does not imply the same value is also a permitted
// token audience, or vice versa.
// derived allowlist and is validated here. Required, with at least one
// entry, for every association: token exchange takes exactly one resource
// per request and grants it as the token audience.
// +optional
// +kubebuilder:validation:MaxItems=50
// +kubebuilder:validation:items:MinLength=1
// +kubebuilder:validation:items:MaxLength=2048
// +kubebuilder:validation:items:Pattern=`^https?://[^@#[:space:]]+$`
// +listType=set
// +optional
Resources []string `json:"resources,omitempty"`

// Audiences are RFC 8693 token audiences this association may request.
// +kubebuilder:validation:Required
// +kubebuilder:validation:MinItems=1
// Deprecated: ignored; use resources.
//
// The field was required in earlier releases and is still accepted so
// existing objects keep validating. A non-empty value is reported by the
// DeprecatedInboundGrantConfiguration condition and has no effect on token
// targeting.
// +optional
// +kubebuilder:validation:MaxItems=50
// +kubebuilder:validation:items:MinLength=1
// +kubebuilder:validation:items:MaxLength=2048
// +listType=set
Audiences []string `json:"audiences"`
Audiences []string `json:"audiences,omitempty"`

// Scopes are OAuth scopes granted to this association. Must be a subset
// of the server's effective supported scopes.
Expand Down Expand Up @@ -1432,7 +1437,10 @@ func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error {
for _, delegate := range grants.delegateClients {
delegateIDs = append(delegateIDs, delegate.ClientID)
}
return authserver.ValidateSPIFFEClientIDsNotDelegates(spiffeIDs, delegateIDs)
if err := authserver.ValidateSPIFFEClientIDsNotDelegates(spiffeIDs, delegateIDs); err != nil {
return err
}
return validateSPIFFEResourcesPresent(c.InboundGrants)
}

// ValidateTLSListener rejects a tlsListener whose certificate or private key
Expand Down Expand Up @@ -2860,12 +2868,13 @@ func (r *MCPExternalAuthConfig) validateEmbeddedAuthServer() error {
// needs the loopback-hostname helper, so it lives only in Go.
//
// The permission-shaped half of SPIFFE trust/client-auth config (grant
// types, scopes, resources, audiences) has no equivalent Go-level
// pre-check here, matching the DelegateClients precedent below — a
// meaningful check needs AllowedAudiences/ScopesSupported, which are only
// known once derived at reconcile time. controllerutil.
// validateDelegateClientsAndTrustedIssuers revalidates the full SPIFFE
// trust config (via RunConfig.Validate) once those derived values exist.
// types, scopes, resources) has no equivalent Go-level pre-check here,
// matching the DelegateClients precedent below — a meaningful check needs
// AllowedAudiences/ScopesSupported, which are only known once derived at
// reconcile time. controllerutil.validateDelegateClientsAndTrustedIssuers
// revalidates the full SPIFFE trust config (via RunConfig.Validate) once
// those derived values exist. Only the resources-present check runs
// earlier, inside ValidateInboundGrants.
//
// The checks below are admission-time-safe: they depend only on this
// object's own spec, so they run here instead of waiting for reconcile.
Expand Down Expand Up @@ -2999,6 +3008,25 @@ func validateSPIFFEPrincipalPatternOverlap(inboundGrants *InboundGrantsConfig) e
return nil
}

// validateSPIFFEResourcesPresent requires resources on every SPIFFE
// association. The CRD rule already does at admission; this reports an object
// stored by an earlier release, which may have no resources, as invalid. It
// runs from ValidateInboundGrants, so MCPExternalAuthConfig and inline
// VirtualMCPServer configuration both report it on their own validation
// condition instead of failing later in the converter. Shape and allowlist
// checks are left to the schema and to RunConfig.Validate.
func validateSPIFFEResourcesPresent(inboundGrants *InboundGrantsConfig) error {
if inboundGrants == nil {
return nil
}
for i, association := range inboundGrants.SPIFFEClientAuth {
if len(association.Resources) == 0 {
return fmt.Errorf("inboundGrants.spiffeClientAuth[%d].resources is required", i)
}
}
return nil
}

func hasJWTBearerTrustedIssuer(issuers []TrustedIssuerConfig) bool {
return slices.ContainsFunc(issuers, func(issuer TrustedIssuerConfig) bool {
return issuer.JWTBearerGrant != nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,16 @@ func TestMCPExternalAuthConfig_validateEmbeddedAuthServer(t *testing.T) {
expectErr: true,
errMsg: "must be an absolute HTTP(S) URI",
},
{
name: "spiffe association without resources is rejected",
config: func() *MCPExternalAuthConfig {
c := mustEmbeddedAuthServerConfigWithResource("https://mcp.example.com/resource")
c.Spec.EmbeddedAuthServer.InboundGrants.SPIFFEClientAuth[0].Resources = nil
return c
}(),
expectErr: true,
errMsg: "spiffeClientAuth[0].resources is required",
},
{
name: "spiffe resource indicator accepts a well-formed URI",
config: mustEmbeddedAuthServerConfigWithResource("https://mcp.example.com/resource"),
Expand Down Expand Up @@ -1270,6 +1280,7 @@ func mustEmbeddedAuthServerConfigWithSPIFFEX509Client(issuer, delegateClientID s
ClientID: "spiffe-client",
Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"},
Resources: []string{"https://mcp.example.com"},
Scopes: []string{"openid"},
}}}
if delegateClientID != "" {
Expand Down Expand Up @@ -1340,12 +1351,12 @@ func mustEmbeddedAuthServerConfigWithPrincipalPatterns(first, second string) *MC
{
TrustDomainRef: "example", PrincipalPattern: first, ClientID: "spiffe-client-1",
Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
Audiences: []string{"https://mcp.example.com"}, Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
},
{
TrustDomainRef: "example", PrincipalPattern: second, ClientID: "spiffe-client-2",
Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
Audiences: []string{"https://mcp.example.com"}, Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
},
},
},
Expand Down Expand Up @@ -1453,7 +1464,7 @@ func TestMCPExternalAuthConfig_ZeroUpstreamAlternatives(t *testing.T) {
TrustDomainRef: "example", PrincipalPattern: "spiffe://example.org/ns/default/agent",
ClientID: "spiffe-client",
Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
Audiences: []string{"https://mcp.example.com"}, Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
}},
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,17 @@ func deprecatedInboundGrantFields(cfg *mcpv1beta1.EmbeddedAuthServerConfig, root
})
}
}
if cfg.InboundGrants != nil {
for i, spiffeClient := range cfg.InboundGrants.SPIFFEClientAuth {
//nolint:staticcheck // Reports the deprecated field to the user.
if len(spiffeClient.Audiences) > 0 {
associationPath := fmt.Sprintf("%s.inboundGrants.spiffeClientAuth[%d]", root, i)
fields = append(fields, deprecatedInboundGrantField{
path: associationPath + ".audiences", replacement: associationPath + ".resources",
})
}
}
}
return fields
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1585,6 +1585,44 @@ func TestMCPExternalAuthConfigReconciler_DeprecatedInboundGrantTransitions(t *te
assert.Zero(t, countContaining(drainEvents(recorder), inboundGrantDeprecationEventReason))
}

func TestDeprecatedInboundGrantFields_SPIFFEAudiences(t *testing.T) {
t.Parallel()

tests := []struct {
name string
cfg *mcpv1beta1.EmbeddedAuthServerConfig
paths []deprecatedInboundGrantField
}{
{name: "nil config"},
{
name: "no audiences",
cfg: &mcpv1beta1.EmbeddedAuthServerConfig{InboundGrants: &mcpv1beta1.InboundGrantsConfig{
SPIFFEClientAuth: []mcpv1beta1.SPIFFEClientConfig{{ClientID: "a", Resources: []string{"https://api.example.com"}}},
}},
},
{
name: "audiences on the second association only",
cfg: &mcpv1beta1.EmbeddedAuthServerConfig{InboundGrants: &mcpv1beta1.InboundGrantsConfig{
SPIFFEClientAuth: []mcpv1beta1.SPIFFEClientConfig{
{ClientID: "a"},
{ClientID: "b", Audiences: []string{"https://api.example.com"}},
},
}},
paths: []deprecatedInboundGrantField{{
path: "spec.embeddedAuthServer.inboundGrants.spiffeClientAuth[1].audiences",
replacement: "spec.embeddedAuthServer.inboundGrants.spiffeClientAuth[1].resources",
}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := deprecatedInboundGrantFields(tt.cfg, "spec.embeddedAuthServer")
assert.ElementsMatch(t, tt.paths, got)
})
}
}

func TestMCPExternalAuthConfigReconciler_ReconcileKeepsExistingForeignCondition(t *testing.T) {
t.Parallel()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4818,6 +4818,7 @@ func TestVirtualMCPServerValidateAuthServerConfig_TLSListener(t *testing.T) {
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"},
Resources: []string{"https://mcp.example.com"},
Scopes: []string{"openid"},
}}}

Expand Down Expand Up @@ -4957,7 +4958,7 @@ func TestVirtualMCPServerValidateAuthServerConfig_ZeroUpstreamAlternatives(t *te
TrustDomainRef: "example", PrincipalPattern: "spiffe://example.org/ns/default/agent",
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
}},
},
},
Expand Down Expand Up @@ -5030,6 +5031,48 @@ func TestVirtualMCPServerValidateAuthServerConfig_CanonicalTrustedIssuer(t *test
assert.Equal(t, metav1.ConditionFalse, condition.Status)
}

func TestVirtualMCPServerValidateAuthServerConfig_SPIFFEAssociationWithoutResources(t *testing.T) {
t.Parallel()

vmcp := v1beta1test.NewVirtualMCPServer(testVmcpName, "default",
v1beta1test.WithVMCPGroupRef("test-group"),
v1beta1test.WithVMCPAuthServerConfig(&mcpv1beta1.EmbeddedAuthServerConfig{
Issuer: "https://auth.example.com",
TLSListener: &mcpv1beta1.TLSListenerConfig{
CertificateSecretRef: &mcpv1beta1.SecretKeyRef{Name: "listener-tls", Key: "certificate"},
PrivateKeySecretRef: &mcpv1beta1.SecretKeyRef{Name: "listener-tls", Key: "private-key"},
},
SPIFFETrustDomains: []mcpv1beta1.SPIFFETrustDomainConfig{{
Name: "example", TrustDomain: "example.org",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
BundleSource: mcpv1beta1.SPIFFEBundleSourceConfig{
Type: mcpv1beta1.SPIFFEBundleSourceTypeFile,
File: &mcpv1beta1.SPIFFEFileBundleSourceConfig{ConfigMapName: "spire-bundle", ConfigMapKey: "bundle.json"},
},
}},
InboundGrants: &mcpv1beta1.InboundGrantsConfig{
SPIFFEClientAuth: []mcpv1beta1.SPIFFEClientConfig{{
TrustDomainRef: "example", PrincipalPattern: "spiffe://example.org/ns/default/agent",
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Resources: nil, Scopes: []string{"openid"},
}},
},
}),
)
statusManager := virtualmcpserverstatus.NewStatusManager(vmcp)

err := (&VirtualMCPServerReconciler{}).validateAuthServerConfig(vmcp, statusManager)
statusManager.UpdateStatus(t.Context(), &vmcp.Status)

require.ErrorContains(t, err, "inboundGrants.spiffeClientAuth[0].resources is required")
condition := findCondition(vmcp.Status.Conditions, mcpv1beta1.ConditionTypeAuthServerConfigValidated)
require.NotNil(t, condition)
assert.Equal(t, metav1.ConditionFalse, condition.Status)
assert.Equal(t, mcpv1beta1.ConditionReasonAuthServerConfigInvalid, condition.Reason)
assert.Contains(t, condition.Message, "inboundGrants.spiffeClientAuth[0].resources is required")
}

func TestVirtualMCPServerValidateAuthServerConfig_TrustedIssuerEndpointRecovery(t *testing.T) {
t.Parallel()

Expand Down
4 changes: 3 additions & 1 deletion cmd/thv-operator/pkg/controllerutil/authserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,13 +400,15 @@ func buildSPIFFEClientAuthRunConfigs(
for j, method := range spiffeClient.Methods {
methods[j] = authserver.SPIFFEAuthenticationMethod(method)
}
// Passed through so the runtime can warn that it is ignored.
deprecatedAudiences := append([]string(nil), spiffeClient.Audiences...) //nolint:staticcheck // See above.
configs[i] = authserver.SPIFFEClientAuthRunConfig{
TrustDomainRef: spiffeClient.TrustDomainRef,
PrincipalPattern: spiffeClient.PrincipalPattern,
ClientID: spiffeClient.ClientID,
Methods: methods,
Resources: append([]string(nil), spiffeClient.Resources...),
Audiences: append([]string(nil), spiffeClient.Audiences...),
Audiences: deprecatedAudiences,
Scopes: append([]string(nil), spiffeClient.Scopes...),
GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ func TestBuildAuthServerRunConfigTLSListener(t *testing.T) {
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{method},
Audiences: []string{"https://mcp.example.com"},
Resources: []string{"https://mcp.example.com"},
Scopes: []string{"openid"},
}}}
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/thv-operator/pkg/controllerutil/authserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3704,7 +3704,7 @@ func TestBuildSPIFFEClientAuthRunConfigs(t *testing.T) {
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Resources: resources,
Audiences: audiences,
Audiences: audiences, //nolint:staticcheck // Exercises the deprecated pass-through.
Scopes: scopes,
}})

Expand Down Expand Up @@ -3767,6 +3767,7 @@ func TestBuildAuthServerRunConfigRejectsUnsupportedSPIFFEBundleSource(t *testing
ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"},
Resources: []string{"https://mcp.example.com"},
Scopes: []string{"openid"},
}},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() {
SPIFFEClientAuth: []mcpv1beta1.SPIFFEClientConfig{{
TrustDomainRef: "example", PrincipalPattern: principalPattern, ClientID: "spiffe-client",
Methods: []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodX509},
Audiences: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
Audiences: []string{"https://mcp.example.com"}, Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"},
}},
}
}
Expand Down Expand Up @@ -212,10 +212,10 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() {
principal: "spiffe://other.example.org/ns/default/agent", errMatch: "principalPattern trust domain must match",
},
{
name: "audiences are required", trustDomains: true, clients: true,
principal: "spiffe://example.org/ns/default/agent", errMatch: "audiences",
name: "deprecated audiences may be omitted", trustDomains: true, clients: true,
principal: "spiffe://example.org/ns/default/agent", shouldAdmit: true,
mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) {
config.InboundGrants.SPIFFEClientAuth[0].Audiences = nil
config.InboundGrants.SPIFFEClientAuth[0].Audiences = nil //nolint:staticcheck // Exercises the deprecated field.
},
},
{
Expand All @@ -226,17 +226,24 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() {
},
},
{
name: "resources are optional", trustDomains: true, clients: true,
name: "a listed resource is admitted", trustDomains: true, clients: true,
principal: "spiffe://example.org/ns/default/agent", shouldAdmit: true,
mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) {
config.InboundGrants.SPIFFEClientAuth[0].Resources = []string{"https://backend.example.com"}
},
},
{
name: "empty-string audience is rejected", trustDomains: true, clients: true,
name: "resources are required", trustDomains: true, clients: true,
principal: "spiffe://example.org/ns/default/agent", errMatch: "resources is required",
mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) {
config.InboundGrants.SPIFFEClientAuth[0].Resources = nil
},
},
{
name: "empty-string deprecated audience is still rejected", trustDomains: true, clients: true,
principal: "spiffe://example.org/ns/default/agent", errMatch: "audiences",
mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) {
config.InboundGrants.SPIFFEClientAuth[0].Audiences = []string{""}
config.InboundGrants.SPIFFEClientAuth[0].Audiences = []string{""} //nolint:staticcheck // Exercises the deprecated field.
},
},
{
Expand Down
Loading
Loading