Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(oauth2): make grant consumption atomic and fail-closed (#20896)

Vincent Huang67249eb038e3
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index 181fb8d380..178e0afaf6 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -141,9 +141,19 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid code_verifier")
}
- // Delete code after all validations pass (single use)
- if err := s.store.DeleteOAuth2AuthorizationCode(ctx, client.ClientID, req.Code); err != nil {
- slog.Warn("failed to delete OAuth2 authorization code after use", slog.String("code", req.Code), log.BBError(err))
+ // Consume the code after all validations pass. This atomic delete is the
+ // single-use gate: PKCE is verified above so a failed verifier never burns
+ // the code, and concurrent redemptions race here so only the caller that
+ // actually claims the row proceeds to issue tokens. A consume failure aborts
+ // issuance rather than warning and continuing (the prior behavior left the
+ // code replayable on a transient error).
+ consumed, err := s.store.ConsumeOAuth2AuthorizationCode(ctx, client.ClientID, req.Code)
+ if err != nil {
+ slog.Error("failed to consume OAuth2 authorization code", slog.String("code", req.Code), log.BBError(err))
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to consume authorization code")
+ }
+ if !consumed {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid or expired code")
}
// Get user
@@ -200,9 +210,18 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "refresh token has expired")
}
- // Delete token after validations pass (single use, will issue new one)
- if err := s.store.DeleteOAuth2RefreshToken(ctx, client.ClientID, tokenHash); err != nil {
- slog.Warn("failed to delete OAuth2 refresh token after use", log.BBError(err))
+ // Consume the refresh token after validations pass. This atomic delete is
+ // the single-use rotation gate: concurrent refreshes race here so only the
+ // caller that actually claims the row issues a new pair. A consume failure
+ // aborts issuance rather than warning and continuing (the prior behavior
+ // left the token replayable on a transient error).
+ consumed, err := s.store.ConsumeOAuth2RefreshToken(ctx, client.ClientID, tokenHash)
+ if err != nil {
+ slog.Error("failed to consume OAuth2 refresh token", log.BBError(err))
+ return oauth2Error(c, http.StatusInternalServerError, "server_error", "failed to consume refresh token")
+ }
+ if !consumed {
+ return oauth2Error(c, http.StatusBadRequest, "invalid_grant", "invalid refresh token")
}
// Get user
diff --git a/backend/store/oauth2_authorization_code.go b/backend/store/oauth2_authorization_code.go
index ddeec1d5fa..08ebc4b836 100644
--- a/backend/store/oauth2_authorization_code.go
+++ b/backend/store/oauth2_authorization_code.go
@@ -86,6 +86,36 @@ func (s *Store) GetOAuth2AuthorizationCode(ctx context.Context, clientID, code s
return msg, nil
}
+// ConsumeOAuth2AuthorizationCode atomically deletes an authorization code and
+// reports whether this call is the one that claimed it. The DELETE ... RETURNING
+// is the single-use issuance gate: concurrent redemptions of the same code race
+// here and exactly one observes consumed=true, so the caller must issue tokens
+// only when consumed is true. RETURNING (not RowsAffected) is used deliberately
+// — Postgres row counts are unreliable for this check. A false return means the
+// code was already consumed or never existed; a non-nil error is a real failure
+// and must abort issuance.
+func (s *Store) ConsumeOAuth2AuthorizationCode(ctx context.Context, clientID, code string) (bool, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_authorization_code
+ WHERE code = ? AND client_id = ?
+ RETURNING code
+ `, code, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, err
+ }
+
+ var consumedCode string
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&consumedCode); err != nil { // NOSONAR: query is parameterized via qb.Query
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return false, errors.Wrap(err, "failed to consume OAuth2 authorization code")
+ }
+ return true, nil
+}
+
func (s *Store) DeleteOAuth2AuthorizationCode(ctx context.Context, clientID, code string) error {
q := qb.Q().Space(`
DELETE FROM oauth2_authorization_code
diff --git a/backend/store/oauth2_consume_test.go b/backend/store/oauth2_consume_test.go
new file mode 100644
index 0000000000..4fcbeb54e5
--- /dev/null
+++ b/backend/store/oauth2_consume_test.go
@@ -0,0 +1,161 @@
+package store_test
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestOAuth2AtomicConsume verifies the single-use issuance gate on
+// authorization codes and refresh tokens. The DELETE ... RETURNING must make
+// consumption atomic so concurrent redemptions of one grant can never both
+// succeed (the double-mint race that the prior read-then-delete flow allowed),
+// and a second sequential redemption must observe consumed=false.
+func TestOAuth2AtomicConsume(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-test');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ s, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ t.Run("authorization code is single-use", func(t *testing.T) {
+ _, err := s.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: "code-single-use",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Config: &storepb.OAuth2AuthorizationCodeConfig{RedirectUri: "http://localhost/cb"},
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ })
+ require.NoError(t, err)
+
+ consumed, err := s.ConsumeOAuth2AuthorizationCode(ctx, "client-A", "code-single-use")
+ require.NoError(t, err)
+ require.True(t, consumed, "first consume must claim the code")
+
+ consumed, err = s.ConsumeOAuth2AuthorizationCode(ctx, "client-A", "code-single-use")
+ require.NoError(t, err)
+ require.False(t, consumed, "second consume must observe the code already used, not error")
+ })
+
+ t.Run("consuming an unknown code returns false without error", func(t *testing.T) {
+ consumed, err := s.ConsumeOAuth2AuthorizationCode(ctx, "client-A", "never-existed")
+ require.NoError(t, err)
+ require.False(t, consumed)
+ })
+
+ t.Run("concurrent redemption of one code claims it exactly once", func(t *testing.T) {
+ _, err := s.CreateOAuth2AuthorizationCode(ctx, &store.OAuth2AuthorizationCodeMessage{
+ Code: "code-racy",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ Config: &storepb.OAuth2AuthorizationCodeConfig{RedirectUri: "http://localhost/cb"},
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ })
+ require.NoError(t, err)
+
+ const racers = 16
+ var wg sync.WaitGroup
+ results := make([]bool, racers)
+ errs := make([]error, racers)
+ start := make(chan struct{})
+ for i := range racers {
+ wg.Go(func() {
+ <-start
+ results[i], errs[i] = s.ConsumeOAuth2AuthorizationCode(ctx, "client-A", "code-racy")
+ })
+ }
+ close(start)
+ wg.Wait()
+
+ wins := 0
+ for i := range racers {
+ require.NoErrorf(t, errs[i], "racer %d must not error", i)
+ if results[i] {
+ wins++
+ }
+ }
+ require.Equal(t, 1, wins, "exactly one concurrent redemption may claim the code")
+ })
+
+ t.Run("refresh token is single-use", func(t *testing.T) {
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-single-use",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
+ })
+ require.NoError(t, err)
+
+ consumed, err := s.ConsumeOAuth2RefreshToken(ctx, "client-A", "rt-single-use")
+ require.NoError(t, err)
+ require.True(t, consumed, "first consume must claim the refresh token")
+
+ consumed, err = s.ConsumeOAuth2RefreshToken(ctx, "client-A", "rt-single-use")
+ require.NoError(t, err)
+ require.False(t, consumed, "second consume must observe the token already rotated, not error")
+ })
+
+ t.Run("concurrent refresh of one token claims it exactly once", func(t *testing.T) {
+ _, err := s.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{
+ TokenHash: "rt-racy",
+ ClientID: "client-A",
+ UserEmail: "[email protected]",
+ Workspace: "ws-test",
+ ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
+ })
+ require.NoError(t, err)
+
+ const racers = 16
+ var wg sync.WaitGroup
+ results := make([]bool, racers)
+ errs := make([]error, racers)
+ start := make(chan struct{})
+ for i := range racers {
+ wg.Go(func() {
+ <-start
+ results[i], errs[i] = s.ConsumeOAuth2RefreshToken(ctx, "client-A", "rt-racy")
+ })
+ }
+ close(start)
+ wg.Wait()
+
+ wins := 0
+ for i := range racers {
+ require.NoErrorf(t, errs[i], "racer %d must not error", i)
+ if results[i] {
+ wins++
+ }
+ }
+ require.Equal(t, 1, wins, "exactly one concurrent refresh may claim the token")
+ })
+}
diff --git a/backend/store/oauth2_refresh_token.go b/backend/store/oauth2_refresh_token.go
index 4e48227ab1..ac0e06444b 100644
--- a/backend/store/oauth2_refresh_token.go
+++ b/backend/store/oauth2_refresh_token.go
@@ -70,6 +70,36 @@ func (s *Store) GetOAuth2RefreshToken(ctx context.Context, clientID, tokenHash s
return msg, nil
}
+// ConsumeOAuth2RefreshToken atomically deletes a refresh token and reports
+// whether this call is the one that claimed it. The DELETE ... RETURNING is the
+// single-use rotation gate: concurrent refreshes of the same token race here and
+// exactly one observes consumed=true, so the caller must issue a new token pair
+// only when consumed is true. RETURNING (not RowsAffected) is used deliberately
+// — Postgres row counts are unreliable for this check. A false return means the
+// token was already consumed or never existed; a non-nil error is a real failure
+// and must abort issuance.
+func (s *Store) ConsumeOAuth2RefreshToken(ctx context.Context, clientID, tokenHash string) (bool, error) {
+ q := qb.Q().Space(`
+ DELETE FROM oauth2_refresh_token
+ WHERE token_hash = ? AND client_id = ?
+ RETURNING token_hash
+ `, tokenHash, clientID)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, err
+ }
+
+ var consumedHash string
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&consumedHash); err != nil { // NOSONAR: query is parameterized via qb.Query
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return false, errors.Wrap(err, "failed to consume OAuth2 refresh token")
+ }
+ return true, nil
+}
+
func (s *Store) DeleteOAuth2RefreshToken(ctx context.Context, clientID, tokenHash string) error {
q := qb.Q().Space(`
DELETE FROM oauth2_refresh_token