From cddba8a003367c2954a563d4b81bb9685a99897e Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 20:36:47 +0100 Subject: [PATCH 01/14] Add the SPIFFE client_credentials handler SPIFFE-authenticated workloads can only exchange tokens today. A workload with no user to act for needs a plain client_credentials grant bound to its verified SPIFFE identity. Add a handler that wraps fosite's stock client-credentials handler and accepts a request only from an AuthenticatedSPIFFEClient whose association lists the grant. It reuses server.GrantSingleResource, so it requires exactly one resource, matched exactly against the association's resources and the server's allowed audiences, and rejects the audience parameter. Scopes must be within the association. The token subject is the SPIFFE ID, it carries the scp claim without a scope string, it is marked as having no upstream session, and no refresh token is issued. Every policy rejection returns a hint and writes a debug log line. buildProvider registers the handler only when the new SupportsSPIFFEClientCredentialsGrant flag is set, which the server derives from the SPIFFE trust config. Validation still admits only the token-exchange grant on an association, so no configuration can set the flag yet and nothing changes at runtime. Comments that described SPIFFE clients as token-exchange only are updated where they touch these code paths. Part of #6204. Co-authored-by: Mecatl --- .../18-spiffe-association-declarations.md | 2 +- pkg/authserver/claimnames/claimnames.go | 7 +- .../server/clientcredentials/handler.go | 122 ++++++++++ .../server/clientcredentials/handler_test.go | 221 ++++++++++++++++++ pkg/authserver/server/provider.go | 9 + .../server/registration/spiffe_client.go | 4 +- .../tokenexchange/refresh_token_handler.go | 5 +- pkg/authserver/server_impl.go | 23 +- pkg/authserver/spiffe_provider_test.go | 98 ++++++++ pkg/authserver/spiffe_trust.go | 8 + pkg/oauthproto/constants.go | 3 + 11 files changed, 490 insertions(+), 12 deletions(-) create mode 100644 pkg/authserver/server/clientcredentials/handler.go create mode 100644 pkg/authserver/server/clientcredentials/handler_test.go create mode 100644 pkg/authserver/spiffe_provider_test.go diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 5fe0b50f6f..656fd5d8bf 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -148,7 +148,7 @@ curl -X POST https://auth.example.com/oauth/token \ --data-urlencode "client_assertion=$JWT_SVID" ``` -After validation, the authentication strategy calls the shared `SPIFFEAssociationRegistry.Resolve` path synchronously through its JWT resolver. The registry verifies the enabled JWT method and either derives the association's configured client ID or checks the supplied selector's ownership, then returns the configured static OAuth client wrapped in `registration.AuthenticatedSPIFFEClient`. 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. It exists only on the client produced by client authentication: a client loaded from storage, for example when a stored request is read back, is the plain static client and does not carry it. After the SPIFFE JWT arm is selected, malformed request fields use generic OAuth `invalid_request` errors; validation, association, and mixed-credential failures use generic `invalid_client` errors. In that arm, an HTTP Basic authorization header or any `client_secret` form field causes client authentication to fail. Credential material is not logged or included in errors. diff --git a/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/server/clientcredentials/handler.go b/pkg/authserver/server/clientcredentials/handler.go new file mode 100644 index 0000000000..5276f935a7 --- /dev/null +++ b/pkg/authserver/server/clientcredentials/handler.go @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package clientcredentials provides SPIFFE-bound client credentials handling. +package clientcredentials + +import ( + "context" + "fmt" + "log/slog" + "slices" + + "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) { + stock, ok := compose.OAuth2ClientCredentialsGrantFactory(config.Config, storage, strategy).(fosite.TokenEndpointHandler) + if !ok { + return nil, fmt.Errorf("fosite client credentials factory returned %T, not a token endpoint handler", stock) + } + 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) + return h.stock.HandleTokenEndpointRequest(ctx, requester) +} + +// 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) + } + return h.stock.PopulateTokenEndpointResponse(ctx, requester, responder) +} + +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..3e680d8fe5 --- /dev/null +++ b/pkg/authserver/server/clientcredentials/handler_test.go @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package clientcredentials + +import ( + "cmp" + "context" + "net/url" + "testing" + + "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 bool } + +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, fosite.AccessRequester) error { + h.called = true + return nil +} +func (*recordingHandler) PopulateTokenEndpointResponse(context.Context, fosite.AccessRequester, fosite.AccessResponder) error { + 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 + // 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.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, + }, + { + name: "ordinary confidential client is unauthorized", + grants: ccGrant, + client: &fosite.DefaultClient{ID: "client", Public: false}, + form: oneResource, + wantError: fosite.ErrUnauthorizedClient, + }, + { + name: "unwrapped static SPIFFE client is unauthorized", + grants: ccGrant, + client: newClient(t, clientOpts{unwrapped: true}), + form: oneResource, + wantError: fosite.ErrUnauthorizedClient, + }, + { + name: "association grant is rejected", + 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, + }, + { + 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, + }, + { + 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) + }) + } +} diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index e2e439c2e3..d786776ee7 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -209,6 +209,10 @@ type AuthorizationServerConfig struct { // delegate client authenticates with private_key_jwt. Discovery advertises // that method and its signing algorithms when this is true. HasStaticPrivateKeyJWTClients bool + // SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE + // association grants client_credentials. It decides whether the grant + // handler is registered. + SupportsSPIFFEClientCredentialsGrant bool // InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible // with confidential clients. InsecureAllowHTTP bool @@ -335,6 +339,10 @@ type AuthorizationServerParams struct { // delegate client authenticates with private_key_jwt. Discovery advertises // that method and its signing algorithms when this is true. HasStaticPrivateKeyJWTClients bool + // SupportsSPIFFEClientCredentialsGrant reports whether some SPIFFE + // association grants client_credentials. It decides whether the grant + // handler is registered. + SupportsSPIFFEClientCredentialsGrant bool // InsecureAllowHTTP permits a non-loopback HTTP issuer. It is incompatible // with confidential clients. InsecureAllowHTTP bool @@ -639,6 +647,7 @@ func NewAuthorizationServerConfig(cfg *AuthorizationServerParams) (*Authorizatio HasStaticConfidentialClients: cfg.HasStaticConfidentialClients, HasStaticSecretClients: cfg.HasStaticSecretClients, HasStaticPrivateKeyJWTClients: cfg.HasStaticPrivateKeyJWTClients, + SupportsSPIFFEClientCredentialsGrant: cfg.SupportsSPIFFEClientCredentialsGrant, InsecureAllowHTTP: cfg.InsecureAllowHTTP, InsecureAllowConfidentialOverLoopbackHTTP: cfg.InsecureAllowConfidentialOverLoopbackHTTP, ForceConfidentialRedirectURIs: cfg.ForceConfidentialRedirectURIs, 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/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..a5a2a2748a 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,7 @@ func authorizationServerParams( InsecureAllowConfidentialOverLoopbackHTTP: cfg.InsecureAllowConfidentialOverLoopbackHTTP, ForceConfidentialRedirectURIs: cfg.ForceConfidentialRedirectURIs, HasStaticPrivateKeyJWTClients: hasPrivateKeyJWTDelegateClient(cfg.DelegateClients), + SupportsSPIFFEClientCredentialsGrant: cfg.SPIFFETrust.permitsGrant(oauthproto.GrantTypeClientCredentials), DisableTokenExchange: cfg.DisableTokenExchange, JWTBearerGrantEnabled: JWTBearerGrantEnabled(cfg.TrustedIssuers), DeviceFlowEnabled: cfg.DeviceFlowEnabled, @@ -811,10 +813,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 +899,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 +914,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_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_trust.go b/pkg/authserver/spiffe_trust.go index 2dbbe62eb4..7916937ef0 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -255,6 +255,14 @@ func NewSPIFFETrustConfig( return config, nil } +// 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) + }) +} + // ValidateSPIFFETrust validates SPIFFE trust declarations without fetching // bundles or validating credentials. func ValidateSPIFFETrust( diff --git a/pkg/oauthproto/constants.go b/pkg/oauthproto/constants.go index 61553af324..6cc6afb4ab 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" From 4af4ee4575cac74144a8d05a9bf67016de6b0d76 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 17:23:54 +0100 Subject: [PATCH 02/14] Count JWT-SVID associations as confidential A JWT-SVID is a bearer credential: anyone who captures one can replay it until it expires. A SPIFFE association that allows the JWT-SVID method was not treated like a delegate client in the cleartext transport check, so it could run over plain HTTP. Treat an association with the spiffe_jwt method as a confidential client everywhere the check runs: RunConfig and Config validation, the authorization server's HasStaticConfidentialClients flag, and the operator's EmbeddedAuthServerConfig. The two CRD rules for insecureAllowHTTP and for http issuers now also match spiffeClientAuth entries with spiffe_jwt in methods. The CRD YAMLs are regenerated. Breaking: an existing config with a JWT-SVID association plus insecureAllowHTTP, or with a non-loopback http issuer, or with a loopback http issuer and no insecureAllowConfidentialOverLoopbackHTTP, now fails validation. For a custom resource, the CRD rules reject such an object at admission (except a non-loopback http issuer that sets the loopback opt-in, which only the Go validation rejects), and reconcile fails for any stored object that still has the combination. X.509-only associations are not affected. Part of #6204. Co-authored-by: Mecatl --- .../v1beta1/mcpexternalauthconfig_types.go | 26 +++++++- .../mcpexternalauthconfig_types_test.go | 47 ++++++++++++++ .../confidential_client_transport_cel_test.go | 18 +++--- .../mcp-external-auth/spiffe_cel_test.go | 35 +++++++++++ ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 36 +++++++---- ...olhive.stacklok.dev_virtualmcpservers.yaml | 36 +++++++---- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 36 +++++++---- ...olhive.stacklok.dev_virtualmcpservers.yaml | 36 +++++++---- .../18-spiffe-association-declarations.md | 11 +++- pkg/authserver/config.go | 22 ++++--- pkg/authserver/config_test.go | 45 +++++++++++++- pkg/authserver/server/provider.go | 15 ++--- pkg/authserver/spiffe_transport_test.go | 62 +++++++++++++++++++ pkg/authserver/spiffe_trust.go | 19 ++++++ pkg/authserver/spiffe_trust_test.go | 33 ++++++++++ 15 files changed, 401 insertions(+), 76 deletions(-) create mode 100644 pkg/authserver/spiffe_transport_test.go diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index eb848a8388..9e31d7fb37 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -945,9 +945,9 @@ type JWTBearerIssuerPolicyConfig struct { // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.startsWith('synthetic:'))",message="spiffeClientAuth clientId must not use the reserved synthetic: prefix" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches('^[A-Za-z][A-Za-z0-9+.-]*://.+'))",message="spiffeClientAuth clientId must not be an absolute URL" // -// +kubebuilder:validation:XValidation:rule="!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) > 0)))",message="insecureAllowHTTP cannot be combined with confidential client registration or delegateClients; client secrets would be issued or used in cleartext over an unauthenticated endpoint" +// +kubebuilder:validation:XValidation:rule="!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) && self.inboundGrants.spiffeClientAuth.exists(a, 'spiffe_jwt' in a.methods))))",message="insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations; client secrets or JWT-SVIDs would be issued or used in cleartext over an unauthenticated endpoint" // +kubebuilder:validation:XValidation:rule="(!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration)",message="forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true" -// +kubebuilder:validation:XValidation:rule="!self.issuer.startsWith('http://') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) || size(self.inboundGrants.tokenExchange.delegateClients) == 0))",message="confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback" +// +kubebuilder:validation:XValidation:rule="!self.issuer.startsWith('http://') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) || size(self.inboundGrants.tokenExchange.delegateClients) == 0) && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) && self.inboundGrants.spiffeClientAuth.exists(a, 'spiffe_jwt' in a.methods)))",message="confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || ((!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.trustedIssuers) || !self.trustedIssuers.exists(issuer, has(issuer.expectedAudience) || has(issuer.actorClaim) || has(issuer.allowedActors) || has(issuer.actorMatcher) || has(issuer.allowedDelegateClients) || (has(issuer.allowMayAct) && issuer.allowMayAct))))",message="canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.jwtBearer) || !has(self.trustedIssuers) || !self.trustedIssuers.exists(issuer, has(issuer.jwtBearerGrant))",message="canonical jwtBearer conflicts with legacy jwtBearerGrant" // +kubebuilder:validation:XValidation:rule="!has(self.trustedIssuers) || self.trustedIssuers.all(issuer, !has(issuer.name) || self.trustedIssuers.filter(other, has(other.name) && other.name == issuer.name).size() == 1)",message="trustedIssuers must not contain duplicate names" @@ -1405,6 +1405,14 @@ func applyEffectiveJWTBearer( return nil } +// hasConfidentialClients reports whether DCR of confidential clients is +// enabled, the effective grants include a delegate client, or a SPIFFE +// association allows the JWT-SVID method. +func (c *EmbeddedAuthServerConfig) hasConfidentialClients(grants effectiveInboundGrants) bool { + return c.AllowConfidentialClientRegistration || len(grants.delegateClients) > 0 || + c.hasSPIFFEJWTClientAuth() +} + // ValidateInboundGrants validates the effective grant projection shared by // MCPExternalAuthConfig and inline VirtualMCPServer auth configuration. func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error { @@ -1413,7 +1421,7 @@ func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error { return err } if err := authserver.ValidateConfidentialClientTransport( - c.AllowConfidentialClientRegistration || len(grants.delegateClients) > 0, + c.hasConfidentialClients(grants), c.InsecureAllowHTTP, c.Issuer, c.InsecureAllowConfidentialOverLoopbackHTTP, @@ -1489,6 +1497,18 @@ func (c *EmbeddedAuthServerConfig) hasSPIFFEX509ClientAuth() bool { return false } +func (c *EmbeddedAuthServerConfig) hasSPIFFEJWTClientAuth() bool { + if c.InboundGrants == nil { + return false + } + for _, association := range c.InboundGrants.SPIFFEClientAuth { + if slices.Contains(association.Methods, SPIFFEAuthenticationMethodJWT) { + return true + } + } + return false +} + func hasLegacyTokenExchangePolicy(issuer TrustedIssuerConfig) bool { return issuer.ExpectedAudience != "" || issuer.ActorClaim != "" || len(issuer.AllowedActors) > 0 || issuer.ActorMatcher != "" || len(issuer.AllowedDelegateClients) > 0 || issuer.AllowMayAct diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index 08ee60b345..ccb93d41bc 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go @@ -2099,11 +2099,58 @@ 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 rejects insecure HTTP", + config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(c *EmbeddedAuthServerConfig) { + c.InsecureAllowHTTP = true + }), + expectErr: true, + }, + { + name: "SPIFFE JWT association rejects HTTP loopback without explicit opt in", + config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(*EmbeddedAuthServerConfig) {}), + expectErr: true, + }, + { + name: "SPIFFE JWT association allows HTTP loopback with explicit opt in", + config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(c *EmbeddedAuthServerConfig) { + c.InsecureAllowConfidentialOverLoopbackHTTP = true + }), + }, + { + 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/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go index 4692406951..7169d4e423 100644 --- a/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go +++ b/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go @@ -101,7 +101,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val allowConfidential: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", }, { name: "allowPrivateKeyJWTRegistration with insecureAllowHTTP is admitted (no secret to protect)", @@ -120,7 +120,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val delegateClient: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", }, { name: "canonical delegate clients with insecureAllowHTTP set", @@ -128,7 +128,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val canonicalDelegateClient: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", }, { name: "legacy delegate clients with insecureAllowHTTP and HTTPS issuer", @@ -136,7 +136,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val insecureHTTP: true, httpsIssuer: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", }, { name: "canonical delegate clients with insecureAllowHTTP and HTTPS issuer", @@ -145,14 +145,14 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val insecureHTTP: true, httpsIssuer: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", }, { name: "delegate clients with loopback HTTP issuer without opt-in", delegateClient: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "canonical delegate clients with loopback HTTP issuer without opt-in", @@ -160,14 +160,14 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val canonicalDelegateClient: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "confidential registration with loopback HTTP issuer without opt-in", allowConfidential: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "confidential registration with opted-in loopback HTTP issuer", @@ -260,6 +260,6 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val err := k8sClient.Create(ctx, vmcp) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring( - "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP")) + "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP")) }) }) 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..211c46b8a2 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,41 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() { config.InboundGrants.SPIFFEClientAuth[0].Resources = nil }, }, + { + name: "JWT-SVID association with insecureAllowHTTP is rejected", trustDomains: true, clients: true, + principal: "spiffe://example.org/ns/default/agent", errMatch: "JWT-SVID SPIFFE associations", + 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 needs the loopback opt-in", trustDomains: true, clients: true, + principal: "spiffe://example.org/ns/default/agent", errMatch: "insecureAllowConfidentialOverLoopbackHTTP", + 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: "JWT-SVID association with an http loopback issuer is admitted with 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.InsecureAllowConfidentialOverLoopbackHTTP = true + 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..5ebbed8fcd 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 @@ -2634,27 +2634,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -5779,27 +5785,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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..0b9d1f3033 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 @@ -2521,27 +2521,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -8058,27 +8064,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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..bb31897ef1 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -2637,27 +2637,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -5782,27 +5788,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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..6fecafc709 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -2524,27 +2524,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -8061,27 +8067,33 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration or delegateClients; client secrets would be - issued or used in cleartext over an unauthenticated endpoint + client registration, delegateClients or JWT-SVID SPIFFE associations; + client secrets or JWT-SVIDs would be issued or used in cleartext + over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0)))' + > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods))))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration or delegateClients with - an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration, delegateClients or JWT-SVID + SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0) + && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) + && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' + in a.methods)))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 656fd5d8bf..b58771354a 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -59,6 +59,8 @@ Delegate clients and other clients (`private_key_jwt`, `client_secret`, DCR and 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. +A second break: an existing CR or RunConfig that has a `spiffe_jwt` association together with `insecureAllowHTTP` (`insecure_allow_http` in a RunConfig), or with an `http://` issuer and no loopback opt-in, now fails validation (see "Known limitation: JWT-SVID replay"). For a CR, the CEL rules reject the object at admission when it sets `insecureAllowHTTP`, or has an `http://` issuer without `insecureAllowConfidentialOverLoopbackHTTP`. A non-loopback `http://` issuer that does set the loopback opt-in passes the CEL rules and is rejected only by the Go validation at reconcile. On clusters with CRD validation ratcheting, an update that leaves `embeddedAuthServer` unchanged may still be admitted, but reconcile fails in every case. For a RunConfig, `RunConfig.Validate` fails. To fix it, remove `insecureAllowHTTP` (`insecure_allow_http`), which is rejected whatever the issuer scheme, and serve the issuer over TLS with an `https://` URL. A plain-HTTP issuer is accepted only when it is a loopback address and `insecureAllowConfidentialOverLoopbackHTTP` (`insecure_allow_confidential_over_loopback_http`) is set; a non-loopback `http://` issuer is always rejected. + ### Trust-bundle source Every trust domain must declare exactly one `bundle_source`, a discriminated union naming the trust-bundle source. `newServer` constructs the configured source and passes its X.509 and JWT bundle views to the authorization server. @@ -152,7 +154,14 @@ After validation, the authentication strategy calls the shared `SPIFFEAssociatio 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. +### 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`), plus the one-minute clock leeway that go-spiffe inherits from go-jose. + +Because the JWT-SVID is a bearer credential, an association that allows the JWT-SVID method counts as a confidential client in the cleartext-transport check (`RunConfig.hasConfidentialClients`, `Config.hasStaticConfidentialClients` and `ValidateConfidentialClientTransport`), as delegate clients do. `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()`, `Config.Validate()` and the operator's `EmbeddedAuthServerConfig.ValidateInboundGrants`. An association that enables only `spiffe_x509` does not trigger it. The API server rejects these configurations at admission: the CEL rule that forbids `insecureAllowHTTP` with confidential clients, and the rule that requires `insecureAllowConfidentialOverLoopbackHTTP` for an `http://` issuer, both treat a `spiffeClientAuth` entry with `spiffe_jwt` in `methods` as a confidential client. The Go check in `ValidateInboundGrants` is the backstop for objects stored before those rules covered SPIFFE associations. ## X.509 client authentication diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index 2e313f63f9..ce1ef67ab7 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -637,9 +637,11 @@ func (c *RunConfig) Validate() error { // 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). + // relaxed later (for example for an in-cluster HTTP issuer). SPIFFE + // associations that allow the JWT-SVID method count too: the JWT-SVID is a + // bearer credential sent in the clear over plain HTTP. 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 +663,14 @@ 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. +func (c *RunConfig) hasConfidentialClients(normalized *NormalizedInboundGrants) bool { + return c.AllowConfidentialClientRegistration || len(normalized.DelegateClients) > 0 || + hasSPIFFEJWTRunConfigAssociation(c.InboundGrants) +} + // validateSPIFFEX509Listener requires the TLS listener and an https issuer when // an association enables spiffe_x509, since only that listener requests a // client certificate. @@ -2390,12 +2400,10 @@ 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. func (c *Config) hasStaticConfidentialClients() bool { - return len(c.DelegateClients) > 0 + return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsJWT() } // validateConfidentialClientConfig groups cleartext-transport validation for diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index 1a58a1e475..f0f8415235 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -123,6 +123,24 @@ func testSPIFFEWildcardAssociation(audience string) SPIFFEClientAuthRunConfig { return association } +func mustNewSPIFFEJWTTrustConfig(t *testing.T) *SPIFFETrustConfig { + t.Helper() + association := testSPIFFEWildcardAssociation("https://mcp.example.com") + association.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + 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 mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceRunConfig) *SPIFFETrustConfig { t.Helper() trust, err := NewSPIFFETrustConfig( @@ -226,6 +244,8 @@ func TestConfigValidate(t *testing.T) { {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: "JWT-SVID association with a plain-HTTP loopback issuer rejects without the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t)}, wantErr: true, errMsg: "insecure_allow_confidential_over_loopback_http"}, + {name: "JWT-SVID association with a plain-HTTP loopback issuer passes with the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t), InsecureAllowConfidentialOverLoopbackHTTP: true}}, {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"}, // RefreshGrantHandlers @@ -871,13 +891,36 @@ func TestRunConfigValidate(t *testing.T) { errMsg: "SPIFFE X.509 authentication requires an https issuer", }, { - name: "JWT-only association with an http issuer passes", + name: "JWT-only association with a non-loopback http issuer is rejected", config: x509Config(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-only association with insecure_allow_http is rejected", + config: x509Config(func(c *RunConfig) { + c.TLSListener = nil + c.InsecureAllowHTTP = true + c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + }), + wantErr: true, + errMsg: "insecure_allow_http", + }, + { + name: "JWT-only association with a loopback http issuer passes with the opt-in", + config: x509Config(func(c *RunConfig) { + c.Issuer = "http://localhost:8080" + c.TLSListener = nil + c.InsecureAllowConfidentialOverLoopbackHTTP = true + c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + }), }, { name: "SPIFFE client_id equal to a delegate client_id is rejected", diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index d786776ee7..ab049a8b33 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -192,9 +192,9 @@ 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 + // 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). It counts for the cleartext-transport check. It does not // drive discovery; see HasStaticSecretClients and // HasStaticPrivateKeyJWTClients. HasStaticConfidentialClients bool @@ -322,9 +322,9 @@ 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 + // 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). It counts for the cleartext-transport check. It does not // drive discovery; see HasStaticSecretClients and // HasStaticPrivateKeyJWTClients. HasStaticConfidentialClients bool @@ -454,7 +454,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. func ValidateConfidentialClientTransport( allowConfidential, insecureAllowHTTP bool, issuer string, insecureAllowConfidentialOverLoopbackHTTP bool, diff --git a/pkg/authserver/spiffe_transport_test.go b/pkg/authserver/spiffe_transport_test.go new file mode 100644 index 0000000000..78155243f3 --- /dev/null +++ b/pkg/authserver/spiffe_transport_test.go @@ -0,0 +1,62 @@ +// 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" +) + +// TestAuthorizationServerParamsGateSPIFFEJWTOnTransport pins that newServer's +// parameter mapping marks a JWT-SVID 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 association is refused", trust: mustNewSPIFFEJWTTrustConfig(t), wantErr: "plain-HTTP non-loopback"}, + {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 7916937ef0..b2cb0df1a2 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -263,6 +263,25 @@ func (c *SPIFFETrustConfig) permitsGrant(grant string) bool { }) } +// permitsJWT reports whether any association allows the JWT-SVID method. It is +// safe on a nil receiver. +func (c *SPIFFETrustConfig) permitsJWT() bool { + return slices.ContainsFunc(c.Associations(), func(a SPIFFEClientAuthConfig) bool { + return containsSPIFFEAuthenticationMethod(a.methods, SPIFFEAuthenticationMethodJWT) + }) +} + +// hasSPIFFEJWTRunConfigAssociation reports whether any association of the +// unvalidated run-config form allows the JWT-SVID method. +func hasSPIFFEJWTRunConfigAssociation(grants *InboundGrantsRunConfig) bool { + if grants == nil { + return false + } + return slices.ContainsFunc(grants.SPIFFEClientAuth, func(a SPIFFEClientAuthRunConfig) bool { + return containsSPIFFEAuthenticationMethod(a.Methods, SPIFFEAuthenticationMethodJWT) + }) +} + // ValidateSPIFFETrust validates SPIFFE trust declarations without fetching // bundles or validating credentials. func ValidateSPIFFETrust( diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index 1716aafdb4..4c3576bd0e 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -318,6 +318,39 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { assert.False(t, ok) } +func TestHasSPIFFEJWTAssociation(t *testing.T) { + t.Parallel() + + x509Only := testSPIFFEAssociation("x509-client", "openid") + jwtOnly := testSPIFFEAssociation("jwt-client", "openid") + jwtOnly.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + + assert.False(t, hasSPIFFEJWTRunConfigAssociation(nil)) + assert.False(t, hasSPIFFEJWTRunConfigAssociation(&InboundGrantsRunConfig{ + SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only}, + })) + assert.True(t, hasSPIFFEJWTRunConfigAssociation(&InboundGrantsRunConfig{ + SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only, jwtOnly}, + })) + assert.False(t, (*SPIFFETrustConfig)(nil).permitsJWT()) + + trust := func(associations ...SPIFFEClientAuthRunConfig) *SPIFFETrustConfig { + cfg, err := NewSPIFFETrustConfig([]SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509, SPIFFEAuthenticationMethodJWT}, + BundleSource: validFileBundleSource(), + }}, &InboundGrantsRunConfig{SPIFFEClientAuth: associations}, + []string{"openid"}, []string{"https://audience.example.com"}) + require.NoError(t, err) + return cfg + } + x509Other := withPrincipal(x509Only, "spiffe://example.org/ns/default/other") + jwtOther := withPrincipal(jwtOnly, "spiffe://example.org/ns/default/jwt") + assert.False(t, trust(x509Only).permitsJWT()) + assert.True(t, trust(x509Other, jwtOther).permitsJWT()) +} + //nolint:paralleltest // Swaps the process-wide default logger. func TestNewSPIFFETrustConfigWarnsOnDeprecatedAudiences(t *testing.T) { var logs bytes.Buffer From 7b42826b19da21e0cfee37cbb20d805e620070b2 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 20:39:48 +0100 Subject: [PATCH 03/14] Drop the SPIFFE token-exchange grant constant authserver.SPIFFEGrantTypeTokenExchange was an alias for oauthproto.GrantTypeTokenExchange, declared as the only grant a SPIFFE association could name. An association is about to be able to name client_credentials as well, so the alias would be misleading. Use the oauthproto constant directly. This commit only renames. Breaking: the exported constant authserver.SPIFFEGrantTypeTokenExchange is removed. Use oauthproto.GrantTypeTokenExchange, which has the same value. Part of #6204. Co-authored-by: Mecatl --- cmd/thv-operator/pkg/controllerutil/authserver.go | 3 ++- cmd/thv-operator/pkg/controllerutil/authserver_test.go | 3 ++- .../delegate_client_restart_integration_test.go | 2 +- pkg/authserver/inbound_grants.go | 2 +- pkg/authserver/inbound_grants_test.go | 3 ++- pkg/authserver/runner/embeddedauthserver_test.go | 2 +- pkg/authserver/spiffe_association_registry_test.go | 4 ++-- pkg/authserver/spiffe_trust.go | 8 ++------ pkg/runner/config_test.go | 5 +++-- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index 01452edb90..dec1e92720 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" ) @@ -410,7 +411,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/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..0833eab137 100644 --- a/pkg/authserver/inbound_grants.go +++ b/pkg/authserver/inbound_grants.go @@ -121,7 +121,7 @@ func NormalizeInboundGrants(cfg *RunConfig) (*NormalizedInboundGrants, error) { result.Capabilities.TokenExchange = legacyTokenExchange } // SPIFFE client-auth associations always require the token-exchange grant - // (SPIFFEGrantTypeTokenExchange is the only grant type they may declare — + // (oauthproto.GrantTypeTokenExchange 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 diff --git a/pkg/authserver/inbound_grants_test.go b/pkg/authserver/inbound_grants_test.go index 8a9c147204..2b2cbd4099 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) { @@ -64,7 +65,7 @@ func TestNormalizeInboundGrants(t *testing.T) { Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, Scopes: []string{"openid"}, Audiences: []string{"https://mcp.example.com"}, - GrantTypes: []string{SPIFFEGrantTypeTokenExchange}, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, }}, }, }, diff --git a/pkg/authserver/runner/embeddedauthserver_test.go b/pkg/authserver/runner/embeddedauthserver_test.go index 3b5a6ddcf4..418795c098 100644 --- a/pkg/authserver/runner/embeddedauthserver_test.go +++ b/pkg/authserver/runner/embeddedauthserver_test.go @@ -2902,7 +2902,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/spiffe_association_registry_test.go b/pkg/authserver/spiffe_association_registry_test.go index be9a48980c..b40f75ec74 100644 --- a/pkg/authserver/spiffe_association_registry_test.go +++ b/pkg/authserver/spiffe_association_registry_test.go @@ -405,7 +405,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 +439,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_trust.go b/pkg/authserver/spiffe_trust.go index b2cb0df1a2..2edfda37a0 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -27,10 +27,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. @@ -876,10 +872,10 @@ func validateDistinctNonEmpty(values []string, field string) error { } func validateSPIFFEGrants(grants []string, index int) error { - if len(grants) != 1 || grants[0] != SPIFFEGrantTypeTokenExchange { + if len(grants) != 1 || grants[0] != oauthproto.GrantTypeTokenExchange { return fmt.Errorf( "inbound_grants.spiffe_client_auth[%d].grant_types must be exactly [%q]", - index, SPIFFEGrantTypeTokenExchange, + index, oauthproto.GrantTypeTokenExchange, ) } return nil 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}, }, }, }, From 0e4cca8088479fa14c50110f32c881feb20c8ae8 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 20:46:06 +0100 Subject: [PATCH 04/14] Let SPIFFE associations grant client_credentials A SPIFFE association could only receive the token-exchange grant, and every association forced token exchange on for the whole server. A workload that only needs a plain access token had no way to ask for one, and a deployment with no token-exchange use still exposed it. Each association's grant_types now decides what it may use: one or both of client_credentials and token exchange. The list is validated in one place. The client_credentials handler is registered when some association lists that grant. The RFC 8693 handler is enabled only when some association lists token exchange, so an association limited to client_credentials no longer turns it on. The runner no longer force-enables it. A config that disables token exchange is rejected only for an association that lists that grant. The grant types are part of the stored association identity hash. On a backend that keeps placeholders between runs (Redis), the first start after upgrading therefore logs one identity_changed WARN for each SPIFFE association, from each replica that reads the old row before it is rewritten. It can repeat if a replica on the previous version restarts during the rollout and writes the old hash back. Later restarts do not log it. Behavior is otherwise unchanged for existing RunConfigs, which already carried grant_types with token exchange. client_credentials is served at the token endpoint but is not advertised in discovery. The operator CRD still injects token exchange, so nothing in a custom resource can list client_credentials yet. Part of #6204. Co-authored-by: Mecatl --- docs/arch/11-auth-server-storage.md | 4 +- docs/arch/17-token-exchange-delegation.md | 23 +- .../18-spiffe-association-declarations.md | 39 ++- docs/arch/README.md | 1 + docs/server/docs.go | 2 +- docs/server/swagger.json | 2 +- docs/server/swagger.yaml | 6 +- pkg/authserver/config.go | 17 +- pkg/authserver/config_test.go | 33 +- pkg/authserver/inbound_grants.go | 15 +- pkg/authserver/inbound_grants_test.go | 65 ++-- pkg/authserver/runner/embeddedauthserver.go | 16 +- .../runner/embeddedauthserver_test.go | 84 +++++ .../runner/spiffe_x509_listener_test.go | 19 +- pkg/authserver/server_impl.go | 7 +- pkg/authserver/spiffe_association_registry.go | 21 +- .../spiffe_association_registry_test.go | 54 ++++ ...ffe_client_credentials_integration_test.go | 306 ++++++++++++++++++ pkg/authserver/spiffe_trust.go | 33 +- pkg/authserver/spiffe_trust_test.go | 42 ++- pkg/authserver/storage/spiffe_decorator.go | 7 +- pkg/authserver/storage/types.go | 5 +- pkg/authserver/storage/types_test.go | 2 +- sdk/go/client/oas_schemas_gen.go | 6 +- sdk/go/openapi.json | 2 +- sdk/go/openapi.yaml | 6 +- 26 files changed, 692 insertions(+), 125 deletions(-) create mode 100644 pkg/authserver/spiffe_client_credentials_integration_test.go 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..71bd6e38db 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -140,11 +140,15 @@ 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, and +JWT bearer when a trusted issuer enables it. 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 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 @@ -713,7 +717,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 +755,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 +865,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 +1733,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 b58771354a..4785094158 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,20 +33,20 @@ 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. 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. @@ -55,6 +55,27 @@ Clients that carry a resource list, such as SPIFFE clients, are targeted by exac 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 below and then lets Fosite issue the token, so lifetime and signing match the other grants. 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. + +```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=openid' \ + --data-urlencode 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-spiffe' \ + --data-urlencode "client_assertion=$JWT_SVID" +``` + ### 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. @@ -117,12 +138,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. @@ -163,6 +184,8 @@ A JWT-SVID is a bearer credential, and the SPIFFE path has no application-level Because the JWT-SVID is a bearer credential, an association that allows the JWT-SVID method counts as a confidential client in the cleartext-transport check (`RunConfig.hasConfidentialClients`, `Config.hasStaticConfidentialClients` and `ValidateConfidentialClientTransport`), as delegate clients do. `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()`, `Config.Validate()` and the operator's `EmbeddedAuthServerConfig.ValidateInboundGrants`. An association that enables only `spiffe_x509` does not trigger it. The API server rejects these configurations at admission: the CEL rule that forbids `insecureAllowHTTP` with confidential clients, and the rule that requires `insecureAllowConfidentialOverLoopbackHTTP` for an `http://` issuer, both treat a `spiffeClientAuth` entry with `spiffe_jwt` in `methods` as a confidential client. The Go check in `ValidateInboundGrants` is the backstop for objects stored before those rules covered SPIFFE associations. +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 for the server's normal access-token lifetime (`AccessTokenLifespan`), and that lifetime is not capped to the SVID's expiry. 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 X.509-SVID client authentication is implemented in `authenticateSPIFFEX509Client` and `verifySPIFFEX509` (`pkg/authserver/server/spiffe_client_auth.go`). The strategy reads the client certificate from `r.TLS` itself. There is no separate middleware and no identity in the request context. @@ -196,7 +219,7 @@ The authenticated client is whichever peer completes the TLS handshake, so TLS m ## 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/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/config.go b/pkg/authserver/config.go index ce1ef67ab7..a452f9414d 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -2447,12 +2447,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 f0f8415235..e8708cacdb 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -123,6 +123,22 @@ func testSPIFFEWildcardAssociation(audience string) SPIFFEClientAuthRunConfig { return association } +func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceRunConfig) *SPIFFETrustConfig { + t.Helper() + trust, err := NewSPIFFETrustConfig( + []SPIFFETrustDomainRunConfig{{ + Name: "production", + TrustDomain: "example.org", + Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, + BundleSource: source, + }}, + &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{testSPIFFEWildcardAssociation("https://mcp.example.com")}}, + []string{"openid"}, []string{"https://mcp.example.com"}, + ) + require.NoError(t, err) + return trust +} + func mustNewSPIFFEJWTTrustConfig(t *testing.T) *SPIFFETrustConfig { t.Helper() association := testSPIFFEWildcardAssociation("https://mcp.example.com") @@ -141,16 +157,24 @@ func mustNewSPIFFEJWTTrustConfig(t *testing.T) *SPIFFETrustConfig { return trust } -func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceRunConfig) *SPIFFETrustConfig { +func mustNewSPIFFETrustConfigWithGrants(t *testing.T, grants []string) *SPIFFETrustConfig { t.Helper() trust, err := NewSPIFFETrustConfig( []SPIFFETrustDomainRunConfig{{ Name: "production", TrustDomain: "example.org", Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509}, - BundleSource: source, + BundleSource: validFileBundleSource(), }}, - &InboundGrantsRunConfig{SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{testSPIFFEWildcardAssociation("https://mcp.example.com")}}, + &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) @@ -246,7 +270,8 @@ func TestConfigValidate(t *testing.T) { {name: "JWT-SVID association with a plain-HTTP loopback issuer rejects without the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t)}, wantErr: true, errMsg: "insecure_allow_confidential_over_loopback_http"}, {name: "JWT-SVID association with a plain-HTTP loopback issuer passes with the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t), InsecureAllowConfidentialOverLoopbackHTTP: true}}, - {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: "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"}, diff --git a/pkg/authserver/inbound_grants.go b/pkg/authserver/inbound_grants.go index 0833eab137..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 - // (oauthproto.GrantTypeTokenExchange 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 2b2cbd4099..a4f35df049 100644 --- a/pkg/authserver/inbound_grants_test.go +++ b/pkg/authserver/inbound_grants_test.go @@ -47,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{oauthproto.GrantTypeTokenExchange}, - }}, + 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}}, }, { @@ -394,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/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 418795c098..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) { diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index a5b472ab84..460224391d 100644 --- a/pkg/authserver/runner/spiffe_x509_listener_test.go +++ b/pkg/authserver/runner/spiffe_x509_listener_test.go @@ -331,15 +331,22 @@ func TestEmbeddedAuthServer_SPIFFEOnlyTokenExchangeOverTLS(t *testing.T) { } // 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_impl.go b/pkg/authserver/server_impl.go index a5a2a2748a..657c1e67a4 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -436,9 +436,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) diff --git a/pkg/authserver/spiffe_association_registry.go b/pkg/authserver/spiffe_association_registry.go index cf28046150..8a418e1d4e 100644 --- a/pkg/authserver/spiffe_association_registry.go +++ b/pkg/authserver/spiffe_association_registry.go @@ -8,6 +8,7 @@ import ( "encoding/hex" "fmt" "slices" + "strconv" "strings" "github.com/ory/fosite" @@ -167,13 +168,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 +193,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 b40f75ec74..e622404120 100644 --- a/pkg/authserver/spiffe_association_registry_test.go +++ b/pkg/authserver/spiffe_association_registry_test.go @@ -338,6 +338,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 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..6f21a5a327 --- /dev/null +++ b/pkg/authserver/spiffe_client_credentials_integration_test.go @@ -0,0 +1,306 @@ +// 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. + tokenKey *rsa.PrivateKey + jwtKey *ecdsa.PrivateKey + leaf *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(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) + leafDER, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ + SerialNumber: big.NewInt(2), + Subject: pkix.Name{CommonName: "test workload"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(time.Hour), + 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) + + 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} +} + +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() + 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(time.Minute)), + }).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]) + }) + } +} diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index 2edfda37a0..681d9d2cc3 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -144,9 +144,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. @@ -697,7 +697,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 @@ -709,7 +709,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, @@ -723,7 +722,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) { @@ -810,9 +809,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). @@ -871,12 +870,16 @@ func validateDistinctNonEmpty(values []string, field string) error { return nil } -func validateSPIFFEGrants(grants []string, index int) error { - if len(grants) != 1 || grants[0] != oauthproto.GrantTypeTokenExchange { - return fmt.Errorf( - "inbound_grants.spiffe_client_auth[%d].grant_types must be exactly [%q]", - index, oauthproto.GrantTypeTokenExchange, - ) +// 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 4c3576bd0e..cc32979e26 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) { @@ -175,12 +181,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 +229,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() 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/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. From c00d3a01768183486f48543cd584fccb7f33a6d2 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 20:46:24 +0100 Subject: [PATCH 05/14] Advertise client_credentials and SPIFFE methods Discovery omitted client_credentials even though its handler is registered when an association grants it, and said nothing about the spiffe_x509 and spiffe_jwt client authentication methods defined by draft-ietf-oauth-spiffe-client-auth. Add one flag per capability, set from the trust config when the params are built. The client_credentials flag drives both handler registration and the grant_types_supported entry, so the two cannot differ. The two method flags drive token_endpoint_auth_methods_supported only. Discovery now lists client_credentials and the SPIFFE methods where they were absent before. Part of #6204. Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 5 +- .../18-spiffe-association-declarations.md | 13 +++- pkg/authserver/config.go | 2 +- pkg/authserver/server/handlers/discovery.go | 21 +++++-- .../server/handlers/handlers_test.go | 62 +++++++++++++------ pkg/authserver/server/provider.go | 22 +++++-- pkg/authserver/server_impl.go | 2 + pkg/authserver/spiffe_trust.go | 8 +-- pkg/authserver/spiffe_trust_test.go | 6 +- pkg/oauthproto/constants.go | 13 +++- 10 files changed, 114 insertions(+), 40 deletions(-) diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 71bd6e38db..96b865f10d 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -143,8 +143,9 @@ 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, 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. It advertises token exchange only when it is enabled, and -JWT bearer when a trusted issuer enables it. Token exchange is enabled by a +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 SPIFFE association that lists only `client_credentials` diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 4785094158..1f076a44fa 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -76,6 +76,8 @@ curl -X POST https://auth.example.com/oauth/token \ --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. @@ -160,7 +162,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 \ @@ -175,6 +177,13 @@ After validation, the authentication strategy calls the shared `SPIFFEAssociatio 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. +### 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: @@ -194,7 +203,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). diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index a452f9414d..2ca3e18cfb 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -2403,7 +2403,7 @@ func (c *Config) validateDelegationConfig() error { // hasStaticConfidentialClients reports whether any delegate client is // configured or a SPIFFE association allows the JWT-SVID method. func (c *Config) hasStaticConfidentialClients() bool { - return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsJWT() + return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsMethod(SPIFFEAuthenticationMethodJWT) } // validateConfidentialClientConfig groups cleartext-transport validation for 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 ab049a8b33..a3d15d1a4a 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -209,9 +209,15 @@ 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 whether the grant - // handler is registered. + // 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. @@ -339,9 +345,15 @@ 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 whether the grant - // handler is registered. + // 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. @@ -648,6 +660,8 @@ 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, diff --git a/pkg/authserver/server_impl.go b/pkg/authserver/server_impl.go index 657c1e67a4..4f47692dc8 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -229,6 +229,8 @@ 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), diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index 681d9d2cc3..e798a7f6ed 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -259,11 +259,11 @@ func (c *SPIFFETrustConfig) permitsGrant(grant string) bool { }) } -// permitsJWT reports whether any association allows the JWT-SVID method. It is -// safe on a nil receiver. -func (c *SPIFFETrustConfig) permitsJWT() bool { +// 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, SPIFFEAuthenticationMethodJWT) + return containsSPIFFEAuthenticationMethod(a.methods, method) }) } diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index cc32979e26..ee0dcfd7ec 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -360,7 +360,7 @@ func TestHasSPIFFEJWTAssociation(t *testing.T) { assert.True(t, hasSPIFFEJWTRunConfigAssociation(&InboundGrantsRunConfig{ SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only, jwtOnly}, })) - assert.False(t, (*SPIFFETrustConfig)(nil).permitsJWT()) + assert.False(t, (*SPIFFETrustConfig)(nil).permitsMethod(SPIFFEAuthenticationMethodJWT)) trust := func(associations ...SPIFFEClientAuthRunConfig) *SPIFFETrustConfig { cfg, err := NewSPIFFETrustConfig([]SPIFFETrustDomainRunConfig{{ @@ -375,8 +375,8 @@ func TestHasSPIFFEJWTAssociation(t *testing.T) { } x509Other := withPrincipal(x509Only, "spiffe://example.org/ns/default/other") jwtOther := withPrincipal(jwtOnly, "spiffe://example.org/ns/default/jwt") - assert.False(t, trust(x509Only).permitsJWT()) - assert.True(t, trust(x509Other, jwtOther).permitsJWT()) + assert.False(t, trust(x509Only).permitsMethod(SPIFFEAuthenticationMethodJWT)) + assert.True(t, trust(x509Other, jwtOther).permitsMethod(SPIFFEAuthenticationMethodJWT)) } //nolint:paralleltest // Swaps the process-wide default logger. diff --git a/pkg/oauthproto/constants.go b/pkg/oauthproto/constants.go index 6cc6afb4ab..fc20aff1ea 100644 --- a/pkg/oauthproto/constants.go +++ b/pkg/oauthproto/constants.go @@ -52,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. @@ -69,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. From 592351ac95739aba13efd2a1f00a6ad0ae040d51 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Sun, 15 Nov 2026 20:48:08 +0100 Subject: [PATCH 06/14] Bind SPIFFE token exchange to the issuing workload A wildcard association gives many workloads one client ID. When a ToolHive-issued subject token is accepted only because its client_id matches the caller's, workload B could present workload A's client_credentials token and obtain a token whose sub is A. For a SPIFFE client on that client_id consent path, require the subject token's sub or its outermost act.sub to equal the caller's verified SPIFFE ID. Otherwise the exchange fails with invalid_grant. The may_act and external-issuer paths are unchanged, and so are clients that are not SPIFFE clients. The runner's subject-token fixture now names the workload's SPIFFE ID as sub, as a token issued to a SPIFFE workload does. Breaking: act.sub currently holds the client ID, so a SPIFFE client can generally not re-exchange a delegated token it received earlier. That exchange used to be accepted on the client_id binding alone and now fails with invalid_grant until act.sub records the SPIFFE ID. Part of #6204. Co-authored-by: Mecatl --- .../18-spiffe-association-declarations.md | 3 + .../runner/spiffe_x509_listener_test.go | 4 +- .../server/tokenexchange/handler.go | 38 +++++- .../server/tokenexchange/handler_test.go | 117 +++++++++++++++++- 4 files changed, 157 insertions(+), 5 deletions(-) diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 1f076a44fa..abc0486938 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -52,6 +52,9 @@ Clients that carry a resource list, such as SPIFFE clients, are targeted by exac - 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 must therefore carry the caller's verified SPIFFE ID, either as its `sub` or as the `sub` of its outermost `act` entry. Otherwise the exchange fails with `invalid_grant` and the hint `The subject token was issued to a different workload of this client.` 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. At present `act.sub` holds the client ID, unless the earlier exchange named the workload through `actor_token`. A SPIFFE client can therefore generally not re-exchange a delegated token it received earlier. That is deliberate: the exchange fails closed until a later change records the SPIFFE ID in `act.sub`. 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. diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index 460224391d..317b3219d2 100644 --- a/pkg/authserver/runner/spiffe_x509_listener_test.go +++ b/pkg/authserver/runner/spiffe_x509_listener_test.go @@ -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) diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index c78867abf7..116f0bfed9 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -21,6 +21,7 @@ import ( "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 +396,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 } @@ -850,7 +855,17 @@ 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 +// the subject token must also name this workload: its sub must be spiffeID, or +// its outermost act.sub must be. 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 +918,29 @@ 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: neither its +// sub nor the sub of its outermost act entry is spiffeID. 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 + } + if validatedClaims.Subject == spiffeID { + return false + } + act, _ := validatedClaims.Extra["act"].(map[string]any) + actSub, _ := act["sub"].(string) + return actSub != spiffeID +} + // 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..102cb76a9e 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,68 @@ 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 a delegated token whose act.sub is the client ID rejected", + 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", + 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 +2286,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 +3291,56 @@ 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 + wantErr bool + }{ + {name: "the workload the token was issued to", caller: workloadA}, + {name: "a sibling workload with the same client ID", caller: workloadB, 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 = workloadA + form := url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {tj.signToken(t, claims, validExtraClaims())}, + "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) + }) + } +} + // TestGrantAndBoundAudiences_DelegateClientKeepsGenericPath proves a // non-SPIFFE client may still send audience= and still gets the default // audience when it sends no target. From 9101628df0df1c021213b8070a0197c61f74abc3 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 15:06:01 +0100 Subject: [PATCH 07/14] Correct SPIFFE grant comments and errors Several comments and messages still described the pre-client_credentials state. The SPIFFEClientConfig and converter comments cited a renamed validator and claimed the runtime accepts only token exchange; they now say the CRD does not expose grantTypes and the converter always supplies the token-exchange grant, and the CRD manifests and API reference are regenerated. The four confidential-client transport errors now name JWT-SVID SPIFFE associations, wrapped to the line-length limit, and the config comment notes that jti and the five-minute cap do not apply to JWT-SVIDs. The client_credentials factory formatted the nil stock handler in its type-assertion error, so it always printed ; it now formats the value the fosite factory returned. The new handler file's SPDX year is corrected to 2026. The architecture docs gain the gateway risk for client_credentials associations, a consistent six-minute and leeway description, the memory versus Redis read-back behavior of the authenticated client wrapper, and the no-inbound_grants default for token exchange. Co-authored-by: Mecatl --- .../api/v1beta1/mcpexternalauthconfig_types.go | 6 ++---- .../api/v1beta1/mcpexternalauthconfig_types_test.go | 2 +- cmd/thv-operator/pkg/controllerutil/authserver.go | 7 +++---- ...toolhive.stacklok.dev_mcpexternalauthconfigs.yaml | 12 ++++-------- .../toolhive.stacklok.dev_virtualmcpservers.yaml | 12 ++++-------- ...toolhive.stacklok.dev_mcpexternalauthconfigs.yaml | 12 ++++-------- .../toolhive.stacklok.dev_virtualmcpservers.yaml | 12 ++++-------- docs/arch/17-token-exchange-delegation.md | 4 +++- docs/arch/18-spiffe-association-declarations.md | 8 ++++---- docs/operator/crd-api.md | 6 ++---- pkg/authserver/config.go | 11 ++++++----- pkg/authserver/config_test.go | 2 +- pkg/authserver/runner/spiffe_x509_listener_test.go | 4 ++-- pkg/authserver/server/clientcredentials/handler.go | 7 ++++--- pkg/authserver/server/provider.go | 12 ++++++++---- 15 files changed, 52 insertions(+), 65 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index 9e31d7fb37..a904be3d2e 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" diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index ccb93d41bc..94d1c23f4d 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) cannot be combined with insecure_allow_http", }, { name: "confidential clients with plain-HTTP loopback issuer without opt-in - invalid", diff --git a/cmd/thv-operator/pkg/controllerutil/authserver.go b/cmd/thv-operator/pkg/controllerutil/authserver.go index dec1e92720..1f048fcac6 100644 --- a/cmd/thv-operator/pkg/controllerutil/authserver.go +++ b/cmd/thv-operator/pkg/controllerutil/authserver.go @@ -388,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 { 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 5ebbed8fcd..478b12b276 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: |- @@ -3707,10 +3705,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 0b9d1f3033..687145407f 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: |- @@ -5986,10 +5984,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 bb31897ef1..5ae14c51bc 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: |- @@ -3710,10 +3708,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 6fecafc709..23af86ec70 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: |- @@ -5989,10 +5987,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/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 96b865f10d..90446e9453 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -148,7 +148,9 @@ JWT bearer when a trusted issuer enables it, and `client_credentials` when a SPI 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 SPIFFE association that lists only `client_credentials` +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 diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index abc0486938..12fe4d880a 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -74,7 +74,7 @@ The access token has these claims: `sub` is the verified SPIFFE ID; `client_id` 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=openid' \ + --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" ``` @@ -176,7 +176,7 @@ curl -X POST https://auth.example.com/oauth/token \ --data-urlencode "client_assertion=$JWT_SVID" ``` -After validation, the authentication strategy calls the shared `SPIFFEAssociationRegistry.Resolve` path synchronously through its JWT resolver. The registry verifies the enabled JWT method and either derives the association's configured client ID or checks the supplied selector's ownership, then returns the configured static OAuth client wrapped in `registration.AuthenticatedSPIFFEClient`. 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. 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. @@ -192,7 +192,7 @@ The `spiffe_x509` and `spiffe_jwt` client authentication methods, and the `urn:i 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`), plus the one-minute clock leeway that go-spiffe inherits from go-jose. +- 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`. Because the JWT-SVID is a bearer credential, an association that allows the JWT-SVID method counts as a confidential client in the cleartext-transport check (`RunConfig.hasConfidentialClients`, `Config.hasStaticConfidentialClients` and `ValidateConfidentialClientTransport`), as delegate clients do. `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()`, `Config.Validate()` and the operator's `EmbeddedAuthServerConfig.ValidateInboundGrants`. An association that enables only `spiffe_x509` does not trigger it. The API server rejects these configurations at admission: the CEL rule that forbids `insecureAllowHTTP` with confidential clients, and the rule that requires `insecureAllowConfidentialOverLoopbackHTTP` for an `http://` issuer, both treat a `spiffeClientAuth` entry with `spiffe_jwt` in `methods` as a confidential client. The Go check in `ValidateInboundGrants` is the backstop for objects stored before those rules covered SPIFFE associations. @@ -225,7 +225,7 @@ 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. 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/pkg/authserver/config.go b/pkg/authserver/config.go index 2ca3e18cfb..922bf3ab81 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -635,11 +635,12 @@ 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). SPIFFE - // associations that allow the JWT-SVID method count too: the JWT-SVID is a - // bearer credential sent in the clear over plain HTTP. + // 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). SPIFFE associations that allow the JWT-SVID method count + // too: the JWT-SVID is a bearer credential sent in the clear over plain HTTP. if err := ValidateConfidentialClientTransport( c.hasConfidentialClients(normalized), c.InsecureAllowHTTP, c.Issuer, c.InsecureAllowConfidentialOverLoopbackHTTP); err != nil { diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index e8708cacdb..6683cc8a86 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -264,7 +264,7 @@ 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) 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"}, diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index 317b3219d2..aa7a8595f7 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() diff --git a/pkg/authserver/server/clientcredentials/handler.go b/pkg/authserver/server/clientcredentials/handler.go index 5276f935a7..0d02e31983 100644 --- a/pkg/authserver/server/clientcredentials/handler.go +++ b/pkg/authserver/server/clientcredentials/handler.go @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. // SPDX-License-Identifier: Apache-2.0 // Package clientcredentials provides SPIFFE-bound client credentials handling. @@ -34,9 +34,10 @@ type Handler struct { // that permit client_credentials. func Factory() server.Factory { return func(config *server.AuthorizationServerConfig, storage fosite.Storage, strategy any) (any, error) { - stock, ok := compose.OAuth2ClientCredentialsGrantFactory(config.Config, storage, strategy).(fosite.TokenEndpointHandler) + 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", stock) + return nil, fmt.Errorf("fosite client credentials factory returned %T, not a token endpoint handler", created) } return &Handler{stock: stock, allowedAudiences: config.AllowedAudiences}, nil } diff --git a/pkg/authserver/server/provider.go b/pkg/authserver/server/provider.go index a3d15d1a4a..3a9e7437c3 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -476,7 +476,8 @@ 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) " + "cannot be combined with insecure_allow_http: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } @@ -496,18 +497,21 @@ 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) " + "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) " + "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) " + "cannot use a plain-HTTP non-loopback issuer: " + "client credentials, authorization codes and tokens would cross cleartext HTTP") } From 536acf1569069b43b794d8f83fe401295dd76ded Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 12:26:46 +0100 Subject: [PATCH 08/14] Share the SPIFFE method check The run-config package had a JWT-only helper and an inline X.509 loop that asked the same question about different methods, and the operator had two copies of the same loop. Replace each pair with one hasSPIFFEMethod that takes the method. HasSPIFFEX509ClientAuth stays exported as a one-line call. The trust-config permit helpers move below the exported functions in spiffe_trust.go. Behavior is unchanged. Co-authored-by: Mecatl --- .../v1beta1/mcpexternalauthconfig_types.go | 30 ++++--------- pkg/authserver/config.go | 20 +++++---- pkg/authserver/spiffe_trust.go | 43 +++++++------------ pkg/authserver/spiffe_trust_test.go | 10 ++--- 4 files changed, 40 insertions(+), 63 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index a904be3d2e..e1552bbebf 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -1408,7 +1408,7 @@ func applyEffectiveJWTBearer( // association allows the JWT-SVID method. func (c *EmbeddedAuthServerConfig) hasConfidentialClients(grants effectiveInboundGrants) bool { return c.AllowConfidentialClientRegistration || len(grants.delegateClients) > 0 || - c.hasSPIFFEJWTClientAuth() + c.hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT) } // ValidateInboundGrants validates the effective grant projection shared by @@ -1429,7 +1429,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 } @@ -1477,34 +1477,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 -} - -func (c *EmbeddedAuthServerConfig) hasSPIFFEJWTClientAuth() bool { - if c.InboundGrants == nil { - return false - } - for _, association := range c.InboundGrants.SPIFFEClientAuth { - if slices.Contains(association.Methods, SPIFFEAuthenticationMethodJWT) { - 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/pkg/authserver/config.go b/pkg/authserver/config.go index 922bf3ab81..33f3d4170a 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -669,7 +669,7 @@ func (c *RunConfig) Validate() error { // grants, or a SPIFFE association that allows the JWT-SVID method. func (c *RunConfig) hasConfidentialClients(normalized *NormalizedInboundGrants) bool { return c.AllowConfidentialClientRegistration || len(normalized.DelegateClients) > 0 || - hasSPIFFEJWTRunConfigAssociation(c.InboundGrants) + c.hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT) } // validateSPIFFEX509Listener requires the TLS listener and an https issuer when @@ -803,17 +803,19 @@ 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 false + return slices.ContainsFunc(c.InboundGrants.SPIFFEClientAuth, func(a SPIFFEClientAuthRunConfig) bool { + return containsSPIFFEAuthenticationMethod(a.Methods, method) + }) } // validateBaselineClientScopes ensures every entry in BaselineClientScopes is diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index e798a7f6ed..ef26098b44 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -251,33 +251,6 @@ func NewSPIFFETrustConfig( return config, nil } -// 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) - }) -} - -// hasSPIFFEJWTRunConfigAssociation reports whether any association of the -// unvalidated run-config form allows the JWT-SVID method. -func hasSPIFFEJWTRunConfigAssociation(grants *InboundGrantsRunConfig) bool { - if grants == nil { - return false - } - return slices.ContainsFunc(grants.SPIFFEClientAuth, func(a SPIFFEClientAuthRunConfig) bool { - return containsSPIFFEAuthenticationMethod(a.Methods, SPIFFEAuthenticationMethodJWT) - }) -} - // ValidateSPIFFETrust validates SPIFFE trust declarations without fetching // bundles or validating credentials. func ValidateSPIFFETrust( @@ -434,6 +407,22 @@ 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) + }) +} + func (c SPIFFEClientAuthConfig) clone() SPIFFEClientAuthConfig { c.methods = slices.Clone(c.methods) return c diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index ee0dcfd7ec..e6c09fbb43 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -353,13 +353,13 @@ func TestHasSPIFFEJWTAssociation(t *testing.T) { jwtOnly := testSPIFFEAssociation("jwt-client", "openid") jwtOnly.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - assert.False(t, hasSPIFFEJWTRunConfigAssociation(nil)) - assert.False(t, hasSPIFFEJWTRunConfigAssociation(&InboundGrantsRunConfig{ + assert.False(t, (*RunConfig)(nil).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) + assert.False(t, (&RunConfig{InboundGrants: &InboundGrantsRunConfig{ SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only}, - })) - assert.True(t, hasSPIFFEJWTRunConfigAssociation(&InboundGrantsRunConfig{ + }}).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) + assert.True(t, (&RunConfig{InboundGrants: &InboundGrantsRunConfig{ SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only, jwtOnly}, - })) + }}).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) assert.False(t, (*SPIFFETrustConfig)(nil).permitsMethod(SPIFFEAuthenticationMethodJWT)) trust := func(associations ...SPIFFEClientAuthRunConfig) *SPIFFETrustConfig { From 6dae1b58f6460e0aa9a22a6c429d525383268a5f Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 12:27:47 +0100 Subject: [PATCH 09/14] Tighten client_credentials tests Five rejection cases had an empty wantHint, so the hint assertion always passed and the cases only pinned the error type. Give each the hint substring from the handler so a wrong rejection path fails, and rename the case that really tests an association without client_credentials. Cover the guard in PopulateTokenEndpointResponse: another grant returns an unknown-request error and never reaches the stock handler. Add a token-endpoint test that when the only inbound capability is a SPIFFE association granting client_credentials, a token-exchange request is refused with invalid_request and issues no token. Co-authored-by: Mecatl --- .../runner/spiffe_x509_listener_test.go | 66 +++++++++++++++++++ .../server/clientcredentials/handler_test.go | 49 +++++++++++++- 2 files changed, 112 insertions(+), 3 deletions(-) diff --git a/pkg/authserver/runner/spiffe_x509_listener_test.go b/pkg/authserver/runner/spiffe_x509_listener_test.go index aa7a8595f7..82fb28751a 100644 --- a/pkg/authserver/runner/spiffe_x509_listener_test.go +++ b/pkg/authserver/runner/spiffe_x509_listener_test.go @@ -332,6 +332,72 @@ 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, whatever its grant types. func TestEmbeddedAuthServer_SPIFFEAssociationWithoutResourcesIsRejected(t *testing.T) { diff --git a/pkg/authserver/server/clientcredentials/handler_test.go b/pkg/authserver/server/clientcredentials/handler_test.go index 3e680d8fe5..2c314db9fc 100644 --- a/pkg/authserver/server/clientcredentials/handler_test.go +++ b/pkg/authserver/server/clientcredentials/handler_test.go @@ -27,7 +27,7 @@ const ( // recordingHandler stands in for Fosite's stock handler; no gomock mock of // fosite.TokenEndpointHandler exists in the repo. -type recordingHandler struct{ called bool } +type recordingHandler struct{ called, populated bool } func (*recordingHandler) CanHandleTokenEndpointRequest(context.Context, fosite.AccessRequester) bool { return true @@ -39,7 +39,8 @@ func (h *recordingHandler) HandleTokenEndpointRequest(context.Context, fosite.Ac h.called = true return nil } -func (*recordingHandler) PopulateTokenEndpointResponse(context.Context, fosite.AccessRequester, fosite.AccessResponder) error { +func (h *recordingHandler) PopulateTokenEndpointResponse(context.Context, fosite.AccessRequester, fosite.AccessResponder) error { + h.populated = true return nil } @@ -131,6 +132,7 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { form: oneResource, scopes: fosite.Arguments{"admin"}, wantError: fosite.ErrInvalidScope, + wantHint: "is not permitted for this client", }, { name: "ordinary confidential client is unauthorized", @@ -138,6 +140,7 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { 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", @@ -145,9 +148,10 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { client: newClient(t, clientOpts{unwrapped: true}), form: oneResource, wantError: fosite.ErrUnauthorizedClient, + wantHint: "only to clients authenticated with a SPIFFE credential", }, { - name: "association grant is rejected", + name: "association without client_credentials is unauthorized", grants: ccGrant, client: newClient(t, clientOpts{grants: []string{oauthproto.GrantTypeTokenExchange}}), form: oneResource, @@ -161,6 +165,7 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { 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", @@ -189,6 +194,7 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { client: newClient(t, defaultClient), form: url.Values{"audience": {testResource}}, wantError: server.ErrInvalidTarget, + wantHint: "audience parameter is not accepted", }, { name: "unauthorized resource is invalid target", @@ -219,3 +225,40 @@ func TestHandlerHandleTokenEndpointRequest(t *testing.T) { }) } } + +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.Session{}) + 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) + }) + } +} From 06bb24d22eddb750d2295ef81502616768fc0178 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 21:26:49 +0100 Subject: [PATCH 10/14] Gate only JWT-SVID client_credentials on TLS Counting every spiffe_jwt association as a confidential client broke existing token-exchange-only JWT-SVID deployments that use a plain-HTTP issuer. The rule is narrowed to keep those deployments working, not because token exchange is safer: a passive observer on a plain-HTTP path captures the JWT-SVID and the subject token from the same request and can re-exchange them within the SVID's validity. An association now counts as confidential in the cleartext-transport check only when it allows spiffe_jwt and lists client_credentials, the grant where one captured SVID mints access tokens directly. Token-exchange-only JWT-SVID associations no longer count, and X.509 associations are unaffected. The four transport error messages say "JWT-SVID SPIFFE associations that grant client_credentials". The CRD cannot express client_credentials yet, so the operator goes back to its previous behavior: hasConfidentialClients is inlined again, the two CEL rules return to their earlier text, and the CRD YAMLs are regenerated. The architecture doc states the compatibility reason, that token exchange over plain HTTP is still exposed, and that the issuer should use TLS. Co-authored-by: Mecatl --- .../v1beta1/mcpexternalauthconfig_types.go | 14 +-- .../mcpexternalauthconfig_types_test.go | 16 +--- .../confidential_client_transport_cel_test.go | 18 ++-- .../mcp-external-auth/spiffe_cel_test.go | 16 +--- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 36 +++----- ...olhive.stacklok.dev_virtualmcpservers.yaml | 36 +++----- ...e.stacklok.dev_mcpexternalauthconfigs.yaml | 36 +++----- ...olhive.stacklok.dev_virtualmcpservers.yaml | 36 +++----- .../18-spiffe-association-declarations.md | 6 +- pkg/authserver/config.go | 30 ++++-- pkg/authserver/config_test.go | 92 +++++++++++++++---- pkg/authserver/server/provider.go | 26 +++--- pkg/authserver/spiffe_transport_test.go | 19 +++- pkg/authserver/spiffe_trust.go | 10 ++ pkg/authserver/spiffe_trust_test.go | 90 ++++++++++++------ 15 files changed, 271 insertions(+), 210 deletions(-) diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go index e1552bbebf..a2e5ca9d6a 100644 --- a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go +++ b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types.go @@ -943,9 +943,9 @@ type JWTBearerIssuerPolicyConfig struct { // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.startsWith('synthetic:'))",message="spiffeClientAuth clientId must not use the reserved synthetic: prefix" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches('^[A-Za-z][A-Za-z0-9+.-]*://.+'))",message="spiffeClientAuth clientId must not be an absolute URL" // -// +kubebuilder:validation:XValidation:rule="!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) && self.inboundGrants.spiffeClientAuth.exists(a, 'spiffe_jwt' in a.methods))))",message="insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations; client secrets or JWT-SVIDs would be issued or used in cleartext over an unauthenticated endpoint" +// +kubebuilder:validation:XValidation:rule="!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) > 0)))",message="insecureAllowHTTP cannot be combined with confidential client registration or delegateClients; client secrets would be issued or used in cleartext over an unauthenticated endpoint" // +kubebuilder:validation:XValidation:rule="(!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration)",message="forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true" -// +kubebuilder:validation:XValidation:rule="!self.issuer.startsWith('http://') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) || size(self.inboundGrants.tokenExchange.delegateClients) == 0) && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) && self.inboundGrants.spiffeClientAuth.exists(a, 'spiffe_jwt' in a.methods)))",message="confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback" +// +kubebuilder:validation:XValidation:rule="!self.issuer.startsWith('http://') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) || size(self.inboundGrants.tokenExchange.delegateClients) == 0))",message="confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || ((!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.trustedIssuers) || !self.trustedIssuers.exists(issuer, has(issuer.expectedAudience) || has(issuer.actorClaim) || has(issuer.allowedActors) || has(issuer.actorMatcher) || has(issuer.allowedDelegateClients) || (has(issuer.allowMayAct) && issuer.allowMayAct))))",message="canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy" // +kubebuilder:validation:XValidation:rule="!has(self.inboundGrants) || !has(self.inboundGrants.jwtBearer) || !has(self.trustedIssuers) || !self.trustedIssuers.exists(issuer, has(issuer.jwtBearerGrant))",message="canonical jwtBearer conflicts with legacy jwtBearerGrant" // +kubebuilder:validation:XValidation:rule="!has(self.trustedIssuers) || self.trustedIssuers.all(issuer, !has(issuer.name) || self.trustedIssuers.filter(other, has(other.name) && other.name == issuer.name).size() == 1)",message="trustedIssuers must not contain duplicate names" @@ -1403,14 +1403,6 @@ func applyEffectiveJWTBearer( return nil } -// hasConfidentialClients reports whether DCR of confidential clients is -// enabled, the effective grants include a delegate client, or a SPIFFE -// association allows the JWT-SVID method. -func (c *EmbeddedAuthServerConfig) hasConfidentialClients(grants effectiveInboundGrants) bool { - return c.AllowConfidentialClientRegistration || len(grants.delegateClients) > 0 || - c.hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT) -} - // ValidateInboundGrants validates the effective grant projection shared by // MCPExternalAuthConfig and inline VirtualMCPServer auth configuration. func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error { @@ -1419,7 +1411,7 @@ func (c *EmbeddedAuthServerConfig) ValidateInboundGrants() error { return err } if err := authserver.ValidateConfidentialClientTransport( - c.hasConfidentialClients(grants), + c.AllowConfidentialClientRegistration || len(grants.delegateClients) > 0, c.InsecureAllowHTTP, c.Issuer, c.InsecureAllowConfidentialOverLoopbackHTTP, diff --git a/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go b/cmd/thv-operator/api/v1beta1/mcpexternalauthconfig_types_test.go index 94d1c23f4d..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, delegate clients or JWT-SVID SPIFFE associations) 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", @@ -2127,22 +2127,14 @@ func TestEmbeddedAuthServerConfig_ValidateInboundGrants_ConfidentialClientTransp expectErr bool }{ { - name: "SPIFFE JWT association rejects insecure HTTP", + name: "SPIFFE JWT association is admitted with insecure HTTP", config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(c *EmbeddedAuthServerConfig) { c.InsecureAllowHTTP = true }), - expectErr: true, - }, - { - name: "SPIFFE JWT association rejects HTTP loopback without explicit opt in", - config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(*EmbeddedAuthServerConfig) {}), - expectErr: true, }, { - name: "SPIFFE JWT association allows HTTP loopback with explicit opt in", - config: spiffeConfig(SPIFFEAuthenticationMethodJWT, func(c *EmbeddedAuthServerConfig) { - c.InsecureAllowConfidentialOverLoopbackHTTP = 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", diff --git a/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go b/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go index 7169d4e423..4692406951 100644 --- a/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go +++ b/cmd/thv-operator/test-integration/mcp-external-auth/confidential_client_transport_cel_test.go @@ -101,7 +101,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val allowConfidential: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", }, { name: "allowPrivateKeyJWTRegistration with insecureAllowHTTP is admitted (no secret to protect)", @@ -120,7 +120,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val delegateClient: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", }, { name: "canonical delegate clients with insecureAllowHTTP set", @@ -128,7 +128,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val canonicalDelegateClient: true, insecureHTTP: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", }, { name: "legacy delegate clients with insecureAllowHTTP and HTTPS issuer", @@ -136,7 +136,7 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val insecureHTTP: true, httpsIssuer: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", }, { name: "canonical delegate clients with insecureAllowHTTP and HTTPS issuer", @@ -145,14 +145,14 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val insecureHTTP: true, httpsIssuer: true, shouldAdmit: false, - expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration, delegateClients or JWT-SVID SPIFFE associations", + expectedMessage: "insecureAllowHTTP cannot be combined with confidential client registration or delegateClients", }, { name: "delegate clients with loopback HTTP issuer without opt-in", delegateClient: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "canonical delegate clients with loopback HTTP issuer without opt-in", @@ -160,14 +160,14 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val canonicalDelegateClient: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "confidential registration with loopback HTTP issuer without opt-in", allowConfidential: true, loopbackHTTP: true, shouldAdmit: false, - expectedMessage: "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", + expectedMessage: "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP", }, { name: "confidential registration with opted-in loopback HTTP issuer", @@ -260,6 +260,6 @@ var _ = Describe("EmbeddedAuthServerConfig confidential-client-transport CEL val err := k8sClient.Create(ctx, vmcp) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring( - "confidential client registration, delegateClients or JWT-SVID SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP")) + "confidential client registration or delegateClients with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP")) }) }) 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 211c46b8a2..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 @@ -240,8 +240,8 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() { }, }, { - name: "JWT-SVID association with insecureAllowHTTP is rejected", trustDomains: true, clients: true, - principal: "spiffe://example.org/ns/default/agent", errMatch: "JWT-SVID SPIFFE associations", + 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} @@ -249,20 +249,10 @@ var _ = Describe("MCPExternalAuthConfig SPIFFE CEL validation", func() { }, }, { - name: "JWT-SVID association with an http loopback issuer needs the loopback opt-in", trustDomains: true, clients: true, - principal: "spiffe://example.org/ns/default/agent", errMatch: "insecureAllowConfidentialOverLoopbackHTTP", - 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: "JWT-SVID association with an http loopback issuer is admitted with the loopback opt-in", trustDomains: true, clients: true, + 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.InsecureAllowConfidentialOverLoopbackHTTP = true config.SPIFFETrustDomains[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} config.InboundGrants.SPIFFEClientAuth[0].Methods = []mcpv1beta1.SPIFFEAuthenticationMethod{mcpv1beta1.SPIFFEAuthenticationMethodJWT} }, 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 478b12b276..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 @@ -2632,33 +2632,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -5781,33 +5775,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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 687145407f..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 @@ -2519,33 +2519,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -8060,33 +8054,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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 5ae14c51bc..ce562a6706 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_mcpexternalauthconfigs.yaml @@ -2635,33 +2635,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -5784,33 +5778,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) 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 23af86ec70..3f0f8bc53f 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -2522,33 +2522,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) @@ -8063,33 +8057,27 @@ spec: rule: '!has(self.inboundGrants) || !has(self.inboundGrants.spiffeClientAuth) || self.inboundGrants.spiffeClientAuth.all(client, !client.clientId.matches(''^[A-Za-z][A-Za-z0-9+.-]*://.+''))' - message: insecureAllowHTTP cannot be combined with confidential - client registration, delegateClients or JWT-SVID SPIFFE associations; - client secrets or JWT-SVIDs would be issued or used in cleartext - over an unauthenticated endpoint + client registration or delegateClients; client secrets would be + issued or used in cleartext over an unauthenticated endpoint rule: '!(has(self.insecureAllowHTTP) && self.insecureAllowHTTP && ((has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) || (has(self.delegateClients) && size(self.delegateClients) > 0) || (has(self.inboundGrants) && has(self.inboundGrants.tokenExchange) && has(self.inboundGrants.tokenExchange.delegateClients) && size(self.inboundGrants.tokenExchange.delegateClients) - > 0) || (has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods))))' + > 0)))' - message: forceConfidentialRedirectUris requires allowConfidentialClientRegistration to be true rule: (!has(self.forceConfidentialRedirectUris) || size(self.forceConfidentialRedirectUris) == 0) || (has(self.allowConfidentialClientRegistration) && self.allowConfidentialClientRegistration) - - message: confidential client registration, delegateClients or JWT-SVID - SPIFFE associations with an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP + - message: confidential client registration or delegateClients with + an HTTP issuer require insecureAllowConfidentialOverLoopbackHTTP to be explicitly enabled; the issuer must still be loopback rule: '!self.issuer.startsWith(''http://'') || (has(self.insecureAllowConfidentialOverLoopbackHTTP) && self.insecureAllowConfidentialOverLoopbackHTTP) || ((!has(self.allowConfidentialClientRegistration) || !self.allowConfidentialClientRegistration) && (!has(self.delegateClients) || size(self.delegateClients) == 0) && (!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) || !has(self.inboundGrants.tokenExchange.delegateClients) - || size(self.inboundGrants.tokenExchange.delegateClients) == 0) - && !(has(self.inboundGrants) && has(self.inboundGrants.spiffeClientAuth) - && self.inboundGrants.spiffeClientAuth.exists(a, ''spiffe_jwt'' - in a.methods)))' + || size(self.inboundGrants.tokenExchange.delegateClients) == 0))' - message: canonical tokenExchange conflicts with legacy delegateClients or RFC 8693 trusted issuer policy rule: '!has(self.inboundGrants) || !has(self.inboundGrants.tokenExchange) diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 12fe4d880a..5727135cab 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -85,8 +85,6 @@ Discovery (`grantTypesSupported` and `tokenEndpointAuthMethodsSupported` in `pkg 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. -A second break: an existing CR or RunConfig that has a `spiffe_jwt` association together with `insecureAllowHTTP` (`insecure_allow_http` in a RunConfig), or with an `http://` issuer and no loopback opt-in, now fails validation (see "Known limitation: JWT-SVID replay"). For a CR, the CEL rules reject the object at admission when it sets `insecureAllowHTTP`, or has an `http://` issuer without `insecureAllowConfidentialOverLoopbackHTTP`. A non-loopback `http://` issuer that does set the loopback opt-in passes the CEL rules and is rejected only by the Go validation at reconcile. On clusters with CRD validation ratcheting, an update that leaves `embeddedAuthServer` unchanged may still be admitted, but reconcile fails in every case. For a RunConfig, `RunConfig.Validate` fails. To fix it, remove `insecureAllowHTTP` (`insecure_allow_http`), which is rejected whatever the issuer scheme, and serve the issuer over TLS with an `https://` URL. A plain-HTTP issuer is accepted only when it is a loopback address and `insecureAllowConfidentialOverLoopbackHTTP` (`insecure_allow_confidential_over_loopback_http`) is set; a non-loopback `http://` issuer is always rejected. - ### Trust-bundle source Every trust domain must declare exactly one `bundle_source`, a discriminated union naming the trust-bundle source. `newServer` constructs the configured source and passes its X.509 and JWT bundle views to the authorization server. @@ -194,7 +192,9 @@ A JWT-SVID is a bearer credential, and the SPIFFE path has no application-level - 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`. -Because the JWT-SVID is a bearer credential, an association that allows the JWT-SVID method counts as a confidential client in the cleartext-transport check (`RunConfig.hasConfidentialClients`, `Config.hasStaticConfidentialClients` and `ValidateConfidentialClientTransport`), as delegate clients do. `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()`, `Config.Validate()` and the operator's `EmbeddedAuthServerConfig.ValidateInboundGrants`. An association that enables only `spiffe_x509` does not trigger it. The API server rejects these configurations at admission: the CEL rule that forbids `insecureAllowHTTP` with confidential clients, and the rule that requires `insecureAllowConfidentialOverLoopbackHTTP` for an `http://` issuer, both treat a `spiffeClientAuth` entry with `spiffe_jwt` in `methods` as a confidential client. The Go check in `ValidateInboundGrants` is the backstop for objects stored before those rules covered SPIFFE associations. +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 for the server's normal access-token lifetime (`AccessTokenLifespan`), and that lifetime is not capped to the SVID's expiry. 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`. diff --git a/pkg/authserver/config.go b/pkg/authserver/config.go index 33f3d4170a..9e8e6771cc 100644 --- a/pkg/authserver/config.go +++ b/pkg/authserver/config.go @@ -639,8 +639,10 @@ func (c *RunConfig) Validate() error { // (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). SPIFFE associations that allow the JWT-SVID method count - // too: the JWT-SVID is a bearer credential sent in the clear over plain HTTP. + // 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.hasConfidentialClients(normalized), c.InsecureAllowHTTP, c.Issuer, c.InsecureAllowConfidentialOverLoopbackHTTP); err != nil { @@ -666,10 +668,11 @@ func (c *RunConfig) Validate() error { // 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. +// 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.hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT) + c.hasJWTClientCredentialsAssociation() } // validateSPIFFEX509Listener requires the TLS listener and an https issuer when @@ -818,6 +821,20 @@ func (c *RunConfig) hasSPIFFEMethod(method SPIFFEAuthenticationMethod) bool { }) } +// 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 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 // also present in ScopesSupported. If a baseline scope is not advertised by // ScopesSupported, the embedded DCR handler would later try to register a @@ -2404,9 +2421,10 @@ func (c *Config) validateDelegationConfig() error { } // hasStaticConfidentialClients reports whether any delegate client is -// configured or a SPIFFE association allows the JWT-SVID method. +// configured or a SPIFFE association allows the JWT-SVID method and grants +// client_credentials. func (c *Config) hasStaticConfidentialClients() bool { - return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsMethod(SPIFFEAuthenticationMethodJWT) + return len(c.DelegateClients) > 0 || c.SPIFFETrust.permitsJWTClientCredentials() } // validateConfidentialClientConfig groups cleartext-transport validation for diff --git a/pkg/authserver/config_test.go b/pkg/authserver/config_test.go index 6683cc8a86..165954ef68 100644 --- a/pkg/authserver/config_test.go +++ b/pkg/authserver/config_test.go @@ -139,10 +139,11 @@ func mustNewSPIFFETrustConfigWithSource(t *testing.T, source SPIFFEBundleSourceR return trust } -func mustNewSPIFFEJWTTrustConfig(t *testing.T) *SPIFFETrustConfig { +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", @@ -264,12 +265,16 @@ 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, delegate clients or JWT-SVID SPIFFE associations) 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: "JWT-SVID association with a plain-HTTP loopback issuer rejects without the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t)}, wantErr: true, errMsg: "insecure_allow_confidential_over_loopback_http"}, - {name: "JWT-SVID association with a plain-HTTP loopback issuer passes with the opt-in", config: Config{Issuer: "http://localhost:8080", KeyProvider: validKeyProvider, HMACSecrets: validHMAC, AllowedAudiences: []string{"https://mcp.example.com"}, SPIFFETrust: mustNewSPIFFEJWTTrustConfig(t), InsecureAllowConfidentialOverLoopbackHTTP: true}}, + {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}}, @@ -785,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 @@ -916,35 +938,67 @@ func TestRunConfigValidate(t *testing.T) { errMsg: "SPIFFE X.509 authentication requires an https issuer", }, { - name: "JWT-only association with a non-loopback http issuer is rejected", - 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-only association with insecure_allow_http is rejected", - config: x509Config(func(c *RunConfig) { - c.TLSListener = nil + name: "JWT-SVID association with both grants and insecure_allow_http is rejected", + config: jwtConfig(bothGrants, func(c *RunConfig) { c.InsecureAllowHTTP = true - c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} }), wantErr: true, errMsg: "insecure_allow_http", }, { - name: "JWT-only association with a loopback http issuer passes with the opt-in", - config: x509Config(func(c *RunConfig) { + 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.TLSListener = nil c.InsecureAllowConfidentialOverLoopbackHTTP = true - c.SPIFFETrustDomains[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - c.InboundGrants.SPIFFEClientAuth[0].Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} + }), + }, + { + 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/server/provider.go b/pkg/authserver/server/provider.go index 3a9e7437c3..12aae7ff09 100644 --- a/pkg/authserver/server/provider.go +++ b/pkg/authserver/server/provider.go @@ -194,9 +194,9 @@ type AuthorizationServerConfig struct { // HasStaticConfidentialClients indicates whether any pre-provisioned // 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). It counts for the cleartext-transport check. It does not - // drive discovery; see HasStaticSecretClients and - // HasStaticPrivateKeyJWTClients. + // 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 @@ -330,9 +330,9 @@ type AuthorizationServerParams struct { // HasStaticConfidentialClients indicates whether any pre-provisioned // 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). It counts for the cleartext-transport check. It does not - // drive discovery; see HasStaticSecretClients and - // HasStaticPrivateKeyJWTClients. + // 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 @@ -467,7 +467,7 @@ func validateTokenLifespans(cfg *AuthorizationServerParams) error { // 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, as do SPIFFE associations that -// allow the JWT-SVID method. +// allow the JWT-SVID method and grant client_credentials. func ValidateConfidentialClientTransport( allowConfidential, insecureAllowHTTP bool, issuer string, insecureAllowConfidentialOverLoopbackHTTP bool, @@ -477,7 +477,8 @@ func ValidateConfidentialClientTransport( } if insecureAllowHTTP { return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + - "delegate clients or JWT-SVID SPIFFE associations) " + + "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") } @@ -498,20 +499,23 @@ func ValidateConfidentialClientTransport( } if insecureAllowConfidentialOverLoopbackHTTP && !networking.IsLocalhost(parsed.Host) { return fmt.Errorf("confidential clients (allow_confidential_client_registration, " + - "delegate clients or JWT-SVID SPIFFE associations) " + + "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, " + - "delegate clients or JWT-SVID SPIFFE associations) " + + "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, " + - "delegate clients or JWT-SVID SPIFFE associations) " + + "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") } diff --git a/pkg/authserver/spiffe_transport_test.go b/pkg/authserver/spiffe_transport_test.go index 78155243f3..9941fa4aff 100644 --- a/pkg/authserver/spiffe_transport_test.go +++ b/pkg/authserver/spiffe_transport_test.go @@ -14,10 +14,11 @@ import ( 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 association as a confidential client, so +// 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) { @@ -28,7 +29,21 @@ func TestAuthorizationServerParamsGateSPIFFEJWTOnTransport(t *testing.T) { trust *SPIFFETrustConfig wantErr string }{ - {name: "JWT-SVID association is refused", trust: mustNewSPIFFEJWTTrustConfig(t), wantErr: "plain-HTTP non-loopback"}, + { + 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 { diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index ef26098b44..b4106681a2 100644 --- a/pkg/authserver/spiffe_trust.go +++ b/pkg/authserver/spiffe_trust.go @@ -423,6 +423,16 @@ func (c *SPIFFETrustConfig) permitsMethod(method SPIFFEAuthenticationMethod) boo }) } +// 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 diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index e6c09fbb43..6833712d75 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -346,37 +346,71 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { assert.False(t, ok) } -func TestHasSPIFFEJWTAssociation(t *testing.T) { +func TestJWTClientCredentialsAssociation(t *testing.T) { t.Parallel() - x509Only := testSPIFFEAssociation("x509-client", "openid") - jwtOnly := testSPIFFEAssociation("jwt-client", "openid") - jwtOnly.Methods = []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodJWT} - - assert.False(t, (*RunConfig)(nil).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) - assert.False(t, (&RunConfig{InboundGrants: &InboundGrantsRunConfig{ - SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only}, - }}).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) - assert.True(t, (&RunConfig{InboundGrants: &InboundGrantsRunConfig{ - SPIFFEClientAuth: []SPIFFEClientAuthRunConfig{x509Only, jwtOnly}, - }}).hasSPIFFEMethod(SPIFFEAuthenticationMethodJWT)) - assert.False(t, (*SPIFFETrustConfig)(nil).permitsMethod(SPIFFEAuthenticationMethodJWT)) - - trust := func(associations ...SPIFFEClientAuthRunConfig) *SPIFFETrustConfig { - cfg, err := NewSPIFFETrustConfig([]SPIFFETrustDomainRunConfig{{ - Name: "production", - TrustDomain: "example.org", - Methods: []SPIFFEAuthenticationMethod{SPIFFEAuthenticationMethodX509, SPIFFEAuthenticationMethodJWT}, - BundleSource: validFileBundleSource(), - }}, &InboundGrantsRunConfig{SPIFFEClientAuth: associations}, - []string{"openid"}, []string{"https://audience.example.com"}) - require.NoError(t, err) - return cfg + assoc := func(principal string, method SPIFFEAuthenticationMethod, grants ...string) SPIFFEClientAuthRunConfig { + a := withPrincipal(testSPIFFEAssociation(principal, "openid"), principal) + a.Methods = []SPIFFEAuthenticationMethod{method} + a.GrantTypes = grants + return a } - x509Other := withPrincipal(x509Only, "spiffe://example.org/ns/default/other") - jwtOther := withPrincipal(jwtOnly, "spiffe://example.org/ns/default/jwt") - assert.False(t, trust(x509Only).permitsMethod(SPIFFEAuthenticationMethodJWT)) - assert.True(t, trust(x509Other, jwtOther).permitsMethod(SPIFFEAuthenticationMethodJWT)) + const ( + tokenExchange = oauthproto.GrantTypeTokenExchange + clientCredentials = oauthproto.GrantTypeClientCredentials + ) + jwtCC := assoc("spiffe://example.org/ns/default/jwt-cc", SPIFFEAuthenticationMethodJWT, clientCredentials) + jwtBoth := assoc("spiffe://example.org/ns/default/jwt-both", SPIFFEAuthenticationMethodJWT, tokenExchange, clientCredentials) + jwtTE := assoc("spiffe://example.org/ns/default/jwt-te", SPIFFEAuthenticationMethodJWT, tokenExchange) + x509CC := assoc("spiffe://example.org/ns/default/x509-cc", SPIFFEAuthenticationMethodX509, clientCredentials) + x509TE := assoc("spiffe://example.org/ns/default/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. From 03de360ab8190b2955cfa97c09515bec58df20cb Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 21:01:33 +0100 Subject: [PATCH 11/14] Narrow SPIFFE workload binding in token exchange The workload binding rejected every ToolHive-issued subject token that did not carry the caller's SPIFFE ID, so a workload could not even re-exchange the user-delegated token it had obtained itself (act.sub is the client ID there). The guard now applies only when the subject token names a workload: its sub or outermost act.sub parses as a SPIFFE ID. Such a token must name the caller, as before. A token that names only the user and the client ID can be re-exchanged by any workload of that client, since the user consented to the client. Also close an actor_token gap: only the client_id claim was checked, so workload B could present workload A's client_credentials token as its actor_token and get act.sub = A, or satisfy a may_act naming A. For an authenticated SPIFFE caller the actor token's sub must now equal the caller's verified SPIFFE ID, otherwise invalid_request. Other clients are unchanged. Co-authored-by: Mecatl --- docs/arch/17-token-exchange-delegation.md | 5 + .../18-spiffe-association-declarations.md | 2 +- .../server/tokenexchange/handler.go | 47 ++++-- .../server/tokenexchange/handler_test.go | 145 +++++++++++++++++- 4 files changed, 182 insertions(+), 17 deletions(-) diff --git a/docs/arch/17-token-exchange-delegation.md b/docs/arch/17-token-exchange-delegation.md index 90446e9453..38c6c748b2 100644 --- a/docs/arch/17-token-exchange-delegation.md +++ b/docs/arch/17-token-exchange-delegation.md @@ -569,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). diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 5727135cab..25548245ec 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -54,7 +54,7 @@ Clients that carry a resource list, such as SPIFFE clients, are targeted by exac - 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 must therefore carry the caller's verified SPIFFE ID, either as its `sub` or as the `sub` of its outermost `act` entry. Otherwise the exchange fails with `invalid_grant` and the hint `The subject token was issued to a different workload of this client.` 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. At present `act.sub` holds the client ID, unless the earlier exchange named the workload through `actor_token`. A SPIFFE client can therefore generally not re-exchange a delegated token it received earlier. That is deliberate: the exchange fails closed until a later change records the SPIFFE ID in `act.sub`. +**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. diff --git a/pkg/authserver/server/tokenexchange/handler.go b/pkg/authserver/server/tokenexchange/handler.go index 116f0bfed9..2d8646f8cc 100644 --- a/pkg/authserver/server/tokenexchange/handler.go +++ b/pkg/authserver/server/tokenexchange/handler.go @@ -16,6 +16,7 @@ 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" @@ -440,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) { @@ -461,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 } @@ -859,9 +874,12 @@ func sourceClientAllowed(validatedClaims *ValidatedClaims, clientID string, poli // 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 -// the subject token must also name this workload: its sub must be spiffeID, or -// its outermost act.sub must be. The may_act and external actor cases name +// 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, @@ -926,19 +944,28 @@ func checkDelegationConsent( } // isAnotherWorkloadsToken reports whether a ToolHive-issued subject token that -// is bound to clientID names a SPIFFE workload other than spiffeID: neither its -// sub nor the sub of its outermost act entry is spiffeID. It is false for a -// caller that is not a SPIFFE client (empty spiffeID). +// 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 } - if validatedClaims.Subject == spiffeID { - return false - } act, _ := validatedClaims.Extra["act"].(map[string]any) actSub, _ := act["sub"].(string) - return actSub != spiffeID + 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 diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index 102cb76a9e..ef69bf6579 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -2241,13 +2241,44 @@ func TestCheckDelegationConsent(t *testing.T) { spiffeID: "spiffe://example.org/ns/default/agent-a", }, { - name: "SPIFFE client re-exchanging a delegated token whose act.sub is the client ID rejected", + 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", + 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", }, @@ -3305,10 +3336,28 @@ func TestHandleTokenEndpointRequest_SPIFFESubjectTokenOwnership(t *testing.T) { tests := []struct { name string caller string + act map[string]any + sub string wantErr bool }{ - {name: "the workload the token was issued to", caller: workloadA}, - {name: "a sibling workload with the same client ID", caller: workloadB, wantErr: true}, + {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) { @@ -3317,10 +3366,14 @@ func TestHandleTokenEndpointRequest_SPIFFESubjectTokenOwnership(t *testing.T) { tj := newTestJWKS(t) h := newTestHandler(t, tj, time.Hour) claims := validClaims() - claims.Subject = workloadA + 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, validExtraClaims())}, + "subject_token": {tj.signToken(t, claims, extra)}, "subject_token_type": {oauthproto.TokenTypeAccessToken}, "resource": {testIssuer}, } @@ -3341,6 +3394,86 @@ func TestHandleTokenEndpointRequest_SPIFFESubjectTokenOwnership(t *testing.T) { } } +// 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 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. From 5d455bdaec1d92b267e943a017181a28a41b4a1b Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 21:26:49 +0100 Subject: [PATCH 12/14] Cap client_credentials tokens at SVID expiry client_credentials access tokens took Fosite's stock lifetime, the server's AccessTokenLifespan (one hour by default, configurable up to a day), regardless of the SVID that authenticated the request. A JWT-SVID is accepted with at most about six minutes left, so a token could outlive its credential many times over. The token now lives for the smaller of AccessTokenLifespan and the remaining validity of the SVID that authenticated the request: the JWT-SVID's exp or the X.509 leaf's NotAfter. expires_in and the token's exp both follow. No new setting is added. An SVID that is already expired normally fails client authentication with invalid_client; a JWT-SVID inside the one-minute leeway go-spiffe grants after exp passes authentication and is now refused with invalid_grant. The verifiers pass the expiry through the SPIFFE client resolver, and the authenticated client carries it. A zero expiry is rejected when the client is built, so every production path supplies one. Populate re-checks the session expiry before issuing so a cap that lapses between the two steps fails closed. Co-authored-by: Mecatl --- .../18-spiffe-association-declarations.md | 8 +- pkg/authserver/internal/spiffetest/client.go | 13 +- .../server/clientcredentials/handler.go | 36 +++++- .../server/clientcredentials/handler_test.go | 74 +++++++++++- .../server/provider_spiffe_x509_test.go | 2 +- .../authenticated_spiffe_client.go | 21 +++- .../server/registration/spiffe_client_test.go | 17 ++- pkg/authserver/server/spiffe_client_auth.go | 35 +++--- .../server/spiffe_client_auth_test.go | 34 +++++- .../server/spiffe_client_auth_x509_test.go | 17 +-- pkg/authserver/server_impl.go | 3 +- pkg/authserver/spiffe_association_registry.go | 10 +- .../spiffe_association_registry_test.go | 6 +- ...ffe_client_credentials_integration_test.go | 114 +++++++++++++++--- pkg/authserver/spiffe_client_resolver_test.go | 3 +- 15 files changed, 321 insertions(+), 72 deletions(-) diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 25548245ec..41a1da25df 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -60,7 +60,7 @@ Delegate clients and other clients (`private_key_jwt`, `client_secret`, DCR and ### 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 below and then lets Fosite issue the token, so lifetime and signing match the other grants. A request is handled as follows: +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. @@ -70,6 +70,8 @@ The `client_credentials` grant is handled by `Handler` in `pkg/authserver/server 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' \ @@ -190,13 +192,13 @@ The `spiffe_x509` and `spiffe_jwt` client authentication methods, and the `urn:i 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 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 for the server's normal access-token lifetime (`AccessTokenLifespan`), and that lifetime is not capped to the SVID's expiry. 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`. +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 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/server/clientcredentials/handler.go b/pkg/authserver/server/clientcredentials/handler.go index 0d02e31983..c661766f96 100644 --- a/pkg/authserver/server/clientcredentials/handler.go +++ b/pkg/authserver/server/clientcredentials/handler.go @@ -9,6 +9,7 @@ import ( "fmt" "log/slog" "slices" + "time" "github.com/ory/fosite" "github.com/ory/fosite/compose" @@ -88,7 +89,10 @@ func (h *Handler) HandleTokenEndpointRequest(ctx context.Context, requester fosi // the token. See claimnames.NoUpstreamSessionKey. sess.JWTClaims.Extra[claimnames.NoUpstreamSessionKey] = true requester.SetSession(sess) - return h.stock.HandleTokenEndpointRequest(ctx, requester) + if err := h.stock.HandleTokenEndpointRequest(ctx, requester); err != nil { + return err + } + return capAtCredentialExpiry(requester, client) } // PopulateTokenEndpointResponse delegates access-token issuance to the stock @@ -99,9 +103,39 @@ func (h *Handler) PopulateTokenEndpointResponse( 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) { diff --git a/pkg/authserver/server/clientcredentials/handler_test.go b/pkg/authserver/server/clientcredentials/handler_test.go index 2c314db9fc..99221ba9f9 100644 --- a/pkg/authserver/server/clientcredentials/handler_test.go +++ b/pkg/authserver/server/clientcredentials/handler_test.go @@ -8,6 +8,7 @@ import ( "context" "net/url" "testing" + "time" "github.com/ory/fosite" "github.com/stretchr/testify/assert" @@ -27,7 +28,12 @@ const ( // recordingHandler stands in for Fosite's stock handler; no gomock mock of // fosite.TokenEndpointHandler exists in the repo. -type recordingHandler struct{ called, populated bool } +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 @@ -35,8 +41,11 @@ func (*recordingHandler) CanHandleTokenEndpointRequest(context.Context, fosite.A func (*recordingHandler) CanSkipClientAuth(context.Context, fosite.AccessRequester) bool { return false } -func (h *recordingHandler) HandleTokenEndpointRequest(context.Context, fosite.AccessRequester) error { +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 { @@ -53,6 +62,7 @@ type clientOpts struct { scopes []string resources []string method spiffeauth.SPIFFEAuthenticationMethod + expiry time.Time // unwrapped returns the static client without the authenticated principal. unwrapped bool } @@ -68,6 +78,9 @@ func newClient(t *testing.T, o clientOpts) fosite.Client { 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...) } @@ -250,7 +263,7 @@ func TestHandlerPopulateTokenEndpointResponse(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() stock := &recordingHandler{} - req := fosite.NewAccessRequest(&session.Session{}) + 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 { @@ -262,3 +275,58 @@ func TestHandlerPopulateTokenEndpointResponse(t *testing.T) { }) } } + +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 + // wantIn is the expected access-token lifetime, within a few seconds. + wantIn time.Duration + wantError bool + }{ + {name: "credential sooner than the access-token lifespan caps the token", credentialIn: 5 * time.Minute, wantIn: 5 * time.Minute}, + {name: "credential outliving the access-token lifespan leaves the lifespan", credentialIn: 24 * time.Hour, wantIn: 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.wantIn.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/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_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_impl.go b/pkg/authserver/server_impl.go index 4f47692dc8..5dabc97535 100644 --- a/pkg/authserver/server_impl.go +++ b/pkg/authserver/server_impl.go @@ -616,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 } diff --git a/pkg/authserver/spiffe_association_registry.go b/pkg/authserver/spiffe_association_registry.go index 8a418e1d4e..584b0a2703 100644 --- a/pkg/authserver/spiffe_association_registry.go +++ b/pkg/authserver/spiffe_association_registry.go @@ -10,6 +10,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/ory/fosite" @@ -82,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") @@ -107,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 diff --git a/pkg/authserver/spiffe_association_registry_test.go b/pkg/authserver/spiffe_association_registry_test.go index e622404120..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) }) diff --git a/pkg/authserver/spiffe_client_credentials_integration_test.go b/pkg/authserver/spiffe_client_credentials_integration_test.go index 6f21a5a327..a5768e6ffe 100644 --- a/pkg/authserver/spiffe_client_credentials_integration_test.go +++ b/pkg/authserver/spiffe_client_credentials_integration_test.go @@ -52,10 +52,12 @@ const ( type ccFixture struct { handler http.Handler // tokenKey verifies access tokens; jwtKey signs JWT-SVIDs; leaf is an - // X.509-SVID for ccX509SPIFFEID. - tokenKey *rsa.PrivateKey - jwtKey *ecdsa.PrivateKey - leaf *x509.Certificate + // 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 { @@ -68,7 +70,7 @@ func newCCFixture(t *testing.T) *ccFixture { SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test CA"}, NotBefore: now.Add(-time.Hour), - NotAfter: now.Add(time.Hour), + NotAfter: now.Add(4 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, @@ -80,18 +82,23 @@ func newCCFixture(t *testing.T) *ccFixture { spiffeURL, err := url.Parse(ccX509SPIFFEID) require.NoError(t, err) leafKey := mustCCECKey(t) - leafDER, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ - SerialNumber: big.NewInt(2), - Subject: pkix.Name{CommonName: "test workload"}, - NotBefore: now.Add(-time.Hour), - NotAfter: now.Add(time.Hour), - 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) + 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, @@ -162,7 +169,7 @@ func newCCFixture(t *testing.T) *ccFixture { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, srv.Close()) }) - return &ccFixture{handler: srv.Handler(), tokenKey: tokenKey, jwtKey: jwtKey, leaf: leaf} + return &ccFixture{handler: srv.Handler(), tokenKey: tokenKey, jwtKey: jwtKey, leaf: leaf, shortLeaf: shortLeaf} } func mustCCECKey(t *testing.T) *ecdsa.PrivateKey { @@ -173,6 +180,11 @@ func mustCCECKey(t *testing.T) *ecdsa.PrivateKey { } 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}, @@ -182,7 +194,7 @@ func (f *ccFixture) jwtSVID(t *testing.T, spiffeID string) string { token, err := jwt.Signed(signer).Claims(jwt.Claims{ Subject: spiffeID, Audience: jwt.Audience{testIssuer}, - Expiry: jwt.NewNumericDate(time.Now().Add(time.Minute)), + Expiry: jwt.NewNumericDate(time.Now().Add(validity)), }).Serialize() require.NoError(t, err) return token @@ -304,3 +316,67 @@ func TestSPIFFEClientCredentialsThroughNewServer(t *testing.T) { }) } } + +// 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 + wantIn time.Duration + wantError string + }{ + {name: "JWT-SVID with a minute left caps the token", form: jwtForm(t, time.Minute), wantIn: 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, wantIn: 5 * time.Minute}, + {name: "X.509-SVID outliving the lifespan leaves the access-token lifespan", form: x509Form, peer: f.leaf, wantIn: 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.wantIn.Seconds(), expiresIn, 30) + assert.LessOrEqual(t, expiresIn, tt.wantIn.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.wantIn).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") From c424ca7ffea0eed8f6cd70b1a19e896267adefa0 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 21:12:46 +0100 Subject: [PATCH 13/14] Reject URL client IDs on SPIFFE associations The operator CRD already refuses an absolute-URL client_id on a SPIFFE association, but a hand-written RunConfig was accepted. The token exchange workload guard reads a token as naming a workload when its outermost act.sub parses as a SPIFFE ID. Without an actor token that act.sub is the client ID, so a client_id such as spiffe://example.org/reporting would make every re-exchange fail. Co-authored-by: Mecatl --- .../18-spiffe-association-declarations.md | 2 +- .../server/tokenexchange/handler_test.go | 4 ++++ pkg/authserver/spiffe_trust.go | 11 ++++++++++ pkg/authserver/spiffe_trust_test.go | 20 ++++++++++++------- 4 files changed, 29 insertions(+), 8 deletions(-) diff --git a/docs/arch/18-spiffe-association-declarations.md b/docs/arch/18-spiffe-association-declarations.md index 41a1da25df..74397a9ebb 100644 --- a/docs/arch/18-spiffe-association-declarations.md +++ b/docs/arch/18-spiffe-association-declarations.md @@ -33,7 +33,7 @@ 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. 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`. +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 diff --git a/pkg/authserver/server/tokenexchange/handler_test.go b/pkg/authserver/server/tokenexchange/handler_test.go index ef69bf6579..7d0d625863 100644 --- a/pkg/authserver/server/tokenexchange/handler_test.go +++ b/pkg/authserver/server/tokenexchange/handler_test.go @@ -3428,6 +3428,10 @@ func TestHandleTokenEndpointRequest_SPIFFEActorToken(t *testing.T) { 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, diff --git a/pkg/authserver/spiffe_trust.go b/pkg/authserver/spiffe_trust.go index b4106681a2..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" @@ -651,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, @@ -686,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 { diff --git a/pkg/authserver/spiffe_trust_test.go b/pkg/authserver/spiffe_trust_test.go index 6833712d75..b660e5cd45 100644 --- a/pkg/authserver/spiffe_trust_test.go +++ b/pkg/authserver/spiffe_trust_test.go @@ -172,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"}, @@ -349,8 +355,8 @@ func TestSPIFFETrustConfigTrustDomainLookup(t *testing.T) { func TestJWTClientCredentialsAssociation(t *testing.T) { t.Parallel() - assoc := func(principal string, method SPIFFEAuthenticationMethod, grants ...string) SPIFFEClientAuthRunConfig { - a := withPrincipal(testSPIFFEAssociation(principal, "openid"), principal) + 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 @@ -359,11 +365,11 @@ func TestJWTClientCredentialsAssociation(t *testing.T) { tokenExchange = oauthproto.GrantTypeTokenExchange clientCredentials = oauthproto.GrantTypeClientCredentials ) - jwtCC := assoc("spiffe://example.org/ns/default/jwt-cc", SPIFFEAuthenticationMethodJWT, clientCredentials) - jwtBoth := assoc("spiffe://example.org/ns/default/jwt-both", SPIFFEAuthenticationMethodJWT, tokenExchange, clientCredentials) - jwtTE := assoc("spiffe://example.org/ns/default/jwt-te", SPIFFEAuthenticationMethodJWT, tokenExchange) - x509CC := assoc("spiffe://example.org/ns/default/x509-cc", SPIFFEAuthenticationMethodX509, clientCredentials) - x509TE := assoc("spiffe://example.org/ns/default/x509-te", SPIFFEAuthenticationMethodX509, tokenExchange) + 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 From a0925c76b7576ca950c18f6ba1576c57fe724f73 Mon Sep 17 00:00:00 2001 From: Jakub Hrozek Date: Tue, 17 Nov 2026 22:38:03 +0100 Subject: [PATCH 14/14] Rename wantIn in lifetime tests Codespell reads the test field wantIn as a misspelling of "wanting" and fails the spellcheck job. Rename it to wantExpiresIn. Test-only. Co-authored-by: Mecatl --- .../server/clientcredentials/handler_test.go | 12 +++++----- ...ffe_client_credentials_integration_test.go | 22 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pkg/authserver/server/clientcredentials/handler_test.go b/pkg/authserver/server/clientcredentials/handler_test.go index 99221ba9f9..ba32859aa7 100644 --- a/pkg/authserver/server/clientcredentials/handler_test.go +++ b/pkg/authserver/server/clientcredentials/handler_test.go @@ -284,12 +284,12 @@ func TestHandlerCapsAccessTokenAtCredentialExpiry(t *testing.T) { name string // credentialIn is the credential's remaining validity. credentialIn time.Duration - // wantIn is the expected access-token lifetime, within a few seconds. - wantIn time.Duration - wantError bool + // 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, wantIn: 5 * time.Minute}, - {name: "credential outliving the access-token lifespan leaves the lifespan", credentialIn: 24 * time.Hour, wantIn: lifespan}, + {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 { @@ -310,7 +310,7 @@ func TestHandlerCapsAccessTokenAtCredentialExpiry(t *testing.T) { return } require.NoError(t, err) - assert.InDelta(t, tt.wantIn.Seconds(), + assert.InDelta(t, tt.wantExpiresIn.Seconds(), time.Until(req.GetSession().GetExpiresAt(fosite.AccessToken)).Seconds(), 5) }) } diff --git a/pkg/authserver/spiffe_client_credentials_integration_test.go b/pkg/authserver/spiffe_client_credentials_integration_test.go index a5768e6ffe..c2a2eb176b 100644 --- a/pkg/authserver/spiffe_client_credentials_integration_test.go +++ b/pkg/authserver/spiffe_client_credentials_integration_test.go @@ -340,16 +340,16 @@ func TestSPIFFEClientCredentialsTokenLifetime(t *testing.T) { } tests := []struct { - name string - form url.Values - peer *x509.Certificate - wantIn time.Duration - wantError string + 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), wantIn: time.Minute}, + {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, wantIn: 5 * time.Minute}, - {name: "X.509-SVID outliving the lifespan leaves the access-token lifespan", form: x509Form, peer: f.leaf, wantIn: time.Hour}, + {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) { @@ -369,14 +369,14 @@ func TestSPIFFEClientCredentialsTokenLifetime(t *testing.T) { 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.wantIn.Seconds(), expiresIn, 30) - assert.LessOrEqual(t, expiresIn, tt.wantIn.Seconds()) + 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.wantIn).Unix()), exp, 30, "exp follows the capped expiry") + assert.InDelta(t, float64(time.Now().Add(tt.wantExpiresIn).Unix()), exp, 30, "exp follows the capped expiry") }) } }