diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index eb848a8388..a2e5ca9d6a 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -742,10 +742,8 @@ type SPIFFETrustDomainConfig struct { // Trust material comes from the declared bundle source (see // SPIFFETrustDomainConfig's doc comment). // -// GrantTypes is deliberately not exposed here: the runtime only accepts -// exactly the RFC 8693 token-exchange grant for a SPIFFE client -// (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter -// always supplies it instead of letting it be configured. +// The CRD does not expose grantTypes. The converter always supplies the +// RFC 8693 token-exchange grant 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" @@ -1423,7 +1421,7 @@ func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error { if err := tokenexchange.ValidateTrustedIssuers(grants.trustedIssuers, c.Issuer, nil); err != nil { return fmt.Errorf("trustedIssuers: %w", err) } - if c.hasSPIFFEX509ClientAuth() { + if c.hasSPIFFEMethod(SPIFFEAuthenticationMethodX509) { if _, err := authserver.ValidateSPIFFEX509Issuer(c.Issuer); err != nil { return err } @@ -1471,22 +1469,20 @@ func (c *EmbeddedAuthServerConfig) ValidateTLSListener() error { } return nil } - if c.hasSPIFFEX509ClientAuth() { + if c.hasSPIFFEMethod(SPIFFEAuthenticationMethodX509) { return fmt.Errorf("tlsListener is required when SPIFFE X.509 client authentication is configured") } return nil } -func (c *EmbeddedAuthServerConfig) hasSPIFFEX509ClientAuth() bool { +// hasSPIFFEMethod reports whether any SPIFFE client association allows method. +func (c *EmbeddedAuthServerConfig) hasSPIFFEMethod(method SPIFFEAuthenticationMethod) bool { if c.InboundGrants == nil { return false } - for _, association := range c.InboundGrants.SPIFFEClientAuth { - if slices.Contains(association.Methods, SPIFFEAuthenticationMethodX509) { - return true - } - } - return false + return slices.ContainsFunc(c.InboundGrants.SPIFFEClientAuth, func(a SPIFFEClientConfig) bool { + return slices.Contains(a.Methods, method) + }) } func hasLegacyTokenExchangePolicy(issuer TrustedIssuerConfig) bool { diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index 08ee60b345..90d5dae947 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -746,7 +746,7 @@ func TestMCPExternalAuthConfig_validateEmbeddedAuthServer(t *testing.T) { }, }, expectErr: true, - errMsg: "confidential clients (allow_confidential_client_registration or delegate clients) cannot be combined with insecure_allow_http", + errMsg: "confidential clients (allow_confidential_client_registration, delegate clients or JWT-SVID SPIFFE associations that grant client_credentials) cannot be combined with insecure_allow_http", }, { name: "confidential clients with plain-HTTP loopback issuer without opt-in - invalid", @@ -2099,11 +2099,50 @@ func TestEmbeddedAuthServerConfig_ValidateInboundGrants_ConfidentialClientTransp Scopes: []string{"openid"}, Audiences: []string{"https://api.example.com"}, }} + spiffeConfig := func(method SPIFFEAuthenticationMethod, mutate func(*EmbeddedAuthServerConfig)) EmbeddedAuthServerConfig { + config := EmbeddedAuthServerConfig{ + Issuer: "http://localhost:8080", + SPIFFETrustDomains: []SPIFFETrustDomainConfig{{ + Name: "example", TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{method}, + BundleSource: SPIFFEBundleSourceConfig{ + Type: SPIFFEBundleSourceTypeFile, + File: &SPIFFEFileBundleSourceConfig{ConfigMapName: "spire-bundle", ConfigMapKey: "bundle.json"}, + }, + }}, + InboundGrants: &InboundGrantsConfig{ + SPIFFEClientAuth: []SPIFFEClientConfig{{ + TrustDomainRef: "example", PrincipalPattern: "spiffe://example.org/ns/default/agent", + ClientID: "spiffe-client", Methods: []SPIFFEAuthenticationMethod{method}, + Resources: []string{"https://mcp.example.com"}, Scopes: []string{"openid"}, + }}, + }, + } + mutate(&config) + return config + } tests := []struct { name string config EmbeddedAuthServerConfig expectErr bool }{ + { + name: "SPIFFE JWT association is admitted with insecure HTTP", + config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(c *EmbeddedAuthServerConfig) { + c.InsecureAllowHTTP = true + }), + }, + { + name: "SPIFFE JWT association is admitted on HTTP loopback without explicit opt in", + config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(*EmbeddedAuthServerConfig) {}), + }, + { + name: "SPIFFE X.509-only association is unaffected by insecure HTTP", + config: spiffeConfig(SPIFFEAuthenticationMethodX509, func(c *EmbeddedAuthServerConfig) { + c.InsecureAllowHTTP = true + c.Issuer = "https://auth.example.com" + }), + }, { name: "delegate clients remain independent of confidential DCR", config: EmbeddedAuthServerConfig{ diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index 01452edb90..1f048fcac6 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -23,6 +23,7 @@ import ( authrunner "github.com/stacklok/toolhive/pkg/authserver/runner" "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" "github.com/stacklok/toolhive/pkg/runner" ) @@ -387,10 +388,9 @@ func buildSPIFFEBundleSourceRunConfig( } // buildSPIFFEClientAuthRunConfigs converts CRD SPIFFEClientConfig entries to -// authserver.SPIFFEClientAuthRunConfig. GrantTypes is not a CRD field: the -// runtime only accepts exactly the RFC 8693 token-exchange grant for a -// SPIFFE client (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so -// it is always supplied here rather than configured. +// authserver.SPIFFEClientAuthRunConfig. The CRD does not expose grantTypes, +// so the RFC 8693 token-exchange grant is always supplied here rather than +// configured. func buildSPIFFEClientAuthRunConfigs( clients []mcpv1beta1.SPIFFEClientConfig, ) []authserver.SPIFFEClientAuthRunConfig { @@ -410,7 +410,7 @@ func buildSPIFFEClientAuthRunConfigs( Resources: append([]string(nil), spiffeClient.Resources...), Audiences: deprecatedAudiences, Scopes: append([]string(nil), spiffeClient.Scopes...), - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, } } return configs diff --git a/cmd/thv-operator/pkg/controllerutil/authserver_test.go b/cmd/thv-operator/pkg/controllerutil/authserver_test.go index 4988c3ad83..6c30680b73 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver_test.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver_test.go @@ -28,6 +28,7 @@ import ( authrunner "github.com/stacklok/toolhive/pkg/authserver/runner" "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" "github.com/stacklok/toolhive/pkg/runner" ) @@ -3718,7 +3719,7 @@ func TestBuildSPIFFEClientAuthRunConfigs(t *testing.T) { assert.Equal(t, []string{"openid"}, configs[0].Scopes) // GrantTypes is not a CRD field; the converter always supplies exactly // the RFC 8693 token-exchange grant. - assert.Equal(t, []string{authserver.SPIFFEGrantTypeTokenExchange}, configs[0].GrantTypes) + assert.Equal(t, []string{oauthproto.GrantTypeTokenExchange}, configs[0].GrantTypes) // The runtime type must not retain the CRD object's backing slices. audiences[0] = "https://mutated.example.com" 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 c1335566ed..74a85366d5 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 @@ -239,6 +239,31 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() { config.InboundGrants.SPIFFEClientAuth[0].Resources = nil }, }, + { + name: "JWT-SVID association with insecureAllowHTTP is admitted", trustDomains: true, clients: true, + principal: "spiffe://example.org/ns/default/agent", shouldAdmit: true, + mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) { + config.InsecureAllowHTTP = true + config.SPIFFETrustDomains[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} + config.InboundGrants.SPIFFEClientAuth[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} + }, + }, + { + name: "JWT-SVID association with an http loopback issuer is admitted without the loopback opt-in", trustDomains: true, clients: true, + principal: "spiffe://example.org/ns/default/agent", shouldAdmit: true, + mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) { + config.Issuer = "http://localhost:8080" + config.SPIFFETrustDomains[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} + config.InboundGrants.SPIFFEClientAuth[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} + }, + }, + { + name: "X.509-only association with insecureAllowHTTP is unaffected", trustDomains: true, clients: true, + principal: "spiffe://example.org/ns/default/agent", shouldAdmit: true, + mutate: func(config *mcpv1beta1.EmbeddedAuthServerConfig) { + config.InsecureAllowHTTP = true + }, + }, { name: "empty-string deprecated audience is still rejected", trustDomains: true, clients: true, principal: "spiffe://example.org/ns/default/agent", errMatch: "audiences", 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 65dfdad836..4c51906c88 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 @@ -556,10 +556,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- @@ -3701,10 +3699,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- 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 1005803ba2..08c8b7a2d6 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 @@ -443,10 +443,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- @@ -5980,10 +5978,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- 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 3d7e415e98..ce562a6706 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -559,10 +559,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- @@ -3704,10 +3702,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- 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 25f01bfe83..3f0f8bc53f 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -446,10 +446,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- @@ -5983,10 +5981,8 @@ spec: Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). - GrantTypes is deliberately not exposed here: the runtime only accepts - exactly the RFC 8693 token-exchange grant for a SPIFFE client - (validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter - always supplies it instead of letting it be configured. + The CRD does not expose grantTypes. The converter always supplies the + RFC 8693 token-exchange grant instead of letting it be configured. properties: audiences: description: |- diff --git a/docs/arch/11-auth-server-storage.md b/docs/arch/11-auth-server-storage.md index 6841195150..7660e79b0c 100644 --- a/docs/arch/11-auth-server-storage.md +++ b/docs/arch/11-auth-server-storage.md @@ -206,7 +206,7 @@ Every JWT has a JOSE header, and its `typ` member says what kind of JWT it is. B The setting is Go-only. Set `authserver.Config.AccessTokenType`, or pass `runner.WithAccessTokenType`. The accepted values are `""` and `"JWT"` (the default) and `"at+jwt"`. Any other value makes server construction fail. The setting is not a RunConfig field, so config files, the CLI and operator CRDs cannot set it yet. -When the value is `at+jwt`, every JWT access token the server issues gets that type. This covers the authorization code grant (with PKCE), the refresh grant, the device code grant, RFC 8693 token exchange, the RFC 7523 JWT-bearer grant and ID-JAG redemption. This server has no client credentials grant. Refresh tokens and authorization codes are opaque HMAC tokens, not JWTs, so the setting does not change them. An ID-JAG this server may issue in the future keeps its own type, `oauth-id-jag+jwt`. +When the value is `at+jwt`, every JWT access token the server issues gets that type. This covers the authorization code grant (with PKCE), the refresh grant, the device code grant, RFC 8693 token exchange, the RFC 7523 JWT-bearer grant, ID-JAG redemption and the SPIFFE client credentials grant. The client credentials grant uses the same access-token strategy as the others, so it gets the same `typ`. Refresh tokens and authorization codes are opaque HMAC tokens, not JWTs, so the setting does not change them. An ID-JAG this server may issue in the future keeps its own type, `oauth-id-jag+jwt`. The type is written when a token is signed. It is not stored with the session. A change therefore takes effect at the next refresh, including for sessions created before the change. @@ -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, 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 SPIFFE placeholders replace each other whatever differs (scopes, resources, or the SPIFFE identity, which includes grant types), 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. A grant-type change appears only as `identity_changed=true`, because the placeholder stores no grant types. 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 78be603448..38c6c748b2 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -140,11 +140,18 @@ policies reference `trusted_issuers`. An embedded authorization server may omit upstream identity providers only when it has a pre-provisioned delegate client, a trusted issuer with `jwtBearerGrant`, -or a SPIFFE client association (`inbound_grants.spiffe_client_auth`). This mode serves token exchange without an interactive login: +or a SPIFFE client association (`inbound_grants.spiffe_client_auth`). This mode serves token exchange, when it is enabled, and the SPIFFE `client_credentials` grant, when a SPIFFE association lists it, without an interactive login: `/oauth/authorize` validates the OAuth client and redirect URI, then returns `unsupported_response_type`. Discovery omits authorization-code, refresh-token, -and PKCE capabilities while retaining token exchange (and JWT bearer when a -trusted issuer enables it). Generic MCP and OIDC authorization-code clients +and PKCE capabilities. It advertises token exchange only when it is enabled, +JWT bearer when a trusted issuer enables it, and `client_credentials` when a SPIFFE +association lists that grant. Token exchange is enabled by a +delegate client, a legacy trusted-issuer token-exchange policy, an +`inbound_grants.token_exchange` block, or a SPIFFE association that lists the +token-exchange grant. A config with no `inbound_grants` block at all also has +it on, because `NormalizeInboundGrants` defaults token exchange to enabled in +that case. A SPIFFE association that lists only `client_credentials` +does not enable it. Generic MCP and OIDC authorization-code clients cannot use token-only servers: the metadata deliberately lacks the authorization-code and PKCE fields those clients require to start an interactive flow. The OpenID well-known route returns the same RFC 8414 token-only metadata @@ -562,6 +569,11 @@ privilege — the resulting actor identity still has to clear `may_act`, `ExternalActor`, the `client_id` binding, or the configured- delegate exemption). +An authenticated SPIFFE client cannot present a distinct actor this way: its +actor token's `sub` must equal the client's verified SPIFFE ID, or the request +fails with `invalid_request`. See [SPIFFE association +declarations](18-spiffe-association-declarations.md). + Plain token exchange is unchanged for every client, including a client with an `actor_profile`. The profile applies only to ID-JAG issuance from an exchange grant; see [Actor-token validation at ID-JAG issuance](#actor-token-validation-at-id-jag-issuance). @@ -713,7 +725,7 @@ in addition to other grants can log users in. with `invalid_target`, before the upstream login. The server-level and the client-level refusal return the same error text, so an unauthenticated caller cannot tell which of the two refused a resource. (SPIFFE clients, which keep - a resource list, are token-exchange only and never reach `/authorize`.) The + a resource list, have no response types and never reach `/authorize`.) The default strategy compares scheme and host exactly and accepts a path that equals the client's audience path or extends it at a segment boundary (`https://api.example.com/v1` matches an audience of @@ -751,8 +763,10 @@ in addition to other grants can log users in. permits nothing. A client that sets `grant_types` explicitly must also list the JWT-bearer grant, or the redemption fails with `unauthorized_client`. SPIFFE association clients are always gated: `idJAGExplicitGrantClientIDs` - includes every association, and their `grant_types` must be exactly the - token-exchange grant. A delegate client that omits `grant_types` is stored + includes every association, and their `grant_types` hold only the grants the + association declares (`client_credentials`, token exchange, or both). They + never include the JWT-bearer grant, so an ID-JAG for such a client always + fails with `unauthorized_client`. A delegate client that omits `grant_types` is stored with token exchange alone but is not gated, for backward compatibility. The plain JWT-bearer grant is not gated this way, because it can run without client authentication. @@ -859,7 +873,7 @@ 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.** `audiences` is ignored. The +- **SPIFFE clients.** Both grants ignore `audiences` and use one rule: 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) @@ -1727,7 +1741,8 @@ an ID token. Its `aud` must contain one of the client's to other exchanges: for a refresh-token request the client's own tokens are not accepted, and the list must not be empty. Startup validation rejects `exchange_refresh_tokens` without a non-empty `allowed_source_clients`. Tokens -made by token exchange, the JWT-bearer grant or an ID-JAG are refused. +made by token exchange, the JWT-bearer grant, an ID-JAG or the +`client_credentials` grant are refused. Last, its scope must contain `offline_access` or `offline`, the server's refresh-token scopes. A grant outlives the sign-in session, so opening one needs diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 5fe0b50f6f..74397a9ebb 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -2,7 +2,7 @@ **Current status: SPIFFE client authentication is enforced when the trust bundle comes from a `file` source.** A SPIFFE trust configuration whose bundle source is `file` starts and is enforced for both JWT-SVID and X.509-SVID client authentication. Only the `file` source has a loader. `bundle_endpoint` (both the `https_web` and `https_spiffe` profiles) and `workload_api` are rejected in four places: by `RunConfig.Validate()`; by the `Config`-level check (`ValidateRuntimeSPIFFEBundleSourceType` and `validateRuntimeSPIFFEBundleSources` in `pkg/authserver/config.go`); by `MCPExternalAuthConfig` validation, so the config resource is reported invalid; and by the VirtualMCPServer inline `authServerConfig` validation. A workload that references a config also fails again when it reconciles. The CRD schema still accepts them on purpose; the restriction is meant to be lifted when loaders exist. -A SPIFFE-only deployment with no upstream, delegate client or trusted issuer is supported: `validateZeroUpstreamMode` counts SPIFFE associations, and associations enable the token-exchange capability. Still not supported: RFC 8705 discovery metadata (`tls_client_auth`, `mtls_endpoint_aliases` are not advertised). A SPIFFE-only VirtualMCPServer cannot set `incomingAuth.authzConfig`: `validateAuthzUpstreamAvailable` in `cmd/thv-operator/controllers/virtualmcpserver_controller.go` rejects any non-nil `authzConfig` when the embedded auth server has no upstreams, as it does for delegate-only setups. The plain `thv run` CLI has no flag for `embedded_auth_server_config`; the only CLI route is a hand-written runner RunConfig loaded with `thv run --from-config`. +A SPIFFE-only deployment with no upstream, delegate client or trusted issuer is supported: `validateZeroUpstreamMode` counts SPIFFE associations. Each association's `grant_types` alone decides which grants it may use. RFC 8693 token exchange is enabled for an association only when that association lists the token-exchange grant; an association that grants only `client_credentials` leaves it off, and the `client_credentials` handler is registered only when some association lists that grant. For a deployment whose associations grant only `client_credentials`, and that has no delegate clients, `token_exchange` block or legacy trusted-issuer token-exchange policy, the token-exchange grant is not registered at the token endpoint, is not listed in `grant_types_supported` in `/.well-known/oauth-authorization-server`, and DCR rejects a registration that requests it. Still not supported: RFC 8705 discovery metadata (`tls_client_auth`, `mtls_endpoint_aliases` are not advertised). A SPIFFE-only VirtualMCPServer cannot set `incomingAuth.authzConfig`: `validateAuthzUpstreamAvailable` in `cmd/thv-operator/controllers/virtualmcpserver_controller.go` rejects any non-nil `authzConfig` when the embedded auth server has no upstreams, as it does for delegate-only setups. The plain `thv run` CLI has no flag for `embedded_auth_server_config`; the only CLI route is a hand-written runner RunConfig loaded with `thv run --from-config`. The embedded authorization server carries the SPIFFE association model across the `RunConfig` boundary. `newServer` builds the configured bundle source, which loads and polls a local trust-bundle file, and passes its X.509 and JWT views to the client-authentication strategy. @@ -33,28 +33,56 @@ Configuration separates top-level trust declarations from canonical client assoc - `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, 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`). +The OAuth client ID is configured explicitly; it is never derived from the SPIFFE ID or pattern. The client ID must not be an absolute URL (a scheme followed by `://`), the same rule the CRD applies, so a hand-written RunConfig cannot set one either. Each association declares its grants in `grant_types`. Each entry is `client_credentials` or `urn:ietf:params:oauth:grant-type:token-exchange`. The list must be non-empty, and an entry may appear only once; an empty or unknown value is rejected. There is no separate per-association `token_exchange` switch, so listing the grant is the only way to enable it. The CRD does not expose `grantTypes` yet: the operator always supplies the token-exchange grant in `buildSPIFFEClientAuthRunConfigs` (`cmd/thv-operator/pkg/controllerutil/authserver.go`), so only a hand-written RunConfig can list `client_credentials`. ### Resources are the only target list -Each association lists the RFC 8707 `resources` its workload may ask for: +Each association lists the RFC 8707 `resources` its workload may ask for. Both grants use them the same way: -- `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. +- `resources` is required and must be non-empty on every association, whatever its `grant_types`. 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`. 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()`. ### 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`: +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, and `client_credentials` uses the same rule. The handler is `grantAndBoundAudiences` in `pkg/authserver/server/tokenexchange/handler.go`, which hands those clients to `GrantSingleResource` in `pkg/authserver/server/audience.go`. `client_credentials` uses the same function, so the two grants refuse the same requests with the same hints: - 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. +- A subject token that ToolHive issued to the client and that is bound only by `client_id` must also name the calling workload (see below). + +**Workloads that share a client ID.** A pattern ending in `/*` gives every workload under it the same client ID. Without a further check, workload B could present workload A's `client_credentials` token as the subject token and receive a token whose `sub` is A's SPIFFE ID. For a SPIFFE client, a ToolHive-issued subject token that is accepted only because its `client_id` matches is therefore checked for the workload it names. A token names a workload when its `sub`, or the `sub` of its outermost `act` entry, is a SPIFFE ID. Such a token must name the caller: its `sub` or its outermost `act.sub` must be the caller's verified SPIFFE ID. Otherwise the exchange fails with `invalid_grant` and the hint `The subject token was issued to a different workload of this client.` A token that names only the user and the client ID (`act.sub` is the client ID) can be re-exchanged by any workload of that client, because the user gave consent to the client and not to one instance of it. Tokens that name the caller in `may_act`, and tokens from an external issuer, follow their own rules and are not affected. Other client types are not affected either. The same reasoning applies to `actor_token`: for a SPIFFE client the actor token's `sub` must be the caller's verified SPIFFE ID, in addition to the usual `client_id` match. Otherwise the request fails with `invalid_request` and the hint `The actor token's subject does not match the authenticated workload.` A workload therefore cannot present a sibling's token as its actor. 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. +### client_credentials requests + +The `client_credentials` grant is handled by `Handler` in `pkg/authserver/server/clientcredentials/handler.go`, a thin wrapper around Fosite's stock client-credentials handler. It adds the association policy checks and the lifetime cap below, and then lets Fosite issue and sign the token. A request is handled as follows: + +- The client must be an authenticated SPIFFE client (JWT-SVID or X.509-SVID) whose association lists `client_credentials`. Any other client, or a SPIFFE client without the grant, gets `unauthorized_client`. This check runs before the scope and resource checks, so a client without the grant learns nothing about its lists. +- The request must carry exactly one non-empty `resource`. A missing, empty or repeated `resource` is rejected with `invalid_target`. Any `audience` parameter is rejected with `invalid_target`; this grant takes `resource` only. +- 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`. +- Token exchange for SPIFFE clients follows the same rule (see above), so neither grant falls back to a default audience. +- Each requested scope must be in the association's `scopes`, otherwise the request fails with `invalid_scope`. If no scope is requested, the token carries no scopes. Resource servers must not read a token without scopes as unrestricted. + +The access token has these claims: `sub` is the verified SPIFFE ID; `client_id` is the association's client ID; `aud` is the requested resource; `scp` is the granted scopes as an array, as for the other grants (there is no space-separated `scope` string); and `https://toolhive.dev/no_upstream_session` (`claimnames.NoUpstreamSessionKey`) is `true`, marking a token that never came from an upstream IdP login. The JOSE `typ` header is `at+jwt` when the server's access-token type is `at+jwt`, as for all grants. No refresh token is issued. + +The access token lives for the smaller of two periods: the server's access-token lifetime (`AccessTokenLifespan`) and the time left on the SVID that authenticated the request. For a JWT-SVID that is its `exp`. For an X.509-SVID it is the leaf certificate's `NotAfter`. Both `expires_in` and the token's `exp` follow this value. A JWT-SVID that has expired but is still inside the one-minute leeway go-spiffe accepts after `exp` passes client authentication and is then refused with `invalid_grant`. An SVID past that leeway, or an expired X.509-SVID, already fails client authentication with `invalid_client`. There is no separate setting for this lifetime. + +```console +curl -X POST https://auth.example.com/oauth/token \ + --data-urlencode 'grant_type=client_credentials' \ + --data-urlencode 'resource=https://mcp.example.com' \ + --data-urlencode 'scope=mcp:tools' \ + --data-urlencode 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-spiffe' \ + --data-urlencode "client_assertion=$JWT_SVID" +``` + +Discovery (`grantTypesSupported` and `tokenEndpointAuthMethodsSupported` in `pkg/authserver/server/handlers/discovery.go`) lists `client_credentials` in `grant_types_supported` exactly when the handler is registered, which is when some association lists that grant. It lists `spiffe_x509` and `spiffe_jwt` in `token_endpoint_auth_methods_supported` when some association enables that method. Both are set once from the trust configuration when the server starts. + ### 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. @@ -115,12 +143,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, 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, grant types, 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 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, 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, grant types, 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 policy values, and takes effect when the new pods roll out. For the SPIFFE identity the WARN shows only `identity_changed=true`, not the hash or any grant value. A changed grant-type list therefore logs the WARN with `identity_changed=true` and no grant value, because the placeholder stores no grant types. On the first rollout after upgrading to this version, every SPIFFE placeholder logs one such WARN, because its stored identity hash changes now that the hash covers grant types. During a mixed-version rolling update, a replica still running the previous version writes the previous hash back, so a later replica start can log the WARN again. 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 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. @@ -137,7 +165,7 @@ The server's own registration, never trial and error, picks the verifier, so exa The implemented JWT-SVID assertion validator accepts a serialized client assertion, limited to 16 KiB, and validates it with go-spiffe `jwtsvid.ParseAndValidate` against the configured JWT bundle source (`AuthorizationServerParams.SPIFFEJWTBundleSource`). The validator requires the assertion's sole audience to be the configured authorization-server issuer. It does not require an `iss` claim: RFC 7519 makes `iss` OPTIONAL, and the SPIFFE JWT-SVID specification does not mandate it either, so a conformant SVID signed by a bundle-trusted key is accepted whether or not it carries one. This path reaches go-jose/v4's default one-minute claim leeway through go-spiffe v2.7.0; the leeway is inherited and not configurable in this code path. The validator rejects an assertion whose remaining validity exceeds six minutes, representing the recommended five-minute JWT-SVID issuer lifetime plus that one-minute clock-skew allowance. The JWT bundle view is the live, polled bundle, so a rotated bundle applies without a restart. -`client_id` is optional for this authentication method. When it is omitted, the registry derives the configured OAuth client from the verified SPIFFE ID association. When it is supplied, it is treated as an exact selector and must match that association's configured client ID; the server does not normalize the value. For example: +`client_id` is optional for this authentication method. When it is omitted, the registry derives the configured OAuth client from the verified SPIFFE ID association. The draft would use the SPIFFE ID itself as the client ID in that case; ToolHive uses the association's configured client ID instead, because client IDs are never derived from the SPIFFE ID. When it is supplied, it is treated as an exact selector and must match that association's configured client ID; the server does not normalize the value. For example: ```console curl -X POST https://auth.example.com/oauth/token \ @@ -148,11 +176,29 @@ 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`. 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 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 and is what the `client_credentials` handler requires: any other client is refused with `unauthorized_client`. In production only this resolver builds it. On Redis, a request read back from storage holds the plain static client, which does not carry it. The memory backend keeps the stored client pointer, so a read-back request there still returns the `AuthenticatedSPIFFEClient` wrapper. No code relies on the wrapper from a read-back request, and the `client_credentials` handler only sees the freshly authenticated client. 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. -JWT-SVID assertions currently have no application-level replay protection, `jti` persistence, nonce, or proof-of-possession binding. A captured valid assertion can therefore be reused until its expiry, subject to the six-minute maximum remaining-validity policy and any acceptance allowed by the inherited claim leeway. +### Relationship to the IETF draft + +The `spiffe_x509` and `spiffe_jwt` client authentication methods, and the `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` assertion type, come from [draft-ietf-oauth-spiffe-client-auth-03](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-spiffe-client-auth-03) (2 November 2026). It is a working draft and may change. ToolHive differs from it in two deliberate ways: + +- **X.509 requires `client_id`.** The draft makes `client_id` optional for `spiffe_x509`. ToolHive requires it (see "Request rules" under X.509 client authentication). +- **An absent `client_id` maps to the association's client ID.** When a JWT-SVID request omits `client_id`, the draft uses the SPIFFE ID as the client ID. ToolHive resolves the SPIFFE ID to an association and uses that association's configured client ID, because a client ID is never derived from a SPIFFE ID or pattern. + +### Known limitation: JWT-SVID replay + +A JWT-SVID is a bearer credential, and the SPIFFE path has no application-level replay protection: no `jti` persistence, nonce, or proof-of-possession binding. Its `jti` is not stored, and the replay store that Fosite uses for `private_key_jwt` is wired only into the default strategy. A captured valid assertion can therefore be reused until its expiry, subject to these limits: + +- The assertion's sole audience must be the authorization-server issuer. +- The assertion's remaining validity must not exceed six minutes when it is checked (`maxSPIFFEJWTAssertionRemainingValidity` in `pkg/authserver/server/spiffe_client_auth.go`): the five-minute issuer lifetime plus one minute of clock skew. Separately, the one-minute leeway that go-spiffe inherits from go-jose accepts an assertion for up to one minute after its `exp`. The `client_credentials` grant refuses such an assertion. + +An association counts as a confidential client in the cleartext-transport check (`RunConfig.hasConfidentialClients`, `Config.hasStaticConfidentialClients` and `ValidateConfidentialClientTransport`), as delegate clients do, only when it allows `spiffe_jwt` and also grants `client_credentials`. For such an association `insecure_allow_http` is rejected, and an `http` issuer is accepted only when `insecure_allow_confidential_over_loopback_http` is set and the issuer host is loopback. The check runs in `RunConfig.Validate()` and `Config.Validate()`. An association that enables only `spiffe_x509` does not trigger it, and neither does one that allows `spiffe_jwt` for token exchange only. + +Token-exchange-only JWT-SVID associations are excluded so that existing deployments keep working, not because they are safer. Token exchange over plain HTTP is still exposed. A passive observer captures the JWT-SVID and the subject token from the same request, and can exchange them again for as long as the SVID is valid. Serve the issuer over TLS. The CRD admission rules do not include the `client_credentials` condition yet, because a custom resource cannot list `client_credentials` on this version. + +With the `client_credentials` grant, each request that presents a replayed SVID mints a new access token. One captured SVID can therefore mint any number of access tokens until it expires, not just one. Each token lives no longer than the SVID that authenticated the request (see "client_credentials requests"), so a replayed SVID mints tokens that expire within its own validity window. Tokens are not bound to the client certificate or key (RFC 8705), and that binding is not implemented. This is accepted behavior: the SPIFFE specification treats JWT-SVIDs as bearer tokens and does not require `jti`. ## X.509 client authentication @@ -162,7 +208,7 @@ X.509-SVID client authentication is implemented in `authenticateSPIFFEX509Client **Request rules.** -- `client_id` is required (RFC 8705 section 2). +- `client_id` is required. The draft makes it optional for `spiffe_x509`; ToolHive requires it (as RFC 8705 section 2 does for `tls_client_auth`) so that the client the workload claims is always named in the request. - No other client credential may be present: no HTTP Basic header, `client_secret`, `client_assertion` or `client_assertion_type`. A duplicated or ambiguous `client_id` gives `invalid_request` (HTTP 400); mixed credentials, a missing or invalid certificate, a failed leaf profile or chain check, or a resolver rejection give `invalid_client` (HTTP 401). @@ -181,13 +227,13 @@ After verification, the SPIFFE ID and `client_id` are resolved through `SPIFFEAs **Where it works.** In the proxy runner and vMCP, X.509 is reachable only on the auth-server TLS listener on port 8443, which requests a client certificate (`tls.RequestClientCert`) and leaves chain verification to the strategy. `RunConfig.Validate()` and the operator reject `spiffe_x509` associations when `tls_listener` is not set, and when the issuer is not an `https` URL. The issuer rule is checked at validation (`ValidateSPIFFEX509Issuer`), not only at startup, so an invalid `MCPExternalAuthConfig` or `VirtualMCPServer` is reported as invalid instead of crash-looping. At startup the runner logs a WARN when the issuer port is not 8443 (`auth server issuer port differs from TLS listener port`), and a WARN when the listener certificate does not match the issuer hostname (`auth server TLS listener certificate does not match issuer hostname`). A program that calls `authserver.New` directly must terminate TLS itself and request client certificates (see the godoc on `New` in `pkg/authserver/server.go`). Behind a TLS-terminating proxy, X.509-SVID authentication is unavailable; use JWT-SVIDs. Identity is never read from forwarded headers such as `X-Forwarded-Client-Cert`. -The authenticated client is whichever peer completes the TLS handshake, so TLS must reach the listener end to end from the workload. A proxy or gateway that opens its own TLS connection to port 8443 is authenticated as itself, not as the caller behind it. Take a gateway whose SVID matches an association's principal pattern, for example `spiffe://example.org/ns/prod/*`. An external caller who sends that association's `client_id` and no credential of its own then authenticates as that client. Token exchange still needs a valid subject token that passes the delegation consent check, which limits the damage, but the client-authentication protection against a stolen subject token is gone. Use TLS passthrough to port 8443, and write principal patterns that cannot match proxy or gateway identities: exact SPIFFE IDs or per-service-account paths, not a namespace wildcard that includes the gateway's service account. The `appProtocol: https` on the Service port is a hint some gateways read to choose the backend protocol. Do not pair it with a setting that makes a gateway re-originate TLS to this port. +The authenticated client is whichever peer completes the TLS handshake, so TLS must reach the listener end to end from the workload. A proxy or gateway that opens its own TLS connection to port 8443 is authenticated as itself, not as the caller behind it. Take a gateway whose SVID matches an association's principal pattern, for example `spiffe://example.org/ns/prod/*`. An external caller who sends that association's `client_id` and no credential of its own then authenticates as that client. Token exchange still needs a valid subject token that passes the delegation consent check, which limits the damage, but the client-authentication protection against a stolen subject token is gone. For an association that grants `client_credentials`, nothing limits the damage: the impersonating caller gets an access token directly, with no subject token needed. For such an association, TLS passthrough and principal patterns that cannot match gateway identities are required, not just advisable. Use TLS passthrough to port 8443, and write principal patterns that cannot match proxy or gateway identities: exact SPIFFE IDs or per-service-account paths, not a namespace wildcard that includes the gateway's service account. The `appProtocol: https` on the Service port is a hint some gateways read to choose the backend protocol. Do not pair it with a setting that makes a gateway re-originate TLS to this port. **Logging.** Rejections are logged at Debug level with the failing stage. The certificate and assertion are never logged. ## ID-JAG grant exclusion -SPIFFE association clients are included in the explicit-grant client set of the ID-JAG handler (`idJAGExplicitGrantClientIDs` in `pkg/authserver/server_impl.go`). They cannot redeem an ID-JAG through the jwt-bearer grant; the redemption fails with `unauthorized_client` and the hint `The client is not registered for the jwt-bearer grant.` Their static client is token-exchange only. +SPIFFE association clients are included in the explicit-grant client set of the ID-JAG handler (`idJAGExplicitGrantClientIDs` in `pkg/authserver/server_impl.go`). They cannot redeem an ID-JAG through the jwt-bearer grant; the redemption fails with `unauthorized_client` and the hint `The client is not registered for the jwt-bearer grant.` Their static client holds exactly the grant types the association declares (`client_credentials`, token exchange, or both), so jwt-bearer is never among them. ## Security and delivery scope diff --git a/docs/arch/README.md b/docs/arch/README.md index 917de24760..fa00b2f272 100644 --- a/docs/arch/README.md +++ b/docs/arch/README.md @@ -148,6 +148,7 @@ Welcome to the ToolHive architecture documentation. This directory contains comp - SPIFFE client authentication is enforced for trust domains with a `file` bundle source; `bundle_endpoint` and `workload_api` fail validation - Auth-server TLS listener runs on the proxy runner and vMCP at fixed port 8443; the operator configures its certificate (`tlsListener`) and exposes the port - JWT-SVID and X.509-SVID client authentication (fail closed, certificate leaf profile, no fallback) + - Per-association `grant_types`: `client_credentials`, token exchange, or both, with the `client_credentials` request rules (exact `resource`, no `audience`, no refresh token) - Fail-closed policy validation and durable, restart-safe static-client reservation - Endpoint/Workload API loading and RFC 8705 discovery metadata remain pending diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 168b4fd327..9592222853 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -4354,10 +4354,8 @@ authenticate with a JWT-SVID or an X.509-SVID and have no client secret. Trust material comes from the declared bundle source (see SPIFFETrustDomainConfig's doc comment). -GrantTypes is deliberately not exposed here: the runtime only accepts -exactly the RFC 8693 token-exchange grant for a SPIFFE client -(validateSPIFFEGrants in pkg/authserver/spiffe_trust.go), so the converter -always supplies it instead of letting it be configured. +The CRD does not expose grantTypes. The converter always supplies the +RFC 8693 token-exchange grant instead of letting it be configured. diff --git a/docs/server/docs.go b/docs/server/docs.go index af31c9d2be..4d9742161e 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -786,7 +786,7 @@ const docTemplate = `{ "type": "string" }, "resources": { - "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.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: both\nclient_credentials and token exchange take exactly one resource per\nrequest and grant it as the token 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 820769761a..382b66f9a1 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -779,7 +779,7 @@ "type": "string" }, "resources": { - "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.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: both\nclient_credentials and token exchange take exactly one resource per\nrequest and grant it as the token 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 2ec5462b9e..9a1ece9b1e 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -1095,9 +1095,9 @@ components: resources: description: |- Resources are RFC 8707 resource indicators this association may - 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 + request. At least one is required for every association: both + client_credentials and token exchange take exactly one resource per + request and grant 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. diff --git a/pkg/authserver/claimnames/claimnames.go b/pkg/authserver/claimnames/claimnames.go index 86d89ec53e..0c705e52ae 100644 --- a/pkg/authserver/claimnames/claimnames.go +++ b/pkg/authserver/claimnames/claimnames.go @@ -14,9 +14,10 @@ const TokenSessionIDKey = "tsid" // NoUpstreamSessionKey marks a token this authorization server minted // without any link to an upstream IdP login, so no upstream credential exists -// for it. Today only the RFC 7523 JWT-bearer grant and the ID-JAG grant set -// it: the subject is a synthetic machine identity (issuer#subject) asserted by -// a separate trust root, with no end user and no upstream session. +// for it. The RFC 7523 JWT-bearer, ID-JAG and client_credentials grants set it: +// their subject is a machine identity (issuer#subject, or the SPIFFE ID for +// client_credentials) asserted by a separate trust root, with no end user and +// no upstream session. // // It exists so a resource server can distinguish "this token was deliberately // minted without an upstream session" from "this identity was never enriched diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index 2e313f63f9..9e8e6771cc 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -635,11 +635,16 @@ func (c *RunConfig) Validate() error { // included. They send no secret, but unlike token-exchange-only DCR // private_key_jwt clients they can hold authorization_code and refresh_token // grants, so codes and long-lived tokens would cross plain HTTP. jti replay - // checks and the 5-minute assertion cap already limit a captured assertion; - // this is a conservative choice, matches the CRD CEL rules, and can be - // relaxed later (for example for an in-cluster HTTP issuer). + // checks and the 5-minute assertion cap already limit a captured assertion + // (neither applies to JWT-SVIDs: there is no jti check, and the cap is six + // minutes of remaining validity). This is a conservative choice, matches the + // CRD CEL rules, and can be relaxed later (for example for an in-cluster + // HTTP issuer). A SPIFFE association that allows the JWT-SVID method and + // grants client_credentials counts too: one captured JWT-SVID, a bearer + // credential, then mints access tokens directly. Token-exchange-only + // JWT-SVID associations do not count. if err := ValidateConfidentialClientTransport( - c.AllowConfidentialClientRegistration || len(normalized.DelegateClients) > 0, c.InsecureAllowHTTP, + c.hasConfidentialClients(normalized), c.InsecureAllowHTTP, c.Issuer, c.InsecureAllowConfidentialOverLoopbackHTTP); err != nil { return err } @@ -661,6 +666,15 @@ func (c *RunConfig) Validate() error { return c.validateBaselineClientScopes() } +// hasConfidentialClients reports whether any confidential client can exist: +// DCR of confidential clients, at least one delegate client in the normalized +// grants, or a SPIFFE association that allows the JWT-SVID method and grants +// client_credentials. +func (c *RunConfig) hasConfidentialClients(normalized *NormalizedInboundGrants) bool { + return c.AllowConfidentialClientRegistration || len(normalized.DelegateClients) > 0 || + c.hasJWTClientCredentialsAssociation() +} + // validateSPIFFEX509Listener requires the TLS listener and an https issuer when // an association enables spiffe_x509, since only that listener requests a // client certificate. @@ -792,17 +806,33 @@ func (c *RunConfig) validateUpstreamFilter() error { // HasSPIFFEX509ClientAuth reports whether any SPIFFE client association // enables spiffe_x509. A nil *RunConfig returns false. func (c *RunConfig) HasSPIFFEX509ClientAuth() bool { + return c.hasSPIFFEMethod(SPIFFEAuthenticationMethodX509) +} + +// hasSPIFFEMethod reports whether any SPIFFE client association in the +// unvalidated run-config form allows method. A nil *RunConfig or nil +// InboundGrants returns false. +func (c *RunConfig) hasSPIFFEMethod(method SPIFFEAuthenticationMethod) bool { if c == nil || c.InboundGrants == nil { return false } - for _, association := range c.InboundGrants.SPIFFEClientAuth { - for _, method := range association.Methods { - if method == SPIFFEAuthenticationMethodX509 { - return true - } - } + return slices.ContainsFunc(c.InboundGrants.SPIFFEClientAuth, func(a SPIFFEClientAuthRunConfig) bool { + return containsSPIFFEAuthenticationMethod(a.Methods, method) + }) +} + +// hasJWTClientCredentialsAssociation reports whether any SPIFFE client +// association in the unvalidated run-config form allows the JWT-SVID method and +// lists the client_credentials grant. A nil *RunConfig or nil InboundGrants +// returns false. +func (c *RunConfig) hasJWTClientCredentialsAssociation() bool { + if c == nil || c.InboundGrants == nil { + return false } - return false + return slices.ContainsFunc(c.InboundGrants.SPIFFEClientAuth, func(a SPIFFEClientAuthRunConfig) bool { + return containsSPIFFEAuthenticationMethod(a.Methods, SPIFFEAuthenticationMethodJWT) && + slices.Contains(a.GrantTypes, oauthproto.GrantTypeClientCredentials) + }) } // validateBaselineClientScopes ensures every entry in BaselineClientScopes is @@ -2390,12 +2420,11 @@ func (c *Config) validateDelegationConfig() error { return validateTrustedIssuers(c.TrustedIssuers, c.Issuer, c.AllowedAudiences) } -// hasStaticConfidentialClients reports whether any pre-provisioned -// confidential client is configured. Today only delegate clients count. SPIFFE -// association clients are deliberately not counted: they are not part of the -// cleartext-transport check. +// hasStaticConfidentialClients reports whether any delegate client is +// configured or a SPIFFE association allows the JWT-SVID method and grants +// client_credentials. func (c *Config) hasStaticConfidentialClients() bool { - return len(c.DelegateClients) > 0 + return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsJWTClientCredentials() } // validateConfidentialClientConfig groups cleartext-transport validation for @@ -2439,12 +2468,19 @@ func (c *Config) validateAuthorizationDetailsRequiresTokenExchange() error { return nil } -// validateSPIFFEAssociationsRequireTokenExchange rejects SPIFFE client -// associations combined with a disabled token-exchange grant. Every SPIFFE -// client receives only the RFC 8693 grant, so an association could never be used. +// validateSPIFFEAssociationsRequireTokenExchange rejects a SPIFFE client +// association that grants token exchange while the token-exchange grant is +// disabled, because that association could never be used. Associations that +// grant only client_credentials do not depend on the token-exchange grant. func (c *Config) validateSPIFFEAssociationsRequireTokenExchange() error { - if len(c.SPIFFETrust.Associations()) > 0 && c.DisableTokenExchange { - return fmt.Errorf("SPIFFE client associations require token exchange to be enabled") + if !c.DisableTokenExchange { + return nil + } + for _, association := range c.SPIFFETrust.Associations() { + if slices.Contains(association.AuthorizationPolicy().GrantTypes(), oauthproto.GrantTypeTokenExchange) { + return fmt.Errorf("SPIFFE client association %q grants token exchange, "+ + "but token exchange is disabled", association.ClientID()) + } } return nil } diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index 1a58a1e475..165954ef68 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -139,6 +139,49 @@ func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceR return trust } +func mustNewSPIFFEJWTTrustConfig(t *testing.T, grants ...string) *SPIFFETrustConfig { + t.Helper() + association := testSPIFFEWildcardAssociation("https://mcp.example.com") + association.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + association.GrantTypes = grants + trust, err := NewSPIFFETrustConfig( + []SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT}, + BundleSource: validFileBundleSource(), + }}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{association}}, + []string{"openid"}, []string{"https://mcp.example.com"}, + ) + require.NoError(t, err) + return trust +} + +func mustNewSPIFFETrustConfigWithGrants(t *testing.T, grants []string) *SPIFFETrustConfig { + t.Helper() + trust, err := NewSPIFFETrustConfig( + []SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + BundleSource: validFileBundleSource(), + }}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ + TrustDomainRef: "production", + PrincipalPattern: "spiffe://example.org/ns/default/*", + ClientID: "agent-client", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + Resources: []string{"https://mcp.example.com"}, + Scopes: []string{"openid"}, + GrantTypes: grants, + }}}, + []string{"openid"}, []string{"https://mcp.example.com"}, + ) + require.NoError(t, err) + return trust +} + func TestConfigValidate(t *testing.T) { t.Parallel() @@ -222,11 +265,18 @@ func TestConfigValidate(t *testing.T) { {name: "CIMD enabled with valid bounds passes", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, CIMDEnabled: true, CIMDCacheMaxSize: 256, CIMDCacheFallbackTTL: 5 * time.Minute}}, // Confidential-client transport gate (same predicate RunConfig.Validate uses) - {name: "confidential clients combined with insecure HTTP rejects", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, AllowConfidentialClientRegistration: true, InsecureAllowHTTP: true}, wantErr: true, errMsg: "confidential clients (allow_confidential_client_registration or delegate clients) cannot be combined with insecure_allow_http"}, + {name: "confidential clients combined with insecure HTTP rejects", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, AllowConfidentialClientRegistration: true, InsecureAllowHTTP: true}, wantErr: true, errMsg: "confidential clients (allow_confidential_client_registration, delegate clients or JWT-SVID SPIFFE associations that grant client_credentials) cannot be combined with insecure_allow_http"}, {name: "private-key JWT registration combined with insecure HTTP passes (no secret to protect)", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, AllowPrivateKeyJWTRegistration: true, InsecureAllowHTTP: true}}, {name: "private-key JWT registration combined with token exchange disabled rejects", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, AllowPrivateKeyJWTRegistration: true, DisableTokenExchange: true}, wantErr: true, errMsg: "token-exchange-only"}, - {name: "SPIFFE association combined with token exchange disabled rejects", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFETrustConfig(t), DisableTokenExchange: true}, wantErr: true, errMsg: "SPIFFE client associations require token exchange"}, + {name: "JWT-SVID client_credentials association with a plain-HTTP loopback issuer rejects without the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeClientCredentials)}, wantErr: true, errMsg: "insecure_allow_confidential_over_loopback_http"}, + {name: "JWT-SVID client_credentials association with a plain-HTTP loopback issuer passes with the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeClientCredentials), InsecureAllowConfidentialOverLoopbackHTTP: true}}, + {name: "JWT-SVID client_credentials association combined with insecure HTTP rejects", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeClientCredentials), InsecureAllowHTTP: true}, wantErr: true, errMsg: "cannot be combined with insecure_allow_http"}, + {name: "JWT-SVID association with both grants combined with insecure HTTP rejects", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeClientCredentials), InsecureAllowHTTP: true}, wantErr: true, errMsg: "cannot be combined with insecure_allow_http"}, + {name: "JWT-SVID token-exchange-only association combined with insecure HTTP passes", config: Config{Issuer: "http://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeTokenExchange), InsecureAllowHTTP: true}}, + {name: "JWT-SVID token-exchange-only association with a plain-HTTP loopback issuer passes without the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeTokenExchange)}}, + {name: "SPIFFE association combined with token exchange disabled rejects", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFETrustConfig(t), DisableTokenExchange: true}, wantErr: true, errMsg: "grants token exchange, but token exchange is disabled"}, + {name: "SPIFFE client-credentials-only association combined with token exchange disabled passes", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFETrustConfigWithGrants(t, []string{oauthproto.GrantTypeClientCredentials}), DisableTokenExchange: true}}, // RefreshGrantHandlers {name: "nil refresh grant handler rejected", config: Config{Issuer: "https://example.com", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, Upstreams: validUpstreams, AllowedAudiences: []string{"https://mcp.example.com"}, RefreshGrantHandlers: []fosite.TokenEndpointHandler{&recordingRefreshHandler{}, nil}}, wantErr: true, errMsg: "refresh grant handler 1 is nil"}, @@ -740,6 +790,23 @@ func TestRunConfigValidate(t *testing.T) { return config } + // jwtConfig is an http-issuer JWT-SVID configuration whose single + // association lists grants. + jwtConfig := func(grants []string, mutate func(*RunConfig)) RunConfig { + return x509Config(func(c *RunConfig) { + c.TLSListener = nil + c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + c.InboundGrants.SPIFFEClientAuth[0].GrantTypes = grants + if mutate != nil { + mutate(c) + } + }) + } + tokenExchange := []string{oauthproto.GrantTypeTokenExchange} + clientCredentials := []string{oauthproto.GrantTypeClientCredentials} + bothGrants := []string{oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeClientCredentials} + tests := []struct { name string config RunConfig @@ -871,12 +938,67 @@ func TestRunConfigValidate(t *testing.T) { errMsg: "SPIFFE X.509 authentication requires an https issuer", }, { - name: "JWT-only association with an http issuer passes", - config: x509Config(func(c *RunConfig) { + name: "JWT-SVID client_credentials association with a non-loopback http issuer is rejected", + config: jwtConfig(clientCredentials, func(c *RunConfig) { c.Issuer = "http://auth.example.org" - c.TLSListener = nil - c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + }), + wantErr: true, + errMsg: "plain-HTTP non-loopback issuer", + }, + { + name: "JWT-SVID association with both grants and insecure_allow_http is rejected", + config: jwtConfig(bothGrants, func(c *RunConfig) { + c.InsecureAllowHTTP = true + }), + wantErr: true, + errMsg: "insecure_allow_http", + }, + { + name: "JWT-SVID client_credentials association with insecure_allow_http is rejected", + config: jwtConfig(clientCredentials, func(c *RunConfig) { + c.InsecureAllowHTTP = true + }), + wantErr: true, + errMsg: "insecure_allow_http", + }, + { + name: "JWT-SVID client_credentials association with a loopback http issuer is rejected without the opt-in", + config: jwtConfig(clientCredentials, func(c *RunConfig) { + c.Issuer = "http://localhost:8080" + }), + wantErr: true, + errMsg: "insecure_allow_confidential_over_loopback_http", + }, + { + name: "JWT-SVID client_credentials association with a loopback http issuer passes with the opt-in", + config: jwtConfig(clientCredentials, func(c *RunConfig) { + c.Issuer = "http://localhost:8080" + c.InsecureAllowConfidentialOverLoopbackHTTP = true + }), + }, + { + name: "JWT-SVID token-exchange-only association with insecure_allow_http passes", + config: jwtConfig(tokenExchange, func(c *RunConfig) { + c.InsecureAllowHTTP = true + }), + }, + { + name: "JWT-SVID token-exchange-only association with a non-loopback http issuer passes", + config: jwtConfig(tokenExchange, func(c *RunConfig) { + c.Issuer = "http://auth.example.org" + }), + }, + { + name: "JWT-SVID token-exchange-only association with a loopback http issuer passes without the opt-in", + config: jwtConfig(tokenExchange, func(c *RunConfig) { + c.Issuer = "http://localhost:8080" + }), + }, + { + name: "X.509 client_credentials association with insecure_allow_http passes because X.509 is not counted as confidential", + config: x509Config(func(c *RunConfig) { + c.InboundGrants.SPIFFEClientAuth[0].GrantTypes = clientCredentials + c.InsecureAllowHTTP = true }), }, { diff --git a/pkg/authserver/delegate_client_restart_integration_test.go b/pkg/authserver/delegate_client_restart_integration_test.go index c2d38f1383..2cd925bac6 100644 --- a/pkg/authserver/delegate_client_restart_integration_test.go +++ b/pkg/authserver/delegate_client_restart_integration_test.go @@ -151,7 +151,7 @@ func spiffeTrustForScope(t *testing.T, scope string) *authserver.SPIFFETrustConf Scopes: []string{scope}, Audiences: []string{delegateAudience}, Resources: []string{delegateAudience}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, }}}, []string{"scope-a", "scope-b", "scope-c"}, []string{delegateAudience}, diff --git a/pkg/authserver/inbound_grants.go b/pkg/authserver/inbound_grants.go index 95859cea0c..2a8e7b4b8b 100644 --- a/pkg/authserver/inbound_grants.go +++ b/pkg/authserver/inbound_grants.go @@ -8,6 +8,7 @@ import ( "slices" tx "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" + "github.com/stacklok/toolhive/pkg/oauthproto" ) // TokenExchangeInboundGrantRunConfig configures RFC 8693 inbound clients and issuer policies. @@ -120,14 +121,12 @@ func NormalizeInboundGrants(cfg *RunConfig) (*NormalizedInboundGrants, error) { } else { result.Capabilities.TokenExchange = legacyTokenExchange } - // SPIFFE client-auth associations always require the token-exchange grant - // (SPIFFEGrantTypeTokenExchange is the only grant type they may declare — - // see validateSPIFFEGrants), independent of the legacy/canonical - // token-exchange projection above. A SPIFFE-only configuration must not - // leave Capabilities.TokenExchange false: that would disable the RFC 8693 - // grant handler server-wide and reject every SPIFFE client's own token - // requests before authentication is even checked. - if len(cfg.InboundGrants.SPIFFEClientAuth) > 0 { + // An association that lists the token-exchange grant needs the RFC 8693 + // handler registered even when no canonical or legacy token-exchange + // configuration exists. Associations limited to client_credentials do not. + if slices.ContainsFunc(cfg.InboundGrants.SPIFFEClientAuth, func(entry SPIFFEClientAuthRunConfig) bool { + return slices.Contains(entry.GrantTypes, oauthproto.GrantTypeTokenExchange) + }) { result.Capabilities.TokenExchange = true } diff --git a/pkg/authserver/inbound_grants_test.go b/pkg/authserver/inbound_grants_test.go index 8a9c147204..a4f35df049 100644 --- a/pkg/authserver/inbound_grants_test.go +++ b/pkg/authserver/inbound_grants_test.go @@ -12,6 +12,7 @@ import ( "go.yaml.in/yaml/v3" "github.com/stacklok/toolhive/pkg/authserver/server/tokenexchange" + "github.com/stacklok/toolhive/pkg/oauthproto" ) func TestNormalizeInboundGrants(t *testing.T) { @@ -46,28 +47,27 @@ func TestNormalizeInboundGrants(t *testing.T) { want: &NormalizedInboundGrants{}, }, { - // Regression test: SPIFFE client-auth associations always - // require the token-exchange grant (see validateSPIFFEGrants), - // so a SPIFFE-only configuration must not leave - // Capabilities.TokenExchange false -- that would disable the - // RFC 8693 grant handler server-wide. This exact fix was - // previously lost during a rebase because its only regression - // coverage lived in a different package (pkg/authserver/runner); - // this case guards it directly where the logic lives. - name: "SPIFFE client auth alone sets the token exchange capability", - cfg: &RunConfig{ - InboundGrants: &InboundGrantsRunConfig{ - SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{{ - TrustDomainRef: "prod", - PrincipalPattern: "spiffe://example.org/ns/default/agent", - ClientID: "spiffe-agent", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - Scopes: []string{"openid"}, - Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, - }}, + name: "SPIFFE token exchange association sets the token exchange capability", + cfg: &RunConfig{InboundGrants: &InboundGrantsRunConfig{ + SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{spiffeTokenExchangeAssociation("spiffe-agent")}, + }}, + want: &NormalizedInboundGrants{Capabilities: InboundGrantCapabilities{TokenExchange: true}}, + }, + { + name: "SPIFFE client credentials association alone leaves token exchange disabled", + cfg: &RunConfig{InboundGrants: &InboundGrantsRunConfig{ + SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{spiffeClientCredentialsAssociation("spiffe-cc")}, + }}, + want: &NormalizedInboundGrants{}, + }, + { + name: "mixed SPIFFE associations set the token exchange capability", + cfg: &RunConfig{InboundGrants: &InboundGrantsRunConfig{ + SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{ + spiffeClientCredentialsAssociation("spiffe-cc"), + spiffeTokenExchangeAssociation("spiffe-agent"), }, - }, + }}, want: &NormalizedInboundGrants{Capabilities: InboundGrantCapabilities{TokenExchange: true}}, }, { @@ -393,3 +393,27 @@ func cloneRunConfigForTest(t *testing.T, cfg *RunConfig) *RunConfig { require.NoError(t, json.Unmarshal(data, &cloned)) return &cloned } + +func spiffeTokenExchangeAssociation(clientID string) SPIFFEClientAuthRunConfig { + return SPIFFEClientAuthRunConfig{ + TrustDomainRef: "prod", + PrincipalPattern: "spiffe://example.org/ns/default/" + clientID, + ClientID: clientID, + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + Scopes: []string{"openid"}, + Resources: []string{"https://mcp.example.com"}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, + } +} + +func spiffeClientCredentialsAssociation(clientID string) SPIFFEClientAuthRunConfig { + return SPIFFEClientAuthRunConfig{ + TrustDomainRef: "prod", + PrincipalPattern: "spiffe://example.org/ns/default/" + clientID, + ClientID: clientID, + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + Scopes: []string{"openid"}, + Resources: []string{"https://mcp.example.com"}, + GrantTypes: []string{oauthproto.GrantTypeClientCredentials}, + } +} diff --git a/pkg/authserver/internal/spiffetest/client.go b/pkg/authserver/internal/spiffetest/client.go index 8db325cd4f..a57164467f 100644 --- a/pkg/authserver/internal/spiffetest/client.go +++ b/pkg/authserver/internal/spiffetest/client.go @@ -7,6 +7,7 @@ package spiffetest import ( "testing" + "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/require" @@ -23,6 +24,7 @@ type config struct { resources []string spiffeID string method spiffeauth.SPIFFEAuthenticationMethod + expiry time.Time } // Option overrides one field of the client built by Client or @@ -50,6 +52,10 @@ func WithAuthMethod(method spiffeauth.SPIFFEAuthenticationMethod) Option { return func(c *config) { c.method = method } } +// WithCredentialExpiry sets the expiry of the verified SVID of the client built +// by AuthenticatedClient. +func WithCredentialExpiry(expiry time.Time) Option { return func(c *config) { c.expiry = expiry } } + // Client returns a valid SPIFFE client with id "spiffe-client", the // token-exchange grant, scope "openid" and no resources, adjusted by opts. func Client(t *testing.T, opts ...Option) *registration.SPIFFEClient { @@ -62,14 +68,14 @@ func Client(t *testing.T, opts ...Option) *registration.SPIFFEClient { // AuthenticatedClient returns the SPIFFE client Client would build, bound to a // verified SPIFFE ID and method as the client-authentication resolver does. The -// SPIFFE ID is "spiffe://example.org/workload/test" and the method is JWT -// unless opts say otherwise. +// SPIFFE ID is "spiffe://example.org/workload/test", the method is JWT and the +// credential expires in 24 hours unless opts say otherwise. func AuthenticatedClient(t *testing.T, opts ...Option) *registration.AuthenticatedSPIFFEClient { t.Helper() c := newConfig(opts) id, err := spiffeid.FromString(c.spiffeID) require.NoError(t, err) - client, err := registration.NewAuthenticatedSPIFFEClient(Client(t, opts...), id, c.method) + client, err := registration.NewAuthenticatedSPIFFEClient(Client(t, opts...), id, c.method, c.expiry) require.NoError(t, err) return client } @@ -81,6 +87,7 @@ func newConfig(opts []Option) config { scopes: []string{"openid"}, spiffeID: "spiffe://example.org/workload/test", method: spiffeauth.SPIFFEAuthenticationMethodJWT, + expiry: time.Now().Add(24 * time.Hour), } for _, opt := range opts { opt(&c) diff --git a/pkg/authserver/runner/embeddedauthserver.go b/pkg/authserver/runner/embeddedauthserver.go index b12b429e1a..6094a3f6dd 100644 --- a/pkg/authserver/runner/embeddedauthserver.go +++ b/pkg/authserver/runner/embeddedauthserver.go @@ -320,20 +320,9 @@ func prepareInboundGrantConfiguration( if err != nil { return nil, nil, nil, fmt.Errorf("build SPIFFE trust config: %w", err) } - // SPIFFE client authentication exclusively uses the token-exchange grant - // (validateSPIFFEGrants enforces this), so configuring any SPIFFE - // association implies token-exchange capability independent of - // legacy/canonical token-exchange enablement. - normalized.Capabilities.TokenExchange = normalized.Capabilities.TokenExchange || hasSPIFFEClientAuth(cfg) return normalized, delegateClients, spiffeTrust, nil } -// hasSPIFFEClientAuth reports whether cfg declares any SPIFFE client-auth -// association. -func hasSPIFFEClientAuth(cfg *authserver.RunConfig) bool { - return cfg.InboundGrants != nil && len(cfg.InboundGrants.SPIFFEClientAuth) > 0 -} - // buildUpstreamFilter constructs an upstreamfilter.UpstreamFilter from the RunConfig, // if one is configured. It returns an untyped nil (not a typed-nil interface // value) when cfg.UpstreamFilter is unset so authserver.Config.UpstreamFilter @@ -515,9 +504,8 @@ func newEmbeddedAuthServerWithStorage( // authorization-critical data is protected without a deep copy here. TrustedIssuers: trustedIssuers, DelegateClients: delegateClients, - // SPIFFE client authentication factors into Capabilities.TokenExchange - // already (see prepareInboundGrantConfiguration): it exclusively uses - // the token-exchange grant, independent of legacy/canonical enablement. + // Capabilities.TokenExchange already accounts for SPIFFE associations + // that list the token-exchange grant (see NormalizeInboundGrants). DisableTokenExchange: !normalized.Capabilities.TokenExchange, AuthorizationDetailsRegistry: options.authorizationDetailsRegistry, SPIFFETrust: spiffeTrust, diff --git a/pkg/authserver/runner/embeddedauthserver_test.go b/pkg/authserver/runner/embeddedauthserver_test.go index 3b5a6ddcf4..f266e16c92 100644 --- a/pkg/authserver/runner/embeddedauthserver_test.go +++ b/pkg/authserver/runner/embeddedauthserver_test.go @@ -23,6 +23,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "strings" "sync" "sync/atomic" @@ -2584,6 +2585,89 @@ func TestNewEmbeddedAuthServer_SPIFFEAndJWTBearerGrant(t *testing.T) { t.Cleanup(func() { require.NoError(t, srv.Close()) }) } +func TestNewEmbeddedAuthServer_SPIFFEGrantsDriveTokenExchangeDiscovery(t *testing.T) { + t.Parallel() + + clientCredentials := authserver.SPIFFEClientAuthRunConfig{ + TrustDomainRef: "production", + PrincipalPattern: "spiffe://example.org/ns/default/cc", + ClientID: "spiffe-cc", + Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, + Scopes: []string{"openid"}, + Resources: []string{"https://mcp.example.com"}, + GrantTypes: []string{oauthproto.GrantTypeClientCredentials}, + } + tokenExchange := testSPIFFEAssociation("spiffe-exchange", "spiffe://example.org/ns/default/exchange") + + tests := []struct { + name string + associations []authserver.SPIFFEClientAuthRunConfig + wantExchange bool + }{ + {name: "client credentials only", associations: []authserver.SPIFFEClientAuthRunConfig{clientCredentials}}, + { + name: "token exchange only", + associations: []authserver.SPIFFEClientAuthRunConfig{tokenExchange}, + wantExchange: true, + }, + { + name: "mixed", + associations: []authserver.SPIFFEClientAuthRunConfig{clientCredentials, tokenExchange}, + wantExchange: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := &authserver.RunConfig{ + TLSListener: writeTestSPIFFEListener(t), + SchemaVersion: authserver.CurrentSchemaVersion, + Issuer: "https://auth.example.com", + ScopesSupported: []string{"openid", "profile"}, + AllowedAudiences: []string{"https://mcp.example.com"}, + Upstreams: []authserver.UpstreamRunConfig{{ + Name: "static-upstream", + Type: authserver.UpstreamProviderTypeOAuth2, + OAuth2Config: &authserver.OAuth2UpstreamRunConfig{ + AuthorizationEndpoint: "https://upstream.example.com/authorize", + TokenEndpoint: "https://upstream.example.com/token", + ClientID: "test-client-id", + RedirectURI: "https://auth.example.com/oauth/callback", + }, + }}, + SPIFFETrustDomains: []authserver.SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []authserver.SPIFFEAuthenticationMethod{authserver.SPIFFEAuthenticationMethodX509}, + BundleSource: authserver.SPIFFEBundleSourceRunConfig{ + Type: authserver.SPIFFEBundleSourceTypeFile, + File: &authserver.SPIFFEFileBundleSourceRunConfig{Path: writeTestSPIFFEBundleFile(t)}, + }, + }}, + InboundGrants: &authserver.InboundGrantsRunConfig{SPIFFEClientAuth: tt.associations}, + } + + srv, err := NewEmbeddedAuthServer(context.Background(), cfg, WithListenerHost("localhost")) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, srv.Close()) }) + + rec := httptest.NewRecorder() + srv.Routes()["/.well-known/oauth-authorization-server"].ServeHTTP( + rec, httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil)) + require.Equal(t, http.StatusOK, rec.Code) + + var metadata struct { + GrantTypesSupported []string `json:"grant_types_supported"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &metadata)) + assert.Equal(t, tt.wantExchange, slices.Contains(metadata.GrantTypesSupported, oauthproto.GrantTypeTokenExchange), + "grant_types_supported: %v", metadata.GrantTypesSupported) + }) + } +} + // TestNewEmbeddedAuthServer_SPIFFEAndCIMD exercises the RunConfig conversion // and the production storage-decoration order with both features enabled. func TestNewEmbeddedAuthServer_SPIFFEAndCIMD(t *testing.T) { @@ -2902,7 +2986,7 @@ func TestEmbeddedAuthServer_SPIFFEClientIDAloneDoesNotAuthenticate(t *testing.T) t.Parallel() form := url.Values{ - "grant_type": {authserver.SPIFFEGrantTypeTokenExchange}, + "grant_type": {oauthproto.GrantTypeTokenExchange}, "subject_token": {"unvalidated-subject-token"}, "subject_token_type": {"urn:ietf:params:oauth:token-type:access_token"}, "client_id": {"spiffe-client"}, diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index a5b472ab84..82fb28751a 100644 --- a/pkg/authserver/runner/spiffe_x509_listener_test.go +++ b/pkg/authserver/runner/spiffe_x509_listener_test.go @@ -179,8 +179,8 @@ func TestEmbeddedAuthServer_SPIFFEX509ClientAuthOverTLS(t *testing.T) { } // TestEmbeddedAuthServer_SPIFFEClientCannotRedeemIDJAG proves a SPIFFE -// association client, which is restricted to token exchange, is refused when it -// redeems an ID-JAG through the jwt-bearer grant, while a delegate client that +// association client, whose grant_types never include jwt-bearer, is refused when +// it redeems an ID-JAG through the jwt-bearer grant, while a delegate client that // lists jwt-bearer redeems the same kind of assertion over the same listener. func TestEmbeddedAuthServer_SPIFFEClientCannotRedeemIDJAG(t *testing.T) { t.Parallel() @@ -281,6 +281,8 @@ func TestEmbeddedAuthServer_SPIFFEClientCannotRedeemIDJAG(t *testing.T) { }) } +// signSPIFFESubjectToken signs a subject token shaped like a client_credentials +// token issued to the SPIFFE workload: its sub is the workload's SPIFFE ID. func signSPIFFESubjectToken( t *testing.T, srv *EmbeddedAuthServer, clientID, scope string, mayAct map[string]any, audiences ...string, ) string { @@ -298,7 +300,7 @@ func signSPIFFESubjectToken( extra["may_act"] = mayAct } token, err := jwt.Signed(signer).Claims(jwt.Claims{ - Issuer: spiffeX509TestIssuer, Subject: "test-user", Audience: jwt.Audience(audiences), + Issuer: spiffeX509TestIssuer, Subject: spiffeX509TestPrincipal, Audience: jwt.Audience(audiences), Expiry: jwt.NewNumericDate(now.Add(30 * time.Minute)), IssuedAt: jwt.NewNumericDate(now), }).Claims(extra).Serialize() require.NoError(t, err) @@ -330,16 +332,89 @@ func TestEmbeddedAuthServer_SPIFFEOnlyTokenExchangeOverTLS(t *testing.T) { assert.NotEmpty(t, body["access_token"]) } +// TestEmbeddedAuthServer_SPIFFEClientCredentialsOnlyDoesNotEnableTokenExchange +// pins that a deployment whose only inbound capability is a SPIFFE association +// granting client_credentials registers no token-exchange handler: the grant +// works, and a token-exchange request is refused with no token issued. +func TestEmbeddedAuthServer_SPIFFEClientCredentialsOnlyDoesNotEnableTokenExchange(t *testing.T) { + t.Parallel() + + const resource = "https://mcp.example.com" + trusted := newSPIFFETestAuthority(t, "ca-1") + tokenURL, roots, srv := startSPIFFEX509TLSServer(t, trusted, func(cfg *authserver.RunConfig) { + cfg.Upstreams = nil + cfg.InboundGrants.SPIFFEClientAuth[0].GrantTypes = []string{oauthproto.GrantTypeClientCredentials} + }) + + tests := []struct { + name string + form func(t *testing.T) url.Values + wantCode int + wantError string + }{ + { + name: "client_credentials issues a token", + form: func(*testing.T) url.Values { + return url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_id": {spiffeX509TestClientID}, + "scope": {"openid"}, + "resource": {resource}, + } + }, + wantCode: http.StatusOK, + }, + { + name: "token exchange is refused", + form: func(t *testing.T) url.Values { + t.Helper() + return url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {signSPIFFESubjectToken(t, srv, spiffeX509TestClientID, "openid", nil, resource)}, + "subject_token_type": {oauthproto.TokenTypeAccessToken}, + "client_id": {spiffeX509TestClientID}, + "scope": {"openid"}, + "resource": {resource}, + } + }, + wantCode: http.StatusBadRequest, + wantError: "invalid_request", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + svid := trusted.issueSVID(t) + status, body := postTokenOverTLS(t, tokenURL, roots, &svid, "", tt.form(t)) + require.Equal(t, tt.wantCode, status, "token response: %v", body) + if tt.wantError == "" { + assert.NotEmpty(t, body["access_token"]) + return + } + assert.Equal(t, tt.wantError, body["error"], "token response: %v", body) + assert.NotContains(t, body, "access_token") + }) + } +} + // TestEmbeddedAuthServer_SPIFFEAssociationWithoutResourcesIsRejected pins that -// an association with no resources fails at startup. +// an association with no resources fails at startup, whatever its grant types. 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") + for _, grant := range []string{oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeClientCredentials} { + t.Run(grant, func(t *testing.T) { + t.Parallel() + + cfg, _ := spiffeX509TestConfig(t, newSPIFFETestAuthority(t, "ca-1"), func(cfg *authserver.RunConfig) { + cfg.InboundGrants.SPIFFEClientAuth[0].GrantTypes = []string{grant} + 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 diff --git a/pkg/authserver/server/clientcredentials/handler.go b/pkg/authserver/server/clientcredentials/handler.go new file mode 100644 index 0000000000..c661766f96 --- /dev/null +++ b/pkg/authserver/server/clientcredentials/handler.go @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package clientcredentials provides SPIFFE-bound client credentials handling. +package clientcredentials + +import ( + "context" + "fmt" + "log/slog" + "slices" + "time" + + "github.com/ory/fosite" + "github.com/ory/fosite/compose" + "github.com/ory/x/errorsx" + + "github.com/stacklok/toolhive/pkg/authserver/claimnames" + "github.com/stacklok/toolhive/pkg/authserver/server" + "github.com/stacklok/toolhive/pkg/authserver/server/registration" + "github.com/stacklok/toolhive/pkg/authserver/server/session" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +// Handler restricts Fosite's client credentials handler to authenticated SPIFFE +// clients and association policy. It delegates token lifetime and issuance to +// exactly one stock Fosite ClientCredentialsGrantHandler. +type Handler struct { + stock fosite.TokenEndpointHandler + allowedAudiences []string +} + +// Factory creates the SPIFFE-aware wrapper around Fosite's stock client +// credentials handler. It must only be installed for configured associations +// that permit client_credentials. +func Factory() server.Factory { + return func(config *server.AuthorizationServerConfig, storage fosite.Storage, strategy any) (any, error) { + created := compose.OAuth2ClientCredentialsGrantFactory(config.Config, storage, strategy) + stock, ok := created.(fosite.TokenEndpointHandler) + if !ok { + return nil, fmt.Errorf("fosite client credentials factory returned %T, not a token endpoint handler", created) + } + return &Handler{stock: stock, allowedAudiences: config.AllowedAudiences}, nil + } +} + +// CanHandleTokenEndpointRequest handles only the exact client_credentials grant. +func (*Handler) CanHandleTokenEndpointRequest(_ context.Context, requester fosite.AccessRequester) bool { + return requester.GetGrantTypes().ExactOne(oauthproto.GrantTypeClientCredentials) +} + +// CanSkipClientAuth requires authenticated SPIFFE client provenance. +func (*Handler) CanSkipClientAuth(_ context.Context, _ fosite.AccessRequester) bool { return false } + +// HandleTokenEndpointRequest validates SPIFFE association policy, establishes +// the SPIFFE subject session, and delegates standard client-credentials work to +// Fosite. +func (h *Handler) HandleTokenEndpointRequest(ctx context.Context, requester fosite.AccessRequester) error { + if !h.CanHandleTokenEndpointRequest(ctx, requester) { + return errorsx.WithStack(fosite.ErrUnknownRequest) + } + + client, ok := requester.GetClient().(*registration.AuthenticatedSPIFFEClient) + if !ok { + clientID := "" + if requester.GetClient() != nil { + clientID = requester.GetClient().GetID() + } + return reject(clientID, fosite.ErrUnauthorizedClient, "client is not an authenticated SPIFFE client", + "The client_credentials grant is available only to clients authenticated with a SPIFFE credential.") + } + // The grant check comes first so a client without the grant cannot probe + // its scope and resource lists. + if !client.GetGrantTypes().Has(oauthproto.GrantTypeClientCredentials) { + return reject(client.GetID(), fosite.ErrUnauthorizedClient, "grant not permitted for association", + "The client is not permitted to use the client_credentials grant.") + } + if err := grantPolicyScopes(requester, client.GetID(), client.GetScopes()); err != nil { + return err + } + if err := server.GrantSingleResource(requester, client.Resources(), h.allowedAudiences); err != nil { + slog.Debug("client_credentials request rejected", + "client_id", client.GetID(), "reason", fosite.ErrorToRFC6749Error(err).HintField) + return errorsx.WithStack(err) + } + + sess := session.New(client.SPIFFEID().String(), "", client.GetID(), session.UserClaims{}) + // A workload credential never links to an upstream IdP login; say so in + // the token. See claimnames.NoUpstreamSessionKey. + sess.JWTClaims.Extra[claimnames.NoUpstreamSessionKey] = true + requester.SetSession(sess) + if err := h.stock.HandleTokenEndpointRequest(ctx, requester); err != nil { + return err + } + return capAtCredentialExpiry(requester, client) +} + +// PopulateTokenEndpointResponse delegates access-token issuance to the stock +// Fosite handler after HandleTokenEndpointRequest has established the session. +func (h *Handler) PopulateTokenEndpointResponse( + ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder, +) error { + if !h.CanHandleTokenEndpointRequest(ctx, requester) { + return errorsx.WithStack(fosite.ErrUnknownRequest) + } + // Handle lowered the session expiry to the credential expiry. If that + // instant passed since, fail closed rather than let the stock handler sign + // a token whose exp is already in the past. A race inside the stock call + // itself is accepted: it can only yield a token that is expired on arrival. + if exp := requester.GetSession().GetExpiresAt(fosite.AccessToken); !exp.IsZero() && !exp.After(time.Now()) { + var id string + if c := requester.GetClient(); c != nil { + id = c.GetID() + } + return reject(id, fosite.ErrInvalidGrant, "client credential expired before token issuance", + "The client credential has expired.") + } + return h.stock.PopulateTokenEndpointResponse(ctx, requester, responder) +} + +// capAtCredentialExpiry makes the access token live no longer than the SVID +// that authenticated the request. Fosite derives both expires_in and the JWT exp +// from the session's access-token expiry, so lowering it is enough. An SVID +// that has already expired is refused, which also closes the one-minute leeway +// the JWT-SVID parser grants after exp. +func capAtCredentialExpiry(requester fosite.AccessRequester, client *registration.AuthenticatedSPIFFEClient) error { + expiry := client.CredentialExpiry() + if !expiry.After(time.Now()) { + return reject(client.GetID(), fosite.ErrInvalidGrant, "client credential expired", + "The client credential has expired.") + } + sess := requester.GetSession() + if current := sess.GetExpiresAt(fosite.AccessToken); current.IsZero() || expiry.Before(current) { + sess.SetExpiresAt(fosite.AccessToken, expiry.UTC()) + } + return nil +} + +func grantPolicyScopes(requester fosite.AccessRequester, clientID string, permitted fosite.Arguments) error { + for _, scope := range requester.GetRequestedScopes() { + if !slices.Contains(permitted, scope) { + return reject(clientID, fosite.ErrInvalidScope, "scope not permitted for association: "+scope, + fmt.Sprintf("The requested scope %q is not permitted for this client.", scope)) + } + requester.GrantScope(scope) + } + return nil +} + +// reject logs the rejection reason at debug level, never the credential or +// request body, and returns base with a hint naming the cause. +func reject(clientID string, base *fosite.RFC6749Error, reason, hint string) error { + slog.Debug("client_credentials request rejected", "client_id", clientID, "reason", reason) + return errorsx.WithStack(base.WithHint(hint)) +} + +var _ fosite.TokenEndpointHandler = (*Handler)(nil) diff --git a/pkg/authserver/server/clientcredentials/handler_test.go b/pkg/authserver/server/clientcredentials/handler_test.go new file mode 100644 index 0000000000..ba32859aa7 --- /dev/null +++ b/pkg/authserver/server/clientcredentials/handler_test.go @@ -0,0 +1,332 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package clientcredentials + +import ( + "cmp" + "context" + "net/url" + "testing" + "time" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/internal/spiffetest" + "github.com/stacklok/toolhive/pkg/authserver/server" + "github.com/stacklok/toolhive/pkg/authserver/server/session" + spiffeauth "github.com/stacklok/toolhive/pkg/authserver/spiffe" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +const ( + testResource = "https://resource.example.com" + testSPIFFEID = "spiffe://example.org/workload/concrete" +) + +// recordingHandler stands in for Fosite's stock handler; no gomock mock of +// fosite.TokenEndpointHandler exists in the repo. +type recordingHandler struct { + called, populated bool + // lifespan, when set, is the access-token lifetime the stand-in stamps on + // the session as the stock handler does. + lifespan time.Duration +} + +func (*recordingHandler) CanHandleTokenEndpointRequest(context.Context, fosite.AccessRequester) bool { + return true +} +func (*recordingHandler) CanSkipClientAuth(context.Context, fosite.AccessRequester) bool { + return false +} +func (h *recordingHandler) HandleTokenEndpointRequest(_ context.Context, requester fosite.AccessRequester) error { + h.called = true + if h.lifespan > 0 { + requester.GetSession().SetExpiresAt(fosite.AccessToken, time.Now().UTC().Add(h.lifespan)) + } + return nil +} +func (h *recordingHandler) PopulateTokenEndpointResponse(context.Context, fosite.AccessRequester, fosite.AccessResponder) error { + h.populated = true + return nil +} + +// clientOpts describes a SPIFFE client for tests; zero fields take defaults +// (client_credentials grant, openid scope, testResource, JWT method). +type clientOpts struct { + clientID string + spiffeID string + grants []string + scopes []string + resources []string + method spiffeauth.SPIFFEAuthenticationMethod + expiry time.Time + // unwrapped returns the static client without the authenticated principal. + unwrapped bool +} + +func newClient(t *testing.T, o clientOpts) fosite.Client { + t.Helper() + + opts := []spiffetest.Option{ + spiffetest.WithID(cmp.Or(o.clientID, "client")), + spiffetest.WithSPIFFEID(cmp.Or(o.spiffeID, testSPIFFEID)), + spiffetest.WithAuthMethod(cmp.Or(o.method, spiffeauth.SPIFFEAuthenticationMethodJWT)), + spiffetest.WithGrantTypes(orDefault(o.grants, oauthproto.GrantTypeClientCredentials)...), + spiffetest.WithScopes(orDefault(o.scopes, "openid")...), + spiffetest.WithResources(orDefault(o.resources, testResource)...), + } + if !o.expiry.IsZero() { + opts = append(opts, spiffetest.WithCredentialExpiry(o.expiry)) + } + if o.unwrapped { + return spiffetest.Client(t, opts...) + } + return spiffetest.AuthenticatedClient(t, opts...) +} + +// orDefault returns v, or def when v is nil; a non-nil empty slice is kept. +func orDefault(v []string, def ...string) []string { + if v == nil { + return def + } + return v +} + +func TestHandlerHandleTokenEndpointRequest(t *testing.T) { + t.Parallel() + + ccGrant := fosite.Arguments{oauthproto.GrantTypeClientCredentials} + defaultClient := clientOpts{} + oneResource := url.Values{"resource": {testResource}} + + tests := []struct { + name string + grants fosite.Arguments + client fosite.Client + form url.Values + scopes fosite.Arguments + wantError error + wantHint string + check func(*testing.T, *fosite.AccessRequest) + }{ + { + name: "exact grant creates SPIFFE subject session", + grants: ccGrant, + client: newClient(t, defaultClient), + form: oneResource, + scopes: fosite.Arguments{"openid"}, + check: func(t *testing.T, req *fosite.AccessRequest) { + t.Helper() + sess, ok := req.GetSession().(*session.Session) + require.True(t, ok) + assert.Equal(t, testSPIFFEID, sess.JWTClaims.Subject) + assert.Equal(t, "client", sess.JWTClaims.Extra[session.ClientIDClaimKey]) + assert.Equal(t, fosite.Arguments{"openid"}, req.GetGrantedScopes()) + assert.Equal(t, fosite.Arguments{testResource}, req.GetGrantedAudience()) + }, + }, + { + name: "omitted scope grants none", + grants: ccGrant, + client: newClient(t, defaultClient), + form: oneResource, + check: func(t *testing.T, req *fosite.AccessRequest) { + t.Helper() + assert.Empty(t, req.GetGrantedScopes()) + }, + }, + { + name: "excess scope is invalid scope", + grants: ccGrant, + client: newClient(t, defaultClient), + form: oneResource, + scopes: fosite.Arguments{"admin"}, + wantError: fosite.ErrInvalidScope, + wantHint: "is not permitted for this client", + }, + { + name: "ordinary confidential client is unauthorized", + grants: ccGrant, + client: &fosite.DefaultClient{ID: "client", Public: false}, + form: oneResource, + wantError: fosite.ErrUnauthorizedClient, + wantHint: "only to clients authenticated with a SPIFFE credential", + }, + { + name: "unwrapped static SPIFFE client is unauthorized", + grants: ccGrant, + client: newClient(t, clientOpts{unwrapped: true}), + form: oneResource, + wantError: fosite.ErrUnauthorizedClient, + wantHint: "only to clients authenticated with a SPIFFE credential", + }, + { + name: "association without client_credentials is unauthorized", + grants: ccGrant, + client: newClient(t, clientOpts{grants: []string{oauthproto.GrantTypeTokenExchange}}), + form: oneResource, + wantError: fosite.ErrUnauthorizedClient, + wantHint: "not permitted to use the client_credentials grant", + }, + { + name: "grant check precedes scope check", + grants: ccGrant, + client: newClient(t, clientOpts{grants: []string{oauthproto.GrantTypeTokenExchange}}), + form: oneResource, + scopes: fosite.Arguments{"admin"}, + wantError: fosite.ErrUnauthorizedClient, + wantHint: "not permitted to use the client_credentials grant", + }, + { + name: "client credentials plus another grant is declined", + grants: fosite.Arguments{oauthproto.GrantTypeClientCredentials, oauthproto.GrantTypeTokenExchange}, + client: newClient(t, defaultClient), + form: oneResource, + wantError: fosite.ErrUnknownRequest, + }, + { + name: "other grant is declined", + grants: fosite.Arguments{oauthproto.GrantTypeTokenExchange}, + client: newClient(t, defaultClient), + form: oneResource, + wantError: fosite.ErrUnknownRequest, + }, + { + name: "missing resource is invalid target", + grants: ccGrant, + client: newClient(t, defaultClient), + wantError: server.ErrInvalidTarget, + wantHint: "Exactly one resource parameter is required", + }, + { + name: "audience only is invalid target", + grants: ccGrant, + client: newClient(t, defaultClient), + form: url.Values{"audience": {testResource}}, + wantError: server.ErrInvalidTarget, + wantHint: "audience parameter is not accepted", + }, + { + name: "unauthorized resource is invalid target", + grants: ccGrant, + client: newClient(t, defaultClient), + form: url.Values{"resource": {"https://other.example.com"}}, + wantError: server.ErrInvalidTarget, + wantHint: "must exactly match a permitted resource", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stock := &recordingHandler{} + req := fosite.NewAccessRequest(&session.Session{}) + req.GrantTypes, req.Client, req.Form, req.RequestedScope = tt.grants, tt.client, tt.form, tt.scopes + handler := &Handler{stock: stock, allowedAudiences: []string{testResource}} + err := handler.HandleTokenEndpointRequest(context.Background(), req) + if tt.wantError != nil { + require.ErrorIs(t, err, tt.wantError) + assert.Contains(t, fosite.ErrorToRFC6749Error(err).HintField, tt.wantHint) + assert.False(t, stock.called) + return + } + require.NoError(t, err) + assert.True(t, stock.called) + tt.check(t, req) + }) + } +} + +func TestHandlerPopulateTokenEndpointResponse(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + grants fosite.Arguments + wantError error + wantCalled bool + }{ + { + name: "client_credentials delegates to the stock handler", + grants: fosite.Arguments{oauthproto.GrantTypeClientCredentials}, + wantCalled: true, + }, + { + name: "other grant is declined without calling the stock handler", + grants: fosite.Arguments{oauthproto.GrantTypeTokenExchange}, + wantError: fosite.ErrUnknownRequest, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stock := &recordingHandler{} + req := fosite.NewAccessRequest(session.New(testSPIFFEID, "", "client", session.UserClaims{})) + req.GrantTypes = tt.grants + err := (&Handler{stock: stock}).PopulateTokenEndpointResponse(context.Background(), req, fosite.NewAccessResponse()) + if tt.wantError != nil { + require.ErrorIs(t, err, tt.wantError) + } else { + require.NoError(t, err) + } + assert.Equal(t, tt.wantCalled, stock.populated) + }) + } +} + +func TestHandlerCapsAccessTokenAtCredentialExpiry(t *testing.T) { + t.Parallel() + + const lifespan = time.Hour + tests := []struct { + name string + // credentialIn is the credential's remaining validity. + credentialIn time.Duration + // wantExpiresIn is the expected access-token lifetime, within a few seconds. + wantExpiresIn time.Duration + wantError bool + }{ + {name: "credential sooner than the access-token lifespan caps the token", credentialIn: 5 * time.Minute, wantExpiresIn: 5 * time.Minute}, + {name: "credential outliving the access-token lifespan leaves the lifespan", credentialIn: 24 * time.Hour, wantExpiresIn: lifespan}, + {name: "expired credential is refused", credentialIn: -time.Second, wantError: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + stock := &recordingHandler{lifespan: lifespan} + req := fosite.NewAccessRequest(&session.Session{}) + req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeClientCredentials} + req.Client = newClient(t, clientOpts{expiry: time.Now().Add(tt.credentialIn)}) + req.Form = url.Values{"resource": {testResource}} + handler := &Handler{stock: stock, allowedAudiences: []string{testResource}} + + err := handler.HandleTokenEndpointRequest(context.Background(), req) + + if tt.wantError { + require.ErrorIs(t, err, fosite.ErrInvalidGrant) + assert.Equal(t, "The client credential has expired.", fosite.ErrorToRFC6749Error(err).HintField) + return + } + require.NoError(t, err) + assert.InDelta(t, tt.wantExpiresIn.Seconds(), + time.Until(req.GetSession().GetExpiresAt(fosite.AccessToken)).Seconds(), 5) + }) + } +} + +func TestHandlerPopulateRefusesElapsedSessionExpiry(t *testing.T) { + t.Parallel() + + stock := &recordingHandler{} + sess := session.New(testSPIFFEID, "", "client", session.UserClaims{}) + sess.SetExpiresAt(fosite.AccessToken, time.Now().Add(-time.Second)) + req := fosite.NewAccessRequest(sess) + req.GrantTypes = fosite.Arguments{oauthproto.GrantTypeClientCredentials} + + err := (&Handler{stock: stock}).PopulateTokenEndpointResponse(context.Background(), req, fosite.NewAccessResponse()) + + require.ErrorIs(t, err, fosite.ErrInvalidGrant) + assert.False(t, stock.populated) +} diff --git a/pkg/authserver/server/handlers/discovery.go b/pkg/authserver/server/handlers/discovery.go index aab784f05c..f93d02ea19 100644 --- a/pkg/authserver/server/handlers/discovery.go +++ b/pkg/authserver/server/handlers/discovery.go @@ -142,8 +142,9 @@ func (h *Handler) buildOAuthMetadata() sharedobauth.AuthorizationServerMetadata // list for discovery, derived from config. "none" is always first — the public-client // default. When confidential DCR is enabled or a configured delegate client authenticates // with a secret, the two client_secret_* methods are appended. Static secret clients need -// these methods even though DCR itself remains public-only. RFC 8414 defines no ordering semantics, so -// "none"-first is a readability convention, not a security control. +// these methods even though DCR itself remains public-only. private_key_jwt and then the +// SPIFFE methods follow when a client can use them. RFC 8414 defines no ordering semantics, +// so this ordering is a readability convention, not a security control. func (h *Handler) tokenEndpointAuthMethodsSupported() []string { methods := []string{sharedobauth.TokenEndpointAuthMethodNone} if h.advertisesClientSecret() { @@ -155,6 +156,12 @@ func (h *Handler) tokenEndpointAuthMethodsSupported() []string { if h.advertisesPrivateKeyJWT() { methods = append(methods, sharedobauth.TokenEndpointAuthMethodPrivateKeyJWT) } + if h.config.SupportsSPIFFEX509ClientAuthentication { + methods = append(methods, sharedobauth.TokenEndpointAuthMethodSPIFFEX509) + } + if h.config.SupportsSPIFFEJWTClientAuthentication { + methods = append(methods, sharedobauth.TokenEndpointAuthMethodSPIFFEJWT) + } return methods } @@ -180,9 +187,12 @@ func (h *Handler) tokenEndpointAuthSigningAlgorithms() []string { return registration.SupportedSigningAlgorithms() } -// grantTypesSupported returns only grant families registered with fosite. +// grantTypesSupported returns the grant families the server advertises. It is +// driven by configuration flags, not by the fosite handler set; the +// client_credentials flag also decides whether its handler is registered, so the +// two cannot differ. func (h *Handler) grantTypesSupported() []string { - grantTypes := make([]string, 0, 4) + grantTypes := make([]string, 0, 5) if h.config.TokenExchangeEnabled { grantTypes = append(grantTypes, sharedobauth.GrantTypeTokenExchange) } @@ -198,6 +208,9 @@ func (h *Handler) grantTypesSupported() []string { if h.config.DeviceFlowEnabled { grantTypes = append(grantTypes, sharedobauth.GrantTypeDeviceCode) } + if h.config.SupportsSPIFFEClientCredentialsGrant { + grantTypes = append(grantTypes, sharedobauth.GrantTypeClientCredentials) + } return grantTypes } diff --git a/pkg/authserver/server/handlers/handlers_test.go b/pkg/authserver/server/handlers/handlers_test.go index f1126fecdd..7c33dc4a08 100644 --- a/pkg/authserver/server/handlers/handlers_test.go +++ b/pkg/authserver/server/handlers/handlers_test.go @@ -48,6 +48,9 @@ type testSetupOptions struct { HasStaticPrivateKeyJWTClients bool DisableTokenExchange bool JWTBearerGrantEnabled bool + SPIFFEX509ClientAuthentication bool + SPIFFEJWTClientAuthentication bool + SPIFFEClientCredentialsGrant bool } // testSetup creates a Handler with all dependencies for testing. @@ -74,23 +77,26 @@ func testSetupWithOptions(t *testing.T, opts testSetupOptions) *Handler { require.NoError(t, err) cfg := &server.AuthorizationServerParams{ - Issuer: "https://auth.example.com", - AuthorizationEndpointBaseURL: opts.AuthorizationEndpointBaseURL, - CIMDEnabled: opts.CIMDEnabled, - AllowConfidentialClientRegistration: opts.AllowConfidentialClientRegistration, - AllowPrivateKeyJWTRegistration: opts.AllowPrivateKeyJWTRegistration, - HasStaticConfidentialClients: opts.HasStaticConfidentialClients, - HasStaticSecretClients: opts.HasStaticSecretClients, - HasStaticPrivateKeyJWTClients: opts.HasStaticPrivateKeyJWTClients, - DisableTokenExchange: opts.DisableTokenExchange, - JWTBearerGrantEnabled: opts.JWTBearerGrantEnabled, - AccessTokenLifespan: time.Hour, - RefreshTokenLifespan: time.Hour * 24, - AuthCodeLifespan: time.Minute * 10, - HMACSecrets: servercrypto.NewHMACSecrets(secret), - SigningKeyID: "test-key-1", - SigningKeyAlgorithm: "RS256", - SigningKey: rsaKey, + Issuer: "https://auth.example.com", + AuthorizationEndpointBaseURL: opts.AuthorizationEndpointBaseURL, + CIMDEnabled: opts.CIMDEnabled, + AllowConfidentialClientRegistration: opts.AllowConfidentialClientRegistration, + AllowPrivateKeyJWTRegistration: opts.AllowPrivateKeyJWTRegistration, + HasStaticConfidentialClients: opts.HasStaticConfidentialClients, + HasStaticSecretClients: opts.HasStaticSecretClients, + HasStaticPrivateKeyJWTClients: opts.HasStaticPrivateKeyJWTClients, + DisableTokenExchange: opts.DisableTokenExchange, + JWTBearerGrantEnabled: opts.JWTBearerGrantEnabled, + SupportsSPIFFEX509ClientAuthentication: opts.SPIFFEX509ClientAuthentication, + SupportsSPIFFEJWTClientAuthentication: opts.SPIFFEJWTClientAuthentication, + SupportsSPIFFEClientCredentialsGrant: opts.SPIFFEClientCredentialsGrant, + AccessTokenLifespan: time.Hour, + RefreshTokenLifespan: time.Hour * 24, + AuthCodeLifespan: time.Minute * 10, + HMACSecrets: servercrypto.NewHMACSecrets(secret), + SigningKeyID: "test-key-1", + SigningKeyAlgorithm: "RS256", + SigningKey: rsaKey, } oauth2Config, err := server.NewAuthorizationServerConfig(cfg) @@ -302,6 +308,8 @@ func TestDiscoveryHandlers_ConfidentialAuthMethods(t *testing.T) { hasStaticConfidential bool hasStaticSecret bool hasStaticPrivateKey bool + spiffeX509 bool + spiffeJWT bool wantMethods []string wantAlgorithms []string }{ @@ -331,6 +339,15 @@ func TestDiscoveryHandlers_ConfidentialAuthMethods(t *testing.T) { {name: "all authentication methods are advertised", allowConfidential: true, allowPrivate: true, hasStaticConfidential: true, hasStaticSecret: true, hasStaticPrivateKey: true, wantMethods: wantSecretsAndPrivateKeyJWT, wantAlgorithms: wantAlgorithms}, + {name: "SPIFFE X.509 association advertises spiffe_x509", spiffeX509: true, + wantMethods: []string{sharedobauth.TokenEndpointAuthMethodNone, sharedobauth.TokenEndpointAuthMethodSPIFFEX509}}, + {name: "SPIFFE JWT association advertises spiffe_jwt", spiffeJWT: true, + wantMethods: []string{sharedobauth.TokenEndpointAuthMethodNone, sharedobauth.TokenEndpointAuthMethodSPIFFEJWT}}, + {name: "SPIFFE methods follow private_key_jwt", allowPrivate: true, spiffeX509: true, spiffeJWT: true, + wantMethods: []string{ + sharedobauth.TokenEndpointAuthMethodNone, sharedobauth.TokenEndpointAuthMethodPrivateKeyJWT, + sharedobauth.TokenEndpointAuthMethodSPIFFEX509, sharedobauth.TokenEndpointAuthMethodSPIFFEJWT, + }, wantAlgorithms: wantAlgorithms}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -341,6 +358,8 @@ func TestDiscoveryHandlers_ConfidentialAuthMethods(t *testing.T) { HasStaticConfidentialClients: tc.hasStaticConfidential, HasStaticSecretClients: tc.hasStaticSecret, HasStaticPrivateKeyJWTClients: tc.hasStaticPrivateKey, + SPIFFEX509ClientAuthentication: tc.spiffeX509, + SPIFFEJWTClientAuthentication: tc.spiffeJWT, }) // OAuth AS metadata endpoint. @@ -466,17 +485,20 @@ func TestDiscoveryHandlers_InboundGrantCapabilities(t *testing.T) { name string disableTokenExchange bool jwtBearerGrantEnabled bool + clientCredentials bool }{ {name: "historical token exchange default"}, {name: "token exchange and JWT bearer", jwtBearerGrantEnabled: true}, {name: "all inbound grants disabled", disableTokenExchange: true}, {name: "JWT bearer independent of token exchange", disableTokenExchange: true, jwtBearerGrantEnabled: true}, + {name: "SPIFFE client credentials", clientCredentials: true}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() handler := testSetupWithOptions(t, testSetupOptions{ - DisableTokenExchange: tc.disableTokenExchange, - JWTBearerGrantEnabled: tc.jwtBearerGrantEnabled, + DisableTokenExchange: tc.disableTokenExchange, + JWTBearerGrantEnabled: tc.jwtBearerGrantEnabled, + SPIFFEClientCredentialsGrant: tc.clientCredentials, }) for _, endpoint := range []struct { @@ -499,6 +521,8 @@ func TestDiscoveryHandlers_InboundGrantCapabilities(t *testing.T) { slices.Contains(meta.GrantTypesSupported, sharedobauth.GrantTypeTokenExchange)) assert.Equal(t, tc.jwtBearerGrantEnabled, slices.Contains(meta.GrantTypesSupported, sharedobauth.GrantTypeJWTBearer)) + assert.Equal(t, tc.clientCredentials, + slices.Contains(meta.GrantTypesSupported, sharedobauth.GrantTypeClientCredentials)) }) } }) diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index e2e439c2e3..12aae7ff09 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -192,11 +192,11 @@ type AuthorizationServerConfig struct { // registration and is used by DCR validation and discovery advertisement. AllowPrivateKeyJWTRegistration bool // HasStaticConfidentialClients indicates whether any pre-provisioned - // confidential client exists at startup. Today only delegate clients count, - // whatever their auth method; SPIFFE association clients are deliberately - // not counted. It counts for the cleartext-transport check. It does not - // drive discovery; see HasStaticSecretClients and - // HasStaticPrivateKeyJWTClients. + // confidential client exists at startup: a delegate client of any auth + // method, or a SPIFFE association that allows the JWT-SVID method (a bearer + // credential) and grants client_credentials. It counts for the + // cleartext-transport check. It does not drive discovery; see + // HasStaticSecretClients and HasStaticPrivateKeyJWTClients. HasStaticConfidentialClients bool // HasStaticSecretClients indicates whether any pre-provisioned delegate // client authenticates with a client secret (an empty, client_secret_basic @@ -209,6 +209,16 @@ type AuthorizationServerConfig struct { // delegate client authenticates with private_key_jwt. Discovery advertises // that method and its signing algorithms when this is true. HasStaticPrivateKeyJWTClients bool + // SupportsSPIFFEX509ClientAuthentication reports whether some SPIFFE + // association enables the spiffe_x509 client authentication method. + SupportsSPIFFEX509ClientAuthentication bool + // SupportsSPIFFEJWTClientAuthentication reports whether some SPIFFE + // association enables the spiffe_jwt client authentication method. + SupportsSPIFFEJWTClientAuthentication bool + // SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE + // association grants client_credentials. It decides both whether the grant + // handler is registered and whether discovery advertises the grant. + SupportsSPIFFEClientCredentialsGrant bool // InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible // with confidential clients. InsecureAllowHTTP bool @@ -318,11 +328,11 @@ type AuthorizationServerParams struct { // registration and is used by DCR validation and discovery advertisement. AllowPrivateKeyJWTRegistration bool // HasStaticConfidentialClients indicates whether any pre-provisioned - // confidential client exists at startup. Today only delegate clients count, - // whatever their auth method; SPIFFE association clients are deliberately - // not counted. It counts for the cleartext-transport check. It does not - // drive discovery; see HasStaticSecretClients and - // HasStaticPrivateKeyJWTClients. + // confidential client exists at startup: a delegate client of any auth + // method, or a SPIFFE association that allows the JWT-SVID method (a bearer + // credential) and grants client_credentials. It counts for the + // cleartext-transport check. It does not drive discovery; see + // HasStaticSecretClients and HasStaticPrivateKeyJWTClients. HasStaticConfidentialClients bool // HasStaticSecretClients indicates whether any pre-provisioned delegate // client authenticates with a client secret (an empty, client_secret_basic @@ -335,6 +345,16 @@ type AuthorizationServerParams struct { // delegate client authenticates with private_key_jwt. Discovery advertises // that method and its signing algorithms when this is true. HasStaticPrivateKeyJWTClients bool + // SupportsSPIFFEX509ClientAuthentication reports whether some SPIFFE + // association enables the spiffe_x509 client authentication method. + SupportsSPIFFEX509ClientAuthentication bool + // SupportsSPIFFEJWTClientAuthentication reports whether some SPIFFE + // association enables the spiffe_jwt client authentication method. + SupportsSPIFFEJWTClientAuthentication bool + // SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE + // association grants client_credentials. It decides both whether the grant + // handler is registered and whether discovery advertises the grant. + SupportsSPIFFEClientCredentialsGrant bool // InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible // with confidential clients. InsecureAllowHTTP bool @@ -446,7 +466,8 @@ func validateTokenLifespans(cfg *AuthorizationServerParams) error { // ValidateConfidentialClientTransport rejects cleartext HTTP configurations // when any confidential client is enabled, whether it is admitted through DCR // or statically declared. Statically declared delegate clients always count, -// regardless of their authentication method. +// regardless of their authentication method, as do SPIFFE associations that +// allow the JWT-SVID method and grant client_credentials. func ValidateConfidentialClientTransport( allowConfidential, insecureAllowHTTP bool, issuer string, insecureAllowConfidentialOverLoopbackHTTP bool, @@ -455,7 +476,9 @@ func ValidateConfidentialClientTransport( return nil } if insecureAllowHTTP { - return fmt.Errorf("confidential clients (allow_confidential_client_registration or delegate clients) " + + return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + + "delegate clients or JWT-SVID SPIFFE associations " + + "that grant client_credentials) " + "cannot be combined with insecure_allow_http: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } @@ -475,18 +498,24 @@ func ValidateConfidentialClientTransport( return fmt.Errorf("confidential clients require a valid issuer URL") } if insecureAllowConfidentialOverLoopbackHTTP && !networking.IsLocalhost(parsed.Host) { - return fmt.Errorf("confidential clients (allow_confidential_client_registration or delegate clients) " + + return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + + "delegate clients or JWT-SVID SPIFFE associations " + + "that grant client_credentials) " + "cannot use the loopback HTTP opt-in with a non-loopback issuer: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } if !insecureAllowConfidentialOverLoopbackHTTP && networking.IsLocalhost(parsed.Host) { - return fmt.Errorf("confidential clients (allow_confidential_client_registration or delegate clients) " + + return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + + "delegate clients or JWT-SVID SPIFFE associations " + + "that grant client_credentials) " + "cannot be combined with a plain-HTTP loopback issuer unless " + "insecure_allow_confidential_over_loopback_http is set: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } if !networking.IsLocalhost(parsed.Host) { - return fmt.Errorf("confidential clients (allow_confidential_client_registration or delegate clients) " + + return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + + "delegate clients or JWT-SVID SPIFFE associations " + + "that grant client_credentials) " + "cannot use a plain-HTTP non-loopback issuer: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } @@ -639,6 +668,9 @@ func NewAuthorizationServerConfig(cfg *AuthorizationServerParams) (*Authorizatio HasStaticConfidentialClients: cfg.HasStaticConfidentialClients, HasStaticSecretClients: cfg.HasStaticSecretClients, HasStaticPrivateKeyJWTClients: cfg.HasStaticPrivateKeyJWTClients, + SupportsSPIFFEX509ClientAuthentication: cfg.SupportsSPIFFEX509ClientAuthentication, + SupportsSPIFFEJWTClientAuthentication: cfg.SupportsSPIFFEJWTClientAuthentication, + SupportsSPIFFEClientCredentialsGrant: cfg.SupportsSPIFFEClientCredentialsGrant, InsecureAllowHTTP: cfg.InsecureAllowHTTP, InsecureAllowConfidentialOverLoopbackHTTP: cfg.InsecureAllowConfidentialOverLoopbackHTTP, ForceConfidentialRedirectURIs: cfg.ForceConfidentialRedirectURIs, diff --git a/pkg/authserver/server/provider_spiffe_x509_test.go b/pkg/authserver/server/provider_spiffe_x509_test.go index 71046a4592..c5daab5332 100644 --- a/pkg/authserver/server/provider_spiffe_x509_test.go +++ b/pkg/authserver/server/provider_spiffe_x509_test.go @@ -70,7 +70,7 @@ func TestNewAuthorizationServerSPIFFEX509ClientAuthentication(t *testing.T) { t.Parallel() resolverCalls := 0 - resolver := func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + resolver := func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { resolverCalls++ return resolvedClient, nil } diff --git a/pkg/authserver/server/registration/authenticated_spiffe_client.go b/pkg/authserver/server/registration/authenticated_spiffe_client.go index e88459c034..642427cac3 100644 --- a/pkg/authserver/server/registration/authenticated_spiffe_client.go +++ b/pkg/authserver/server/registration/authenticated_spiffe_client.go @@ -5,6 +5,7 @@ package registration import ( "fmt" + "time" "github.com/ory/fosite" "github.com/spiffe/go-spiffe/v2/spiffeid" @@ -23,14 +24,16 @@ type staticSPIFFEClient = SPIFFEClient // request is what tells grant handlers a workload credential was verified. type AuthenticatedSPIFFEClient struct { *staticSPIFFEClient - spiffeID spiffeid.ID - method spiffeauth.SPIFFEAuthenticationMethod + spiffeID spiffeid.ID + method spiffeauth.SPIFFEAuthenticationMethod + credentialExpiry time.Time } // NewAuthenticatedSPIFFEClient binds a static SPIFFE client to the verified -// SPIFFE ID and authentication method of the workload. +// SPIFFE ID and authentication method of the workload. credentialExpiry is when +// the verified SVID stops being valid and must not be zero. func NewAuthenticatedSPIFFEClient( - client *SPIFFEClient, id spiffeid.ID, method spiffeauth.SPIFFEAuthenticationMethod, + client *SPIFFEClient, id spiffeid.ID, method spiffeauth.SPIFFEAuthenticationMethod, credentialExpiry time.Time, ) (*AuthenticatedSPIFFEClient, error) { if client == nil { return nil, fmt.Errorf("SPIFFE client is required") @@ -41,7 +44,12 @@ func NewAuthenticatedSPIFFEClient( if method != spiffeauth.SPIFFEAuthenticationMethodX509 && method != spiffeauth.SPIFFEAuthenticationMethodJWT { return nil, fmt.Errorf("unknown SPIFFE authentication method %q", method) } - return &AuthenticatedSPIFFEClient{staticSPIFFEClient: client, spiffeID: id, method: method}, nil + if credentialExpiry.IsZero() { + return nil, fmt.Errorf("credential expiry is required") + } + return &AuthenticatedSPIFFEClient{ + staticSPIFFEClient: client, spiffeID: id, method: method, credentialExpiry: credentialExpiry, + }, nil } // SPIFFEID returns the verified SPIFFE ID of the workload. @@ -52,4 +60,7 @@ func (c *AuthenticatedSPIFFEClient) AuthenticationMethod() spiffeauth.SPIFFEAuth return c.method } +// CredentialExpiry returns when the verified SVID stops being valid. +func (c *AuthenticatedSPIFFEClient) CredentialExpiry() time.Time { return c.credentialExpiry } + var _ fosite.Client = (*AuthenticatedSPIFFEClient)(nil) diff --git a/pkg/authserver/server/registration/spiffe_client.go b/pkg/authserver/server/registration/spiffe_client.go index 6ed17ad7a3..bdcdf66572 100644 --- a/pkg/authserver/server/registration/spiffe_client.go +++ b/pkg/authserver/server/registration/spiffe_client.go @@ -64,8 +64,8 @@ func (*SPIFFEClient) GetResponseTypes() fosite.Arguments { return nil } func (c *SPIFFEClient) GetScopes() fosite.Arguments { return slices.Clone(c.scopes) } // Resources returns a copy of the allowed RFC 8707 resource request values. -// Token exchange checks the "resource" request parameter against this, never -// against GetAudience. +// Token exchange and client_credentials check the "resource" request parameter +// against this, never against GetAudience. func (c *SPIFFEClient) Resources() []string { return slices.Clone(c.resources) } // GetAudience returns nil: SPIFFE clients carry no audience allowlist. diff --git a/pkg/authserver/server/registration/spiffe_client_test.go b/pkg/authserver/server/registration/spiffe_client_test.go index feb1fec13d..f9ef90e433 100644 --- a/pkg/authserver/server/registration/spiffe_client_test.go +++ b/pkg/authserver/server/registration/spiffe_client_test.go @@ -5,6 +5,7 @@ package registration import ( "testing" + "time" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/stretchr/testify/assert" @@ -86,24 +87,27 @@ func TestNewAuthenticatedSPIFFEClient(t *testing.T) { []string{"openid"}, []string{"https://resource.example.com"}) require.NoError(t, err) id := spiffeid.RequireFromString("spiffe://example.org/workload/concrete") + expiry := time.Now().Add(time.Hour) tests := []struct { name string client *SPIFFEClient id spiffeid.ID method spiffeauth.SPIFFEAuthenticationMethod + expiry time.Time wantErr string }{ - {name: "JWT", client: static, id: id, method: spiffeauth.SPIFFEAuthenticationMethodJWT}, - {name: "X.509", client: static, id: id, method: spiffeauth.SPIFFEAuthenticationMethodX509}, - {name: "nil client", id: id, method: spiffeauth.SPIFFEAuthenticationMethodJWT, wantErr: "SPIFFE client is required"}, - {name: "zero ID", client: static, method: spiffeauth.SPIFFEAuthenticationMethodJWT, wantErr: "SPIFFE ID is required"}, - {name: "unknown method", client: static, id: id, method: "unknown", wantErr: "unknown SPIFFE authentication method"}, + {name: "JWT", client: static, id: id, method: spiffeauth.SPIFFEAuthenticationMethodJWT, expiry: expiry}, + {name: "X.509", client: static, id: id, method: spiffeauth.SPIFFEAuthenticationMethodX509, expiry: expiry}, + {name: "nil client", id: id, method: spiffeauth.SPIFFEAuthenticationMethodJWT, expiry: expiry, wantErr: "SPIFFE client is required"}, + {name: "zero ID", client: static, method: spiffeauth.SPIFFEAuthenticationMethodJWT, expiry: expiry, wantErr: "SPIFFE ID is required"}, + {name: "unknown method", client: static, id: id, method: "unknown", expiry: expiry, wantErr: "unknown SPIFFE authentication method"}, + {name: "zero expiry", client: static, id: id, method: spiffeauth.SPIFFEAuthenticationMethodJWT, wantErr: "credential expiry is required"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - got, err := NewAuthenticatedSPIFFEClient(tt.client, tt.id, tt.method) + got, err := NewAuthenticatedSPIFFEClient(tt.client, tt.id, tt.method, tt.expiry) if tt.wantErr != "" { require.ErrorContains(t, err, tt.wantErr) assert.Nil(t, got) @@ -112,6 +116,7 @@ func TestNewAuthenticatedSPIFFEClient(t *testing.T) { require.NoError(t, err) assert.Equal(t, id, got.SPIFFEID()) assert.Equal(t, tt.method, got.AuthenticationMethod()) + assert.Equal(t, expiry, got.CredentialExpiry()) assert.Equal(t, static.GetID(), got.GetID()) assert.Equal(t, static.GetGrantTypes(), got.GetGrantTypes()) assert.Equal(t, static.GetScopes(), got.GetScopes()) diff --git a/pkg/authserver/server/spiffe_client_auth.go b/pkg/authserver/server/spiffe_client_auth.go index 2df318566a..aa3d0f9a57 100644 --- a/pkg/authserver/server/spiffe_client_auth.go +++ b/pkg/authserver/server/spiffe_client_auth.go @@ -58,9 +58,12 @@ var ( // explicit discriminator, so the two arms share a single resolution path // instead of each inventing its own. spiffeID is passed explicitly rather // than pulled from ctx, so an identity resolved from the wrong source cannot -// be mistaken for a verified one. +// be mistaken for a verified one. credentialExpiry is the expiry of the +// verified SVID (the X.509 leaf's NotAfter or the JWT-SVID's exp); the resolver +// carries it on the client so grant handlers can bound token lifetimes by it. type SPIFFEClientResolver func( ctx context.Context, spiffeID, clientID string, method spiffeauth.SPIFFEAuthenticationMethod, + credentialExpiry time.Time, ) (fosite.Client, error) // SPIFFEX509ClientMatcher reports whether clientID names an association that @@ -147,13 +150,15 @@ func authenticateSPIFFEX509Client( "stage", "mixed credentials", "client_id", clientID) return nil, fosite.ErrInvalidClient } - verifiedID, err := verifySPIFFEX509(r, source) + verifiedID, credentialExpiry, err := verifySPIFFEX509(r, source) if err != nil { slog.Debug("SPIFFE X.509 client authentication rejected", "stage", "certificate verification", "error", err, "client_id", clientID) return nil, fosite.ErrInvalidClient } - client, err := resolver(ctx, verifiedID.String(), clientID, spiffeauth.SPIFFEAuthenticationMethodX509) + client, err := resolver( + ctx, verifiedID.String(), clientID, spiffeauth.SPIFFEAuthenticationMethodX509, credentialExpiry, + ) if !validResolvedSPIFFEClient(client, err, clientID) { slog.Debug("SPIFFE X.509 client authentication rejected", "stage", "resolver", "error", err, "client_id", clientID, "spiffe_id", verifiedID.String()) @@ -184,32 +189,32 @@ func rejectedSPIFFEX509Request(r *http.Request, form url.Values) bool { // and a leaf without exactly one URI SAN. A chain longer than // maxClientCertificateChainLength is rejected first. A missing or malformed certificate // is always rejected; there is no fallback to public or secret-based client -// authentication. -func verifySPIFFEX509(r *http.Request, source x509bundle.Source) (spiffeid.ID, error) { +// authentication. It also returns the leaf certificate's NotAfter, the SVID expiry. +func verifySPIFFEX509(r *http.Request, source x509bundle.Source) (spiffeid.ID, time.Time, error) { if source == nil || r.TLS == nil || len(r.TLS.PeerCertificates) == 0 { - return spiffeid.ID{}, errClientCertificateRequired + return spiffeid.ID{}, time.Time{}, errClientCertificateRequired } if len(r.TLS.PeerCertificates) > maxClientCertificateChainLength { - return spiffeid.ID{}, errClientChainTooLong + return spiffeid.ID{}, time.Time{}, errClientChainTooLong } leaf := r.TLS.PeerCertificates[0] id, err := spiffeauth.SPIFFEIDFromCertificate(leaf) if err != nil { - return spiffeid.ID{}, err + return spiffeid.ID{}, time.Time{}, err } if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 { - return spiffeid.ID{}, fmt.Errorf("%w: key usage lacks digitalSignature", errInvalidX509SVIDLeaf) + return spiffeid.ID{}, time.Time{}, fmt.Errorf("%w: key usage lacks digitalSignature", errInvalidX509SVIDLeaf) } if err := validSPIFFEX509RequiredExtensions(leaf); err != nil { - return spiffeid.ID{}, err + return spiffeid.ID{}, time.Time{}, err } if err := validSPIFFEX509ExtendedKeyUsage(leaf); err != nil { - return spiffeid.ID{}, err + return spiffeid.ID{}, time.Time{}, err } if _, _, err := x509svid.Verify(r.TLS.PeerCertificates, source); err != nil { - return spiffeid.ID{}, err + return spiffeid.ID{}, time.Time{}, err } - return id, nil + return id, leaf.NotAfter, nil } // validSPIFFEX509RequiredExtensions checks that the leaf has a critical @@ -318,7 +323,9 @@ func authenticateSPIFFEJWTClient( "stage", "assertion lifetime exceeds limit", "client_id", clientID, "spiffe_id", svid.ID.String()) return nil, fosite.ErrInvalidClient } - client, err := resolver(ctx, svid.ID.String(), clientID, spiffeauth.SPIFFEAuthenticationMethodJWT) + client, err := resolver( + ctx, svid.ID.String(), clientID, spiffeauth.SPIFFEAuthenticationMethodJWT, svid.Expiry, + ) if !validResolvedSPIFFEClient(client, err, clientID) { slog.Debug("SPIFFE JWT-SVID client authentication rejected", "stage", "resolver", "error", err, "client_id", clientID, "spiffe_id", svid.ID.String()) diff --git a/pkg/authserver/server/spiffe_client_auth_test.go b/pkg/authserver/server/spiffe_client_auth_test.go index eef0f34369..6561082217 100644 --- a/pkg/authserver/server/spiffe_client_auth_test.go +++ b/pkg/authserver/server/spiffe_client_auth_test.go @@ -37,7 +37,7 @@ const testIssuer = "https://auth.example.com" // stubResolver is a SPIFFEClientResolver that is never called by these tests; // it exists only to make "resolver configured" distinguishable from "resolver // nil" for the client-authentication strategy under test. -func stubResolver(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { +func stubResolver(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { panic("not called") } @@ -291,7 +291,7 @@ func TestSPIFFEJWTClientAuthentication(t *testing.T) { return nil, nil }, testIssuer, tt.source, nil, - func(_ context.Context, gotSPIFFEID, clientID string, method spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + func(_ context.Context, gotSPIFFEID, clientID string, method spiffeauth.SPIFFEAuthenticationMethod, _ time.Time) (fosite.Client, error) { called = true assert.Equal(t, id.String(), gotSPIFFEID) assert.Equal(t, spiffeauth.SPIFFEAuthenticationMethodJWT, method) @@ -360,7 +360,7 @@ func TestSPIFFEJWTClientAuthenticationAlgorithms(t *testing.T) { return nil, nil }, testIssuer, source, nil, - func(_ context.Context, gotSPIFFEID, _ string, method spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + func(_ context.Context, gotSPIFFEID, _ string, method spiffeauth.SPIFFEAuthenticationMethod, _ time.Time) (fosite.Client, error) { assert.Equal(t, id.String(), gotSPIFFEID) assert.Equal(t, spiffeauth.SPIFFEAuthenticationMethodJWT, method) return &fosite.DefaultClient{ID: "client"}, nil @@ -376,6 +376,34 @@ func TestSPIFFEJWTClientAuthenticationAlgorithms(t *testing.T) { } } +func TestSPIFFEJWTClientAuthPassesSVIDExpiryToResolver(t *testing.T) { + t.Parallel() + + id := spiffeid.RequireFromString("spiffe://example.org/workload/my-service") + key := mustRSAKey(t) + claims := claimsExpiringIn(id, 5*time.Minute) + token := signedJWT(t, jose.RS256, key, "key-1", "JWT", claims) + source := jwtbundle.NewSet(jwtbundle.FromJWTAuthorities(id.TrustDomain(), map[string]crypto.PublicKey{"key-1": key.Public()})) + + var gotExpiry time.Time + strategy := newSPIFFEClientAuthenticationStrategy( + func(context.Context, *http.Request, url.Values) (fosite.Client, error) { + t.Fatal("default strategy called") + return nil, nil + }, + testIssuer, source, nil, + func(_ context.Context, _, _ string, _ spiffeauth.SPIFFEAuthenticationMethod, expiry time.Time) (fosite.Client, error) { + gotExpiry = expiry + return &fosite.DefaultClient{ID: "client"}, nil + }, + nil, + ) + + _, err := strategy(context.Background(), httptest.NewRequest(http.MethodPost, "/", nil), jwtForm(token)) + require.NoError(t, err) + assert.True(t, gotExpiry.Equal(claims.Expiry.Time()), "got %s, want the assertion's exp %s", gotExpiry, claims.Expiry.Time()) +} + func TestSPIFFEJWTDispatchRejectsDuplicateAssertionType(t *testing.T) { t.Parallel() diff --git a/pkg/authserver/server/spiffe_client_auth_x509_test.go b/pkg/authserver/server/spiffe_client_auth_x509_test.go index 19a983b710..eda8d516c3 100644 --- a/pkg/authserver/server/spiffe_client_auth_x509_test.go +++ b/pkg/authserver/server/spiffe_client_auth_x509_test.go @@ -53,7 +53,8 @@ func TestSPIFFEX509ClientAuthentication(t *testing.T) { form: url.Values{"client_id": {"spiffe-client"}}, certificate: certificate, source: source, - resolve: func(_ context.Context, identity, clientID string, method spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + resolve: func(_ context.Context, identity, clientID string, method spiffeauth.SPIFFEAuthenticationMethod, expiry time.Time) (fosite.Client, error) { + assert.Equal(t, certificate.NotAfter, expiry, "the leaf's NotAfter is the credential expiry") assert.Equal(t, spiffeID.String(), identity) assert.Equal(t, "spiffe-client", clientID) assert.Equal(t, spiffeauth.SPIFFEAuthenticationMethodX509, method) @@ -80,7 +81,7 @@ func TestSPIFFEX509ClientAuthentication(t *testing.T) { form: url.Values{"client_id": {"spiffe-client"}}, certificate: certificate, source: source, - resolve: func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + resolve: func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { return nil, errors.New("association not found") }, wantErrIs: fosite.ErrInvalidClient, @@ -91,7 +92,7 @@ func TestSPIFFEX509ClientAuthentication(t *testing.T) { form: url.Values{"client_id": {"spiffe-client"}}, certificate: certificate, source: source, - resolve: func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + resolve: func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { return &fosite.DefaultClient{ID: "other-client"}, nil }, wantErrIs: fosite.ErrInvalidClient, @@ -153,13 +154,13 @@ func TestSPIFFEX509ClientAuthentication(t *testing.T) { defaultCalled := false resolve := tt.resolve if resolve == nil { - resolve = func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + resolve = func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { return nil, errors.New("unexpected resolver call") } } - wrapped := func(ctx context.Context, identity, clientID string, method spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + wrapped := func(ctx context.Context, identity, clientID string, method spiffeauth.SPIFFEAuthenticationMethod, expiry time.Time) (fosite.Client, error) { resolverCalled = true - return resolve(ctx, identity, clientID, method) + return resolve(ctx, identity, clientID, method, expiry) } strategy := newSPIFFEClientAuthenticationStrategy( func(_ context.Context, _ *http.Request, _ url.Values) (fosite.Client, error) { @@ -405,7 +406,7 @@ func TestVerifySPIFFEX509(t *testing.T) { request, source := tt.build(t) - verifiedID, err := verifySPIFFEX509(request, source) + verifiedID, _, err := verifySPIFFEX509(request, source) switch tt.want { case wantRequired: @@ -461,7 +462,7 @@ func TestSPIFFEX509ClientAuthenticationFollowsBundleRotation(t *testing.T) { return nil, nil }, testIssuer, nil, live, - func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod) (fosite.Client, error) { + func(context.Context, string, string, spiffeauth.SPIFFEAuthenticationMethod, time.Time) (fosite.Client, error) { resolverCalls++ return resolvedClient, nil }, diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index c78867abf7..2d8646f8cc 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -16,11 +16,13 @@ import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" "github.com/ory/x/errorsx" + "github.com/spiffe/go-spiffe/v2/spiffeid" coreaudit "github.com/stacklok/toolhive-core/audit" "github.com/stacklok/toolhive/pkg/authserver/authorizationdetails" "github.com/stacklok/toolhive/pkg/authserver/claimnames" "github.com/stacklok/toolhive/pkg/authserver/server" + "github.com/stacklok/toolhive/pkg/authserver/server/registration" "github.com/stacklok/toolhive/pkg/authserver/server/session" "github.com/stacklok/toolhive/pkg/oauthproto" ) @@ -395,7 +397,11 @@ func (h *Handler) authorizeDelegation( return err } } - if err := checkDelegationConsent(validatedClaims, client.GetID(), actorSub, configuredDelegate); err != nil { + spiffeID := "" + if spiffeClient, ok := client.(*registration.AuthenticatedSPIFFEClient); ok { + spiffeID = spiffeClient.SPIFFEID().String() + } + if err := checkDelegationConsent(validatedClaims, client.GetID(), actorSub, spiffeID, configuredDelegate); err != nil { return err } @@ -435,6 +441,13 @@ func (h *Handler) authorizeDelegation( // actor identity still has to satisfy checkDelegationConsent (may_act, // ExternalActor, client_id binding, or the configured-delegate exemption) // like any other actor identity would. +// +// An authenticated SPIFFE client is held to a stricter rule: a wildcard +// association gives many workloads one client ID, so the client_id claim alone +// would let workload B present workload A's client_credentials token as its +// actor_token and become act.sub = A. For such a caller the actor token's sub +// must therefore also equal the caller's verified SPIFFE ID, which means it +// cannot assert a different actor. func (h *Handler) resolveActorIdentity( ctx context.Context, params *formParams, client fosite.Client, ) (string, error) { @@ -456,6 +469,13 @@ func (h *Handler) resolveActorIdentity( return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint( "The actor token's client_id claim does not match the authenticated client identity.")) } + if spiffeClient, ok := client.(*registration.AuthenticatedSPIFFEClient); ok && + actorClaims.Subject != spiffeClient.SPIFFEID().String() { + slog.Debug("Actor token subject does not match the authenticated workload", + "client_id", client.GetID()) + return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint( + "The actor token's subject does not match the authenticated workload.")) + } return actorClaims.Subject, nil } @@ -850,7 +870,20 @@ func sourceClientAllowed(validatedClaims *ValidatedClaims, clientID string, poli // If none of the three consent sources apply, the subject token carries no // verifiable binding to any client at all — this fails closed (CWE-863) // rather than allowing an unbound token through. -func checkDelegationConsent(validatedClaims *ValidatedClaims, clientID, actorSub string, configuredDelegate bool) error { +// +// spiffeID is the verified SPIFFE ID of an authenticated SPIFFE client, empty +// for every other client. A wildcard association gives many workloads the same +// client ID, so for a SPIFFE client the client_id binding in case 3 alone would +// let workload B exchange workload A's token and obtain sub = A. For that case, +// when the subject token names a workload (its sub or outermost act.sub is a +// SPIFFE ID), it must name this one: its sub must be spiffeID, or its outermost +// act.sub must be. A token that names only a user and the client ID (act.sub is +// the client ID) can be exchanged by any workload of that client, because the +// user consented to the client. The may_act and external actor cases name +// their party explicitly and are unaffected. +func checkDelegationConsent( + validatedClaims *ValidatedClaims, clientID, actorSub, spiffeID string, configuredDelegate bool, +) error { // selfIssuedDelegate is true only when a configured delegate client is // presenting a self-issued token (ExternalIssuer == "" rules out the // external-issuer path explicitly, rather than relying on ExternalActor @@ -903,10 +936,38 @@ func checkDelegationConsent(validatedClaims *ValidatedClaims, clientID, actorSub case validatedClaims.ClientID == "": return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint( "The subject token carries no verifiable client binding: it has neither a 'may_act' claim nor a 'client_id' claim.")) + case isAnotherWorkloadsToken(validatedClaims, clientID, spiffeID): + return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint( + "The subject token was issued to a different workload of this client.")) } return nil } +// isAnotherWorkloadsToken reports whether a ToolHive-issued subject token that +// is bound to clientID names a SPIFFE workload other than spiffeID. A token +// names a workload when its sub or the sub of its outermost act entry parses as +// a SPIFFE ID; it then belongs to the caller only if one of those two is +// spiffeID. A token that names only a user and the client ID (act.sub is the +// client ID) names no workload, so it is never another workload's token. It is +// false for a caller that is not a SPIFFE client (empty spiffeID). +func isAnotherWorkloadsToken(validatedClaims *ValidatedClaims, clientID, spiffeID string) bool { + if spiffeID == "" || validatedClaims.ExternalIssuer != "" || validatedClaims.ClientID != clientID { + return false + } + act, _ := validatedClaims.Extra["act"].(map[string]any) + actSub, _ := act["sub"].(string) + if !isSPIFFEID(validatedClaims.Subject) && !isSPIFFEID(actSub) { + return false + } + return validatedClaims.Subject != spiffeID && actSub != spiffeID +} + +// isSPIFFEID reports whether s is a well-formed SPIFFE ID. +func isSPIFFEID(s string) bool { + _, err := spiffeid.FromString(s) + return err == nil +} + // grantScopes validates that each requested scope is allowed for both the // client and the subject token, granting the intersection. The delegated // token's scope set is the intersection of the client's registered scopes diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index 5a2d3dc0ef..7d0d625863 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -1976,7 +1976,8 @@ func TestCheckDelegationConsent(t *testing.T) { // that test the clientID/actorSub split itself. clientID string actorSub string - configuredDelegate bool // defaults to false, reproducing pre-delegate-exception behavior + spiffeID string // verified SPIFFE ID of the caller; empty for a non-SPIFFE client + configuredDelegate bool // defaults to false, reproducing pre-delegate-exception behavior wantErr bool errContains string }{ @@ -2211,6 +2212,99 @@ func TestCheckDelegationConsent(t *testing.T) { wantErr: true, errContains: "different client", }, + { + // A wildcard association gives both workloads this client ID. + name: "SPIFFE client exchanging its own client_credentials token accepted", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "spiffe://example.org/ns/default/agent-a", + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-a", + }, + { + name: "SPIFFE client exchanging a sibling workload's token rejected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "spiffe://example.org/ns/default/agent-a", + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-b", + wantErr: true, + errContains: "different workload", + }, + { + name: "SPIFFE client re-exchanging a token whose act.sub is its SPIFFE ID accepted", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "user-1", + Extra: map[string]any{"act": map[string]any{"sub": "spiffe://example.org/ns/default/agent-a"}}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-a", + }, + { + name: "SPIFFE client re-exchanging its own delegated token whose act.sub is the client ID accepted", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "user-1", + Extra: map[string]any{"act": map[string]any{"sub": "wildcard-client"}}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-a", + }, + { + // Consent was given to the client, and RFC 8693 has no notion of + // instances within one client. + name: "SPIFFE client re-exchanging a sibling's delegated token whose act.sub is the client ID accepted", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "user-1", + Extra: map[string]any{"act": map[string]any{"sub": "wildcard-client"}}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-b", + }, + { + name: "SPIFFE client exchanging a sibling's exchanged token {sub: A, act.sub: client ID} rejected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "spiffe://example.org/ns/default/agent-a", + Extra: map[string]any{"act": map[string]any{"sub": "wildcard-client"}}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-b", + wantErr: true, + errContains: "different workload", + }, + { + name: "SPIFFE client re-exchanging a token whose act.sub names a sibling workload rejected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "user-1", + Extra: map[string]any{"act": map[string]any{"sub": "spiffe://example.org/ns/default/agent-a"}}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-b", + wantErr: true, + errContains: "different workload", + }, + { + name: "SPIFFE client with may_act naming it is unaffected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "user-1", MayAct: &MayActClaim{Sub: "wildcard-client"}, + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-a", + }, + { + name: "SPIFFE client with an external issuer token is unaffected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "ext-user", ExternalIssuer: "https://idp.example.com", + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + spiffeID: "spiffe://example.org/ns/default/agent-a", + }, + { + name: "non-SPIFFE client with another subject is unaffected", + claims: &ValidatedClaims{ + ClientID: "wildcard-client", Subject: "spiffe://example.org/ns/default/agent-a", + }, + clientID: "wildcard-client", actorSub: "wildcard-client", + }, } for _, tt := range tests { @@ -2223,7 +2317,7 @@ func TestCheckDelegationConsent(t *testing.T) { if actorSub == "" { actorSub = actorID } - err := checkDelegationConsent(tt.claims, clientID, actorSub, tt.configuredDelegate) + err := checkDelegationConsent(tt.claims, clientID, actorSub, tt.spiffeID, tt.configuredDelegate) if tt.wantErr { require.Error(t, err) var rfcErr *fosite.RFC6749Error @@ -3228,6 +3322,162 @@ func TestGrantAndBoundAudiences_SPIFFEClient(t *testing.T) { } } +// TestHandleTokenEndpointRequest_SPIFFESubjectTokenOwnership proves the SPIFFE +// ID of the caller reaches the consent check: two workloads share one client ID +// through a wildcard association, and only the one a client_credentials token +// was issued to may exchange it. +func TestHandleTokenEndpointRequest_SPIFFESubjectTokenOwnership(t *testing.T) { + t.Parallel() + + const ( + workloadA = "spiffe://example.org/ns/default/agent-a" + workloadB = "spiffe://example.org/ns/default/agent-b" + ) + tests := []struct { + name string + caller string + act map[string]any + sub string + wantErr bool + }{ + {name: "the workload the token was issued to", caller: workloadA, sub: workloadA}, + {name: "a sibling workload with the same client ID", caller: workloadB, sub: workloadA, wantErr: true}, + { + name: "a sibling re-exchanging a token naming the workload in sub and the client in act", + caller: workloadB, sub: workloadA, act: map[string]any{"sub": testAgentClientID}, wantErr: true, + }, + { + name: "the workload re-exchanging its own user-delegated token", + caller: workloadA, sub: "user-123", act: map[string]any{"sub": testAgentClientID}, + }, + { + name: "a sibling re-exchanging a user-delegated token that names only the client", + caller: workloadB, sub: "user-123", act: map[string]any{"sub": testAgentClientID}, + }, + { + name: "a sibling re-exchanging a user token whose act.sub names the workload", + caller: workloadB, sub: "user-123", act: map[string]any{"sub": workloadA}, wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tj := newTestJWKS(t) + h := newTestHandler(t, tj, time.Hour) + claims := validClaims() + claims.Subject = tt.sub + extra := validExtraClaims() + if tt.act != nil { + extra["act"] = tt.act + } + form := url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {tj.signToken(t, claims, extra)}, + "subject_token_type": {oauthproto.TokenTypeAccessToken}, + "resource": {testIssuer}, + } + client := spiffetest.AuthenticatedClient(t, + spiffetest.WithID(testAgentClientID), spiffetest.WithSPIFFEID(tt.caller), + spiffetest.WithResources(testIssuer)) + req := newAccessRequest(t, client, form) + + err := h.HandleTokenEndpointRequest(context.Background(), req) + + if tt.wantErr { + require.ErrorIs(t, err, fosite.ErrInvalidGrant) + assert.Contains(t, fosite.ErrorToRFC6749Error(err).HintField, "different workload") + return + } + require.NoError(t, err) + }) + } +} + +// TestHandleTokenEndpointRequest_SPIFFEActorToken proves an authenticated SPIFFE +// caller can only present an actor_token whose subject is its own SPIFFE ID, so +// a sibling workload cannot borrow another workload's identity as act.sub or to +// satisfy a may_act claim. +func TestHandleTokenEndpointRequest_SPIFFEActorToken(t *testing.T) { + t.Parallel() + + const ( + workloadA = "spiffe://example.org/ns/default/agent-a" + workloadB = "spiffe://example.org/ns/default/agent-b" + ) + tests := []struct { + name string + caller string + actorSubject string + mayAct string + wantErr error + wantHint string + wantActSub string + }{ + { + name: "caller presents its own client_credentials token", caller: workloadA, + actorSubject: workloadA, wantActSub: workloadA, + }, + { + name: "caller presents a sibling's client_credentials token", caller: workloadB, + actorSubject: workloadA, wantErr: fosite.ErrInvalidRequest, + wantHint: "does not match the authenticated workload", + }, + { + name: "sibling cannot satisfy a may_act naming the other workload", caller: workloadB, + actorSubject: workloadA, mayAct: workloadA, wantErr: fosite.ErrInvalidRequest, + wantHint: "does not match the authenticated workload", + }, + { + name: "caller's own actor token satisfies a may_act naming it", caller: workloadA, + actorSubject: workloadA, mayAct: workloadA, wantActSub: workloadA, + }, + { + name: "caller cannot assert a distinct actor", caller: workloadA, + actorSubject: "other-agent", wantErr: fosite.ErrInvalidRequest, + wantHint: "does not match the authenticated workload", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tj := newTestJWKS(t) + h := newTestHandler(t, tj, time.Hour) + extra := validExtraClaims() + if tt.mayAct != "" { + extra["may_act"] = map[string]any{"sub": tt.mayAct} + } + form := url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {tj.signToken(t, validClaims(), extra)}, + "subject_token_type": {oauthproto.TokenTypeAccessToken}, + "actor_token": {signActorToken(t, tj, tt.actorSubject)}, + "actor_token_type": {oauthproto.TokenTypeJWT}, + "resource": {testIssuer}, + } + client := spiffetest.AuthenticatedClient(t, + spiffetest.WithID(testAgentClientID), spiffetest.WithSPIFFEID(tt.caller), + spiffetest.WithResources(testIssuer)) + req := newAccessRequest(t, client, form) + + err := h.HandleTokenEndpointRequest(context.Background(), req) + + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr) + assert.Contains(t, fosite.ErrorToRFC6749Error(err).HintField, tt.wantHint) + return + } + require.NoError(t, err) + sess, ok := req.GetSession().(*session.Session) + require.True(t, ok) + act, ok := sess.JWTClaims.Extra["act"].(map[string]interface{}) + require.True(t, ok, "act claim must be a map") + assert.Equal(t, tt.wantActSub, act["sub"]) + }) + } +} + // TestGrantAndBoundAudiences_DelegateClientKeepsGenericPath proves a // non-SPIFFE client may still send audience= and still gets the default // audience when it sends no target. diff --git a/pkg/authserver/server/tokenexchange/refresh_token_handler.go b/pkg/authserver/server/tokenexchange/refresh_token_handler.go index a16f1d20cc..b3ff123fc8 100644 --- a/pkg/authserver/server/tokenexchange/refresh_token_handler.go +++ b/pkg/authserver/server/tokenexchange/refresh_token_handler.go @@ -833,8 +833,9 @@ func loginSubjectError(reason string) error { // checkLoginToken reports why a validated subject token is not a user login // access token, or "" if it is. A refresh token of any kind needs this, because // the token is tied to a real login. A token minted by token exchange (act), by -// the JWT-bearer or ID-JAG grant (external subject or no upstream session) is -// refused, since its subject did not log in here. +// the JWT-bearer or ID-JAG grant (external subject or no upstream session), or +// by client_credentials (no upstream session), is refused, since its subject +// did not log in here. // // The jti is checked here because a later profile must share the single-use // (iss, jti) marker, so one login access token cannot open one grant of each diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index b1f32284e1..5dabc97535 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -23,6 +23,7 @@ import ( "github.com/stacklok/toolhive/pkg/authserver/internal/consentpolicy" oauthserver "github.com/stacklok/toolhive/pkg/authserver/server" + "github.com/stacklok/toolhive/pkg/authserver/server/clientcredentials" "github.com/stacklok/toolhive/pkg/authserver/server/deviceflow" "github.com/stacklok/toolhive/pkg/authserver/server/handlers" "github.com/stacklok/toolhive/pkg/authserver/server/keys" @@ -228,6 +229,9 @@ func authorizationServerParams( InsecureAllowConfidentialOverLoopbackHTTP: cfg.InsecureAllowConfidentialOverLoopbackHTTP, ForceConfidentialRedirectURIs: cfg.ForceConfidentialRedirectURIs, HasStaticPrivateKeyJWTClients: hasPrivateKeyJWTDelegateClient(cfg.DelegateClients), + SupportsSPIFFEX509ClientAuthentication: cfg.SPIFFETrust.permitsMethod(SPIFFEAuthenticationMethodX509), + SupportsSPIFFEJWTClientAuthentication: cfg.SPIFFETrust.permitsMethod(SPIFFEAuthenticationMethodJWT), + SupportsSPIFFEClientCredentialsGrant: cfg.SPIFFETrust.permitsGrant(oauthproto.GrantTypeClientCredentials), DisableTokenExchange: cfg.DisableTokenExchange, JWTBearerGrantEnabled: JWTBearerGrantEnabled(cfg.TrustedIssuers), DeviceFlowEnabled: cfg.DeviceFlowEnabled, @@ -434,9 +438,10 @@ func explicitGrantClientIDs(clients []DelegateClient) []string { // idJAGExplicitGrantClientIDs lists the clients whose registered grant_types // the ID-JAG handler enforces: delegate clients that set grant_types // explicitly, and every configured SPIFFE association client. SPIFFE -// associations are gated too because their static clients are restricted to -// token-exchange; without this, a jwt-bearer ID-JAG bound to such a client_id -// would redeem despite the association's grant policy. DCR and CIMD clients +// associations are gated too because their static clients carry only the +// grants the association declares, never jwt-bearer; without this, a +// jwt-bearer ID-JAG bound to such a client_id would redeem despite the +// association's grant policy. DCR and CIMD clients // are deliberately not in the set and are not held to their grant types. func idJAGExplicitGrantClientIDs(cfg Config) []string { ids := explicitGrantClientIDs(cfg.DelegateClients) @@ -611,8 +616,9 @@ func newSPIFFEClientResolver(registry *SPIFFEAssociationRegistry) oauthserver.SP } return func( _ context.Context, spiffeID, clientID string, method spiffeauth.SPIFFEAuthenticationMethod, + credentialExpiry time.Time, ) (fosite.Client, error) { - client, err := registry.Resolve(spiffeID, clientID, method) + client, err := registry.Resolve(spiffeID, clientID, method, credentialExpiry) if err != nil { return nil, err } @@ -811,10 +817,12 @@ func discoverExchangeGrantStorage( } // buildProvider assembles the fosite OAuth2 provider, registering the RFC 8693 -// token-exchange handler and/or the RFC 7523 JWT-bearer handler as extension -// grants alongside the standard grants -- whichever of the two are enabled -// for cfg (token exchange can be disabled via canonical inbound grants -// configuration; JWT-bearer is enabled per JWTBearerGrantEnabled). +// token-exchange handler, the RFC 7523 JWT-bearer handler, and the SPIFFE +// client-credentials handler as extension grants alongside the standard +// grants -- each registered only when cfg enables it (token exchange can be +// disabled via canonical inbound grants configuration; JWT-bearer is enabled +// per JWTBearerGrantEnabled; client credentials when a SPIFFE association +// permits it, see SPIFFETrustConfig.permitsGrant). // // refresher is the server's shared upstream token refresher (nil without // upstreams) and upstreams are the resolved upstreams it refreshes, both used @@ -895,6 +903,7 @@ func buildProvider( } factories = append(factories, deviceFlowFactory) } + factories = append(factories, buildSPIFFEGrantFactories(authServerConfig.SupportsSPIFFEClientCredentialsGrant)...) // Refresh-grant validators go last so each runs after the built-in refresh // handler has validated the grant. validators, err := refreshGrantValidatorChain(cfg, stor, refresher, upstreams) @@ -909,6 +918,16 @@ func buildProvider( return provider, shared, nil } +// buildSPIFFEGrantFactories returns the grant factories SPIFFE associations +// need beyond token exchange: the client_credentials handler, only when an +// association grants it. +func buildSPIFFEGrantFactories(clientCredentials bool) []oauthserver.Factory { + if !clientCredentials { + return nil + } + return []oauthserver.Factory{clientcredentials.Factory()} +} + // buildTokenExchangeFactories builds the RFC 8693 token-exchange factory // together with the factory that issues refresh tokens through token exchange. // It returns none when token exchange is disabled. diff --git a/pkg/authserver/spiffe_association_registry.go b/pkg/authserver/spiffe_association_registry.go index cf28046150..584b0a2703 100644 --- a/pkg/authserver/spiffe_association_registry.go +++ b/pkg/authserver/spiffe_association_registry.go @@ -8,7 +8,9 @@ import ( "encoding/hex" "fmt" "slices" + "strconv" "strings" + "time" "github.com/ory/fosite" @@ -81,9 +83,10 @@ func NewSPIFFEAssociationRegistry(trust *SPIFFETrustConfig) (*SPIFFEAssociationR // clientID must match the association's client ID. It fails closed for // unknown IDs, mismatched client ownership, and disabled methods. This // method does not validate a credential: the caller must have verified the -// SVID, because the returned client asserts that it was. +// SVID, because the returned client asserts that it was. credentialExpiry is +// the verified SVID's expiry, carried on the returned client. func (r *SPIFFEAssociationRegistry) Resolve( - spiffeID, clientID string, method SPIFFEAuthenticationMethod, + spiffeID, clientID string, method SPIFFEAuthenticationMethod, credentialExpiry time.Time, ) (*registration.AuthenticatedSPIFFEClient, error) { if r == nil { return nil, fmt.Errorf("no SPIFFE associations are configured") @@ -106,7 +109,9 @@ func (r *SPIFFEAssociationRegistry) Resolve( ) } - return registration.NewAuthenticatedSPIFFEClient(r.clients[association.ClientID()].SPIFFEClient, parsedID, method) + return registration.NewAuthenticatedSPIFFEClient( + r.clients[association.ClientID()].SPIFFEClient, parsedID, method, credentialExpiry, + ) } // usesX509 reports whether clientID names an association whose methods include @@ -167,13 +172,15 @@ func (r *SPIFFEAssociationRegistry) staticClients() map[string]fosite.Client { } // fingerprintSPIFFEAssociation hashes the SPIFFE association identity (trust -// domain reference, principal pattern, and accepted methods). Storage compares -// it only to set identity_changed in the replacement WARN when an edited -// association replaces its placeholder. Each value is +// domain reference, principal pattern, grant types, and accepted methods). +// Storage compares it only to set identity_changed in the replacement WARN +// when an edited association replaces its placeholder. Each value is // length-prefixed with an unambiguous decimal-and-colon marker so -// concatenation can't alias two different value sequences to the same hash, -// and methods are sorted first so their original order never affects the -// result. +// concatenation can't alias two different value sequences to the same hash. +// Grant types and methods are each sorted before hashing so their original +// order never affects the result. The grant-type count is written before the +// grant types, since methods follow them with no count and the boundary would +// otherwise be ambiguous. // // Note: TrustDomainRef() hashes the trust-domain *reference name* (e.g. // "production"), not the trust domain value itself. In practice this doesn't @@ -190,6 +197,12 @@ func fingerprintSPIFFEAssociation(association SPIFFEClientAuthConfig) string { } write(association.TrustDomainRef()) write(association.Principal()) + grantTypes := association.AuthorizationPolicy().GrantTypes() + slices.Sort(grantTypes) + write(strconv.Itoa(len(grantTypes))) + for _, grantType := range grantTypes { + write(grantType) + } methods := association.Methods() slices.Sort(methods) for _, method := range methods { diff --git a/pkg/authserver/spiffe_association_registry_test.go b/pkg/authserver/spiffe_association_registry_test.go index be9a48980c..7ec6bec043 100644 --- a/pkg/authserver/spiffe_association_registry_test.go +++ b/pkg/authserver/spiffe_association_registry_test.go @@ -5,6 +5,7 @@ package authserver import ( "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -112,11 +113,12 @@ func TestSPIFFEAssociationRegistryResolve(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() + expiry := time.Now().Add(time.Hour) var registry *SPIFFEAssociationRegistry if !tt.nilRegistry { registry = newTestSPIFFEAssociationRegistry(t, tt.associations) } - client, err := registry.Resolve(tt.spiffeID, tt.clientID, tt.method) + client, err := registry.Resolve(tt.spiffeID, tt.clientID, tt.method, expiry) if tt.wantErr != "" { require.ErrorContains(t, err, tt.wantErr) assert.Nil(t, client) @@ -131,6 +133,7 @@ func TestSPIFFEAssociationRegistryResolve(t *testing.T) { assert.Equal(t, tt.spiffeID, client.SPIFFEID().String()) assert.Equal(t, "example.org", client.SPIFFEID().TrustDomain().String()) assert.Equal(t, tt.method, client.AuthenticationMethod()) + assert.Equal(t, expiry, client.CredentialExpiry()) assert.Equal(t, []string{tt.wantScope}, []string(client.GetScopes())) assert.Equal(t, []string{oauthproto.GrantTypeTokenExchange}, []string(client.GetGrantTypes())) wantResource := tt.wantResource @@ -147,6 +150,7 @@ func TestSPIFFEAssociationRegistryResolve(t *testing.T) { spiffetest.WithResources(wantResource...), spiffetest.WithSPIFFEID(tt.spiffeID), spiffetest.WithAuthMethod(tt.method), + spiffetest.WithCredentialExpiry(expiry), ) assert.Equal(t, want, client) }) @@ -338,6 +342,60 @@ func TestSPIFFEAssociationFingerprintFieldsDoNotConcatenateAmbiguously(t *testin assert.NotEqual(t, a, b, "length prefixing must keep field boundaries unambiguous") } +func TestSPIFFEAssociationFingerprintCoversGrantTypes(t *testing.T) { + t.Parallel() + + withGrants := func(grantTypes ...string) SPIFFEClientAuthConfig { + return SPIFFEClientAuthConfig{ + trustDomainRef: "production", + principal: "spiffe://example.org/ns/default/agent", + authorization: SPIFFEAuthorizationPolicy{grantTypes: grantTypes}, + } + } + methodOnly := withGrants() + methodOnly.methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509} + + tests := []struct { + name string + a, b SPIFFEClientAuthConfig + wantEqual bool + }{ + { + name: "grant-types-only change differs", + a: withGrants(oauthproto.GrantTypeTokenExchange), + b: withGrants(oauthproto.GrantTypeClientCredentials), + }, + { + name: "grant type order is ignored", + a: withGrants(oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeClientCredentials), + b: withGrants(oauthproto.GrantTypeClientCredentials, oauthproto.GrantTypeTokenExchange), + wantEqual: true, + }, + { + // Built directly because config validation admits only known grant types. + name: "length prefix keeps grant type boundaries unambiguous", + a: withGrants("a", "bc"), + b: withGrants("ab", "c"), + }, + { + name: "grant type cannot alias a method at the list boundary", + a: withGrants(string(SPIFFEAuthenticationMethodX509)), + b: methodOnly, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + fa, fb := fingerprintSPIFFEAssociation(tt.a), fingerprintSPIFFEAssociation(tt.b) + if tt.wantEqual { + assert.Equal(t, fa, fb) + } else { + assert.NotEqual(t, fa, fb) + } + }) + } +} + // TestNewSPIFFEAssociationRegistryRejectsOverlappingPatterns proves // NewSPIFFEAssociationRegistry itself fails closed when two associations' // patterns could both match the same concrete SPIFFE ID, since resolution at @@ -405,7 +463,7 @@ func testNormalizedSPIFFEAssociation(clientID, principal string) SPIFFEClientAut clientID: clientID, methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, authorization: SPIFFEAuthorizationPolicy{ - grantTypes: []string{SPIFFEGrantTypeTokenExchange}, scopes: []string{"openid"}, + grantTypes: []string{oauthproto.GrantTypeTokenExchange}, scopes: []string{"openid"}, }, } } @@ -439,6 +497,6 @@ func testSPIFFEAssociation(clientID, scope string) SPIFFEClientAuthRunConfig { Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, Scopes: []string{scope}, Resources: []string{"https://audience.example.com"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, } } diff --git a/pkg/authserver/spiffe_client_credentials_integration_test.go b/pkg/authserver/spiffe_client_credentials_integration_test.go new file mode 100644 index 0000000000..c2a2eb176b --- /dev/null +++ b/pkg/authserver/spiffe_client_credentials_integration_test.go @@ -0,0 +1,382 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "math/big" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/claimnames" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" + spiffeauth "github.com/stacklok/toolhive/pkg/authserver/spiffe" + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +const ( + ccTestResource = "https://resource.example.com" + ccTestAudience = "https://audience.example.com" + ccJWTSPIFFEID = "spiffe://example.org/ns/default/jwt-agent" + ccX509SPIFFEID = "spiffe://example.org/ns/default/x509-agent" + ccJWTClientID = "spiffe-jwt-client" + ccX509ClientID = "spiffe-x509-client" + ccDelegateID = "delegate-client" + ccDelegateSec = "delegate-secret-value-0123456789abcdef" +) + +// ccFixture is an auth server built through newServer, so the SPIFFE storage +// decorator, association registry, client resolver and bundle source are the +// production ones. +type ccFixture struct { + handler http.Handler + // tokenKey verifies access tokens; jwtKey signs JWT-SVIDs; leaf is an + // X.509-SVID for ccX509SPIFFEID that outlives the access-token lifespan; + // shortLeaf is the same identity with five minutes left. + tokenKey *rsa.PrivateKey + jwtKey *ecdsa.PrivateKey + leaf *x509.Certificate + shortLeaf *x509.Certificate +} + +func newCCFixture(t *testing.T) *ccFixture { + t.Helper() + + jwtKey := mustCCECKey(t) + caKey := mustCCECKey(t) + now := time.Now() + caTemplate := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "test CA"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(4 * time.Hour), + IsCA: true, + BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + } + caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) + require.NoError(t, err) + ca, err := x509.ParseCertificate(caDER) + require.NoError(t, err) + spiffeURL, err := url.Parse(ccX509SPIFFEID) + require.NoError(t, err) + leafKey := mustCCECKey(t) + newLeaf := func(serial int64, notAfter time.Time) *x509.Certificate { + leafDER, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ + SerialNumber: big.NewInt(serial), + Subject: pkix.Name{CommonName: "test workload"}, + NotBefore: now.Add(-time.Hour), + NotAfter: notAfter, + KeyUsage: x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + URIs: []*url.URL{spiffeURL}, + }, ca, &leafKey.PublicKey, caKey) + require.NoError(t, err) + leaf, err := x509.ParseCertificate(leafDER) + require.NoError(t, err) + return leaf + } + leaf := newLeaf(2, now.Add(3*time.Hour)) + shortLeaf := newLeaf(3, now.Add(5*time.Minute)) + + bundleJSON, err := json.Marshal(map[string]any{ + "spiffe_sequence": 1, + "keys": []jose.JSONWebKey{ + {Key: &jwtKey.PublicKey, KeyID: "jwt-key", Use: "jwt-svid"}, + {Key: &caKey.PublicKey, KeyID: "x509-key", Use: "x509-svid", Certificates: []*x509.Certificate{ca}}, + }, + }) + require.NoError(t, err) + dir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + bundlePath := filepath.Join(dir, "bundle.json") + require.NoError(t, os.WriteFile(bundlePath, bundleJSON, 0o600)) + + association := func(clientID, principal string, method SPIFFEAuthenticationMethod) SPIFFEClientAuthRunConfig { + return SPIFFEClientAuthRunConfig{ + TrustDomainRef: "production", + PrincipalPattern: principal, + ClientID: clientID, + Methods: []SPIFFEAuthenticationMethod{method}, + GrantTypes: []string{oauthproto.GrantTypeClientCredentials}, + Scopes: []string{"openid"}, + Resources: []string{ccTestResource}, + Audiences: []string{ccTestAudience}, + } + } + trust, err := NewSPIFFETrustConfig([]SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509, SPIFFEAuthenticationMethodJWT}, + BundleSource: SPIFFEBundleSourceRunConfig{ + Type: SPIFFEBundleSourceTypeFile, + File: &SPIFFEFileBundleSourceRunConfig{Path: bundlePath}, + }, + }}, &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{ + association(ccJWTClientID, ccJWTSPIFFEID, SPIFFEAuthenticationMethodJWT), + association(ccX509ClientID, ccX509SPIFFEID, SPIFFEAuthenticationMethodX509), + }}, []string{"openid"}, []string{ccTestResource, ccTestAudience}) + require.NoError(t, err) + + secret := make([]byte, 32) + _, err = rand.Read(secret) + require.NoError(t, err) + tokenKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + stor := storage.NewMemoryStorage() + t.Cleanup(func() { _ = stor.Close() }) + srv, err := newServer(context.Background(), Config{ + Issuer: testIssuer, + KeyProvider: &testKeyProvider{key: tokenKey}, + HMACSecrets: servercrypto.NewHMACSecrets(secret), + AccessTokenLifespan: time.Hour, + RefreshTokenLifespan: 24 * time.Hour, + AuthCodeLifespan: 10 * time.Minute, + ScopesSupported: []string{"openid"}, + AllowedAudiences: []string{ccTestResource, ccTestAudience}, + SPIFFETrust: trust, + // The issuer is a plain-HTTP loopback URL, and both the delegate client's + // secret and the JWT-SVID association are confidential credentials. + InsecureAllowConfidentialOverLoopbackHTTP: true, + DelegateClients: []DelegateClient{{ + ClientID: ccDelegateID, + ClientSecret: ccDelegateSec, + Scopes: []string{"openid"}, + Audiences: []string{ccTestAudience}, + }}, + }, stor) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, srv.Close()) }) + + return &ccFixture{handler: srv.Handler(), tokenKey: tokenKey, jwtKey: jwtKey, leaf: leaf, shortLeaf: shortLeaf} +} + +func mustCCECKey(t *testing.T) *ecdsa.PrivateKey { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + return key +} + +func (f *ccFixture) jwtSVID(t *testing.T, spiffeID string) string { + t.Helper() + return f.jwtSVIDExpiringIn(t, spiffeID, time.Minute) +} + +func (f *ccFixture) jwtSVIDExpiringIn(t *testing.T, spiffeID string, validity time.Duration) string { + t.Helper() + signer, err := jose.NewSigner( + jose.SigningKey{Algorithm: jose.ES256, Key: f.jwtKey}, + (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "jwt-key"), + ) + require.NoError(t, err) + token, err := jwt.Signed(signer).Claims(jwt.Claims{ + Subject: spiffeID, + Audience: jwt.Audience{testIssuer}, + Expiry: jwt.NewNumericDate(time.Now().Add(validity)), + }).Serialize() + require.NoError(t, err) + return token +} + +func (f *ccFixture) postToken(t *testing.T, form url.Values, peer *x509.Certificate) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, testIssuer+"/oauth/token", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if peer != nil { + req.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{peer}} + } + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, req) + return rec +} + +func (f *ccFixture) accessTokenClaims(t *testing.T, raw string) map[string]any { + t.Helper() + parsed, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.RS256}) + require.NoError(t, err) + var claims map[string]any + require.NoError(t, parsed.Claims(f.tokenKey.Public(), &claims)) + return claims +} + +func decodeCCBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + var body map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body), rec.Body.String()) + return body +} + +// TestSPIFFEClientCredentialsThroughNewServer drives the grant through newServer +// with the real SPIFFE storage decorator and resolver. Stored SPIFFE clients are +// wrapped by the decorator; a resolver that asserts the bare type rejects every +// SPIFFE request, which only a test on this path can catch. +func TestSPIFFEClientCredentialsThroughNewServer(t *testing.T) { + t.Parallel() + f := newCCFixture(t) + + tests := []struct { + name string + form func(t *testing.T) url.Values + peer *x509.Certificate + wantCode int + wantError string + wantSub string + wantCID string + }{ + { + name: "JWT-SVID issues an access token for the SPIFFE ID", + form: func(t *testing.T) url.Values { + t.Helper() + return url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_assertion_type": {spiffeauth.SPIFFEJWTAssertionType}, + "client_assertion": {f.jwtSVID(t, ccJWTSPIFFEID)}, + "resource": {ccTestResource}, + "scope": {"openid"}, + } + }, + wantCode: http.StatusOK, + wantSub: ccJWTSPIFFEID, + wantCID: ccJWTClientID, + }, + { + name: "X.509-SVID issues an access token for the SPIFFE ID", + form: func(*testing.T) url.Values { + return url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_id": {ccX509ClientID}, + "resource": {ccTestResource}, + "scope": {"openid"}, + } + }, + peer: f.leaf, + wantCode: http.StatusOK, + wantSub: ccX509SPIFFEID, + wantCID: ccX509ClientID, + }, + { + name: "delegate client with a secret is unauthorized_client", + form: func(*testing.T) url.Values { + return url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_id": {ccDelegateID}, + "client_secret": {ccDelegateSec}, + "resource": {ccTestAudience}, + } + }, + wantCode: http.StatusBadRequest, + wantError: "unauthorized_client", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rec := f.postToken(t, tt.form(t), tt.peer) + require.Equal(t, tt.wantCode, rec.Code, rec.Body.String()) + body := decodeCCBody(t, rec) + if tt.wantError != "" { + assert.Equal(t, tt.wantError, body["error"]) + assert.NotContains(t, body, "access_token") + return + } + + assert.NotContains(t, body, "refresh_token") + raw, ok := body["access_token"].(string) + require.True(t, ok, rec.Body.String()) + claims := f.accessTokenClaims(t, raw) + assert.Equal(t, tt.wantSub, claims["sub"]) + assert.Equal(t, tt.wantCID, claims["client_id"]) + assert.Equal(t, []any{ccTestResource}, claims["aud"], "aud is the requested resource, not the association audiences") + assert.Equal(t, []any{"openid"}, claims["scp"]) + assert.NotContains(t, claims, "scope") + assert.Equal(t, true, claims[claimnames.NoUpstreamSessionKey]) + }) + } +} + +// TestSPIFFEClientCredentialsTokenLifetime checks that the access token lives +// no longer than the SVID that authenticated the request, and no longer than +// the server's access-token lifespan (one hour in the fixture). +func TestSPIFFEClientCredentialsTokenLifetime(t *testing.T) { + t.Parallel() + f := newCCFixture(t) + + jwtForm := func(t *testing.T, validity time.Duration) url.Values { + t.Helper() + return url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_assertion_type": {spiffeauth.SPIFFEJWTAssertionType}, + "client_assertion": {f.jwtSVIDExpiringIn(t, ccJWTSPIFFEID, validity)}, + "resource": {ccTestResource}, + } + } + x509Form := url.Values{ + "grant_type": {oauthproto.GrantTypeClientCredentials}, + "client_id": {ccX509ClientID}, + "resource": {ccTestResource}, + } + + tests := []struct { + name string + form url.Values + peer *x509.Certificate + wantExpiresIn time.Duration + wantError string + }{ + {name: "JWT-SVID with a minute left caps the token", form: jwtForm(t, time.Minute), wantExpiresIn: time.Minute}, + {name: "JWT-SVID within the parser leeway after exp is refused", form: jwtForm(t, -30*time.Second), wantError: "invalid_grant"}, + {name: "short-lived X.509-SVID caps the token", form: x509Form, peer: f.shortLeaf, wantExpiresIn: 5 * time.Minute}, + {name: "X.509-SVID outliving the lifespan leaves the access-token lifespan", form: x509Form, peer: f.leaf, wantExpiresIn: time.Hour}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rec := f.postToken(t, tt.form, tt.peer) + body := decodeCCBody(t, rec) + if tt.wantError != "" { + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + assert.Equal(t, tt.wantError, body["error"]) + assert.NotContains(t, body, "access_token") + return + } + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + expiresIn, ok := body["expires_in"].(float64) + require.True(t, ok, rec.Body.String()) + // The fixture's certificates are minted before the request, and the + // race detector can slow the run, so allow a generous lower bound. + assert.InDelta(t, tt.wantExpiresIn.Seconds(), expiresIn, 30) + assert.LessOrEqual(t, expiresIn, tt.wantExpiresIn.Seconds()) + + raw, ok := body["access_token"].(string) + require.True(t, ok, rec.Body.String()) + exp, ok := f.accessTokenClaims(t, raw)["exp"].(float64) + require.True(t, ok) + assert.InDelta(t, float64(time.Now().Add(tt.wantExpiresIn).Unix()), exp, 30, "exp follows the capped expiry") + }) + } +} diff --git a/pkg/authserver/spiffe_client_resolver_test.go b/pkg/authserver/spiffe_client_resolver_test.go index ce4b98bd77..8f402d70d4 100644 --- a/pkg/authserver/spiffe_client_resolver_test.go +++ b/pkg/authserver/spiffe_client_resolver_test.go @@ -6,6 +6,7 @@ package authserver import ( "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -50,7 +51,7 @@ func TestNewSPIFFEClientResolver(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - got, err := resolver(context.Background(), tt.spiffeID, tt.clientID, tt.method) + got, err := resolver(context.Background(), tt.spiffeID, tt.clientID, tt.method, time.Now().Add(time.Hour)) if tt.wantErr { require.Error(t, err) assert.Nil(t, got, "an error must return a nil interface, not a typed nil") diff --git a/pkg/authserver/spiffe_provider_test.go b/pkg/authserver/spiffe_provider_test.go new file mode 100644 index 0000000000..f4ff70a30b --- /dev/null +++ b/pkg/authserver/spiffe_provider_test.go @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "testing" + "time" + + "github.com/ory/fosite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/authserver/server/clientcredentials" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" + "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +func TestBuildProviderRegistersSPIFFEClientCredentialsOnlyWhenPermitted(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + grants []string + wantHandler bool + }{ + { + name: "no SPIFFE trust", + }, + { + name: "token exchange only association", + grants: []string{oauthproto.GrantTypeTokenExchange}, + }, + { + name: "client credentials association", + grants: []string{oauthproto.GrantTypeClientCredentials}, + wantHandler: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + store := storage.NewMemoryStorage() + t.Cleanup(func() { _ = store.Close() }) + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + cfg := Config{ + Issuer: "https://auth.example.com", + KeyProvider: &testKeyProvider{key: key}, + HMACSecrets: servercrypto.NewHMACSecrets([]byte("test-secret-with-32-bytes-long!!")), + AccessTokenLifespan: time.Hour, + RefreshTokenLifespan: 24 * time.Hour, + AuthCodeLifespan: time.Minute, + DelegationTokenLifespan: 15 * time.Minute, + AllowedAudiences: []string{"https://resource.example.com"}, + } + if tt.grants != nil { + cfg.SPIFFETrust = providerTrust(tt.grants) + } + provider, err := BuildProviderForTest(context.Background(), cfg, store) + require.NoError(t, err) + // Read the handlers from the constructed provider, not the config + // passed in: NewAuthorizationServer works on its own independent + // copy of *fosite.Config (so concurrent constructions from a shared + // AuthorizationServerConfig cannot alias each other's handler + // slices), so factories registered during construction are visible + // only through the provider's own Config, not the caller's. + f, ok := provider.(*fosite.Fosite) + require.True(t, ok) + handlers := f.Config.GetTokenEndpointHandlers(context.Background()) + assert.Equal(t, tt.wantHandler, containsSPIFFEClientCredentialsHandler(handlers)) + }) + } +} + +// providerTrust builds the trust config directly: only the association's +// grant list matters to provider construction, and the run-config validation that +// would otherwise admit the association is not under test here. +func providerTrust(grants []string) *SPIFFETrustConfig { + return &SPIFFETrustConfig{associations: []SPIFFEClientAuthConfig{{ + clientID: "client", + authorization: SPIFFEAuthorizationPolicy{grantTypes: grants, scopes: []string{"openid"}}, + }}} +} + +func containsSPIFFEClientCredentialsHandler(handlers fosite.TokenEndpointHandlers) bool { + for _, handler := range handlers { + if _, ok := handler.(*clientcredentials.Handler); ok { + return true + } + } + return false +} diff --git a/pkg/authserver/spiffe_transport_test.go b/pkg/authserver/spiffe_transport_test.go new file mode 100644 index 0000000000..9941fa4aff --- /dev/null +++ b/pkg/authserver/spiffe_transport_test.go @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package authserver + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "testing" + "time" + + "github.com/stretchr/testify/require" + + oauthserver "github.com/stacklok/toolhive/pkg/authserver/server" + servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" + "github.com/stacklok/toolhive/pkg/oauthproto" +) + +// TestAuthorizationServerParamsGateSPIFFEJWTOnTransport pins that newServer's +// parameter mapping marks a JWT-SVID client_credentials association as a confidential client, so +// the provider's own transport check still refuses a plain-HTTP non-loopback +// issuer if Config.Validate is bypassed. +func TestAuthorizationServerParamsGateSPIFFEJWTOnTransport(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + trust *SPIFFETrustConfig + wantErr string + }{ + { + name: "JWT-SVID client_credentials association is refused", + trust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeClientCredentials), + wantErr: "plain-HTTP non-loopback", + }, + { + name: "JWT-SVID association with both grants is refused", + trust: mustNewSPIFFEJWTTrustConfig(t, + oauthproto.GrantTypeTokenExchange, oauthproto.GrantTypeClientCredentials), + wantErr: "plain-HTTP non-loopback", + }, + { + name: "JWT-SVID token-exchange-only association is unaffected", + trust: mustNewSPIFFEJWTTrustConfig(t, oauthproto.GrantTypeTokenExchange), + }, + {name: "X.509-only association is unaffected", trust: mustNewSPIFFETrustConfig(t)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + cfg := Config{ + Issuer: "http://auth.example.com", + KeyProvider: &testKeyProvider{key: key}, + HMACSecrets: servercrypto.NewHMACSecrets(make([]byte, 32)), + AccessTokenLifespan: time.Hour, + RefreshTokenLifespan: 24 * time.Hour, + AuthCodeLifespan: time.Minute, + AllowedAudiences: []string{"https://mcp.example.com"}, + SPIFFETrust: tt.trust, + } + signingKey, publicKeys, err := loadKeyMaterial(context.Background(), cfg.KeyProvider) + require.NoError(t, err) + + _, err = oauthserver.NewAuthorizationServerConfig( + authorizationServerParams(cfg, signingKey, publicKeys, nil, nil)) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + }) + } +} diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index 2dbbe62eb4..41c8181af2 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -9,6 +9,7 @@ import ( "net" "net/url" "path/filepath" + "regexp" "slices" "strings" @@ -27,10 +28,6 @@ const ( // SPIFFEAuthenticationMethodJWT authenticates a workload with a JWT-SVID. SPIFFEAuthenticationMethodJWT = spiffeauth.SPIFFEAuthenticationMethodJWT - // SPIFFEGrantTypeTokenExchange is the only SPIFFE client grant supported by - // this configuration surface. - SPIFFEGrantTypeTokenExchange = oauthproto.GrantTypeTokenExchange - // SPIFFEBundleSourceTypeEndpoint selects a HTTPS SPIFFE Bundle Endpoint. SPIFFEBundleSourceTypeEndpoint SPIFFEBundleSourceType = "bundle_endpoint" // SPIFFEBundleSourceTypeFile selects a locally mounted SPIFFE trust bundle. @@ -148,9 +145,9 @@ type SPIFFEClientAuthRunConfig struct { Methods []SPIFFEAuthenticationMethod `json:"methods" yaml:"methods"` // Resources are RFC 8707 resource indicators this association may - // 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 + // request. At least one is required for every association: both + // client_credentials and token exchange take exactly one resource per + // request and grant 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. @@ -411,6 +408,32 @@ func (c SPIFFEClientAuthConfig) AuthorizationPolicy() SPIFFEAuthorizationPolicy return c.authorization } +// permitsGrant reports whether any association lists grant. It is safe on a +// nil receiver. +func (c *SPIFFETrustConfig) permitsGrant(grant string) bool { + return slices.ContainsFunc(c.Associations(), func(a SPIFFEClientAuthConfig) bool { + return slices.Contains(a.AuthorizationPolicy().GrantTypes(), grant) + }) +} + +// permitsMethod reports whether any association allows method. It is safe on a +// nil receiver. +func (c *SPIFFETrustConfig) permitsMethod(method SPIFFEAuthenticationMethod) bool { + return slices.ContainsFunc(c.Associations(), func(a SPIFFEClientAuthConfig) bool { + return containsSPIFFEAuthenticationMethod(a.methods, method) + }) +} + +// permitsJWTClientCredentials reports whether any single association allows +// the JWT-SVID method and lists the client_credentials grant. It is safe on a +// nil receiver. +func (c *SPIFFETrustConfig) permitsJWTClientCredentials() bool { + return slices.ContainsFunc(c.Associations(), func(a SPIFFEClientAuthConfig) bool { + return containsSPIFFEAuthenticationMethod(a.methods, SPIFFEAuthenticationMethodJWT) && + slices.Contains(a.AuthorizationPolicy().GrantTypes(), oauthproto.GrantTypeClientCredentials) + }) +} + func (c SPIFFEClientAuthConfig) clone() SPIFFEClientAuthConfig { c.methods = slices.Clone(c.methods) return c @@ -629,6 +652,10 @@ func validateSPIFFEClientAuth( return nil } +// absoluteURLClientIDPattern matches the same client_id shape the operator CRD +// rejects, so a hand-written RunConfig is held to the same rule. +var absoluteURLClientIDPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*://.+`) + func validateSPIFFEClientAssociation( entry SPIFFEClientAuthRunConfig, index int, @@ -664,6 +691,12 @@ func validateSPIFFEClientAssociation( index, entry.ClientID, ) } + if absoluteURLClientIDPattern.MatchString(entry.ClientID) { + return "", fmt.Errorf( + "inbound_grants.spiffe_client_auth[%d]: client_id must not be an absolute URL: %q", + index, entry.ClientID, + ) + } fieldPrefix := fmt.Sprintf("inbound_grants.spiffe_client_auth[%d]", index) methods, err := validateMethods(entry.Methods, fieldPrefix+".methods") if err != nil { @@ -674,7 +707,7 @@ func validateSPIFFEClientAssociation( return "", fmt.Errorf("%s.methods: method %q is not enabled by trust domain %q", fieldPrefix, method, entry.TrustDomainRef) } } - if err := validateSPIFFEClientAssociationPermissions(entry, index, fieldPrefix, effectiveScopes, allowedResources); err != nil { + if err := validateSPIFFEClientAssociationPermissions(entry, fieldPrefix, effectiveScopes, allowedResources); err != nil { return "", err } return principal, nil @@ -686,7 +719,6 @@ func validateSPIFFEClientAssociation( // allowed_audiences allowlist. The deprecated audiences field is not checked. func validateSPIFFEClientAssociationPermissions( entry SPIFFEClientAuthRunConfig, - index int, fieldPrefix string, effectiveScopes []string, allowedResources []string, @@ -700,7 +732,7 @@ func validateSPIFFEClientAssociationPermissions( if err := registration.ValidateScopeSubset(entry.Scopes, effectiveScopes, fieldPrefix+".scopes"); err != nil { return err } - return validateSPIFFEGrants(entry.GrantTypes, index) + return validateSPIFFEGrantTypes(entry.GrantTypes, fieldPrefix+".grant_types") } func parseTrustDomain(trustDomain string) (spiffeid.TrustDomain, error) { @@ -787,9 +819,9 @@ func validateMethods(methods []SPIFFEAuthenticationMethod, field string) (map[SP } // validateSPIFFEResources validates the RFC 8707 resource indicators an -// 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 +// association may request. At least one is required: client_credentials and +// token exchange each take 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). @@ -848,12 +880,16 @@ func validateDistinctNonEmpty(values []string, field string) error { return nil } -func validateSPIFFEGrants(grants []string, index int) error { - if len(grants) != 1 || grants[0] != SPIFFEGrantTypeTokenExchange { - return fmt.Errorf( - "inbound_grants.spiffe_client_auth[%d].grant_types must be exactly [%q]", - index, SPIFFEGrantTypeTokenExchange, - ) +// validateSPIFFEGrantTypes requires a distinct, non-empty list naming only +// client_credentials and the RFC 8693 token-exchange grant. +func validateSPIFFEGrantTypes(grants []string, field string) error { + if err := validateDistinctNonEmpty(grants, field); err != nil { + return err + } + for _, grant := range grants { + if grant != oauthproto.GrantTypeClientCredentials && grant != oauthproto.GrantTypeTokenExchange { + return fmt.Errorf("%s: unknown grant %q", field, grant) + } } return nil } diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index 1716aafdb4..b660e5cd45 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stacklok/toolhive/pkg/authserver/storage" + "github.com/stacklok/toolhive/pkg/oauthproto" ) func TestNormalizeSPIFFEPrincipal(t *testing.T) { @@ -126,7 +127,12 @@ 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) { + {name: "empty resources rejected for token exchange only", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + grants.SPIFFEClientAuth[0].GrantTypes = []string{oauthproto.GrantTypeTokenExchange} + grants.SPIFFEClientAuth[0].Resources = nil + }, wantErr: "spiffe_client_auth[0].resources is required"}, + {name: "empty resources rejected for client_credentials", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + grants.SPIFFEClientAuth[0].GrantTypes = []string{oauthproto.GrantTypeClientCredentials} grants.SPIFFEClientAuth[0].Resources = nil }, wantErr: "spiffe_client_auth[0].resources is required"}, {name: "duplicate client", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { @@ -166,6 +172,12 @@ func TestValidateSPIFFETrust(t *testing.T) { {name: "client_id must not be a malformed client metadata document URL", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { grants.SPIFFEClientAuth[0].ClientID = "https://example.org/%zz" }, wantErr: "client_id must not be a client metadata document URL"}, + {name: "client_id must not be an absolute non-HTTP URL", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + grants.SPIFFEClientAuth[0].ClientID = "spiffe://example.org/reporting" + }, wantErr: "client_id must not be an absolute URL"}, + {name: "client_id without a scheme separator is accepted", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { + grants.SPIFFEClientAuth[0].ClientID = "urn:foo" + }}, {name: "scope must be supported", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { grants.SPIFFEClientAuth[0].Scopes = []string{"admin"} }, wantErr: "not in scopes_supported"}, @@ -175,12 +187,6 @@ func TestValidateSPIFFETrust(t *testing.T) { {name: "method not enabled by trust domain", mutate: func(domains []SPIFFETrustDomainRunConfig, _ *InboundGrantsRunConfig) { domains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} }, wantErr: "not enabled by trust domain"}, - {name: "grant_types must be exactly token exchange", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { - grants.SPIFFEClientAuth[0].GrantTypes = []string{"authorization_code"} - }, wantErr: "grant_types must be exactly"}, - {name: "grant_types is required", mutate: func(_ []SPIFFETrustDomainRunConfig, grants *InboundGrantsRunConfig) { - grants.SPIFFEClientAuth[0].GrantTypes = nil - }, wantErr: "grant_types must be exactly"}, {name: "bundle_source type is required", mutate: func(domains []SPIFFETrustDomainRunConfig, _ *InboundGrantsRunConfig) { domains[0].BundleSource = SPIFFEBundleSourceRunConfig{} }, wantErr: "unknown source type"}, @@ -229,6 +235,34 @@ func TestValidateSPIFFETrust(t *testing.T) { } } +func TestValidateSPIFFEGrantsMatrix(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + grants []string + wantErr string + }{ + {name: "client credentials only", grants: []string{oauthproto.GrantTypeClientCredentials}}, + {name: "token exchange only", grants: []string{oauthproto.GrantTypeTokenExchange}}, + {name: "both grants", grants: []string{oauthproto.GrantTypeClientCredentials, oauthproto.GrantTypeTokenExchange}}, + {name: "empty", wantErr: "is required"}, + {name: "duplicate", grants: []string{oauthproto.GrantTypeClientCredentials, oauthproto.GrantTypeClientCredentials}, wantErr: "duplicate"}, + {name: "unknown", grants: []string{"authorization_code"}, wantErr: "unknown grant"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := validateSPIFFEGrantTypes(tt.grants, "grant_types") + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + }) + } +} + func TestValidateSPIFFETrustRejectsDuplicateCanonicalTrustDomains(t *testing.T) { t.Parallel() @@ -318,6 +352,73 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { assert.False(t, ok) } +func TestJWTClientCredentialsAssociation(t *testing.T) { + t.Parallel() + + assoc := func(clientID string, method SPIFFEAuthenticationMethod, grants ...string) SPIFFEClientAuthRunConfig { + a := withPrincipal(testSPIFFEAssociation(clientID, "openid"), "spiffe://example.org/ns/default/"+clientID) + a.Methods = []SPIFFEAuthenticationMethod{method} + a.GrantTypes = grants + return a + } + const ( + tokenExchange = oauthproto.GrantTypeTokenExchange + clientCredentials = oauthproto.GrantTypeClientCredentials + ) + jwtCC := assoc("jwt-cc", SPIFFEAuthenticationMethodJWT, clientCredentials) + jwtBoth := assoc("jwt-both", SPIFFEAuthenticationMethodJWT, tokenExchange, clientCredentials) + jwtTE := assoc("jwt-te", SPIFFEAuthenticationMethodJWT, tokenExchange) + x509CC := assoc("x509-cc", SPIFFEAuthenticationMethodX509, clientCredentials) + x509TE := assoc("x509-te", SPIFFEAuthenticationMethodX509, tokenExchange) + + tests := []struct { + name string + associations []SPIFFEClientAuthRunConfig + want bool + }{ + {name: "no associations", want: false}, + {name: "JWT-SVID with client_credentials", associations: []SPIFFEClientAuthRunConfig{jwtCC}, want: true}, + {name: "JWT-SVID with both grants", associations: []SPIFFEClientAuthRunConfig{jwtBoth}, want: true}, + {name: "JWT-SVID token exchange only", associations: []SPIFFEClientAuthRunConfig{jwtTE}, want: false}, + {name: "X.509 with client_credentials", associations: []SPIFFEClientAuthRunConfig{x509CC}, want: false}, + {name: "X.509 token exchange only", associations: []SPIFFEClientAuthRunConfig{x509TE}, want: false}, + { + name: "method and grant on different associations", + associations: []SPIFFEClientAuthRunConfig{jwtTE, x509CC}, + want: false, + }, + { + name: "one qualifying association among others", + associations: []SPIFFEClientAuthRunConfig{x509TE, jwtTE, jwtCC}, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + runConfig := &RunConfig{InboundGrants: &InboundGrantsRunConfig{SPIFFEClientAuth: tt.associations}} + assert.Equal(t, tt.want, runConfig.hasJWTClientCredentialsAssociation()) + + if len(tt.associations) == 0 { + return + } + trust, err := NewSPIFFETrustConfig([]SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509, SPIFFEAuthenticationMethodJWT}, + BundleSource: validFileBundleSource(), + }}, runConfig.InboundGrants, []string{"openid"}, []string{"https://audience.example.com"}) + require.NoError(t, err) + assert.Equal(t, tt.want, trust.permitsJWTClientCredentials()) + }) + } + + assert.False(t, (*RunConfig)(nil).hasJWTClientCredentialsAssociation()) + assert.False(t, (&RunConfig{}).hasJWTClientCredentialsAssociation()) + assert.False(t, (*SPIFFETrustConfig)(nil).permitsJWTClientCredentials()) +} + //nolint:paralleltest // Swaps the process-wide default logger. func TestNewSPIFFETrustConfigWarnsOnDeprecatedAudiences(t *testing.T) { var logs bytes.Buffer diff --git a/pkg/authserver/storage/spiffe_decorator.go b/pkg/authserver/storage/spiffe_decorator.go index f4189609d1..0e0a7da658 100644 --- a/pkg/authserver/storage/spiffe_decorator.go +++ b/pkg/authserver/storage/spiffe_decorator.go @@ -96,8 +96,8 @@ type resourceScopedClient interface { // spiffeIdentityClient is implemented by fosite.Client types (e.g. // spiffeStaticClient) that carry a durable SPIFFE association identity -// fingerprint independent of OAuth policy. Mirrors resourceScopedClient's -// structural-matching pattern above. +// fingerprint covering trust domain ref, principal, grant types and methods. +// Mirrors resourceScopedClient's structural-matching pattern above. type spiffeIdentityClient interface { IdentityFingerprint() string } @@ -162,7 +162,8 @@ func isReservedPlaceholder(client fosite.Client) bool { // 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 (nil for SPIFFE clients), (RFC 8707) Resources, -// and SPIFFE association identity fingerprint so ReconcileConfiguredClient can tell +// and SPIFFE association identity fingerprint (covering trust domain ref, principal, +// grant types and methods) so ReconcileConfiguredClient can tell // "same association, restarted" (silent) from "changed association" // (replaced, with a WARN). // Scopes and Audience are taken directly from actual.GetScopes() / diff --git a/pkg/authserver/storage/types.go b/pkg/authserver/storage/types.go index 7eb1dc1aa6..c1c9612a7b 100644 --- a/pkg/authserver/storage/types.go +++ b/pkg/authserver/storage/types.go @@ -1029,8 +1029,9 @@ type clientFingerprint struct { // 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 - // is only populated for reserved rows. + // identityFingerprint is the SPIFFE association hash, covering trust + // domain ref, principal, grant types and methods. Like resources, it is + // only populated for reserved rows. identityFingerprint string public bool // reserved marks a SPIFFE static-client placeholder, as opposed to an diff --git a/pkg/authserver/storage/types_test.go b/pkg/authserver/storage/types_test.go index 3362d6fc79..2c6c3eda7c 100644 --- a/pkg/authserver/storage/types_test.go +++ b/pkg/authserver/storage/types_test.go @@ -412,7 +412,7 @@ func TestClientFingerprintFieldsAreJustified(t *testing.T) { "redirectURIs": "placeholders carry no redirect URIs; one appearing is a different client", "tokenEndpointAuthMethod": "placeholders never carry an auth method; one appearing is a different client", "resources": "a changed RFC 8707 resource allowlist is reported in the replacement WARN", - "identityFingerprint": "a different SPIFFE association identity (trust domain, principal, methods) " + + "identityFingerprint": "a different SPIFFE association identity (trust domain, principal, grant types, methods) " + "behind the same placeholder ID is reported in the replacement WARN", "public": "public vs. confidential is a different client class, refused for non-reserved clients", "reserved": "a SPIFFE-reserved placeholder and an ordinary configured client at the same ID " + diff --git a/pkg/oauthproto/constants.go b/pkg/oauthproto/constants.go index 61553af324..fc20aff1ea 100644 --- a/pkg/oauthproto/constants.go +++ b/pkg/oauthproto/constants.go @@ -36,6 +36,9 @@ const ( // Grant types as defined by RFC 6749. const ( + // GrantTypeClientCredentials is the client credentials grant (RFC 6749 Section 4.4). + GrantTypeClientCredentials = "client_credentials" + // GrantTypeAuthorizationCode is the authorization code grant type (RFC 6749 Section 4.1). GrantTypeAuthorizationCode = "authorization_code" @@ -49,7 +52,10 @@ const ( ResponseTypeCode = "code" ) -// Token endpoint authentication methods as defined by RFC 7591. +// Token endpoint authentication methods as defined by RFC 7591 and +// draft-ietf-oauth-spiffe-client-auth. +// +//nolint:gosec // G101: SPIFFE authentication-method identifiers are protocol constants, not credentials. const ( // TokenEndpointAuthMethodNone indicates no client authentication (public clients). // Typically used with PKCE for native/mobile applications. @@ -66,6 +72,14 @@ const ( // TokenEndpointAuthMethodPrivateKeyJWT authenticates with a signed client // assertion at the token endpoint (RFC 7523). TokenEndpointAuthMethodPrivateKeyJWT = "private_key_jwt" //nolint:gosec // G101: RFC 7591 auth-method identifier + + // TokenEndpointAuthMethodSPIFFEX509 authenticates with an X.509-SVID presented + // in the TLS handshake (draft-ietf-oauth-spiffe-client-auth Section 4). + TokenEndpointAuthMethodSPIFFEX509 = "spiffe_x509" + + // TokenEndpointAuthMethodSPIFFEJWT authenticates with a JWT-SVID sent as a + // client assertion (draft-ietf-oauth-spiffe-client-auth Section 4). + TokenEndpointAuthMethodSPIFFEJWT = "spiffe_jwt" ) // PKCE (Proof Key for Code Exchange) methods as defined by RFC 7636. diff --git a/pkg/runner/config_test.go b/pkg/runner/config_test.go index 35767a5689..cf15b926e2 100644 --- a/pkg/runner/config_test.go +++ b/pkg/runner/config_test.go @@ -29,6 +29,7 @@ import ( runtimemocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" "github.com/stacklok/toolhive/pkg/ignore" "github.com/stacklok/toolhive/pkg/networking" + "github.com/stacklok/toolhive/pkg/oauthproto" "github.com/stacklok/toolhive/pkg/secrets" secretsmocks "github.com/stacklok/toolhive/pkg/secrets/mocks" "github.com/stacklok/toolhive/pkg/telemetry" @@ -2349,7 +2350,7 @@ func TestRunConfig_WriteJSON_ReadJSON_EmbeddedAuthServer(t *testing.T) { Scopes: []string{"openid"}, Audiences: []string{"https://mcp.example.com"}, Resources: []string{"https://mcp.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, }, { TrustDomainRef: "development", @@ -2359,7 +2360,7 @@ func TestRunConfig_WriteJSON_ReadJSON_EmbeddedAuthServer(t *testing.T) { Scopes: []string{"profile"}, Audiences: []string{"https://api.example.com"}, Resources: []string{"https://api.example.com"}, - GrantTypes: []string{authserver.SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, }, }, }, diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index b9cd162916..df96c3c2dd 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -2396,9 +2396,9 @@ type AuthenticationSPIFFEClientAuthRunConfig struct { // the declared trust domain. PrincipalPattern OptString `json:"principal_pattern"` // Resources are RFC 8707 resource indicators this association may - // 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 + // request. At least one is required for every association: both + // client_credentials and token exchange take exactly one resource per + // request and grant 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. diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index 12bb66b13c..256d0bd4ca 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -860,7 +860,7 @@ "type": "string" }, "resources": { - "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.", + "description": "Resources are RFC 8707 resource indicators this association may\nrequest. At least one is required for every association: both\nclient_credentials and token exchange take exactly one resource per\nrequest and grant it as the token 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 e07425b222..9ad9d2d4a7 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -1164,9 +1164,9 @@ components: resources: description: |- Resources are RFC 8707 resource indicators this association may - 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 + request. At least one is required for every association: both + client_credentials and token exchange take exactly one resource per + request and grant 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.