diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index 9310059b19..eb848a8388 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -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 { @@ -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. @@ -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 @@ -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. @@ -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 diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index ba78c5f272..08ee60b345 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -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"), @@ -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 != "" { @@ -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"}, }, }, }, @@ -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"}, }}, }, }, diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go index abbbeecae5..9262ea81ba 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller.go @@ -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 } diff --git a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go index cdd9864400..a6673ac689 100644 --- a/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go +++ b/cmd/thv-operator/controllers/mcpexternalauthconfig_controller_test.go @@ -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() diff --git a/cmd/thv-operator/controllers/virtualmcpserver_controller_test.go b/cmd/thv-operator/controllers/virtualmcpserver_controller_test.go index be18c2576a..863999883f 100644 --- a/cmd/thv-operator/controllers/virtualmcpserver_controller_test.go +++ b/cmd/thv-operator/controllers/virtualmcpserver_controller_test.go @@ -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"}, }}} @@ -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"}, }}, }, }, @@ -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() diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index 35640627ba..01452edb90 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -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}, } diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_listener_tls_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_listener_tls_test.go index c299115404..bc1c02696d 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_listener_tls_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_listener_tls_test.go @@ -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"}, }}} } diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_test.go index 5e75f40d36..4988c3ad83 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_test.go @@ -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, }}) @@ -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"}, }}, }, diff --git a/cmd/thv-operator/test-integration/mcp-external-auth/spiffe_cel_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/spiffe_cel_test.go index 3c4161115e..c1335566ed 100644 --- a/cmd/thv-operator/test-integration/mcp-external-auth/spiffe_cel_test.go +++ b/cmd/thv-operator/test-integration/mcp-external-auth/spiffe_cel_test.go @@ -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"}, }}, } } @@ -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. }, }, { @@ -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. }, }, { 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 587df9446f..65dfdad836 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 @@ -562,14 +562,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -612,9 +616,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -641,7 +645,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -653,6 +656,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic @@ -3702,14 +3707,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -3752,9 +3761,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -3781,7 +3790,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -3793,6 +3801,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic 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 96a61f6f1d..1005803ba2 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 @@ -449,14 +449,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -499,9 +503,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -528,7 +532,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -540,6 +543,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic @@ -5981,14 +5986,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -6031,9 +6040,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -6060,7 +6069,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -6072,6 +6080,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic 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 3c7e27f791..3d7e415e98 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -565,14 +565,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -615,9 +619,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -644,7 +648,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -656,6 +659,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic @@ -3705,14 +3710,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -3755,9 +3764,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -3784,7 +3793,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -3796,6 +3804,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic 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 5726a43497..25f01bfe83 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -452,14 +452,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -502,9 +506,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -531,7 +535,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -543,6 +546,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic @@ -5984,14 +5989,18 @@ spec: always supplies it instead of letting it be configured. properties: audiences: - description: Audiences are RFC 8693 token audiences - this association may request. + description: |- + 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. items: maxLength: 2048 minLength: 1 type: string maxItems: 50 - minItems: 1 type: array x-kubernetes-list-type: set clientId: @@ -6034,9 +6043,9 @@ spec: 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. items: maxLength: 2048 minLength: 1 @@ -6063,7 +6072,6 @@ spec: minLength: 1 type: string required: - - audiences - clientId - methods - principalPattern @@ -6075,6 +6083,8 @@ spec: segments rule: self.principalPattern.split('/').all(segment, segment != '.' && segment != '..') + - message: resources is required + rule: has(self.resources) && size(self.resources) > 0 maxItems: 100 type: array x-kubernetes-list-type: atomic diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 0bb1bc770a..6841195150 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -779,7 +779,7 @@ Operator-declared clients are written at startup by `ReconcileConfiguredClient`. - A DCR-issued client is never overwritten. Startup fails. - A SPIFFE placeholder and a non-placeholder client never replace each other, in either direction. Startup fails. -- Two SPIFFE placeholders replace each other whatever differs (scopes, audiences, resources, SPIFFE identity), so an edited association takes effect on rollout. The placeholder row is inert, so this authorizes nothing differently. During the rollout, old and new replicas each serve their own configuration, and nothing marks when it ends. The server logs the same WARN as for delegates, including old and new resources and whether the identity changed. See [SPIFFE Association Declarations](18-spiffe-association-declarations.md). +- Two SPIFFE placeholders replace each other whatever differs (scopes, resources, or the SPIFFE identity), so an edited association takes effect on rollout. The placeholder row is inert, so this authorizes nothing differently. A SPIFFE placeholder stores no audiences, but every placeholder stored by v0.65.0 carries them. So on Redis, the first start of the new version logs the WARN below once for each association, even if `audiences` was already removed from the configuration. Each replica that reads the old row before it is rewritten logs it, and it can repeat if a v0.65.0 replica restarts during the rollout and writes the old row back. Later restarts do not log it. During the rollout, old and new replicas each serve their own configuration, and nothing marks when it ends. The server logs the same WARN as for delegates, including old and new resources and whether the identity changed. See [SPIFFE Association Declarations](18-spiffe-association-declarations.md). - Two non-placeholder clients, such as delegate clients, are replaced. A changed scope, audience, grant type, redirect URI or token endpoint auth method takes effect on restart, and so does a rotated secret or JWKS key. The one refusal is a flip between public and confidential, which fails startup. When scopes, audiences, grant types, redirect URIs or the token endpoint auth method change, the server logs a WARN, `configured client replaced with a different policy`, with the `client_id` and the old and new values of each. This covers replicas that roll out with different redirect URIs and overwrite each other's shared row. Secret and JWKS rotation and response type changes do not log it. An unchanged restart does not log this warning (the per-delegate startup WARN from `warnBlanketSelfIssuedExchange` still fires on every start for delegates whose `token_exchange.self_issued_subject_tokens` is `any` or that have no `token_exchange` block). Before this rule, a changed delegate scope or audience on Redis failed startup with "already registered as a different configured client", and the new pod never became ready. The memory backend never hit this, because it starts empty. diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index fb73e4550d..78be603448 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -704,7 +704,7 @@ in addition to other grants can log users in. the server's sole allowed audience and is checked the same way. The check applies to every client, including dynamically registered and CIMD clients. It uses the client's own `audiences`, or its resource allowlist for SPIFFE - clients, and the server's configured audience matching strategy (fosite's + clients (which have no audiences), and the server's configured audience matching strategy (fosite's path-prefix strategy by default), which is the rule the authorization code callback and the refresh grant already apply to a client's audiences. For a client without a separate resource list, a request the check accepts therefore @@ -732,7 +732,10 @@ in addition to other grants can log users in. names no target and the server's sole default audience is not one of the client's audiences, the refusal stays `invalid_request`: the client named no target, and the fix is to send an explicit `resource` or `audience`, which - the hint says. + the hint says. SPIFFE-authenticated clients use the resource-only rule + instead: any `audience` parameter, and a request with no `resource`, get + `invalid_target`. See + [SPIFFE Association Declarations](18-spiffe-association-declarations.md). - **Dynamically registered clients.** A DCR client keeps the audience list the server had when it registered, and that list is never refreshed. After an operator adds an audience, an existing DCR client that asks for it gets @@ -856,8 +859,11 @@ the client type: - **Configured delegate clients.** A per-client allowlist. `audience` matches by path prefix. `resource` must also be an exact member of `allowed_audiences`. -- **SPIFFE clients.** `audience` is checked the same way. `resource` is checked - against the client's own resource list. +- **SPIFFE clients.** `audiences` is ignored. The + request must send exactly one `resource` that exactly matches an entry in the + association's resource list, and `audience` is rejected (see + [SPIFFE Association Declarations](18-spiffe-association-declarations.md) + for the full rule). - **DCR and CIMD clients.** A copy of the server's list taken at registration. ID-JAG redemption does not narrow them, so only the server list applies. - **Device flow.** The client receives all of its `audiences`. diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index cc105f28dc..5fe0b50f6f 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -31,20 +31,33 @@ In the operator, set `embeddedAuthServer.tlsListener` with `certificateSecretRef Configuration separates top-level trust declarations from canonical client associations: - `spiffe_trust_domains` in `RunConfig` (`spiffeTrustDomains` in the CRD) names a canonical SPIFFE trust domain, declares the methods intended for authentication, and selects a trust-bundle source. -- `inbound_grants.spiffe_client_auth` in `RunConfig` (`inboundGrants.spiffeClientAuth` in the CRD) associates an exact SPIFFE ID or a terminal `/*` descendant `principalPattern` with one explicit OAuth `client_id`, methods, resources, audiences, and scopes. This is a sibling of `inbound_grants.token_exchange` and `inbound_grants.jwt_bearer`, not nested under either — client authentication does not by itself confer a grant. +- `inbound_grants.spiffe_client_auth` in `RunConfig` (`inboundGrants.spiffeClientAuth` in the CRD) associates an exact SPIFFE ID or a terminal `/*` descendant `principalPattern` with one explicit OAuth `client_id`, methods, resources, and scopes. This is a sibling of `inbound_grants.token_exchange` and `inbound_grants.jwt_bearer`, not nested under either — client authentication does not by itself confer a grant. The OAuth client ID is configured explicitly; it is never derived from the SPIFFE ID or pattern. Every SPIFFE client implicitly receives only the RFC 8693 token-exchange grant. The standalone `RunConfig` schema (`SPIFFEClientAuthRunConfig.GrantTypes`) does expose a `grant_types` field, but validation restricts it to that single value; the CRD omits it entirely and the operator's conversion always synthesizes it (`cmd/thv-operator/pkg/controllerutil/authserver.go`). -### Resources and audiences are separate dimensions +### Resources are the only target list -Each association can configure two independent request dimensions: +Each association lists the RFC 8707 `resources` its workload may ask for: -- `audiences` are RFC 8693 token audiences. They are not bounded by the server's `allowed_audiences` allowlist and may contain non-URI logical identifiers. -- `resources` are RFC 8707 resource indicators. Each one must be a syntactically valid absolute HTTP(S) URI, and each must also be a member of the server's `allowed_audiences` allowlist (`RunConfig.AllowedAudiences`) — the same allowlist `DelegateClientRunConfig.Audiences` is validated against. +- `resources` is required and must be non-empty on every association. Each entry must be a syntactically valid absolute HTTP(S) URI, and each must also be a member of the server's `allowed_audiences` allowlist (`RunConfig.AllowedAudiences`) — the same allowlist `DelegateClientRunConfig.Audiences` is validated against. The CRD requires a non-empty list (a CEL rule) and checks the shape of each entry (an item pattern). The operator checks allowlist membership at reconcile time, and `validateSPIFFEResources` in `pkg/authserver/spiffe_trust.go` checks all of it again at startup. +- `audiences` is deprecated and ignored. It stays in the CRD and the RunConfig as an optional field because v0.65.0 required it, so existing objects keep validating. A non-empty value is listed by the `DeprecatedInboundGrantConfiguration` status condition (the operator reports `inboundGrants.spiffeClientAuth[i].audiences`, with `...spiffeClientAuth[i].resources` as the replacement), and the auth server logs one WARN per association at startup. It never affects which tokens are issued. Remove it and list the target in `resources`. -Permission in one dimension never implies permission in the other: a value allowed as a `resource` is not automatically a permitted `audience`, and vice versa. `resources` is optional; `audiences` is required. +The runtime OAuth client built for a SPIFFE association (`registration.NewSPIFFEClient`) is constructed from `grant_types`, `scopes`, and `resources`. Its `GetAudience()` is always empty; request handlers read `Resources()`. -`resources` is validated for shape and allowlist membership at startup, and the runtime OAuth client built for a SPIFFE association (`registration.NewSPIFFEClient`) is constructed from `grant_types`, `scopes`, `audiences`, and `resources` — `Resources()` and `GetAudience()` are checked independently during a token-exchange request, matching the `audiences`/`resources` dimension split above. +### Token exchange requests + +Clients that carry a resource list, such as SPIFFE clients, are targeted by exactly one RFC 8707 resource from their association in RFC 8693 token exchange. The handler is `grantAndBoundAudiences` in `pkg/authserver/server/tokenexchange/handler.go`, which hands those clients to `GrantSingleResource` in `pkg/authserver/server/audience.go`: + +- The request must carry exactly one non-empty `resource`. A missing, empty or repeated `resource` is rejected with `invalid_target`. There is no default audience. +- Any `audience` parameter is rejected with `invalid_target`, even when a valid `resource` is also sent. +- The resource must be an absolute `http` or `https` URI with a host and no fragment, must be a member of the server's `allowed_audiences`, and must be an **exact** member of the association's `resources`. Otherwise the request fails with `invalid_target`. +- The granted audience must also be covered by the subject token's `aud`, as for every client. A resource outside the subject token's audience is rejected. + +Delegate clients and other clients (`private_key_jwt`, `client_secret`, DCR and CIMD) keep the existing rule: `audience`, `resource` or the default audience, checked against the client's own audiences. + +### Upgrading + +Compared with v0.65.0, every association needs `resources`, and SPIFFE token exchange now uses the resource-only rule above. An association without `resources` (previously allowed for token exchange only) fails validation. The CEL rules reject a CR at admission when it is created, or when its `spiffeClientAuth` list is changed, without `resources`. The list is at `spec.embeddedAuthServer.inboundGrants.spiffeClientAuth` on MCPExternalAuthConfig and `spec.authServerConfig.inboundGrants.spiffeClientAuth` on VirtualMCPServer. On clusters with CRD validation ratcheting (the `CRDValidationRatcheting` feature, on by default since Kubernetes 1.30), an update that leaves that list unchanged is still admitted, including other edits to the auth server config and finalizer removal on delete. The MCPExternalAuthConfig's own `Valid` condition then reports the missing `resources`, and servers that consume it fail to reconcile until it is added. An inline VirtualMCPServer configuration reports it on its `AuthServerConfigValidated` condition. The auth server refuses to start with such a RunConfig. A SPIFFE client that sends `audience=` or no target now gets `invalid_target` instead of a token; it must send one `resource` listed in its association. On a backend that keeps placeholders between runs (Redis), the first start of the new version logs one `configured client replaced with a different policy` WARN for each association. This happens because every placeholder stored by v0.65.0 carries `audiences` (they were required then), and the new placeholder does not. It happens even if you already removed `audiences` from the configuration, since the WARN comes from the stored row, not the current config. Each replica that reads the old row before it is rewritten logs it, and it can repeat if a v0.65.0 replica restarts during the rollout and writes the old row back. Later restarts do not log it, because a nil and an empty `audiences` list compare equal. Nothing is authorized differently by the replacement. Setting `audiences` still validates and is only reported as deprecated. ### Trust-bundle source @@ -86,7 +99,6 @@ spec: clientId: reporting-workloads methods: [spiffe_x509] resources: [https://mcp.example.com] - audiences: [https://mcp.example.com] scopes: [openid] ``` @@ -103,12 +115,12 @@ Within one configuration, a SPIFFE client ID that equals a delegate client ID is Startup does not simply refuse to start whenever a client with a static ID already exists in durable storage. Each configured static client ID is durably claimed through `ReconcileConfiguredClient` (`preflightDurableCollisions` in `pkg/authserver/storage/spiffe_decorator.go`), which creates the placeholder or replaces an existing one, and refuses anything that is not a placeholder: - If no client is stored at that ID, it creates an inert placeholder and starts normally. -- If a placeholder for the same client ID already exists, reconciliation replaces it. With an unchanged configuration (the restart case) nothing differs and nothing is logged. With a changed association (different scopes, audiences, resources, or SPIFFE identity) the server logs the `configured client replaced with a different policy` WARN, and the change takes effect on rollout. +- If a placeholder for the same client ID already exists, reconciliation replaces it. With an unchanged configuration (the restart case) nothing differs and nothing is logged. With a changed association (different scopes, resources, or SPIFFE identity) the server logs the `configured client replaced with a different policy` WARN, and the change takes effect on rollout. - If the existing record is DCR-issued, or is not a reserved placeholder (for example a delegate client), reconciliation fails and the server refuses to start. A placeholder and a non-placeholder client never replace each other, in either direction. -The durably-claimed record is always an inert placeholder — a client with no grant types and no response types, so it can never itself be issued a token — never the real SPIFFE client with its configured scopes and audiences. This durable claim, not just an in-process `GetClient` check, closes a cross-replica race: with Redis and multiple replicas, an older or still-rolling replica without this SPIFFE config could otherwise DCR-register the same client ID after a newer replica's read-only check passed. Claiming the ID durably makes the reservation visible to every replica immediately. +The durably-claimed record is always an inert placeholder — a client with no grant types and no response types, so it can never itself be issued a token — never the real SPIFFE client with its configured scopes and resources. This durable claim, not just an in-process `GetClient` check, closes a cross-replica race: with Redis and multiple replicas, an older or still-rolling replica without this SPIFFE config could otherwise DCR-register the same client ID after a newer replica's read-only check passed. Claiming the ID durably makes the reservation visible to every replica immediately. -On every startup, the server reconstructs the static registry and its overlay from serialized configuration. A restart with the same configuration produces the same associations and reconciles cleanly against the previous run's placeholders. A **changed** association (different scopes, audiences, resources, principal pattern, methods, or trust-domain reference at the same client ID) replaces the stored placeholder, logs the `configured client replaced with a different policy` WARN with the old and new values (for the SPIFFE identity, only whether it changed), and takes effect when the new pods roll out. The placeholder row is inert: it has no grant types, is never admitted for a token, and `GetClient` serves each replica's in-process overlay, so replacing it authorizes nothing differently. Strictness remains only against non-reserved clients, so a DCR or delegate client cannot take over a SPIFFE client ID, and the reverse. Old and new replicas each serve their own configuration during a rollout, and nothing marks when it ends. A rename of the trust-domain reference counts as a change, because the reference is part of the identity hash. Edits that the placeholder does not store, such as grant types or a trust domain's bundle source, do not log the WARN. +On every startup, the server reconstructs the static registry and its overlay from serialized configuration. A restart with the same configuration produces the same associations and reconciles cleanly against the previous run's placeholders. A **changed** association (different scopes, resources, principal pattern, methods, or trust-domain reference at the same client ID) replaces the stored placeholder, logs the `configured client replaced with a different policy` WARN with the old and new values (for the SPIFFE identity, only whether it changed), and takes effect when the new pods roll out. The placeholder row is inert: it has no grant types, is never admitted for a token, and `GetClient` serves each replica's in-process overlay, so replacing it authorizes nothing differently. Strictness remains only against non-reserved clients, so a DCR or delegate client cannot take over a SPIFFE client ID, and the reverse. Old and new replicas each serve their own configuration during a rollout, and nothing marks when it ends. A rename of the trust-domain reference counts as a change, because the reference is part of the identity hash. Edits that the placeholder does not store, such as grant types or a trust domain's bundle source, do not log the WARN. A **removed** association's active policy does take effect on a successful restart — the in-memory overlay is rebuilt from the current configuration, so a client with no matching association is no longer served as a static client. What does *not* clean up is its durable reservation: nothing currently deletes the inert placeholder `ReconcileConfiguredClient` claimed for that client ID, so it persists in storage indefinitely, preventing the ID from being reused by DCR or a delegate client (tracked as [#6477](https://github.com/stacklok/toolhive/issues/6477)). Dynamic clients remain subject to the storage backend's own persistence, but no stale static client is restored from storage — the in-memory overlay's clients always come from the current configuration, never from a prior run's storage state. @@ -136,7 +148,7 @@ curl -X POST https://auth.example.com/oauth/token \ --data-urlencode "client_assertion=$JWT_SVID" ``` -After validation, the authentication strategy calls the shared `SPIFFEAssociationRegistry.Resolve` path synchronously through its JWT resolver. The registry verifies the enabled JWT method and either derives the association's configured client ID or checks the supplied selector's ownership, then returns the configured static OAuth client wrapped in `registration.AuthenticatedSPIFFEClient`. The wrapper carries the verified SPIFFE ID and authentication method and is available to grant handlers, though none consume it yet. In production only this resolver builds it. It exists only on the client produced by client authentication: a client loaded from storage, for example when a stored request is read back, is the plain static client and does not carry it. +After validation, the authentication strategy calls the shared `SPIFFEAssociationRegistry.Resolve` path synchronously through its JWT resolver. The registry verifies the enabled JWT method and either derives the association's configured client ID or checks the supplied selector's ownership, then returns the configured static OAuth client wrapped in `registration.AuthenticatedSPIFFEClient`. Token exchange selects the single-resource rule for any client that carries a resource list, and the wrapper carries one through the client it embeds. The wrapper also carries the verified SPIFFE ID and authentication method, but no grant handler reads those two values. In production only this resolver builds it. It exists only on the client produced by client authentication: a client loaded from storage, for example when a stored request is read back, is the plain static client and does not carry it. After the SPIFFE JWT arm is selected, malformed request fields use generic OAuth `invalid_request` errors; validation, association, and mixed-credential failures use generic `invalid_client` errors. In that arm, an HTTP Basic authorization header or any `client_secret` form field causes client authentication to fail. Credential material is not logged or included in errors. diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index d57fd51621..168b4fd327 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -4370,8 +4370,8 @@ _Appears in:_ | `principalPattern` _string_ | PrincipalPattern is a concrete SPIFFE ID or a terminal /* pattern within
the declared trust domain. This pattern is a best-effort CRD-level
approximation; runtime parsing via spiffeid.FromString remains
authoritative. | | MaxLength: 2048
Pattern: `^spiffe://[a-z0-9._-]+((/[a-zA-Z0-9._-]+)+(/\*)?\|/\*)$`
Required: \{\}
| | `clientId` _string_ | ClientID is the explicit OAuth client_id. It is never derived from a
SPIFFE ID. | | MaxLength: 253
MinLength: 1
Required: \{\}
| | `methods` _[api.v1beta1.SPIFFEAuthenticationMethod](#apiv1beta1spiffeauthenticationmethod) array_ | Methods are the credential types this association may authenticate
with. Must be a subset of the referenced trust domain's methods. | | MaxItems: 2
MinItems: 1
Required: \{\}
items:Enum: [spiffe_x509 spiffe_jwt]
| -| `resources` _string array_ | Resources are RFC 8707 resource indicators this association may
request. Must be a subset of the server's allowed_audiences allowlist,
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. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^@#[:space:]]+$`
Optional: \{\}
| -| `audiences` _string array_ | Audiences are RFC 8693 token audiences this association may request. | | MaxItems: 50
MinItems: 1
Required: \{\}
items:MaxLength: 2048
items:MinLength: 1
| +| `resources` _string array_ | Resources are RFC 8707 resource indicators this association may
request. Must be a subset of the server's allowed_audiences allowlist,
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. Required, with at least one
entry, for every association: token exchange takes exactly one resource
per request and grants it as the token audience. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
items:Pattern: `^https?://[^@#[:space:]]+$`
Optional: \{\}
| +| `audiences` _string array_ | 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. | | MaxItems: 50
items:MaxLength: 2048
items:MinLength: 1
Optional: \{\}
| | `scopes` _string array_ | Scopes are OAuth scopes granted to this association. Must be a subset
of the server's effective supported scopes. | | MaxItems: 50
MinItems: 1
Required: \{\}
items:MaxLength: 256
items:MinLength: 1
| diff --git a/docs/server/docs.go b/docs/server/docs.go index d1b2db8daa..af31c9d2be 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -755,7 +755,7 @@ const docTemplate = `{ "authserver.SPIFFEClientAuthRunConfig": { "properties": { "audiences": { - "description": "Audiences are RFC 8693 token audiences this association may request.\nThis is an independent request dimension from Resources: it is not\nbounded by allowed_audiences (which is an RFC 8707 resource-URI list)\nand may contain non-URI logical audience identifiers.", + "description": "Audiences is deprecated and ignored; use Resources. It stays in the\nschema because v0.65.0 required it, and a warning is logged at startup\nwhen it is set.", "items": { "type": "string" }, @@ -786,7 +786,7 @@ const docTemplate = `{ "type": "string" }, "resources": { - "description": "Resources are RFC 8707 resource indicators this association may\nrequest. Must be a subset of the server's allowed_audiences allowlist\n(RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list\nDelegateClientRunConfig.Audiences is validated against. Distinct from\nAudiences: a resource permission does not imply the same value is also\na permitted token audience, or vice versa.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: token\nexchange takes exactly one resource per request and grants it as the\ntoken audience. Must be a subset of the\nserver's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the\nsame RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is\nvalidated against.", "items": { "type": "string" }, diff --git a/docs/server/swagger.json b/docs/server/swagger.json index 84a26c07bc..820769761a 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -748,7 +748,7 @@ "authserver.SPIFFEClientAuthRunConfig": { "properties": { "audiences": { - "description": "Audiences are RFC 8693 token audiences this association may request.\nThis is an independent request dimension from Resources: it is not\nbounded by allowed_audiences (which is an RFC 8707 resource-URI list)\nand may contain non-URI logical audience identifiers.", + "description": "Audiences is deprecated and ignored; use Resources. It stays in the\nschema because v0.65.0 required it, and a warning is logged at startup\nwhen it is set.", "items": { "type": "string" }, @@ -779,7 +779,7 @@ "type": "string" }, "resources": { - "description": "Resources are RFC 8707 resource indicators this association may\nrequest. Must be a subset of the server's allowed_audiences allowlist\n(RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list\nDelegateClientRunConfig.Audiences is validated against. Distinct from\nAudiences: a resource permission does not imply the same value is also\na permitted token audience, or vice versa.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: token\nexchange takes exactly one resource per request and grants it as the\ntoken audience. Must be a subset of the\nserver's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the\nsame RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is\nvalidated against.", "items": { "type": "string" }, diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index d6c484270c..2ec5462b9e 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -1062,10 +1062,9 @@ components: properties: audiences: description: |- - Audiences are RFC 8693 token audiences this association may request. - This is an independent request dimension from Resources: it is not - bounded by allowed_audiences (which is an RFC 8707 resource-URI list) - and may contain non-URI logical audience identifiers. + Audiences is deprecated and ignored; use Resources. It stays in the + schema because v0.65.0 required it, and a warning is logged at startup + when it is set. items: type: string type: array @@ -1096,11 +1095,12 @@ components: resources: description: |- Resources are RFC 8707 resource indicators this association may - request. Must be a subset of the server's allowed_audiences allowlist - (RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list - DelegateClientRunConfig.Audiences is validated against. Distinct from - Audiences: a resource permission does not imply the same value is also - a permitted token audience, or vice versa. + request. At least one is required for every association: token + exchange takes exactly one resource per request and grants it as the + token audience. Must be a subset of the + server's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the + same RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is + validated against. items: type: string type: array diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index 78e032997c..1a58a1e475 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -113,6 +113,16 @@ func mustNewSPIFFETrustConfig(t *testing.T) *SPIFFETrustConfig { return mustNewSPIFFETrustConfigWithSource(t, validFileBundleSource()) } +// testSPIFFEWildcardAssociation returns a valid token-exchange association for +// the "production" trust domain that matches any workload in the default +// namespace and allows audience as a resource. +func testSPIFFEWildcardAssociation(audience string) SPIFFEClientAuthRunConfig { + association := testSPIFFEAssociation("agent-client", "openid") + association.PrincipalPattern = "spiffe://example.org/ns/default/*" + association.Resources = []string{audience} + return association +} + func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceRunConfig) *SPIFFETrustConfig { t.Helper() trust, err := NewSPIFFETrustConfig( @@ -122,15 +132,7 @@ func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceR Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, BundleSource: source, }}, - &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/*", - ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Audiences: []string{"https://mcp.example.com"}, - Scopes: []string{"openid"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{testSPIFFEWildcardAssociation("https://mcp.example.com")}}, []string{"openid"}, []string{"https://mcp.example.com"}, ) require.NoError(t, err) @@ -721,23 +723,16 @@ func TestRunConfigValidate(t *testing.T) { x509Config := func(mutate func(*RunConfig)) RunConfig { config := RunConfig{ - Issuer: "https://auth.example.org", - TLSListener: &TLSListenerRunConfig{CertFile: "cert", KeyFile: "key"}, + Issuer: "https://auth.example.org", + AllowedAudiences: []string{"https://mcp.example.org/resource"}, + TLSListener: &TLSListenerRunConfig{CertFile: "cert", KeyFile: "key"}, SPIFFETrustDomains: []SPIFFETrustDomainRunConfig{{ Name: "production", TrustDomain: "example.org", Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, BundleSource: validFileBundleSource(), }}, - InboundGrants: &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/*", - ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Audiences: []string{"https://mcp.example.org/resource"}, - Scopes: []string{"openid"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}}, + InboundGrants: &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{testSPIFFEWildcardAssociation("https://mcp.example.org/resource")}}, } if mutate != nil { mutate(&config) @@ -3223,15 +3218,7 @@ func spiffeBundleSourceTestTrust(source SPIFFEBundleSourceRunConfig) ([]SPIFFETr Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, BundleSource: source, }} - grants := &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/*", - ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Audiences: []string{"https://mcp.example.com"}, - Scopes: []string{"openid"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}} + grants := &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{testSPIFFEWildcardAssociation("https://mcp.example.com")}} return domains, grants } @@ -3280,6 +3267,7 @@ func TestSPIFFEBundleSourceRuntimeSupport(t *testing.T) { domains, grants := spiffeBundleSourceTestTrust(tt.source) cfg := RunConfig{ Issuer: "https://auth.example.org", + AllowedAudiences: []string{"https://mcp.example.com"}, TLSListener: &TLSListenerRunConfig{CertFile: "cert", KeyFile: "key"}, SPIFFETrustDomains: domains, InboundGrants: grants, diff --git a/pkg/authserver/delegate_client_restart_integration_test.go b/pkg/authserver/delegate_client_restart_integration_test.go index cac2aeaf91..c2d38f1383 100644 --- a/pkg/authserver/delegate_client_restart_integration_test.go +++ b/pkg/authserver/delegate_client_restart_integration_test.go @@ -150,6 +150,7 @@ func spiffeTrustForScope(t *testing.T, scope string) *authserver.SPIFFETrustConf Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, Scopes: []string{scope}, Audiences: []string{delegateAudience}, + Resources: []string{delegateAudience}, GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, }}}, []string{"scope-a", "scope-b", "scope-c"}, diff --git a/pkg/authserver/inbound_grants_test.go b/pkg/authserver/inbound_grants_test.go index 82d8e1a6fa..8a9c147204 100644 --- a/pkg/authserver/inbound_grants_test.go +++ b/pkg/authserver/inbound_grants_test.go @@ -325,7 +325,7 @@ func TestInboundGrantsRunConfigSerializationLayouts(t *testing.T) { }, { name: "canonical YAML", - input: "trusted_issuers:\n - name: idp\n issuer_url: https://idp.example.com\n expected_audience: \"\"\ninbound_grants:\n spiffe_client_auth:\n - trust_domain_ref: prod\n principal_pattern: spiffe://example.org/agent\n client_id: agent\n methods: [spiffe_x509]\n audiences: [resource]\n scopes: [openid]\n grant_types: [\"urn:ietf:params:oauth:grant-type:token-exchange\"]\n token_exchange:\n issuer_policies:\n - issuer_ref: idp\n expected_audience: resource\n allowed_delegate_clients: [delegate]\n jwt_bearer:\n issuer_policies:\n - issuer_ref: idp\n max_assertion_age: 5m\n subject_bindings:\n - subject: workload\n allowed_resources: [resource]\n", + input: "trusted_issuers:\n - name: idp\n issuer_url: https://idp.example.com\n expected_audience: \"\"\ninbound_grants:\n spiffe_client_auth:\n - trust_domain_ref: prod\n principal_pattern: spiffe://example.org/agent\n client_id: agent\n methods: [spiffe_x509]\n audiences: [resource]\n resources: [\"https://resource.example.com\"]\n scopes: [openid]\n grant_types: [\"urn:ietf:params:oauth:grant-type:token-exchange\"]\n token_exchange:\n issuer_policies:\n - issuer_ref: idp\n expected_audience: resource\n allowed_delegate_clients: [delegate]\n jwt_bearer:\n issuer_policies:\n - issuer_ref: idp\n max_assertion_age: 5m\n subject_bindings:\n - subject: workload\n allowed_resources: [resource]\n", unmarshal: func(data []byte, cfg *RunConfig) error { return yaml.Unmarshal(data, cfg) }, marshal: func(cfg *RunConfig) ([]byte, error) { return yaml.Marshal(cfg) }, serializedFields: []string{"inbound_grants:", "token_exchange:", "jwt_bearer:", "spiffe_client_auth:", "issuer_ref:"}, diff --git a/pkg/authserver/internal/spiffetest/client.go b/pkg/authserver/internal/spiffetest/client.go index 03a4080f36..8db325cd4f 100644 --- a/pkg/authserver/internal/spiffetest/client.go +++ b/pkg/authserver/internal/spiffetest/client.go @@ -20,7 +20,6 @@ type config struct { id string grants []string scopes []string - audiences []string resources []string spiffeID string method spiffeauth.SPIFFEAuthenticationMethod @@ -39,9 +38,6 @@ func WithGrantTypes(grants ...string) Option { return func(c *config) { c.grants // WithScopes sets the allowed scopes. func WithScopes(scopes ...string) Option { return func(c *config) { c.scopes = scopes } } -// WithAudiences sets the allowed audiences. -func WithAudiences(audiences ...string) Option { return func(c *config) { c.audiences = audiences } } - // WithResources sets the allowed RFC 8707 resources. func WithResources(resources ...string) Option { return func(c *config) { c.resources = resources } } @@ -55,12 +51,11 @@ func WithAuthMethod(method spiffeauth.SPIFFEAuthenticationMethod) Option { } // Client returns a valid SPIFFE client with id "spiffe-client", the -// token-exchange grant, scope "openid", audience "https://api.example.com" and -// no resources, adjusted by opts. +// token-exchange grant, scope "openid" and no resources, adjusted by opts. func Client(t *testing.T, opts ...Option) *registration.SPIFFEClient { t.Helper() c := newConfig(opts) - client, err := registration.NewSPIFFEClient(c.id, c.grants, c.scopes, c.audiences, c.resources) + client, err := registration.NewSPIFFEClient(c.id, c.grants, c.scopes, c.resources) require.NoError(t, err) return client } @@ -81,12 +76,11 @@ func AuthenticatedClient(t *testing.T, opts ...Option) *registration.Authenticat func newConfig(opts []Option) config { c := config{ - id: "spiffe-client", - grants: []string{oauthproto.GrantTypeTokenExchange}, - scopes: []string{"openid"}, - audiences: []string{"https://api.example.com"}, - spiffeID: "spiffe://example.org/workload/test", - method: spiffeauth.SPIFFEAuthenticationMethodJWT, + id: "spiffe-client", + grants: []string{oauthproto.GrantTypeTokenExchange}, + scopes: []string{"openid"}, + spiffeID: "spiffe://example.org/workload/test", + method: spiffeauth.SPIFFEAuthenticationMethodJWT, } for _, opt := range opts { opt(&c) diff --git a/pkg/authserver/runner/embeddedauthserver_integration_test.go b/pkg/authserver/runner/embeddedauthserver_integration_test.go index 8f6b236868..ec4229e8e5 100644 --- a/pkg/authserver/runner/embeddedauthserver_integration_test.go +++ b/pkg/authserver/runner/embeddedauthserver_integration_test.go @@ -82,15 +82,7 @@ func TestIntegration_EmbeddedAuthServer_SPIFFERedisRestartAndCollision(t *testin }, }} cfg.InboundGrants = &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent")}, } return cfg } diff --git a/pkg/authserver/runner/embeddedauthserver_test.go b/pkg/authserver/runner/embeddedauthserver_test.go index ac02197bea..3b5a6ddcf4 100644 --- a/pkg/authserver/runner/embeddedauthserver_test.go +++ b/pkg/authserver/runner/embeddedauthserver_test.go @@ -2565,15 +2565,7 @@ func TestNewEmbeddedAuthServer_SPIFFEAndJWTBearerGrant(t *testing.T) { }, }}, InboundGrants: &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent")}, }, TrustedIssuers: []tokenexchange.TrustedIssuer{{ IssuerURL: "https://issuer.example.com", @@ -2628,15 +2620,7 @@ func TestNewEmbeddedAuthServer_SPIFFEAndCIMD(t *testing.T) { }, }}, InboundGrants: &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent")}, }, } @@ -2672,15 +2656,7 @@ func TestNewEmbeddedAuthServerWithStorage_SPIFFECollisionPrecedesDCR(t *testing. }, }}, InboundGrants: &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent")}, }, Upstreams: []authserver.UpstreamRunConfig{{ Name: "dcr-upstream", @@ -2734,16 +2710,10 @@ func TestEmbeddedAuthServer_SPIFFESerializedRestartPolicy(t *testing.T) { File: &authserver.SPIFFEFileBundleSourceRunConfig{Path: writeTestSPIFFEBundleFile(t)}, }, }} + spiffeClient := testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent") + spiffeClient.Scopes = []string{scope} cfg.InboundGrants = &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{scope}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{spiffeClient}, } return cfg } @@ -2886,6 +2856,8 @@ func TestEmbeddedAuthServer_SPIFFEClientIDAloneDoesNotAuthenticate(t *testing.T) t.Run(tt.name, func(t *testing.T) { t.Parallel() + spiffeClient := testSPIFFEAssociation("spiffe-client", "spiffe://example.org/ns/default/agent") + spiffeClient.Methods = tt.methods cfg := authserver.RunConfig{ SchemaVersion: authserver.CurrentSchemaVersion, Issuer: "https://auth.example.com", @@ -2910,16 +2882,7 @@ func TestEmbeddedAuthServer_SPIFFEClientIDAloneDoesNotAuthenticate(t *testing.T) File: &authserver.SPIFFEFileBundleSourceRunConfig{Path: writeTestSPIFFEBundleFile(t)}, }, }}, - InboundGrants: &authserver.InboundGrantsRunConfig{SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: tt.methods, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - Scopes: []string{"openid"}, - Resources: []string{"https://mcp.example.com"}, - Audiences: []string{"https://mcp.example.com"}, - }}}, + InboundGrants: &authserver.InboundGrantsRunConfig{SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{spiffeClient}}, } if tt.methods[0] == authserver.SPIFFEAuthenticationMethodX509 { cfg.TLSListener = writeTestSPIFFEListener(t) @@ -4229,3 +4192,18 @@ func TestCloseIdleConnectionsWithoutCapability(t *testing.T) { assert.NotPanics(t, eas.CloseIdleConnections) assert.Zero(t, stub.closed.Load(), "must not fall back to Close") } + +// testSPIFFEAssociation returns a valid token-exchange association for the +// "production" trust domain; callers override only the fields their case +// cares about. +func testSPIFFEAssociation(clientID, principal string) authserver.SPIFFEClientAuthRunConfig { + return authserver.SPIFFEClientAuthRunConfig{ + TrustDomainRef: "production", + PrincipalPattern: principal, + ClientID: clientID, + Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, + Scopes: []string{"openid"}, + Resources: []string{"https://mcp.example.com"}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, + } +} diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index 44e451af4d..a5b472ab84 100644 --- a/pkg/authserver/runner/spiffe_x509_listener_test.go +++ b/pkg/authserver/runner/spiffe_x509_listener_test.go @@ -137,15 +137,7 @@ func TestEmbeddedAuthServer_SPIFFEX509ClientAuthOverTLS(t *testing.T) { trusted := newSPIFFETestAuthority(t, "ca-1") untrusted := newSPIFFETestAuthority(t, "ca-2") tokenURL, roots, _ := startSPIFFEX509TLSServer(t, trusted, func(cfg *authserver.RunConfig) { - cfg.InboundGrants.SPIFFEClientAuth = append(cfg.InboundGrants.SPIFFEClientAuth, authserver.SPIFFEClientAuthRunConfig{ - TrustDomainRef: "production", - PrincipalPattern: spiffeX509TestOtherPrincipal, - ClientID: spiffeX509TestOtherClientID, - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }) + cfg.InboundGrants.SPIFFEClientAuth = append(cfg.InboundGrants.SPIFFEClientAuth, testSPIFFEAssociation(spiffeX509TestOtherClientID, spiffeX509TestOtherPrincipal)) }) postToken := func(t *testing.T, svid tls.Certificate, clientID string) (int, string) { @@ -338,6 +330,18 @@ func TestEmbeddedAuthServer_SPIFFEOnlyTokenExchangeOverTLS(t *testing.T) { assert.NotEmpty(t, body["access_token"]) } +// TestEmbeddedAuthServer_SPIFFEAssociationWithoutResourcesIsRejected pins that +// an association with no resources fails at startup. +func TestEmbeddedAuthServer_SPIFFEAssociationWithoutResourcesIsRejected(t *testing.T) { + t.Parallel() + + cfg, _ := spiffeX509TestConfig(t, newSPIFFETestAuthority(t, "ca-1"), func(cfg *authserver.RunConfig) { + cfg.InboundGrants.SPIFFEClientAuth[0].Resources = nil + }) + _, err := NewEmbeddedAuthServer(context.Background(), cfg, WithListenerHost("127.0.0.1")) + require.ErrorContains(t, err, "resources is required") +} + // TestEmbeddedAuthServer_SPIFFETokenExchangeOverTLS completes RFC 8693 // exchanges over the TLS listener with X.509-SVID and JWT-SVID client // authentication, checking the issued token and the policy and consent limits. @@ -473,11 +477,11 @@ func TestEmbeddedAuthServer_SPIFFETokenExchangeOverTLS(t *testing.T) { wantError: "invalid_scope", }, { - name: "audience outside the association audiences is invalid_target", + name: "audience parameter is invalid_target", build: func(t *testing.T) request { t.Helper() svid := trusted.issueSVID(t) - // The subject token covers otherAudience: only the association refuses it. + // The subject token covers otherAudience: only the targeting rule refuses it. form := exchangeForm(subjectToken(t, spiffeX509TestClientID, "openid", nil, otherAudience), spiffeX509TestClientID, url.Values{"audience": {otherAudience}}) form.Del("resource") @@ -485,7 +489,7 @@ func TestEmbeddedAuthServer_SPIFFETokenExchangeOverTLS(t *testing.T) { }, wantStatus: http.StatusBadRequest, wantError: "invalid_target", - wantDesc: "not permitted to request audience", + wantDesc: "audience parameter is not accepted", }, { name: "subject token issued to another client without may_act is invalid_grant", @@ -576,6 +580,27 @@ func startSPIFFEX509TLSServer( ) (string, *x509.CertPool, *EmbeddedAuthServer) { t.Helper() + cfg, listenerPair := spiffeX509TestConfig(t, trusted, configure) + srv, err := NewEmbeddedAuthServer(context.Background(), cfg, WithListenerHost("127.0.0.1")) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, srv.Close()) }) + require.NotNil(t, srv.tlsListener) + srv.tlsListener.port = 0 + require.NoError(t, srv.Start()) + addr := srv.tlsListener.listener.Addr().(*net.TCPAddr) + + roots := x509.NewCertPool() + roots.AddCert(listenerPair.cert) + return fmt.Sprintf("https://127.0.0.1:%d/oauth/token", addr.Port), roots, srv +} + +// spiffeX509TestConfig builds the RunConfig startSPIFFEX509TLSServer starts, +// together with the listener certificate pair. +func spiffeX509TestConfig( + t *testing.T, trusted spiffeTestAuthority, configure func(*authserver.RunConfig), +) (*authserver.RunConfig, testCertificate) { + t.Helper() + bundlePath := filepath.Join(t.TempDir(), "bundle.json") writeSPIFFEBundleFile(t, bundlePath, trusted) @@ -607,32 +632,13 @@ func startSPIFFEX509TLSServer( }, }}, InboundGrants: &authserver.InboundGrantsRunConfig{ - SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: spiffeX509TestPrincipal, - ClientID: spiffeX509TestClientID, - Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, - }}, + SPIFFEClientAuth: []authserver.SPIFFEClientAuthRunConfig{testSPIFFEAssociation(spiffeX509TestClientID, spiffeX509TestPrincipal)}, }, } if configure != nil { configure(cfg) } - - srv, err := NewEmbeddedAuthServer(context.Background(), cfg, WithListenerHost("127.0.0.1")) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, srv.Close()) }) - require.NotNil(t, srv.tlsListener) - srv.tlsListener.port = 0 - require.NoError(t, srv.Start()) - addr := srv.tlsListener.listener.Addr().(*net.TCPAddr) - - roots := x509.NewCertPool() - roots.AddCert(listenerPair.cert) - return fmt.Sprintf("https://127.0.0.1:%d/oauth/token", addr.Port), roots, srv + return cfg, listenerPair } // postTokenOverTLS posts form to tokenURL over a fresh TLS handshake. svid, when diff --git a/pkg/authserver/server/audience.go b/pkg/authserver/server/audience.go index 83164c2fd6..a13b969376 100644 --- a/pkg/authserver/server/audience.go +++ b/pkg/authserver/server/audience.go @@ -99,20 +99,52 @@ func ValidateAudienceAllowed(resource string, allowedAudiences []string) error { return errResourceNotPermitted(resource) } -// resourceScopedClient is implemented by clients (e.g. SPIFFE clients) that -// keep an RFC 8707 resource allowlist independent of GetAudience. Resources and -// audiences are independent request dimensions: permission in one must never -// imply permission in the other. A client that does not implement this -// interface falls back to GetAudience, preserving behavior for clients (e.g. -// delegate clients) that only ever had one list. -type resourceScopedClient interface { +// GrantSingleResource grants the one RFC 8707 resource a SPIFFE client asked +// for as the token audience. It refuses the "audience" parameter and any +// request without exactly one resource, and requires the resource to match +// permitted exactly (a sub-path of a permitted resource is refused) and to be +// an allowed audience of the server. Every refusal is ErrInvalidTarget with a +// hint naming the cause. +func GrantSingleResource(requester fosite.AccessRequester, permitted, allowedAudiences []string) error { + form := requester.GetRequestForm() + resources := form["resource"] + switch { + case len(form["audience"]) != 0: + return ErrInvalidTarget.WithHint("The audience parameter is not accepted for this client; use the resource parameter.") + case len(resources) == 0 || (len(resources) == 1 && resources[0] == ""): + return ErrInvalidTarget.WithHint("Exactly one resource parameter is required.") + case len(resources) > 1: + return ErrInvalidTarget.WithHint("Exactly one resource parameter is allowed.") + } + resource := resources[0] + if err := ValidateAudienceURI(resource); err != nil { + return ErrInvalidTarget.WithHint( + "The resource parameter must be an absolute http or https URI with a host and no fragment.") + } + if !slices.Contains(permitted, resource) { + return ErrInvalidTarget.WithHint( + "The requested resource is not permitted for this client; it must exactly match a permitted resource.") + } + if err := ValidateAudienceAllowed(resource, allowedAudiences); err != nil { + return ErrInvalidTarget.WithHint("The requested resource is not an allowed audience of this authorization server.") + } + requester.GrantAudience(resource) + return nil +} + +// ResourceScopedClient is implemented by clients (SPIFFE clients) whose RFC 8707 +// resource allowlist is their only target list; their GetAudience is nil. A +// client that does not implement this interface falls back to GetAudience, +// preserving behavior for clients (e.g. delegate clients) that only ever had +// one list. Token exchange also uses it to select the single-resource rule. +type ResourceScopedClient interface { Resources() []string } // ClientResources returns the resources client may request: its own resource // allowlist if it keeps one, otherwise its audiences. func ClientResources(client fosite.Client) []string { - if rc, ok := client.(resourceScopedClient); ok { + if rc, ok := client.(ResourceScopedClient); ok { return rc.Resources() } return client.GetAudience() @@ -129,10 +161,10 @@ func ClientResources(client fosite.Client) []string { // For a client that keeps no separate resource list, the callback checks the // same audiences this check does, so a request accepted here does not fail the // callback's audience check later, and one refused here fails with -// invalid_target before the user logs in upstream. A client that keeps its own -// resource list (a SPIFFE client) is checked against that list here but against -// GetAudience at the callback; such clients are token-exchange only and never -// reach /authorize, so the two never meet today. +// invalid_target before the user logs in upstream. A SPIFFE client is checked +// against its resource list here but has no audiences at the callback; such +// clients have no response types and never reach /authorize, so the two never +// meet today. // // With fosite's default path-prefix strategy, scheme and host are compared // exactly, and the client's path must equal the resource path or be a @@ -160,7 +192,7 @@ func ValidateClientAudience(resource string, client fosite.Client, match fosite. // no resource allowlist: such a client may request nothing. Clients with a // resource allowlist, such as SPIFFE clients, are checked against it. func ValidateIDJAGClientAudience(resource string, client fosite.Client, match fosite.AudienceMatchingStrategy) error { - if _, scoped := client.(resourceScopedClient); !scoped && registration.DCRIssued(client) { + if _, scoped := client.(ResourceScopedClient); !scoped && registration.DCRIssued(client) { return nil } return ValidateClientAudience(resource, client, match) diff --git a/pkg/authserver/server/audience_test.go b/pkg/authserver/server/audience_test.go index c814c44acf..5810d46bd0 100644 --- a/pkg/authserver/server/audience_test.go +++ b/pkg/authserver/server/audience_test.go @@ -4,6 +4,7 @@ package server import ( + "net/url" "testing" "github.com/ory/fosite" @@ -114,7 +115,7 @@ type resourceClient struct { func (c resourceClient) Resources() []string { return c.resources } -var _ resourceScopedClient = (*registration.AuthenticatedSPIFFEClient)(nil) +var _ ResourceScopedClient = (*registration.AuthenticatedSPIFFEClient)(nil) func TestValidateClientAudience_AuthenticatedSPIFFEClient(t *testing.T) { t.Parallel() @@ -133,6 +134,93 @@ func TestValidateClientAudience_AuthenticatedSPIFFEClient(t *testing.T) { assert.ErrorIs(t, ValidateClientAudience(other, client, fosite.DefaultAudienceMatchingStrategy), ErrInvalidTarget) } +func TestGrantSingleResource(t *testing.T) { + t.Parallel() + + const ( + permitted = "https://resource.example.com" + notPermitted = "https://other.example.com" + notAllowed = "https://not-allowed.example.com" + ) + tests := []struct { + name string + form url.Values + permitted []string + allowed []string + wantGranted []string + wantHint string + }{ + { + name: "one permitted resource is granted", form: url.Values{"resource": {permitted}}, + permitted: []string{permitted}, allowed: []string{permitted}, wantGranted: []string{permitted}, + }, + { + name: "audience parameter is refused", form: url.Values{"audience": {permitted}}, + permitted: []string{permitted}, allowed: []string{permitted}, + wantHint: "audience parameter is not accepted", + }, + { + name: "empty audience parameter is refused", form: url.Values{"resource": {permitted}, "audience": {""}}, + permitted: []string{permitted}, allowed: []string{permitted}, + wantHint: "audience parameter is not accepted", + }, + { + name: "no resource is refused", form: url.Values{}, + permitted: []string{permitted}, allowed: []string{permitted}, + wantHint: "Exactly one resource parameter is required", + }, + { + name: "empty resource is refused", form: url.Values{"resource": {""}}, + permitted: []string{permitted}, allowed: []string{permitted}, + wantHint: "Exactly one resource parameter is required", + }, + { + name: "two resources are refused", form: url.Values{"resource": {permitted, notPermitted}}, + permitted: []string{permitted, notPermitted}, allowed: []string{permitted, notPermitted}, + wantHint: "Exactly one resource parameter is allowed", + }, + { + name: "malformed resource is refused", form: url.Values{"resource": {"relative"}}, + permitted: []string{"relative"}, allowed: []string{"relative"}, + wantHint: "absolute http or https URI", + }, + { + name: "resource outside the permitted list is refused", form: url.Values{"resource": {notPermitted}}, + permitted: []string{permitted}, allowed: []string{permitted, notPermitted}, + wantHint: "must exactly match a permitted resource", + }, + { + name: "sub-path of a permitted resource is refused", form: url.Values{"resource": {permitted + "/v1"}}, + permitted: []string{permitted}, allowed: []string{permitted, permitted + "/v1"}, + wantHint: "must exactly match a permitted resource", + }, + { + name: "permitted resource outside the server allowlist is refused", form: url.Values{"resource": {notAllowed}}, + permitted: []string{notAllowed}, allowed: []string{permitted}, + wantHint: "not an allowed audience", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + req := fosite.NewAccessRequest(nil) + req.Form = tt.form + + err := GrantSingleResource(req, tt.permitted, tt.allowed) + + if tt.wantHint == "" { + require.NoError(t, err) + assert.Equal(t, tt.wantGranted, []string(req.GetGrantedAudience())) + return + } + require.ErrorIs(t, err, ErrInvalidTarget) + assert.Contains(t, fosite.ErrorToRFC6749Error(err).HintField, tt.wantHint) + assert.Empty(t, req.GetGrantedAudience()) + }) + } +} + func TestValidateClientAudience(t *testing.T) { t.Parallel() diff --git a/pkg/authserver/server/handlers/authorize_test.go b/pkg/authserver/server/handlers/authorize_test.go index 93ee9b7c07..3a6fbeab2f 100644 --- a/pkg/authserver/server/handlers/authorize_test.go +++ b/pkg/authserver/server/handlers/authorize_test.go @@ -251,7 +251,7 @@ func TestAuthorizeRoutes_MultipartBackChannelOnlyAndUnknownClientsMatch(t *testi t.Parallel() handler, state, _ := handlerTestSetup(t) - client := spiffetest.Client(t, spiffetest.WithAudiences("https://mcp.example.com")) + client := spiffetest.Client(t) state.clients[client.GetID()] = client configured := httptest.NewRecorder() @@ -303,7 +303,7 @@ func TestAuthorizeHandler_BackChannelOnlyClientsMatchMissingClient(t *testing.T) name: "SPIFFE client", client: func(t *testing.T) fosite.Client { t.Helper() - return spiffetest.Client(t, spiffetest.WithAudiences("https://mcp.example.com")) + return spiffetest.Client(t) }, explicitMarker: true, }, diff --git a/pkg/authserver/server/provider_spiffe_x509_test.go b/pkg/authserver/server/provider_spiffe_x509_test.go index 93f0dd90b2..71046a4592 100644 --- a/pkg/authserver/server/provider_spiffe_x509_test.go +++ b/pkg/authserver/server/provider_spiffe_x509_test.go @@ -168,7 +168,7 @@ func TestStaticSPIFFEClientCannotAuthenticateByDefaultStrategy(t *testing.T) { signingKey, err := rsa.GenerateKey(rand.Reader, 2048) require.NoError(t, err) - spiffeClient := spiffetest.Client(t, spiffetest.WithAudiences("https://mcp.example.com")) + spiffeClient := spiffetest.Client(t) hashed, err := registration.SHA256Hasher.Hash(context.Background(), []byte("control-secret")) require.NoError(t, err) control := &fosite.DefaultClient{ID: "control-client", Secret: hashed} diff --git a/pkg/authserver/server/registration/spiffe_client.go b/pkg/authserver/server/registration/spiffe_client.go index 31279800ef..6ed17ad7a3 100644 --- a/pkg/authserver/server/registration/spiffe_client.go +++ b/pkg/authserver/server/registration/spiffe_client.go @@ -18,31 +18,28 @@ type SPIFFEClient struct { id string grantTypes fosite.Arguments scopes fosite.Arguments - audiences []string resources []string } // NewSPIFFEClient creates an immutable, secretless, non-public client for a -// configured SPIFFE association. grantTypes are the grants the association -// permits. GetAudience returns the configured audience allowlist. resources is -// the independent RFC 8707 resource allowlist, available via Resources(); it -// may be empty. -func NewSPIFFEClient(id string, grantTypes, scopes, audiences, resources []string) (*SPIFFEClient, error) { +// configured SPIFFE association. resources is the RFC 8707 resource allowlist, +// available via Resources(). GetAudience returns nil: SPIFFE clients are +// targeted by resource only. +func NewSPIFFEClient(id string, grantTypes, scopes, resources []string) (*SPIFFEClient, error) { if id == "" { return nil, fmt.Errorf("SPIFFE client ID is required") } if len(grantTypes) == 0 { return nil, fmt.Errorf("SPIFFE client grant types are required") } - if len(scopes) == 0 || len(audiences) == 0 { - return nil, fmt.Errorf("SPIFFE client scopes and audiences are required") + if len(scopes) == 0 { + return nil, fmt.Errorf("SPIFFE client scopes are required") } return &SPIFFEClient{ id: id, grantTypes: slices.Clone(grantTypes), scopes: slices.Clone(scopes), - audiences: slices.Clone(audiences), resources: slices.Clone(resources), }, nil } @@ -66,17 +63,13 @@ func (*SPIFFEClient) GetResponseTypes() fosite.Arguments { return nil } // GetScopes returns a copy of the configured scopes. func (c *SPIFFEClient) GetScopes() fosite.Arguments { return slices.Clone(c.scopes) } -// Audiences returns a copy of the allowed RFC 8693 audience request values. -func (c *SPIFFEClient) Audiences() []string { return slices.Clone(c.audiences) } - // Resources returns a copy of the allowed RFC 8707 resource request values. -// Resources and audiences are independent request dimensions; the token -// exchange handler checks the "resource" request parameter against this, -// not against GetAudience. +// Token exchange checks the "resource" request parameter against this, never +// against GetAudience. func (c *SPIFFEClient) Resources() []string { return slices.Clone(c.resources) } -// GetAudience returns the allowed RFC 8693 audience request values. -func (c *SPIFFEClient) GetAudience() fosite.Arguments { return slices.Clone(c.audiences) } +// GetAudience returns nil: SPIFFE clients carry no audience allowlist. +func (*SPIFFEClient) GetAudience() fosite.Arguments { return nil } // IsPublic returns false so Fosite does not treat unauthenticated requests as // public-client requests. diff --git a/pkg/authserver/server/registration/spiffe_client_test.go b/pkg/authserver/server/registration/spiffe_client_test.go index 6a285bcdb8..feb1fec13d 100644 --- a/pkg/authserver/server/registration/spiffe_client_test.go +++ b/pkg/authserver/server/registration/spiffe_client_test.go @@ -14,21 +14,17 @@ import ( "github.com/stacklok/toolhive/pkg/oauthproto" ) -var tokenExchangeGrants = []string{oauthproto.GrantTypeTokenExchange} - func TestNewSPIFFEClient(t *testing.T) { t.Parallel() scopes := []string{"openid"} - audiences := []string{"https://api.example.com"} resources := []string{"https://resource.example.com"} grants := []string{oauthproto.GrantTypeTokenExchange} - client, err := NewSPIFFEClient("spiffe-client", grants, scopes, audiences, resources) + client, err := NewSPIFFEClient("spiffe-client", grants, scopes, resources) require.NoError(t, err) grants[0] = "changed" scopes[0] = "changed" - audiences[0] = "changed" resources[0] = "changed" assert.Equal(t, "spiffe-client", client.GetID()) @@ -38,83 +34,45 @@ func TestNewSPIFFEClient(t *testing.T) { assert.False(t, client.IsPublic()) assert.Equal(t, []string{oauthproto.GrantTypeTokenExchange}, []string(client.GetGrantTypes())) assert.Equal(t, "openid", client.GetScopes()[0]) - assert.Equal(t, []string{"https://api.example.com"}, client.Audiences()) - assert.Equal(t, []string{"https://api.example.com"}, []string(client.GetAudience())) + assert.Nil(t, client.GetAudience()) assert.Equal(t, []string{"https://resource.example.com"}, client.Resources()) client.GetGrantTypes()[0] = "mutated" client.GetScopes()[0] = "mutated" - client.Audiences()[0] = "mutated" - client.GetAudience()[0] = "mutated" client.Resources()[0] = "mutated" assert.Equal(t, []string{oauthproto.GrantTypeTokenExchange}, []string(client.GetGrantTypes())) assert.Equal(t, "openid", client.GetScopes()[0]) - assert.Equal(t, []string{"https://api.example.com"}, client.Audiences()) - assert.Equal(t, []string{"https://api.example.com"}, []string(client.GetAudience())) assert.Equal(t, []string{"https://resource.example.com"}, client.Resources()) - _, err = NewSPIFFEClient("spiffe-client", tokenExchangeGrants, nil, nil, nil) + _, err = NewSPIFFEClient("disabled-exchange", []string{oauthproto.GrantTypeTokenExchange}, nil, nil) require.Error(t, err) } -// TestNewSPIFFEClient_DisjointAudiencesAndResources proves audiences and -// resources are independently tracked, not aliases of the same underlying -// field: a client configured with disjoint allowlists must return each list -// unmodified by the other, and GetAudience (the RFC 8693 audience allowlist) -// must never leak the RFC 8707 resource allowlist or vice versa. -func TestNewSPIFFEClient_DisjointAudiencesAndResources(t *testing.T) { - t.Parallel() - - client, err := NewSPIFFEClient( - "spiffe-client", - tokenExchangeGrants, - []string{"openid"}, - []string{"https://audience.example.com"}, - []string{"https://resource.example.com"}, - ) - require.NoError(t, err) - - assert.Equal(t, []string{"https://audience.example.com"}, []string(client.GetAudience())) - assert.Equal(t, []string{"https://resource.example.com"}, client.Resources()) - assert.NotContains(t, client.GetAudience(), "https://resource.example.com") - assert.NotContains(t, client.Resources(), "https://audience.example.com") -} - func TestNewSPIFFEClient_Validation(t *testing.T) { t.Parallel() + const tokenExchange = oauthproto.GrantTypeTokenExchange tests := []struct { - name string - id string - grants []string - scopes []string - audiences []string - wantErr string + name string + id string + grants []string + scopes []string + wantErr string }{ + {name: "missing ID", wantErr: "SPIFFE client ID is required"}, { - name: "missing ID", grants: tokenExchangeGrants, - wantErr: "SPIFFE client ID is required", - }, - { - name: "missing grant types", id: "spiffe-client", - scopes: []string{"openid"}, audiences: []string{"https://api.example.com"}, + name: "missing grant types", id: "spiffe-client", scopes: []string{"openid"}, wantErr: "SPIFFE client grant types are required", }, { - name: "missing audiences", id: "spiffe-client", grants: tokenExchangeGrants, - scopes: []string{"openid"}, - wantErr: "SPIFFE client scopes and audiences are required", - }, - { - name: "missing scopes", id: "spiffe-client", grants: tokenExchangeGrants, - audiences: []string{"https://api.example.com"}, - wantErr: "SPIFFE client scopes and audiences are required", + name: "missing scopes", id: "spiffe-client", grants: []string{tokenExchange}, + wantErr: "SPIFFE client scopes are required", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - client, err := NewSPIFFEClient(tt.id, tt.grants, tt.scopes, tt.audiences, nil) + client, err := NewSPIFFEClient(tt.id, tt.grants, tt.scopes, nil) require.EqualError(t, err, tt.wantErr) assert.Nil(t, client) }) @@ -124,8 +82,8 @@ func TestNewSPIFFEClient_Validation(t *testing.T) { func TestNewAuthenticatedSPIFFEClient(t *testing.T) { t.Parallel() - static, err := NewSPIFFEClient("client", tokenExchangeGrants, - []string{"openid"}, []string{"https://api.example.com"}, []string{"https://resource.example.com"}) + static, err := NewSPIFFEClient("client", []string{oauthproto.GrantTypeTokenExchange}, + []string{"openid"}, []string{"https://resource.example.com"}) require.NoError(t, err) id := spiffeid.RequireFromString("spiffe://example.org/workload/concrete") @@ -157,8 +115,8 @@ func TestNewAuthenticatedSPIFFEClient(t *testing.T) { assert.Equal(t, static.GetID(), got.GetID()) assert.Equal(t, static.GetGrantTypes(), got.GetGrantTypes()) assert.Equal(t, static.GetScopes(), got.GetScopes()) - assert.Equal(t, static.GetAudience(), got.GetAudience()) assert.Equal(t, []string{"https://resource.example.com"}, got.Resources()) + assert.Nil(t, got.GetAudience()) assert.False(t, got.IsPublic()) assert.True(t, BackChannelOnly(got)) }) diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index 84dc81c3af..c78867abf7 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -936,9 +936,12 @@ func (h *Handler) grantScopes( return nil } -// grantAndBoundAudiences resolves the delegated token's audience from the -// request (explicit "audience", RFC 8707 "resource", or the configured -// default) and then bounds the result by the subject token. +// grantAndBoundAudiences resolves the delegated token's audience and then +// bounds the result by the subject token. Clients that carry a resource list +// (server.ResourceScopedClient, today the SPIFFE clients) are targeted by one +// RFC 8707 resource from that list, with no "audience" parameter and no default +// audience. All other clients use the explicit +// "audience", RFC 8707 "resource", or the configured default. // // The delegated token must not target a resource the subject token was not // itself valid for: every granted audience must be covered by the subject @@ -950,6 +953,14 @@ func (h *Handler) grantScopes( func (h *Handler) grantAndBoundAudiences( ctx context.Context, requester fosite.AccessRequester, client fosite.Client, validatedClaims *ValidatedClaims, ) error { + if scoped, ok := client.(server.ResourceScopedClient); ok { + if err := server.GrantSingleResource(requester, scoped.Resources(), h.allowedAudiences); err != nil { + slog.Debug("SPIFFE token exchange rejected", + "client_id", client.GetID(), "reason", fosite.ErrorToRFC6749Error(err).HintField) + return errorsx.WithStack(err) + } + return ensureAudienceSubsetOfSubject(requester.GetGrantedAudience(), validatedClaims.Audience) + } if err := h.grantAudiences(ctx, requester, client); err != nil { return err } diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index 1ca8c96451..5a2d3dc0ef 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -3174,41 +3174,138 @@ func TestTokenExchangeHandler_PopulateTokenEndpointResponse(t *testing.T) { }) } -// TestGrantResourceAudience_SPIFFEClientEnforcesResourcesIndependentlyOfAudiences -// is a regression test for a bug where the RFC 8707 "resource" parameter was -// checked against a SPIFFE client's audience allowlist instead of its -// independently configured resource allowlist: a resource the client was -// registered for was rejected, and a resource the client was NOT registered -// for -- but which happened to be one of its audiences -- was granted. -func TestGrantResourceAudience_SPIFFEClientEnforcesResourcesIndependentlyOfAudiences(t *testing.T) { +// TestGrantAndBoundAudiences_SPIFFEClient checks that the handler hands SPIFFE +// clients to server.GrantSingleResource (one refusal row, the full rule is +// covered by server.TestGrantSingleResource) and then bounds the result by the +// subject token's audience. +func TestGrantAndBoundAudiences_SPIFFEClient(t *testing.T) { t.Parallel() + const ( + permitted = testIssuer + notPermitted = "https://other.example.com" + ) + tests := []struct { + name string + form url.Values + subjectAud []string + wantGranted []string + wantErr error + }{ + { + name: "one resource in the association is granted", form: url.Values{"resource": {permitted}}, + subjectAud: []string{permitted}, wantGranted: []string{permitted}, + }, + { + name: "audience parameter is rejected", form: url.Values{"audience": {permitted}}, + subjectAud: []string{permitted}, wantErr: server.ErrInvalidTarget, + }, + { + name: "resource outside the subject token audience is rejected", form: url.Values{"resource": {permitted}}, + subjectAud: []string{notPermitted}, wantErr: server.ErrInvalidTarget, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tj := newTestJWKS(t) + h := newTestHandler(t, tj, time.Hour) + h.allowedAudiences = []string{permitted, notPermitted} + client := spiffetest.AuthenticatedClient(t, spiffetest.WithResources(permitted)) + req := newAccessRequest(t, client, tt.form) + + err := h.grantAndBoundAudiences( + context.Background(), req, client, &ValidatedClaims{Audience: tt.subjectAud}) + if tt.wantErr != nil { + require.Error(t, err) + assert.True(t, errors.Is(err, tt.wantErr), "got %v", err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantGranted, []string(req.GetGrantedAudience())) + }) + } +} + +// TestGrantAndBoundAudiences_DelegateClientKeepsGenericPath proves a +// non-SPIFFE client may still send audience= and still gets the default +// audience when it sends no target. +func TestGrantAndBoundAudiences_DelegateClientKeepsGenericPath(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + requested fosite.Arguments + }{ + {name: "audience parameter is granted", requested: fosite.Arguments{testIssuer}}, + {name: "no target gets the default audience"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tj := newTestJWKS(t) + h := newTestHandler(t, tj, time.Hour) + h.allowedAudiences = []string{testIssuer} + client := &fosite.DefaultClient{ID: "delegate", Audience: []string{testIssuer}} + req := newAccessRequest(t, client, url.Values{}) + req.SetRequestedAudience(tt.requested) + + require.NoError(t, h.grantAndBoundAudiences( + context.Background(), req, client, &ValidatedClaims{Audience: []string{testIssuer}})) + assert.Equal(t, []string{testIssuer}, []string(req.GetGrantedAudience())) + }) + } +} + +// resourceListClient is a plain client that is not a SPIFFE client but carries a +// resource list. +type resourceListClient struct { + *fosite.DefaultClient + resources []string +} + +func (c resourceListClient) Resources() []string { return c.resources } + +// TestGrantAndBoundAudiences_ResourceListClientGetsSingleResourceRule proves the +// single-resource rule is chosen by the Resources capability, not by the SPIFFE +// wrapper type: a sub-path of a listed resource, which the generic path would +// grant, is refused. +func TestGrantAndBoundAudiences_ResourceListClientGetsSingleResourceRule(t *testing.T) { + t.Parallel() + + const subPath = testIssuer + "/v1" tj := newTestJWKS(t) h := newTestHandler(t, tj, time.Hour) - // Both values must be server-wide allowed so the test isolates the - // per-client check (grantResourceAudience) from the server-wide one. - h.allowedAudiences = []string{testIssuer, "https://other.example.com"} - - const registeredResource = testIssuer - const registeredAudience = "https://other.example.com" - client := spiffetest.Client(t, - spiffetest.WithAudiences(registeredAudience), spiffetest.WithResources(registeredResource)) + h.allowedAudiences = []string{testIssuer, subPath} + client := resourceListClient{ + DefaultClient: &fosite.DefaultClient{ID: "scoped"}, + resources: []string{testIssuer}, + } + req := newAccessRequest(t, client, url.Values{"resource": {subPath}}) - t.Run("resource in the client's resources is granted", func(t *testing.T) { - t.Parallel() + err := h.grantAndBoundAudiences( + context.Background(), req, client, &ValidatedClaims{Audience: []string{subPath}}) + require.Error(t, err) + assert.True(t, errors.Is(err, server.ErrInvalidTarget), "got %v", err) +} - req := newAccessRequest(t, client, url.Values{"resource": {registeredResource}}) - require.NoError(t, h.grantResourceAudience(context.Background(), req, client)) - assert.Contains(t, req.GetGrantedAudience(), registeredResource) - }) +// TestGrantAndBoundAudiences_DelegateClientGrantsSubPathResource proves the +// generic path grants a sub-path of a registered audience as a resource, which +// the SPIFFE path rejects (see server.TestGrantSingleResource in +// pkg/authserver/server/audience_test.go). +func TestGrantAndBoundAudiences_DelegateClientGrantsSubPathResource(t *testing.T) { + t.Parallel() - t.Run("resource that is only an audience, not a resource, is rejected", func(t *testing.T) { - t.Parallel() + const subPath = testIssuer + "/v1" + tj := newTestJWKS(t) + h := newTestHandler(t, tj, time.Hour) + h.allowedAudiences = []string{testIssuer, subPath} + client := &fosite.DefaultClient{ID: "delegate", Audience: []string{testIssuer}} + req := newAccessRequest(t, client, url.Values{"resource": {subPath}}) - req := newAccessRequest(t, client, url.Values{"resource": {registeredAudience}}) - err := h.grantResourceAudience(context.Background(), req, client) - require.Error(t, err) - assert.True(t, errors.Is(err, server.ErrInvalidTarget)) - assert.Empty(t, req.GetGrantedAudience()) - }) + require.NoError(t, h.grantAndBoundAudiences( + context.Background(), req, client, &ValidatedClaims{Audience: []string{subPath}})) + assert.Equal(t, []string{subPath}, []string(req.GetGrantedAudience())) } diff --git a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go index a2e871643f..b0f438113d 100644 --- a/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go +++ b/pkg/authserver/server/tokenexchange/jwt_bearer_handler_test.go @@ -527,7 +527,7 @@ func TestAssertionJWTConsumer_ForwardsThroughFullSPIFFEDecoratorChain(t *testing }) require.NoError(t, err) - spiffeClient := spiffetest.Client(t, spiffetest.WithAudiences("https://mcp.example.com")) + spiffeClient := spiffetest.Client(t) chain, err := storage.NewSPIFFEStorageDecorator( ctx, cimdDecorated, map[string]fosite.Client{spiffeClient.GetID(): spiffeClient}) require.NoError(t, err) diff --git a/pkg/authserver/server_test.go b/pkg/authserver/server_test.go index 48a7c840fd..35d25ffdca 100644 --- a/pkg/authserver/server_test.go +++ b/pkg/authserver/server_test.go @@ -727,6 +727,9 @@ func TestServer_TokenEndpoint_CIMDFetchesAreRateLimited(t *testing.T) { func TestNewServer_SPIFFEAndCIMD_WrapStorageInOrder(t *testing.T) { t.Parallel() + spiffeClient := testSPIFFEAssociation("spiffe-client", "openid") + spiffeClient.Audiences = []string{"https://mcp.example.com"} + spiffeClient.Resources = []string{"https://mcp.example.com"} trust, err := NewSPIFFETrustConfig( []SPIFFETrustDomainRunConfig{{ Name: "production", @@ -737,15 +740,7 @@ func TestNewServer_SPIFFEAndCIMD_WrapStorageInOrder(t *testing.T) { WorkloadAPI: &SPIFFEWorkloadAPIBundleSourceRunConfig{}, }, }}, - &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{spiffeClient}}, []string{"openid", "profile"}, []string{"https://mcp.example.com"}, ) diff --git a/pkg/authserver/spiffe_association_registry.go b/pkg/authserver/spiffe_association_registry.go index 0845797775..cf28046150 100644 --- a/pkg/authserver/spiffe_association_registry.go +++ b/pkg/authserver/spiffe_association_registry.go @@ -61,7 +61,7 @@ func NewSPIFFEAssociationRegistry(trust *SPIFFETrustConfig) (*SPIFFEAssociationR policy := association.AuthorizationPolicy() client, err := registration.NewSPIFFEClient( - association.ClientID(), policy.GrantTypes(), policy.Scopes(), policy.Audiences(), policy.Resources(), + association.ClientID(), policy.GrantTypes(), policy.Scopes(), policy.Resources(), ) if err != nil { return nil, fmt.Errorf("SPIFFE client %q: %w", association.ClientID(), err) diff --git a/pkg/authserver/spiffe_association_registry_test.go b/pkg/authserver/spiffe_association_registry_test.go index 82c8deb193..be9a48980c 100644 --- a/pkg/authserver/spiffe_association_registry_test.go +++ b/pkg/authserver/spiffe_association_registry_test.go @@ -25,7 +25,6 @@ func TestSPIFFEAssociationRegistryResolve(t *testing.T) { jwtOnly := testSPIFFEAssociation("jwt-client", "profile") jwtOnly.PrincipalPattern = "spiffe://example.org/ns/jwt/agent" jwtOnly.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - jwtOnly.Audiences = []string{"https://audience.example.com"} jwtOnly.Resources = []string{"https://resource.example.com"} tests := []struct { @@ -134,15 +133,18 @@ func TestSPIFFEAssociationRegistryResolve(t *testing.T) { assert.Equal(t, tt.method, client.AuthenticationMethod()) assert.Equal(t, []string{tt.wantScope}, []string(client.GetScopes())) assert.Equal(t, []string{oauthproto.GrantTypeTokenExchange}, []string(client.GetGrantTypes())) - assert.Equal(t, []string{"https://audience.example.com"}, []string(client.GetAudience())) - assert.Equal(t, tt.wantResource, client.Resources()) + wantResource := tt.wantResource + if wantResource == nil { + wantResource = []string{"https://audience.example.com"} + } + assert.Nil(t, client.GetAudience()) + assert.Equal(t, wantResource, client.Resources()) want := spiffetest.AuthenticatedClient(t, spiffetest.WithID(wantClientID), spiffetest.WithGrantTypes(oauthproto.GrantTypeTokenExchange), spiffetest.WithScopes(tt.wantScope), - spiffetest.WithAudiences("https://audience.example.com"), - spiffetest.WithResources(tt.wantResource...), + spiffetest.WithResources(wantResource...), spiffetest.WithSPIFFEID(tt.spiffeID), spiffetest.WithAuthMethod(tt.method), ) @@ -160,8 +162,7 @@ func TestNewSPIFFEAssociationRegistry_RejectsAssociationWithoutValidPolicy(t *te clientID: "no-grants", methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, authorization: SPIFFEAuthorizationPolicy{ - scopes: []string{"openid"}, - audiences: []string{"https://audience.example.com"}, + scopes: []string{"openid"}, }, }}} @@ -217,28 +218,11 @@ func TestSPIFFEAssociationRegistryRebuildsChangedAndRemovedAuthority(t *testing. assert.Empty(t, removedClients) } -func TestSPIFFEAssociationRegistryKeepsClientAudiencesIsolated(t *testing.T) { - t.Parallel() - - first := testSPIFFEAssociation("first-client", "openid") - first.Audiences = []string{"https://first-audience.example.com"} - second := testSPIFFEAssociation("second-client", "profile") - second.PrincipalPattern = "spiffe://example.org/ns/default/other-agent" - second.Audiences = []string{"https://second-audience.example.com"} - - registry := newTestSPIFFEAssociationRegistry(t, []SPIFFEClientAuthRunConfig{first, second}) - clients := registry.staticClients() - - assert.Equal(t, []string{"https://first-audience.example.com"}, []string(clients["first-client"].GetAudience())) - assert.Equal(t, []string{"https://second-audience.example.com"}, []string(clients["second-client"].GetAudience())) -} - -// TestSPIFFEAssociationRegistryKeepsResourcesIndependentOfAudiences proves the +// TestSPIFFEAssociationRegistryIgnoresDeprecatedAudiences proves the // association registry wires an association's RFC 8707 resources through to -// the runtime client as a dimension independent of RFC 8693 audiences: a -// client configured with disjoint audiences and resources must expose each -// list separately, not have one silently discarded or aliased to the other. -func TestSPIFFEAssociationRegistryKeepsResourcesIndependentOfAudiences(t *testing.T) { +// the runtime client and drops the deprecated audiences field: the client has +// no audiences even when the association sets some. +func TestSPIFFEAssociationRegistryIgnoresDeprecatedAudiences(t *testing.T) { t.Parallel() association := testSPIFFEAssociation("client", "openid") @@ -254,7 +238,7 @@ func TestSPIFFEAssociationRegistryKeepsResourcesIndependentOfAudiences(t *testin resourceScoped, ok := client.(interface{ Resources() []string }) require.True(t, ok, "SPIFFE client must expose a Resources() accessor") - assert.Equal(t, []string{"https://audience.example.com"}, []string(client.GetAudience())) + assert.Empty(t, client.GetAudience()) assert.Equal(t, []string{"https://resource.example.com"}, resourceScoped.Resources()) } @@ -421,9 +405,7 @@ func testNormalizedSPIFFEAssociation(clientID, principal string) SPIFFEClientAut clientID: clientID, methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, authorization: SPIFFEAuthorizationPolicy{ - grantTypes: []string{SPIFFEGrantTypeTokenExchange}, - scopes: []string{"openid"}, - audiences: []string{"https://audience.example.com"}, + grantTypes: []string{SPIFFEGrantTypeTokenExchange}, scopes: []string{"openid"}, }, } } @@ -447,6 +429,8 @@ func newTestSPIFFEAssociationRegistry(t *testing.T, associations []SPIFFEClientA return registry } +// testSPIFFEAssociation returns a valid token-exchange association; callers +// override only the fields their case cares about. func testSPIFFEAssociation(clientID, scope string) SPIFFEClientAuthRunConfig { return SPIFFEClientAuthRunConfig{ TrustDomainRef: "production", @@ -454,7 +438,7 @@ func testSPIFFEAssociation(clientID, scope string) SPIFFEClientAuthRunConfig { ClientID: clientID, Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, Scopes: []string{scope}, - Audiences: []string{"https://audience.example.com"}, + Resources: []string{"https://audience.example.com"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, } } diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index c9b3764970..2dbbe62eb4 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -5,6 +5,7 @@ package authserver import ( "fmt" + "log/slog" "net" "net/url" "path/filepath" @@ -147,18 +148,18 @@ type SPIFFEClientAuthRunConfig struct { Methods []SPIFFEAuthenticationMethod `json:"methods" yaml:"methods"` // Resources are RFC 8707 resource indicators this association may - // request. Must be a subset of the server's allowed_audiences allowlist - // (RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list - // DelegateClientRunConfig.Audiences is validated against. Distinct from - // Audiences: a resource permission does not imply the same value is also - // a permitted token audience, or vice versa. + // request. At least one is required for every association: token + // exchange takes exactly one resource per request and grants it as the + // token audience. Must be a subset of the + // server's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the + // same RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is + // validated against. Resources []string `json:"resources,omitempty" yaml:"resources,omitempty"` - // Audiences are RFC 8693 token audiences this association may request. - // This is an independent request dimension from Resources: it is not - // bounded by allowed_audiences (which is an RFC 8707 resource-URI list) - // and may contain non-URI logical audience identifiers. - Audiences []string `json:"audiences" yaml:"audiences"` + // Audiences is deprecated and ignored; use Resources. It stays in the + // schema because v0.65.0 required it, and a warning is logged at startup + // when it is set. + Audiences []string `json:"audiences,omitempty" yaml:"audiences,omitempty"` // Scopes are OAuth scopes granted to this association. They must be a // subset of the server's effective supported scopes. @@ -175,7 +176,6 @@ type SPIFFEAuthorizationPolicy struct { grantTypes []string scopes []string resources []string - audiences []string } // GrantTypes returns a copy of the permitted OAuth grant types. @@ -187,9 +187,6 @@ func (p SPIFFEAuthorizationPolicy) Scopes() []string { return slices.Clone(p.sco // Resources returns a copy of the permitted RFC 8707 resource indicators. func (p SPIFFEAuthorizationPolicy) Resources() []string { return slices.Clone(p.resources) } -// Audiences returns a copy of the permitted RFC 8693 token audiences. -func (p SPIFFEAuthorizationPolicy) Audiences() []string { return slices.Clone(p.audiences) } - // matchSPIFFEPrincipalPattern reports whether principal matches pattern. A // terminal /* matches descendants only at a path-segment boundary: /agent/* // matches /agent/one but not /agent or /agent-two. @@ -225,6 +222,7 @@ func NewSPIFFETrustConfig( return nil, err } associations := inboundAssociations(inboundGrants) + warnDeprecatedSPIFFEAudiences(associations) config := &SPIFFETrustConfig{ associations: make([]SPIFFEClientAuthConfig, 0, len(associations)), trustDomains: make(map[string]SPIFFETrustDomain, len(trustDomainByName)), @@ -251,7 +249,6 @@ func NewSPIFFETrustConfig( grantTypes: slices.Clone(association.GrantTypes), scopes: slices.Clone(association.Scopes), resources: slices.Clone(association.Resources), - audiences: slices.Clone(association.Audiences), }, }) } @@ -409,19 +406,13 @@ func (c SPIFFEClientAuthConfig) Methods() []SPIFFEAuthenticationMethod { return slices.Clone(c.methods) } -// AuthorizationPolicy returns a defensive copy of the association policy. +// AuthorizationPolicy returns the association policy. Its getters return copies. func (c SPIFFEClientAuthConfig) AuthorizationPolicy() SPIFFEAuthorizationPolicy { - return SPIFFEAuthorizationPolicy{ - grantTypes: slices.Clone(c.authorization.grantTypes), - scopes: slices.Clone(c.authorization.scopes), - resources: slices.Clone(c.authorization.resources), - audiences: slices.Clone(c.authorization.audiences), - } + return c.authorization } func (c SPIFFEClientAuthConfig) clone() SPIFFEClientAuthConfig { c.methods = slices.Clone(c.methods) - c.authorization = c.AuthorizationPolicy() return c } @@ -690,10 +681,9 @@ func validateSPIFFEClientAssociation( } // validateSPIFFEClientAssociationPermissions validates the resources, -// audiences, scopes, and grant types an association is permitted to request. -// Resources (RFC 8707) and audiences (RFC 8693) are independent request -// dimensions: permission in one must never imply permission in the other, so -// only resources are bounded by the server's allowed_audiences allowlist. +// scopes, and grant types an association is permitted to request. Resources +// (RFC 8707) are the only target list and are bounded by the server's +// allowed_audiences allowlist. The deprecated audiences field is not checked. func validateSPIFFEClientAssociationPermissions( entry SPIFFEClientAuthRunConfig, index int, @@ -704,9 +694,6 @@ func validateSPIFFEClientAssociationPermissions( if err := validateSPIFFEResources(entry.Resources, fieldPrefix+".resources", allowedResources); err != nil { return err } - if err := validateDistinctNonEmpty(entry.Audiences, fieldPrefix+".audiences"); err != nil { - return err - } if err := validateDistinctNonEmpty(entry.Scopes, fieldPrefix+".scopes"); err != nil { return err } @@ -800,13 +787,15 @@ func validateMethods(methods []SPIFFEAuthenticationMethod, field string) (map[SP } // validateSPIFFEResources validates the RFC 8707 resource indicators an -// association may request: each must be a syntactically valid absolute -// HTTP(S) URI and a member of the server's allowed_audiences allowlist, the -// same RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is -// validated against (see validateDelegateClients in config.go). +// association may request. At least one is required: token exchange takes +// exactly one resource per request. Each must be a syntactically valid +// absolute HTTP(S) URI +// and a member of the server's allowed_audiences allowlist, the same RFC 8707 +// resource-URI list DelegateClientRunConfig.Audiences is validated against +// (see validateDelegateClients in config.go). func validateSPIFFEResources(values []string, field string, allowedResources []string) error { if len(values) == 0 { - return nil + return fmt.Errorf("%s is required", field) } if err := ValidateResourceIndicators(values, field); err != nil { return err @@ -869,6 +858,18 @@ func validateSPIFFEGrants(grants []string, index int) error { return nil } +// warnDeprecatedSPIFFEAudiences logs one warning per association that still +// sets the ignored audiences field. +func warnDeprecatedSPIFFEAudiences(associations []SPIFFEClientAuthRunConfig) { + for _, association := range associations { + if len(association.Audiences) == 0 { + continue + } + slog.Warn("SPIFFE association sets audiences, which is deprecated and ignored; use resources instead", + "client_id", association.ClientID, "trust_domain_ref", association.TrustDomainRef) + } +} + func overlapsSPIFFEPatterns(patterns []string, principal string) bool { for _, pattern := range patterns { if spiffePatternsOverlap(pattern, principal) { diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index 471f1d6729..1716aafdb4 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -4,6 +4,9 @@ package authserver import ( + "bytes" + "log/slog" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -91,18 +94,20 @@ func TestValidateSPIFFETrust(t *testing.T) { Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509, SPIFFEAuthenticationMethodJWT}, BundleSource: validWorkloadAPIBundleSource(), }} - grants := &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", - PrincipalPattern: "spiffe://example.org/ns/default/*", - ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Audiences: []string{"https://mcp.example.org/resource"}, - Scopes: []string{"openid"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}} + grants := &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{ + testSPIFFEWildcardAssociation("https://mcp.example.org/resource"), + }} return domains, grants } + jwtAssociation := func(clientID, principal string) SPIFFEClientAuthRunConfig { + association := testSPIFFEAssociation(clientID, "openid") + association.PrincipalPattern = principal + association.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + association.Resources = []string{"https://mcp.example.org/resource"} + return association + } + tests := []struct { name string mutate func([]SPIFFETrustDomainRunConfig, *InboundGrantsRunConfig) @@ -121,32 +126,20 @@ func TestValidateSPIFFETrust(t *testing.T) { {name: "wrong trust domain", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { grants.SPIFFEClientAuth[0].PrincipalPattern = "spiffe://other.org/ns/default/agent" }, wantErr: "does not match"}, + {name: "empty resources rejected", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + grants.SPIFFEClientAuth[0].Resources = nil + }, wantErr: "spiffe_client_auth[0].resources is required"}, {name: "duplicate client", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { - grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, SPIFFEClientAuthRunConfig{ - TrustDomainRef: "production", PrincipalPattern: "spiffe://example.org/ns/other/agent", ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, Audiences: []string{"https://mcp.example.org/other"}, - Scopes: []string{"openid"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }) + grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, jwtAssociation("agent-client", "spiffe://example.org/ns/other/agent")) }, wantErr: "duplicate client_id"}, {name: "exact parent does not overlap descendant wildcard", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { grants.SPIFFEClientAuth[0].PrincipalPattern = "spiffe://example.org/ns/default" - grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, SPIFFEClientAuthRunConfig{ - TrustDomainRef: "production", PrincipalPattern: "spiffe://example.org/ns/default/*", ClientID: "other-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, Audiences: []string{"https://mcp.example.org/other"}, - Scopes: []string{"openid"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }) + grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, jwtAssociation("other-client", "spiffe://example.org/ns/default/*")) }}, {name: "nested wildcards overlap", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { - grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, SPIFFEClientAuthRunConfig{ - TrustDomainRef: "production", PrincipalPattern: "spiffe://example.org/ns/default/sa/*", ClientID: "other-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, Audiences: []string{"https://mcp.example.org/other"}, - Scopes: []string{"openid"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }) + grants.SPIFFEClientAuth = append(grants.SPIFFEClientAuth, jwtAssociation("other-client", "spiffe://example.org/ns/default/sa/*")) }, wantErr: "overlaps"}, - {name: "audiences are required", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { - grants.SPIFFEClientAuth[0].Audiences = nil - }, wantErr: "audiences is required"}, - {name: "audiences need not be in the resource allowlist", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + {name: "deprecated audiences are accepted and not checked against the resource allowlist", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { grants.SPIFFEClientAuth[0].Audiences = []string{"urn:example:logical-audience"} }}, {name: "resource indicator must be an absolute HTTP(S) URI", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { @@ -258,40 +251,40 @@ func TestValidateSPIFFETrustRejectsDuplicateCanonicalTrustDomains(t *testing.T) assert.Contains(t, err.Error(), "duplicate trust domain \"example.org\" already declared as \"production\"") } -func TestNewSPIFFETrustConfigDefensivelyCopiesAudiences(t *testing.T) { +func TestNewSPIFFETrustConfigDefensivelyCopiesResources(t *testing.T) { t.Parallel() - audiences := []string{"https://mcp.example.org/resource"} resources := []string{"https://mcp.example.org/api"} + association := testSPIFFEAssociation("agent-client", "openid") + association.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + association.Resources = resources trust, err := NewSPIFFETrustConfig( []SPIFFETrustDomainRunConfig{{ Name: "production", TrustDomain: "example.org", Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, BundleSource: validWorkloadAPIBundleSource(), }}, - &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", PrincipalPattern: "spiffe://example.org/ns/default/agent", ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, Audiences: audiences, Resources: resources, - Scopes: []string{"openid"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{association}}, []string{"openid"}, []string{"https://mcp.example.org/resource", "https://mcp.example.org/api"}, ) require.NoError(t, err) require.NotNil(t, trust) - audiences[0] = "https://mutated.example.org" resources[0] = "https://mutated.example.org" policy := trust.Associations()[0].AuthorizationPolicy() - assert.Equal(t, []string{"https://mcp.example.org/resource"}, policy.Audiences()) assert.Equal(t, []string{"https://mcp.example.org/api"}, policy.Resources()) - policyAudiences := policy.Audiences() - policyAudiences[0] = "https://mutated.example.org" - assert.Equal(t, []string{"https://mcp.example.org/resource"}, trust.Associations()[0].AuthorizationPolicy().Audiences()) + policyResources := policy.Resources() + policyResources[0] = "https://mutated.example.org" + assert.Equal(t, []string{"https://mcp.example.org/api"}, trust.Associations()[0].AuthorizationPolicy().Resources()) } func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { t.Parallel() + association := testSPIFFEAssociation("agent-client", "openid") + association.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + association.Resources = []string{"https://mcp.example.org/resource"} + trust, err := NewSPIFFETrustConfig( []SPIFFETrustDomainRunConfig{{ Name: "production", TrustDomain: "example.org", @@ -303,11 +296,7 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { }, }, }}, - &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "production", PrincipalPattern: "spiffe://example.org/ns/default/agent", ClientID: "agent-client", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, Audiences: []string{"https://mcp.example.org/resource"}, - Scopes: []string{"openid"}, GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{association}}, []string{"openid"}, []string{"https://mcp.example.org/resource"}, ) require.NoError(t, err) @@ -328,3 +317,32 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { _, ok = nilTrust.TrustDomain("production") assert.False(t, ok) } + +//nolint:paralleltest // Swaps the process-wide default logger. +func TestNewSPIFFETrustConfigWarnsOnDeprecatedAudiences(t *testing.T) { + var logs bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(previous) }) + + withAudiences := testSPIFFEAssociation("with-audiences", "openid") + withAudiences.Audiences = []string{"urn:example:legacy"} + withAudiences.Resources = []string{"https://mcp.example.org/resource"} + without := testSPIFFEAssociation("without-audiences", "openid") + without.PrincipalPattern = "spiffe://example.org/ns/default/other" + without.Resources = []string{"https://mcp.example.org/resource"} + + _, err := NewSPIFFETrustConfig( + []SPIFFETrustDomainRunConfig{{ + Name: "production", TrustDomain: "example.org", Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + BundleSource: validWorkloadAPIBundleSource(), + }}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{withAudiences, without}}, + []string{"openid"}, []string{"https://mcp.example.org/resource"}, + ) + require.NoError(t, err) + + assert.Equal(t, 1, strings.Count(logs.String(), "client_id=with-audiences")) + assert.Contains(t, logs.String(), "use resources instead") + assert.NotContains(t, logs.String(), "client_id=without-audiences") +} diff --git a/pkg/authserver/storage/spiffe_decorator.go b/pkg/authserver/storage/spiffe_decorator.go index d53ad5efe4..f4189609d1 100644 --- a/pkg/authserver/storage/spiffe_decorator.go +++ b/pkg/authserver/storage/spiffe_decorator.go @@ -86,10 +86,10 @@ func preflightDurableCollisions(ctx context.Context, base Storage, clients map[s // resourceScopedClient is implemented by fosite.Client types (e.g. // registration.SPIFFEClient) that maintain an RFC 8707 resource allowlist -// independent of GetAudience's audience allowlist. This mirrors the -// identically-shaped interface in pkg/authserver/server/tokenexchange -- both -// packages match it structurally against the same concrete client types -// without either importing the other's unexported interface. +// independent of GetAudience's audience allowlist. It mirrors +// server.ResourceScopedClient. This package keeps its own copy so storage does +// not depend on the server package; both match the same concrete client types +// structurally. type resourceScopedClient interface { Resources() []string } @@ -161,15 +161,15 @@ func isReservedPlaceholder(client fosite.Client) bool { // server registers, and it carries no secret. This guarantee holds on every // backend, including a bare read-back from Redis by a replica with no SPIFFE // overlay — see inertPlaceholderClient and storedClient.Reserved. It keeps -// the real client's Scopes, Audience, (RFC 8707) Resources, and SPIFFE -// association identity fingerprint so ReconcileConfiguredClient can tell +// the real client's Scopes, Audience (nil for SPIFFE clients), (RFC 8707) Resources, +// and SPIFFE association identity fingerprint so ReconcileConfiguredClient can tell // "same association, restarted" (silent) from "changed association" // (replaced, with a WARN). // Scopes and Audience are taken directly from actual.GetScopes() / // GetAudience() without an extra defensive clone here: the only production // caller (registration.SPIFFEClient) already returns a fresh slice.Clone -// from both getters (see its doc comments), so there is no live backing -// array to alias. The same applies to Resources() when actual implements +// of its scopes and nil audience (see its doc comments), so there is no live +// backing array to alias. The same applies to Resources() when actual implements // resourceScopedClient; a client that doesn't (falls back to nil). func staticClientPlaceholder(actual fosite.Client) fosite.Client { var resources []string diff --git a/pkg/authserver/storage/types.go b/pkg/authserver/storage/types.go index 49a90d4ea6..7eb1dc1aa6 100644 --- a/pkg/authserver/storage/types.go +++ b/pkg/authserver/storage/types.go @@ -1025,8 +1025,8 @@ type clientFingerprint struct { // fosite.OpenIDConnectClient, including unpinned secret clients and // reserved placeholders. tokenEndpointAuthMethod string - // resources is the RFC 8707 resource allowlist, distinct from audience - // (see resourceScopedClient in spiffe_decorator.go). Only reserved rows + // resources is the RFC 8707 resource allowlist, the only target list a + // SPIFFE client has (see resourceScopedClient in spiffe_decorator.go). Only reserved rows // carry it: buildStoredClient persists it for them alone. resources []string // identityFingerprint is the SPIFFE association hash. Like resources, it diff --git a/pkg/runner/config_test.go b/pkg/runner/config_test.go index 34fc8312cd..35767a5689 100644 --- a/pkg/runner/config_test.go +++ b/pkg/runner/config_test.go @@ -2348,6 +2348,7 @@ func TestRunConfig_WriteJSON_ReadJSON_EmbeddedAuthServer(t *testing.T) { Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, Scopes: []string{"openid"}, Audiences: []string{"https://mcp.example.com"}, + Resources: []string{"https://mcp.example.com"}, GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, }, { @@ -2357,6 +2358,7 @@ func TestRunConfig_WriteJSON_ReadJSON_EmbeddedAuthServer(t *testing.T) { Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodJWT}, Scopes: []string{"profile"}, Audiences: []string{"https://api.example.com"}, + Resources: []string{"https://api.example.com"}, GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, }, }, diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index afc3fbd419..b9cd162916 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -2381,10 +2381,9 @@ func (s *AuthenticationSPIFFEBundleSourceRunConfig) SetWorkloadAPI(val *Authenti // Ref: #/components/schemas/AuthenticationSPIFFEClientAuthRunConfig type AuthenticationSPIFFEClientAuthRunConfig struct { - // Audiences are RFC 8693 token audiences this association may request. - // This is an independent request dimension from Resources: it is not - // bounded by allowed_audiences (which is an RFC 8707 resource-URI list) - // and may contain non-URI logical audience identifiers. + // Audiences is deprecated and ignored; use Resources. It stays in the + // schema because v0.65.0 required it, and a warning is logged at startup + // when it is set. Audiences []string `json:"audiences"` // ClientID is the explicit OAuth client_id. It is never derived from a // SPIFFE ID. @@ -2397,11 +2396,12 @@ type AuthenticationSPIFFEClientAuthRunConfig struct { // the declared trust domain. PrincipalPattern OptString `json:"principal_pattern"` // Resources are RFC 8707 resource indicators this association may - // request. Must be a subset of the server's allowed_audiences allowlist - // (RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list - // DelegateClientRunConfig.Audiences is validated against. Distinct from - // Audiences: a resource permission does not imply the same value is also - // a permitted token audience, or vice versa. + // request. At least one is required for every association: token + // exchange takes exactly one resource per request and grants it as the + // token audience. Must be a subset of the + // server's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the + // same RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is + // validated against. Resources []string `json:"resources"` // Scopes are OAuth scopes granted to this association. They must be a // subset of the server's effective supported scopes. diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 44b17e7e65..12bb66b13c 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -829,7 +829,7 @@ "AuthenticationSPIFFEClientAuthRunConfig": { "properties": { "audiences": { - "description": "Audiences are RFC 8693 token audiences this association may request.\nThis is an independent request dimension from Resources: it is not\nbounded by allowed_audiences (which is an RFC 8707 resource-URI list)\nand may contain non-URI logical audience identifiers.", + "description": "Audiences is deprecated and ignored; use Resources. It stays in the\nschema because v0.65.0 required it, and a warning is logged at startup\nwhen it is set.", "items": { "type": "string" }, @@ -860,7 +860,7 @@ "type": "string" }, "resources": { - "description": "Resources are RFC 8707 resource indicators this association may\nrequest. Must be a subset of the server's allowed_audiences allowlist\n(RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list\nDelegateClientRunConfig.Audiences is validated against. Distinct from\nAudiences: a resource permission does not imply the same value is also\na permitted token audience, or vice versa.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: token\nexchange takes exactly one resource per request and grants it as the\ntoken audience. Must be a subset of the\nserver's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the\nsame RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is\nvalidated against.", "items": { "type": "string" }, diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 2d983086fb..e07425b222 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -1131,10 +1131,9 @@ components: properties: audiences: description: |- - Audiences are RFC 8693 token audiences this association may request. - This is an independent request dimension from Resources: it is not - bounded by allowed_audiences (which is an RFC 8707 resource-URI list) - and may contain non-URI logical audience identifiers. + Audiences is deprecated and ignored; use Resources. It stays in the + schema because v0.65.0 required it, and a warning is logged at startup + when it is set. items: type: string type: array @@ -1165,11 +1164,12 @@ components: resources: description: |- Resources are RFC 8707 resource indicators this association may - request. Must be a subset of the server's allowed_audiences allowlist - (RunConfig.AllowedAudiences) — the same RFC 8707 resource-URI list - DelegateClientRunConfig.Audiences is validated against. Distinct from - Audiences: a resource permission does not imply the same value is also - a permitted token audience, or vice versa. + request. At least one is required for every association: token + exchange takes exactly one resource per request and grants it as the + token audience. Must be a subset of the + server's allowed_audiences allowlist (RunConfig.AllowedAudiences) — the + same RFC 8707 resource-URI list DelegateClientRunConfig.Audiences is + validated against. items: type: string type: array