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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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!
Expand Down Expand Up @@ -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)
Expand Down
46 changes: 46 additions & 0 deletions internal/api/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
157 changes: 157 additions & 0 deletions internal/api/external_client_assertion_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
106 changes: 103 additions & 3 deletions internal/api/provider/client_assertion.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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.
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Loading
Loading