diff --git a/internal/api/api.go b/internal/api/api.go index 79060647b4..2c35415265 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -52,6 +52,8 @@ type API struct { mailer mailer.Mailer oidcCache *provider.OIDCProviderCache + clientAssertionCache *provider.ClientAssertionCache + captchaVerifier security.CaptchaVerifier // overrideTime can be used to override the clock used by handlers. Should only be used in tests! @@ -105,6 +107,7 @@ func NewAPIWithVersion(globalConfig *conf.GlobalConfiguration, db *storage.Conne } api.oidcCache = provider.NewOIDCProviderCache(globalConfig.External.OIDCProviderCacheTTL) + api.clientAssertionCache = provider.NewClientAssertionCache() for _, o := range opt { o.apply(api) diff --git a/internal/api/external.go b/internal/api/external.go index f32420ee75..957a327946 100644 --- a/internal/api/external.go +++ b/internal/api/external.go @@ -739,6 +739,12 @@ func (a *API) loadCustomProvider(ctx context.Context, db *storage.Connection, id scopeList = customProvider.Scopes } + // Fail closed before any request goes out if the provider can't be used + // with private_key_jwt right now. + if err := checkClientAssertionAvailable(customProvider, &config.Experimental.ClientAssertion); err != nil { + return nil, pConfig, err + } + // Decrypt client secret for runtime use clientSecret, err := customProvider.GetClientSecret(config.Security.DBEncryption) if err != nil { @@ -806,6 +812,15 @@ func (a *API) loadCustomProvider(ctx context.Context, db *storage.Connection, id return nil, pConfig, fmt.Errorf("error creating OIDC provider: %w", err) } + if customProvider.ClientAuthMethod == models.ClientAuthMethodPrivateKeyJWT { + p.UseClientAssertion( + a.clientAssertionCache, + &config.Experimental.ClientAssertion, + clientAssertionRequestFor(customProvider), + identifier, + ) + } + // Build provider configuration pConfig = conf.OAuthProviderConfiguration{ Enabled: true, @@ -819,6 +834,37 @@ func (a *API) loadCustomProvider(ctx context.Context, db *storage.Connection, id return p, pConfig, nil } +// checkClientAssertionAvailable returns an error if customProvider uses +// private_key_jwt but client assertions are disabled, no signing key is +// configured, or the provider isn't OIDC. +func checkClientAssertionAvailable(customProvider *models.CustomOAuthProvider, assertionConfig *conf.ClientAssertionConfiguration) error { + if customProvider.ClientAuthMethod != models.ClientAuthMethodPrivateKeyJWT { + return nil + } + if !assertionConfig.Enabled || assertionConfig.SigningKey == nil { + return fmt.Errorf("custom provider %s uses private_key_jwt, but client assertions are not enabled", customProvider.Identifier) + } + if !customProvider.IsOIDC() || customProvider.Issuer == nil { + return fmt.Errorf("custom provider %s uses private_key_jwt, which requires an OIDC provider with an issuer", customProvider.Identifier) + } + return nil +} + +// clientAssertionRequestFor returns the assertion request for a +// private_key_jwt provider. The audience is the configured override, or the +// provider's issuer. +func clientAssertionRequestFor(customProvider *models.CustomOAuthProvider) provider.ClientAssertionRequest { + audience := *customProvider.Issuer + if customProvider.ClientAssertionAudience != nil && *customProvider.ClientAssertionAudience != "" { + audience = *customProvider.ClientAssertionAudience + } + return provider.ClientAssertionRequest{ + ProviderID: customProvider.ID.String(), + ClientID: customProvider.ClientID, + Audience: audience, + } +} + func redirectErrors(handler apiHandler, w http.ResponseWriter, r *http.Request, u *url.URL) { ctx := r.Context() log := observability.GetLogEntry(r).Entry diff --git a/internal/api/external_client_assertion_test.go b/internal/api/external_client_assertion_test.go new file mode 100644 index 0000000000..0244cebcff --- /dev/null +++ b/internal/api/external_client_assertion_test.go @@ -0,0 +1,157 @@ +package api + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/gofrs/uuid" + "github.com/golang-jwt/jwt/v5" + "github.com/lestrrat-go/jwx/v2/jwk" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/supabase/auth/internal/api/provider" + "github.com/supabase/auth/internal/conf" + "github.com/supabase/auth/internal/models" + "github.com/supabase/auth/internal/utilities" + "golang.org/x/oauth2" +) + +func newPrivateKeyJWTModel(issuer string) *models.CustomOAuthProvider { + return &models.CustomOAuthProvider{ + ID: uuid.Must(uuid.NewV4()), + ProviderType: models.ProviderTypeOIDC, + Identifier: "custom:pkjwt", + ClientID: "test-client-id", + Issuer: &issuer, + ClientAuthMethod: models.ClientAuthMethodPrivateKeyJWT, + } +} + +func TestCheckClientAssertionAvailable(t *testing.T) { + enabled := &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningKey: func(context.Context) (any, error) { return nil, nil }, + } + + // client_secret providers are never affected + secretProvider := newPrivateKeyJWTModel("https://issuer.example.com") + secretProvider.ClientAuthMethod = models.ClientAuthMethodClientSecret + require.NoError(t, checkClientAssertionAvailable(secretProvider, &conf.ClientAssertionConfiguration{})) + + require.NoError(t, checkClientAssertionAvailable(newPrivateKeyJWTModel("https://issuer.example.com"), enabled)) + + err := checkClientAssertionAvailable(newPrivateKeyJWTModel("https://issuer.example.com"), &conf.ClientAssertionConfiguration{}) + require.ErrorContains(t, err, "client assertions are not enabled") + + noKey := &conf.ClientAssertionConfiguration{Enabled: true} + err = checkClientAssertionAvailable(newPrivateKeyJWTModel("https://issuer.example.com"), noKey) + require.ErrorContains(t, err, "client assertions are not enabled") + + oauth2Provider := newPrivateKeyJWTModel("https://issuer.example.com") + oauth2Provider.ProviderType = models.ProviderTypeOAuth2 + oauth2Provider.Issuer = nil + err = checkClientAssertionAvailable(oauth2Provider, enabled) + require.ErrorContains(t, err, "requires an OIDC provider") +} + +func TestClientAssertionRequestFor(t *testing.T) { + p := newPrivateKeyJWTModel("https://issuer.example.com") + + req := clientAssertionRequestFor(p) + assert.Equal(t, p.ID.String(), req.ProviderID) + assert.Equal(t, "test-client-id", req.ClientID) + assert.Equal(t, "https://issuer.example.com", req.Audience, "defaults to the issuer") + + audience := "https://issuer.example.com/token" + p.ClientAssertionAudience = &audience + assert.Equal(t, audience, clientAssertionRequestFor(p).Audience, "the override wins") +} + +// TestLoadCustomProviderFailsClosedForPrivateKeyJWT checks that a +// private_key_jwt provider can't be loaded while client assertions are off, +// so neither the authorize redirect nor the token exchange can happen. +func (ts *CustomOAuthAdminTestSuite) TestLoadCustomProviderFailsClosedForPrivateKeyJWT() { + provider := ts.createOIDCProviderInDB("pkjwt-fail-closed", "https://pkjwt-fail-closed.example.com") + provider.ClientAuthMethod = models.ClientAuthMethodPrivateKeyJWT + provider.ClientSecret = "" + require.NoError(ts.T(), models.UpdateCustomOAuthProvider(ts.API.db, provider)) + + _, _, err := ts.API.loadCustomProvider(context.Background(), ts.API.db, provider.Identifier, "") + require.ErrorContains(ts.T(), err, "client assertions are not enabled") +} + +// TestLoadCustomProviderUsesClientAssertion checks that a private_key_jwt +// provider loaded with client assertions enabled authenticates its token +// exchange with a signed assertion instead of a client secret. +func (ts *CustomOAuthAdminTestSuite) TestLoadCustomProviderUsesClientAssertion() { + var tokenForm url.Values + var server *httptest.Server + // TLS, because custom OIDC issuers must be https + server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/.well-known/openid-configuration": + _, _ = w.Write([]byte(`{"issuer":"` + server.URL + `","authorization_endpoint":"` + server.URL + + `/authorize","token_endpoint":"` + server.URL + `/token","jwks_uri":"` + server.URL + `/jwks"}`)) + case "/token": + require.NoError(ts.T(), r.ParseForm()) + tokenForm = r.PostForm + _, _ = w.Write([]byte(`{"access_token":"test-access-token","token_type":"Bearer","expires_in":3600}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + + // the production fetcher rejects loopback addresses + restore := utilities.SetOIDCDiscoveryHTTPFetcherForTest(func(ctx context.Context, discoveryURL string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, discoveryURL, nil) + if err != nil { + return nil, err + } + return server.Client().Do(req) + }) + defer restore() + // the token exchange trusts the test server's certificate + ctx := context.WithValue(context.Background(), oauth2.HTTPClient, server.Client()) + + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(ts.T(), err) + signingJwk, err := jwk.FromRaw(key) + require.NoError(ts.T(), err) + require.NoError(ts.T(), signingJwk.Set(jwk.KeyIDKey, "assertion-key")) + require.NoError(ts.T(), signingJwk.Set(jwk.AlgorithmKey, "RS256")) + ts.Config.Experimental.ClientAssertion = conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: signingJwk, + SigningKey: func(context.Context) (any, error) { return key, nil }, + } + + model := ts.createOIDCProviderInDB("pkjwt-load", server.URL) + model.ClientAuthMethod = models.ClientAuthMethodPrivateKeyJWT + model.ClientSecret = "" + require.NoError(ts.T(), models.UpdateCustomOAuthProvider(ts.API.db, model)) + + p, _, err := ts.API.loadCustomProvider(ctx, ts.API.db, model.Identifier, "") + require.NoError(ts.T(), err) + oauthProvider, ok := p.(provider.OAuthProvider) + require.True(ts.T(), ok) + _, err = oauthProvider.GetOAuthToken(ctx, "test-code") + require.NoError(ts.T(), err) + + require.NotNil(ts.T(), tokenForm, "the token endpoint was called") + assert.NotContains(ts.T(), tokenForm, "client_secret") + assert.Equal(ts.T(), "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", tokenForm.Get("client_assertion_type")) + _, err = jwt.Parse(tokenForm.Get("client_assertion"), func(*jwt.Token) (any, error) { return &key.PublicKey, nil }, + jwt.WithValidMethods([]string{"RS256"}), + jwt.WithAudience(server.URL), + jwt.WithIssuer("test-client-id"), + jwt.WithSubject("test-client-id"), + ) + require.NoError(ts.T(), err) +} diff --git a/internal/api/provider/client_assertion.go b/internal/api/provider/client_assertion.go index 0d69561d27..b94db57f57 100644 --- a/internal/api/provider/client_assertion.go +++ b/internal/api/provider/client_assertion.go @@ -3,12 +3,18 @@ package provider import ( "context" "errors" + "fmt" "strings" "sync" "time" "github.com/golang-jwt/jwt/v5" + "github.com/sirupsen/logrus" "github.com/supabase/auth/internal/conf" + "github.com/supabase/auth/internal/observability" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "golang.org/x/oauth2" "golang.org/x/sync/singleflight" ) @@ -28,8 +34,35 @@ const ( // clientAssertionType is the JWT typ header for client assertions. clientAssertionType = "client-authentication+jwt" + + // ClientAssertionTypeJWTBearer is the client_assertion_type value for + // JWT client assertions (RFC 7523 section 2.2). + ClientAssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" // #nosec G101 -- Not a secret value. +) + +var ( + clientAssertionSignDuration = mustFloat64Histogram( + "gotrue_client_assertion_sign_duration_seconds", + "Time taken to sign a client assertion, including KMS calls", + ) + clientAssertionSignErrors = observability.ObtainMetricCounter( + "gotrue_client_assertion_sign_errors_total", + "Number of client assertion signing errors, including KMS errors", + ) + clientAssertionInvalidClient = observability.ObtainMetricCounter( + "gotrue_client_assertion_invalid_client_total", + "Number of invalid_client responses to token requests authenticated with a client assertion", + ) ) +func mustFloat64Histogram(name, desc string) metric.Float64Histogram { + h, err := observability.Meter("gotrue").Float64Histogram(name, metric.WithDescription(desc), metric.WithUnit("s")) + if err != nil { + panic(err) + } + return h +} + var errClientAssertionNotConfigured = errors.New("client assertions are not enabled or no signing key is configured") // ClientAssertionRequest identifies the provider an assertion is signed for. @@ -179,11 +212,15 @@ func (c *ClientAssertionCache) sign(ctx context.Context, config *conf.ClientAsse token.Header["typ"] = clientAssertionType token.Header["kid"] = config.SigningJwk.KeyID() - signingKey, err := config.SigningKey(ctx) + started := time.Now() + signed, err := signClientAssertion(ctx, config, token) + result := "success" if err != nil { - return clientAssertionEntry{}, err + result = "error" + clientAssertionSignErrors.Add(ctx, 1) } - signed, err := token.SignedString(signingKey) + clientAssertionSignDuration.Record(ctx, time.Since(started).Seconds(), + metric.WithAttributes(attribute.String("result", result))) if err != nil { return clientAssertionEntry{}, err } @@ -193,3 +230,66 @@ func (c *ClientAssertionCache) sign(ctx context.Context, config *conf.ClientAsse expiresAt: time.Unix(expiresAt.Unix(), 0), }, nil } + +func signClientAssertion(ctx context.Context, config *conf.ClientAssertionConfiguration, token *jwt.Token) (string, error) { + signingKey, err := config.SigningKey(ctx) + if err != nil { + return "", err + } + return token.SignedString(signingKey) +} + +// clientAssertionSource binds a provider to the cache and the request it +// signs assertions for. +type clientAssertionSource struct { + cache *ClientAssertionCache + config *conf.ClientAssertionConfiguration + req ClientAssertionRequest + providerName string +} + +// UseClientAssertion makes the provider authenticate its token requests with +// a client assertion (private_key_jwt) instead of a client secret. The +// assertion goes in the form body only, never in a Basic auth header or the +// query string. +func (p *CustomOIDCProvider) UseClientAssertion(cache *ClientAssertionCache, config *conf.ClientAssertionConfiguration, req ClientAssertionRequest, providerName string) { + p.config.ClientSecret = "" + p.config.Endpoint.AuthStyle = oauth2.AuthStyleInParams + p.clientAssertion = &clientAssertionSource{ + cache: cache, + config: config, + req: req, + providerName: providerName, + } +} + +func (p *CustomOIDCProvider) exchangeWithClientAssertion(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { + src := p.clientAssertion + + assertion, err := src.cache.Get(ctx, src.config, src.req) + if err != nil { + // fail closed: without an assertion no token request is sent + return nil, fmt.Errorf("unable to sign client assertion for provider %s: %w", src.providerName, err) + } + + opts = append(opts, + oauth2.SetAuthURLParam("client_assertion_type", ClientAssertionTypeJWTBearer), + oauth2.SetAuthURLParam("client_assertion", assertion), + ) + token, err := p.config.Exchange(ctx, code, opts...) + + var retrieveErr *oauth2.RetrieveError + if errors.As(err, &retrieveErr) && retrieveErr.ErrorCode == "invalid_client" { + // sign a fresh assertion next time, in case this one is the problem + src.cache.Invalidate(src.config, src.req) + clientAssertionInvalidClient.Add(ctx, 1, + metric.WithAttributes(attribute.String("provider", src.providerName))) + logrus.WithFields(logrus.Fields{ + "provider": src.providerName, + "error_code": retrieveErr.ErrorCode, + "error_description": retrieveErr.ErrorDescription, + }).Warn("token endpoint rejected the client assertion") + } + + return token, err +} diff --git a/internal/api/provider/client_assertion_exchange_test.go b/internal/api/provider/client_assertion_exchange_test.go new file mode 100644 index 0000000000..19cac5de66 --- /dev/null +++ b/internal/api/provider/client_assertion_exchange_test.go @@ -0,0 +1,237 @@ +package provider + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/supabase/auth/internal/conf" + "golang.org/x/oauth2" +) + +// fakeTokenEndpoint records every token request it receives. +type fakeTokenEndpoint struct { + mu sync.Mutex + requests []recordedTokenRequest + // reject makes the endpoint answer with invalid_client + reject bool +} + +type recordedTokenRequest struct { + form url.Values + query url.Values + authorization string +} + +func (f *fakeTokenEndpoint) handler(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + f.mu.Lock() + f.requests = append(f.requests, recordedTokenRequest{ + form: r.PostForm, + query: r.URL.Query(), + authorization: r.Header.Get("Authorization"), + }) + reject := f.reject + f.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + if reject { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":"invalid_client","error_description":"client authentication failed"}`)) + return + } + _, _ = w.Write([]byte(`{"access_token":"test-access-token","token_type":"Bearer","expires_in":3600}`)) +} + +func (f *fakeTokenEndpoint) last(t *testing.T) recordedTokenRequest { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + require.NotEmpty(t, f.requests) + return f.requests[len(f.requests)-1] +} + +func (f *fakeTokenEndpoint) setReject(reject bool) { + f.mu.Lock() + defer f.mu.Unlock() + f.reject = reject +} + +func (f *fakeTokenEndpoint) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.requests) +} + +func newTestOIDCProviderWithTokenEndpoint(t *testing.T, clientSecret string) (*CustomOIDCProvider, *fakeTokenEndpoint) { + t.Helper() + endpoint := &fakeTokenEndpoint{} + server := httptest.NewServer(http.HandlerFunc(endpoint.handler)) + t.Cleanup(server.Close) + + return &CustomOIDCProvider{ + config: &oauth2.Config{ + ClientID: "test-client-id", + ClientSecret: clientSecret, + RedirectURL: "https://auth.example.com/callback", + Scopes: []string{"openid"}, + Endpoint: oauth2.Endpoint{ + AuthURL: server.URL + "/authorize", + TokenURL: server.URL + "/token", + }, + }, + }, endpoint +} + +var testExchangeAssertionRequest = ClientAssertionRequest{ + ProviderID: "7f0c6a1e-1111-4222-8333-944445555666", + ClientID: "test-client-id", + Audience: "https://issuer.example.com", +} + +func TestClientAssertionExchangeRequestShape(t *testing.T) { + key := newTestRSAKey(t) + config, _ := newTestAssertionConfig(t, key, "assertion-key") + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "") + p.UseClientAssertion(NewClientAssertionCache(), config, testExchangeAssertionRequest, "custom:test") + + token, err := p.GetOAuthToken(context.Background(), "test-code", oauth2.VerifierOption("test-verifier")) + require.NoError(t, err) + assert.Equal(t, "test-access-token", token.AccessToken) + + req := endpoint.last(t) + assert.Empty(t, req.authorization, "no Basic auth header") + assert.Empty(t, req.query, "no credentials in the query string") + assert.NotContains(t, req.form, "client_secret") + assert.Equal(t, "test-client-id", req.form.Get("client_id")) + assert.Equal(t, "authorization_code", req.form.Get("grant_type")) + assert.Equal(t, "test-code", req.form.Get("code")) + assert.Equal(t, "test-verifier", req.form.Get("code_verifier")) + assert.Equal(t, "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", req.form.Get("client_assertion_type")) + + parsed, err := jwt.Parse(req.form.Get("client_assertion"), func(*jwt.Token) (any, error) { return &key.PublicKey, nil }, + jwt.WithValidMethods([]string{"RS256"}), + jwt.WithAudience("https://issuer.example.com"), + jwt.WithIssuer("test-client-id"), + jwt.WithSubject("test-client-id"), + ) + require.NoError(t, err) + assert.Equal(t, "assertion-key", parsed.Header["kid"]) +} + +func TestClientAssertionExchangeReusesCachedAssertion(t *testing.T) { + config, signs := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "") + p.UseClientAssertion(NewClientAssertionCache(), config, testExchangeAssertionRequest, "custom:test") + + _, err := p.GetOAuthToken(context.Background(), "code-1") + require.NoError(t, err) + first := endpoint.last(t).form.Get("client_assertion") + + _, err = p.GetOAuthToken(context.Background(), "code-2") + require.NoError(t, err) + assert.Equal(t, first, endpoint.last(t).form.Get("client_assertion")) + assert.EqualValues(t, 1, signs.Load()) +} + +func TestClientAssertionExchangeFailsClosed(t *testing.T) { + t.Run("no signing key", func(t *testing.T) { + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "") + p.UseClientAssertion(NewClientAssertionCache(), &conf.ClientAssertionConfiguration{}, testExchangeAssertionRequest, "custom:test") + + _, err := p.GetOAuthToken(context.Background(), "test-code") + require.ErrorIs(t, err, errClientAssertionNotConfigured) + assert.Equal(t, 0, endpoint.count(), "no token request is sent") + }) + + t.Run("signing error", func(t *testing.T) { + sentinel := errors.New("kms unavailable") + config, _ := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + config.SigningKey = func(context.Context) (any, error) { return nil, sentinel } + + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "") + p.UseClientAssertion(NewClientAssertionCache(), config, testExchangeAssertionRequest, "custom:test") + + _, err := p.GetOAuthToken(context.Background(), "test-code") + require.ErrorIs(t, err, sentinel) + assert.Equal(t, 0, endpoint.count(), "no token request is sent") + }) +} + +func TestClientAssertionExchangeInvalidClientDropsCache(t *testing.T) { + config, signs := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + clock := newTestClock() + cache := newTestCache(clock) + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "") + p.UseClientAssertion(cache, config, testExchangeAssertionRequest, "custom:test") + + endpoint.setReject(true) + _, err := p.GetOAuthToken(context.Background(), "test-code") + var retrieveErr *oauth2.RetrieveError + require.ErrorAs(t, err, &retrieveErr) + assert.Equal(t, "invalid_client", retrieveErr.ErrorCode) + rejected := endpoint.last(t).form.Get("client_assertion") + + // the error does not carry the assertion + assert.NotContains(t, err.Error(), rejected) + + // the next exchange signs a new assertion instead of reusing the rejected one + endpoint.setReject(false) + clock.advance(time.Second) // so the new assertion differs + _, err = p.GetOAuthToken(context.Background(), "test-code") + require.NoError(t, err) + assert.NotEqual(t, rejected, endpoint.last(t).form.Get("client_assertion")) + assert.EqualValues(t, 2, signs.Load()) +} + +func TestClientAssertionExchangeOtherErrorsKeepCache(t *testing.T) { + config, signs := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + p, _ := newTestOIDCProviderWithTokenEndpoint(t, "") + cache := NewClientAssertionCache() + p.UseClientAssertion(cache, config, testExchangeAssertionRequest, "custom:test") + + // warm the cache, then point the provider at an endpoint that returns invalid_grant + _, err := p.GetOAuthToken(context.Background(), "code-1") + require.NoError(t, err) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"invalid_grant"}`)) + })) + t.Cleanup(server.Close) + p.config.Endpoint.TokenURL = server.URL + + _, err = p.GetOAuthToken(context.Background(), "code-2") + require.Error(t, err) + _, err = p.GetOAuthToken(context.Background(), "code-3") + require.Error(t, err) + assert.EqualValues(t, 1, signs.Load(), "invalid_grant does not drop the cached assertion") +} + +func TestClientSecretExchangeUnchanged(t *testing.T) { + p, endpoint := newTestOIDCProviderWithTokenEndpoint(t, "test-client-secret") + + _, err := p.GetOAuthToken(context.Background(), "test-code") + require.NoError(t, err) + + req := endpoint.last(t) + assert.NotContains(t, req.form, "client_assertion") + assert.NotContains(t, req.form, "client_assertion_type") + // x/oauth2 auto-detects the auth style and tries a Basic auth header first + user, pass, ok := (&http.Request{Header: http.Header{"Authorization": {req.authorization}}}).BasicAuth() + require.True(t, ok) + assert.Equal(t, "test-client-id", user) + assert.Equal(t, "test-client-secret", pass) +} diff --git a/internal/api/provider/custom_oauth.go b/internal/api/provider/custom_oauth.go index 971bf5176e..a75f8fdbd4 100644 --- a/internal/api/provider/custom_oauth.go +++ b/internal/api/provider/custom_oauth.go @@ -115,6 +115,10 @@ type CustomOIDCProvider struct { attributeMapping map[string]interface{} authorizationParams map[string]interface{} customClaimsAllowlist []string + + // clientAssertion is set for private_key_jwt providers; see + // UseClientAssertion. + clientAssertion *clientAssertionSource } // NewCustomOIDCProvider creates a new custom OIDC provider. @@ -188,6 +192,9 @@ func (p *CustomOIDCProvider) AuthCodeURL(state string, opts ...oauth2.AuthCodeOp // GetOAuthToken exchanges the authorization code for an access token func (p *CustomOIDCProvider) GetOAuthToken(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { + if p.clientAssertion != nil { + return p.exchangeWithClientAssertion(ctx, code, opts...) + } return p.config.Exchange(ctx, code, opts...) }