diff --git a/internal/api/provider/client_assertion.go b/internal/api/provider/client_assertion.go new file mode 100644 index 0000000000..0d69561d27 --- /dev/null +++ b/internal/api/provider/client_assertion.go @@ -0,0 +1,195 @@ +package provider + +import ( + "context" + "errors" + "strings" + "sync" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/supabase/auth/internal/conf" + "golang.org/x/sync/singleflight" +) + +const ( + // clientAssertionLifetime is how long a signed client assertion is valid. + clientAssertionLifetime = 15 * time.Minute + + // clientAssertionRefreshBefore is how long before expiry a cached + // assertion is replaced, so a request never goes out with an assertion + // that is about to expire. + clientAssertionRefreshBefore = 5 * time.Minute + + // clientAssertionSignTimeout bounds one signing call. The call is detached + // from the caller's context (see Get), so this is what stops a stuck KMS + // call from blocking every waiting request. + clientAssertionSignTimeout = 10 * time.Second + + // clientAssertionType is the JWT typ header for client assertions. + clientAssertionType = "client-authentication+jwt" +) + +var errClientAssertionNotConfigured = errors.New("client assertions are not enabled or no signing key is configured") + +// ClientAssertionRequest identifies the provider an assertion is signed for. +type ClientAssertionRequest struct { + ProviderID string + ClientID string + // Audience is the aud claim: the provider's configured assertion + // audience if set, otherwise its issuer. + Audience string +} + +type clientAssertionEntry struct { + assertion string + expiresAt time.Time +} + +// ClientAssertionCache signs private_key_jwt client assertions (RFC 7523) and +// caches one per provider in memory, so the signing key (which may be in a +// KMS) is used about once every 10 minutes per provider instead of on every +// token request. Concurrent requests for the same provider share one signing +// call via singleflight. +// +// Assertions are bearer credentials: they must never be logged, stored, or +// included in errors. +type ClientAssertionCache struct { + mu sync.Mutex + entries map[string]clientAssertionEntry + sf singleflight.Group + now func() time.Time // injectable for tests +} + +// NewClientAssertionCache creates an empty cache. +func NewClientAssertionCache() *ClientAssertionCache { + return &ClientAssertionCache{ + entries: make(map[string]clientAssertionEntry), + now: time.Now, + } +} + +// cacheKey includes the signing kid and issuer as well as the request, so a +// key rotation or issuer change on config reload stops serving old assertions. +func (c *ClientAssertionCache) cacheKey(config *conf.ClientAssertionConfiguration, req ClientAssertionRequest) string { + return strings.Join([]string{ + req.ProviderID, + req.ClientID, + req.Audience, + config.SigningJwk.KeyID(), + config.Issuer, + }, "\x00") +} + +func (c *ClientAssertionCache) getFresh(key string) (string, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[key] + if !ok || c.now().Add(clientAssertionRefreshBefore).After(entry.expiresAt) { + return "", false + } + return entry.assertion, true +} + +// put stores entry and drops every expired entry. Keys that are no longer +// requested (deleted providers, rotated signing keys, changed audiences or +// issuers) are therefore removed within one assertion lifetime of the next +// signing. put runs about once per provider per refresh interval and the map +// holds one entry per provider, so the sweep is cheap. +func (c *ClientAssertionCache) put(key string, entry clientAssertionEntry) { + c.mu.Lock() + defer c.mu.Unlock() + + now := c.now() + for k, e := range c.entries { + if !now.Before(e.expiresAt) { + delete(c.entries, k) + } + } + c.entries[key] = entry +} + +// Get returns a client assertion for req, signing a new one if there is no +// cached assertion or it has less than clientAssertionRefreshBefore left. +func (c *ClientAssertionCache) Get(ctx context.Context, config *conf.ClientAssertionConfiguration, req ClientAssertionRequest) (string, error) { + if !config.Enabled || config.SigningJwk == nil || config.SigningKey == nil { + return "", errClientAssertionNotConfigured + } + + key := c.cacheKey(config, req) + if assertion, ok := c.getFresh(key); ok { + return assertion, nil + } + + val, err, _ := c.sf.Do(key, func() (any, error) { + // another caller may have refreshed the entry while this one waited + if assertion, ok := c.getFresh(key); ok { + return assertion, nil + } + + // every request waiting on this key shares the signing call, so it + // must not fail because the first caller's request was canceled + signCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), clientAssertionSignTimeout) + defer cancel() + + entry, err := c.sign(signCtx, config, req) + if err != nil { + return nil, err + } + c.put(key, entry) + return entry.assertion, nil + }) + if err != nil { + return "", err + } + return val.(string), nil +} + +// Invalidate drops the cached assertion for req, for example after the +// provider rejects it with invalid_client. +func (c *ClientAssertionCache) Invalidate(config *conf.ClientAssertionConfiguration, req ClientAssertionRequest) { + if config.SigningJwk == nil { + return + } + key := c.cacheKey(config, req) + + c.mu.Lock() + defer c.mu.Unlock() + delete(c.entries, key) +} + +func (c *ClientAssertionCache) sign(ctx context.Context, config *conf.ClientAssertionConfiguration, req ClientAssertionRequest) (clientAssertionEntry, error) { + issuer := req.ClientID + if config.Issuer != "" { + issuer = config.Issuer + } + + now := c.now() + expiresAt := now.Add(clientAssertionLifetime) + + // MapClaims keeps aud a single string regardless of the package-level + // jwt.MarshalSingleStringAsArray setting. + token := jwt.NewWithClaims(conf.GetSigningAlg(config.SigningJwk), jwt.MapClaims{ + "iss": issuer, + "sub": req.ClientID, + "aud": req.Audience, + "iat": now.Unix(), + "exp": expiresAt.Unix(), + }) + token.Header["typ"] = clientAssertionType + token.Header["kid"] = config.SigningJwk.KeyID() + + signingKey, err := config.SigningKey(ctx) + if err != nil { + return clientAssertionEntry{}, err + } + signed, err := token.SignedString(signingKey) + if err != nil { + return clientAssertionEntry{}, err + } + + return clientAssertionEntry{ + assertion: signed, + expiresAt: time.Unix(expiresAt.Unix(), 0), + }, nil +} diff --git a/internal/api/provider/client_assertion_test.go b/internal/api/provider/client_assertion_test.go new file mode 100644 index 0000000000..26f621d7a9 --- /dev/null +++ b/internal/api/provider/client_assertion_test.go @@ -0,0 +1,401 @@ +package provider + +import ( + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/json" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/golang-jwt/jwt/v5" + "github.com/lestrrat-go/jwx/v2/jwk" + "github.com/stretchr/testify/require" + "github.com/supabase/auth/internal/conf" + "github.com/supabase/auth/internal/conf/awskmsjwk" +) + +type testClock struct{ t time.Time } + +func (c *testClock) now() time.Time { return c.t } +func (c *testClock) advance(d time.Duration) { c.t = c.t.Add(d) } +func newTestClock() *testClock { return &testClock{t: time.Unix(1_800_000_000, 0)} } +func newTestCache(clock *testClock) *ClientAssertionCache { + c := NewClientAssertionCache() + c.now = clock.now + return c +} + +func newTestRSAKey(t *testing.T) *rsa.PrivateKey { + t.Helper() + k, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + return k +} + +func newTestSigningJwk(t *testing.T, raw any, kid string) jwk.Key { + t.Helper() + k, err := jwk.FromRaw(raw) + require.NoError(t, err) + require.NoError(t, k.Set(jwk.KeyIDKey, kid)) + require.NoError(t, k.Set(jwk.AlgorithmKey, "RS256")) + require.NoError(t, k.Set(jwk.KeyOpsKey, jwk.KeyOperationList{jwk.KeyOpSign})) + return k +} + +// newTestAssertionConfig returns a plain-key config and a counter of how many +// times the signing key was requested (once per signed assertion). +func newTestAssertionConfig(t *testing.T, key *rsa.PrivateKey, kid string) (*conf.ClientAssertionConfiguration, *atomic.Int32) { + t.Helper() + var signs atomic.Int32 + return &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: newTestSigningJwk(t, key, kid), + SigningKey: func(context.Context) (any, error) { + signs.Add(1) + return key, nil + }, + }, &signs +} + +var testAssertionRequest = ClientAssertionRequest{ + ProviderID: "7f0c6a1e-1111-4222-8333-944445555666", + ClientID: "test-client-id", + Audience: "https://issuer.example.com", +} + +func parseTestAssertion(t *testing.T, assertion string, pub *rsa.PublicKey) *jwt.Token { + t.Helper() + token, err := jwt.Parse(assertion, func(*jwt.Token) (any, error) { return pub, nil }, + jwt.WithValidMethods([]string{"RS256"}), + jwt.WithTimeFunc(func() time.Time { return time.Unix(1_800_000_000, 0) }), + ) + require.NoError(t, err) + return token +} + +func TestClientAssertionHeaderAndClaims(t *testing.T) { + key := newTestRSAKey(t) + config, _ := newTestAssertionConfig(t, key, "assertion-key") + clock := newTestClock() + + assertion, err := newTestCache(clock).Get(context.Background(), config, testAssertionRequest) + require.NoError(t, err) + + token := parseTestAssertion(t, assertion, &key.PublicKey) + require.Equal(t, "RS256", token.Header["alg"]) + require.Equal(t, "assertion-key", token.Header["kid"]) + require.Equal(t, "client-authentication+jwt", token.Header["typ"]) + + payload, err := base64.RawURLEncoding.DecodeString(strings.Split(assertion, ".")[1]) + require.NoError(t, err) + var claims map[string]any + require.NoError(t, json.Unmarshal(payload, &claims)) + require.Equal(t, map[string]any{ + "iss": "test-client-id", + "sub": "test-client-id", + "aud": "https://issuer.example.com", // a single string, never an array + "iat": float64(clock.t.Unix()), + "exp": float64(clock.t.Add(15 * time.Minute).Unix()), + }, claims) +} + +func TestClientAssertionIssuerOverride(t *testing.T) { + key := newTestRSAKey(t) + config, _ := newTestAssertionConfig(t, key, "assertion-key") + config.Issuer = "https://auth.example.com" + + assertion, err := newTestCache(newTestClock()).Get(context.Background(), config, testAssertionRequest) + require.NoError(t, err) + + claims := parseTestAssertion(t, assertion, &key.PublicKey).Claims.(jwt.MapClaims) + require.Equal(t, "https://auth.example.com", claims["iss"]) + require.Equal(t, "test-client-id", claims["sub"]) +} + +func TestClientAssertionCacheLifetime(t *testing.T) { + key := newTestRSAKey(t) + config, signs := newTestAssertionConfig(t, key, "assertion-key") + clock := newTestClock() + cache := newTestCache(clock) + ctx := context.Background() + + first, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + + // reused while at least 5 minutes are left + clock.advance(10 * time.Minute) + again, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + require.Equal(t, first, again) + require.EqualValues(t, 1, signs.Load()) + + // replaced once less than 5 minutes are left + clock.advance(time.Second) + refreshed, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + require.NotEqual(t, first, refreshed) + require.EqualValues(t, 2, signs.Load()) + + claims := parseTestAssertion(t, refreshed, &key.PublicKey).Claims.(jwt.MapClaims) + require.Equal(t, float64(clock.t.Unix()), claims["iat"]) +} + +func TestClientAssertionCacheEvictsExpiredEntries(t *testing.T) { + config, _ := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + clock := newTestClock() + cache := newTestCache(clock) + ctx := context.Background() + + stale := testAssertionRequest + stale.ProviderID = "deleted-provider" + _, err := cache.Get(ctx, config, stale) + require.NoError(t, err) + + // not yet expired: kept when another entry is stored + clock.advance(14 * time.Minute) + _, err = cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + require.Len(t, cache.entries, 2) + + // expired: dropped on the next store, while live entries stay + clock.advance(time.Minute) + other := testAssertionRequest + other.ProviderID = "other-provider" + _, err = cache.Get(ctx, config, other) + require.NoError(t, err) + require.Len(t, cache.entries, 2) + require.NotContains(t, cache.entries, cache.cacheKey(config, stale)) + require.Contains(t, cache.entries, cache.cacheKey(config, testAssertionRequest)) +} + +func TestClientAssertionCacheKey(t *testing.T) { + key := newTestRSAKey(t) + config, signs := newTestAssertionConfig(t, key, "assertion-key") + cache := newTestCache(newTestClock()) + ctx := context.Background() + + _, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + + otherProvider := testAssertionRequest + otherProvider.ProviderID = "another-provider" + otherClient := testAssertionRequest + otherClient.ClientID = "another-client" + otherAudience := testAssertionRequest + otherAudience.Audience = "https://other.example.com" + for _, req := range []ClientAssertionRequest{otherProvider, otherClient, otherAudience} { + _, err := cache.Get(ctx, config, req) + require.NoError(t, err) + } + require.EqualValues(t, 4, signs.Load()) + + // a rotated signing key or a changed issuer must not reuse the old assertion + rotated, rotatedSigns := newTestAssertionConfig(t, newTestRSAKey(t), "rotated-key") + _, err = cache.Get(ctx, rotated, testAssertionRequest) + require.NoError(t, err) + require.EqualValues(t, 1, rotatedSigns.Load()) + + config.Issuer = "https://auth.example.com" + _, err = cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + require.EqualValues(t, 5, signs.Load()) +} + +func TestClientAssertionConcurrentRequestsSignOnce(t *testing.T) { + key := newTestRSAKey(t) + release := make(chan struct{}) + var signs atomic.Int32 + config := &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: newTestSigningJwk(t, key, "assertion-key"), + SigningKey: func(context.Context) (any, error) { + signs.Add(1) + <-release + return key, nil + }, + } + cache := newTestCache(newTestClock()) + + const n = 20 + results := make([]string, n) + errs := make([]error, n) + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + results[i], errs[i] = cache.Get(context.Background(), config, testAssertionRequest) + }() + } + // give the goroutines time to queue up behind the in-flight signing call; + // any that arrive later are served from the cache, so the count holds + // either way + time.Sleep(50 * time.Millisecond) + close(release) + wg.Wait() + + require.EqualValues(t, 1, signs.Load()) + for i := range n { + require.NoError(t, errs[i]) + require.Equal(t, results[0], results[i]) + } +} + +func TestClientAssertionCanceledCallerDoesNotFailOthers(t *testing.T) { + key := newTestRSAKey(t) + started := make(chan struct{}) + release := make(chan struct{}) + var signCtxErr error + config := &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: newTestSigningJwk(t, key, "assertion-key"), + SigningKey: func(ctx context.Context) (any, error) { + close(started) + <-release + signCtxErr = ctx.Err() + return key, nil + }, + } + cache := newTestCache(newTestClock()) + + // the first caller starts the signing call, then its request is canceled + firstCtx, cancelFirst := context.WithCancel(context.Background()) + firstDone := make(chan error, 1) + go func() { + _, err := cache.Get(firstCtx, config, testAssertionRequest) + firstDone <- err + }() + <-started + + // a second caller joins the in-flight signing call + secondDone := make(chan error, 1) + go func() { + _, err := cache.Get(context.Background(), config, testAssertionRequest) + secondDone <- err + }() + time.Sleep(50 * time.Millisecond) + + cancelFirst() + close(release) + + require.NoError(t, <-secondDone) + require.NoError(t, <-firstDone) + require.NoError(t, signCtxErr, "the shared signing call must not see the first caller's cancellation") +} + +func TestClientAssertionDisabled(t *testing.T) { + config, signs := newTestAssertionConfig(t, newTestRSAKey(t), "assertion-key") + config.Enabled = false + + _, err := newTestCache(newTestClock()).Get(context.Background(), config, testAssertionRequest) + require.ErrorIs(t, err, errClientAssertionNotConfigured) + require.EqualValues(t, 0, signs.Load()) +} + +func TestClientAssertionInvalidate(t *testing.T) { + key := newTestRSAKey(t) + config, signs := newTestAssertionConfig(t, key, "assertion-key") + clock := newTestClock() + cache := newTestCache(clock) + ctx := context.Background() + + first, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + + other := testAssertionRequest + other.ProviderID = "another-provider" + _, err = cache.Get(ctx, config, other) + require.NoError(t, err) + + cache.Invalidate(config, testAssertionRequest) + clock.advance(time.Second) + + second, err := cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) + require.NotEqual(t, first, second) + + // other providers keep their cached assertion + _, err = cache.Get(ctx, config, other) + require.NoError(t, err) + require.EqualValues(t, 3, signs.Load()) +} + +func TestClientAssertionSigningErrors(t *testing.T) { + cache := newTestCache(newTestClock()) + ctx := context.Background() + + _, err := cache.Get(ctx, &conf.ClientAssertionConfiguration{}, testAssertionRequest) + require.ErrorIs(t, err, errClientAssertionNotConfigured) + + key := newTestRSAKey(t) + sentinel := errors.New("signing unavailable") + fail := true + config := &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: newTestSigningJwk(t, key, "assertion-key"), + SigningKey: func(context.Context) (any, error) { + if fail { + return nil, sentinel + } + return key, nil + }, + } + + _, err = cache.Get(ctx, config, testAssertionRequest) + require.ErrorIs(t, err, sentinel) + + // failures are not cached + fail = false + _, err = cache.Get(ctx, config, testAssertionRequest) + require.NoError(t, err) +} + +type fakeKMS struct { + key *rsa.PrivateKey + calls atomic.Int32 +} + +func (f *fakeKMS) Sign(_ context.Context, in *kms.SignInput, _ ...func(*kms.Options)) (*kms.SignOutput, error) { + f.calls.Add(1) + sig, err := rsa.SignPKCS1v15(rand.Reader, f.key, crypto.SHA256, in.Message) + if err != nil { + return nil, err + } + return &kms.SignOutput{Signature: sig}, nil +} + +func TestClientAssertionKMSKey(t *testing.T) { + key := newTestRSAKey(t) + const arn = "arn:aws:kms:us-east-1:123456789012:key/00000000-0000-0000-0000-000000000000" + + signingJwk := newTestSigningJwk(t, &key.PublicKey, "kms-key") + require.NoError(t, signingJwk.Set("aws:kms:arn", arn)) + + fake := &fakeKMS{key: key} + config := &conf.ClientAssertionConfiguration{ + Enabled: true, + SigningJwk: signingJwk, + SigningKey: func(ctx context.Context) (any, error) { + return &awskmsjwk.RS256Key{Ctx: ctx, KMS: fake, KeyID: arn, Raw: &key.PublicKey}, nil + }, + } + cache := newTestCache(newTestClock()) + + assertion, err := cache.Get(context.Background(), config, testAssertionRequest) + require.NoError(t, err) + _, err = cache.Get(context.Background(), config, testAssertionRequest) + require.NoError(t, err) + require.EqualValues(t, 1, fake.calls.Load()) + + token := parseTestAssertion(t, assertion, &key.PublicKey) + require.Equal(t, "RS256", token.Header["alg"]) + require.Equal(t, "kms-key", token.Header["kid"]) +}