From dbea42e7a572f102f3336e95612f9e2bf28e2c98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:35:20 +0100 Subject: [PATCH] feat(auth): add single-use totp recovery codes Codes are stored as SHA-256 hashes and consumed with one conditional update, so concurrent use of the same code succeeds at most once. Refs #40 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/recovery.go | 70 +++++++++++++++++++ internal/auth/recovery_test.go | 43 ++++++++++++ .../migrations/sql/00008_recovery_codes.sql | 13 ++++ internal/store/copyfrom.go | 43 ++++++++++++ internal/store/db.go | 1 + internal/store/models.go | 7 ++ internal/store/querier.go | 4 ++ internal/store/queries/recovery_codes.sql | 12 ++++ internal/store/recovery_codes.sql.go | 55 +++++++++++++++ 9 files changed, 248 insertions(+) create mode 100644 internal/auth/recovery.go create mode 100644 internal/auth/recovery_test.go create mode 100644 internal/migrations/sql/00008_recovery_codes.sql create mode 100644 internal/store/copyfrom.go create mode 100644 internal/store/queries/recovery_codes.sql create mode 100644 internal/store/recovery_codes.sql.go diff --git a/internal/auth/recovery.go b/internal/auth/recovery.go new file mode 100644 index 0000000..c1f5ad9 --- /dev/null +++ b/internal/auth/recovery.go @@ -0,0 +1,70 @@ +package auth + +import ( + "crypto/rand" + "crypto/sha256" + "strings" +) + +// RecoveryCodeCount is how many codes a user receives per set. +const RecoveryCodeCount = 10 + +// recoveryAlphabet omits characters that are easily confused on paper +// (0/o, 1/l/i). +const recoveryAlphabet = "abcdefghjkmnpqrstuvwxyz23456789" + +const recoveryLen = 10 + +// NewRecoveryCodes returns RecoveryCodeCount codes formatted as +// "xxxxx-xxxxx", about 49 bits each. +func NewRecoveryCodes() []string { + codes := make([]string, RecoveryCodeCount) + for i := range codes { + b := make([]byte, recoveryLen) + for j := range b { + b[j] = recoveryAlphabet[randIndex(len(recoveryAlphabet))] + } + codes[i] = string(b[:recoveryLen/2]) + "-" + string(b[recoveryLen/2:]) + } + return codes +} + +// randIndex returns a uniform index below n using rejection sampling. +func randIndex(n int) int { + limit := 256 - 256%n + var b [1]byte + for { + _, _ = rand.Read(b[:]) + if int(b[0]) < limit { + return int(b[0]) % n + } + } +} + +// NormalizeRecoveryCode strips separators and case so users can type codes +// the way they wrote them down. It returns "" if the input cannot be a code. +func NormalizeRecoveryCode(s string) string { + s = strings.Map(func(r rune) rune { + switch r { + case '-', ' ': + return -1 + } + return r + }, strings.ToLower(strings.TrimSpace(s))) + if len(s) != recoveryLen { + return "" + } + for _, r := range s { + if !strings.ContainsRune(recoveryAlphabet, r) { + return "" + } + } + return s +} + +// HashRecoveryCode hashes a normalized code. The codes carry enough entropy +// that a fast hash suffices; attempts are rate limited. +func HashRecoveryCode(normalized string) []byte { + sum := sha256.Sum256([]byte(normalized)) + return sum[:] +} diff --git a/internal/auth/recovery_test.go b/internal/auth/recovery_test.go new file mode 100644 index 0000000..6449c1a --- /dev/null +++ b/internal/auth/recovery_test.go @@ -0,0 +1,43 @@ +package auth + +import ( + "regexp" + "testing" +) + +func TestNewRecoveryCodes(t *testing.T) { + codes := NewRecoveryCodes() + if len(codes) != RecoveryCodeCount { + t.Fatalf("len(NewRecoveryCodes()) = %d, want %d", len(codes), RecoveryCodeCount) + } + format := regexp.MustCompile(`^[a-z2-9]{5}-[a-z2-9]{5}$`) + seen := map[string]bool{} + for _, c := range codes { + if !format.MatchString(c) { + t.Errorf("code %q does not match %s", c, format) + } + if NormalizeRecoveryCode(c) == "" { + t.Errorf("NormalizeRecoveryCode(%q) = \"\", want the code", c) + } + if seen[c] { + t.Errorf("duplicate code %q", c) + } + seen[c] = true + } +} + +func TestNormalizeRecoveryCode(t *testing.T) { + tests := []struct{ in, want string }{ + {"abcde-fghjk", "abcdefghjk"}, + {" ABCDE FGHJK ", "abcdefghjk"}, + {"abcdefghjk", "abcdefghjk"}, + {"123456", ""}, + {"abcde-fghj0", ""}, + {"abcde-fghjkm", ""}, + } + for _, tt := range tests { + if got := NormalizeRecoveryCode(tt.in); got != tt.want { + t.Errorf("NormalizeRecoveryCode(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} diff --git a/internal/migrations/sql/00008_recovery_codes.sql b/internal/migrations/sql/00008_recovery_codes.sql new file mode 100644 index 0000000..7367935 --- /dev/null +++ b/internal/migrations/sql/00008_recovery_codes.sql @@ -0,0 +1,13 @@ +-- +goose Up +-- Like users, these rows belong to a person rather than an organization and +-- are not under row-level security. +CREATE TABLE recovery_codes ( + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + code_hash bytea NOT NULL, + used_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, code_hash) +); + +-- +goose Down +DROP TABLE recovery_codes; diff --git a/internal/store/copyfrom.go b/internal/store/copyfrom.go new file mode 100644 index 0000000..d60d6fd --- /dev/null +++ b/internal/store/copyfrom.go @@ -0,0 +1,43 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: copyfrom.go + +package store + +import ( + "context" +) + +// iteratorForInsertRecoveryCodes implements pgx.CopyFromSource. +type iteratorForInsertRecoveryCodes struct { + rows []InsertRecoveryCodesParams + skippedFirstNextCall bool +} + +func (r *iteratorForInsertRecoveryCodes) Next() bool { + if len(r.rows) == 0 { + return false + } + if !r.skippedFirstNextCall { + r.skippedFirstNextCall = true + return true + } + r.rows = r.rows[1:] + return len(r.rows) > 0 +} + +func (r iteratorForInsertRecoveryCodes) Values() ([]interface{}, error) { + return []interface{}{ + r.rows[0].UserID, + r.rows[0].CodeHash, + }, nil +} + +func (r iteratorForInsertRecoveryCodes) Err() error { + return nil +} + +func (q *Queries) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) { + return q.db.CopyFrom(ctx, []string{"recovery_codes"}, []string{"user_id", "code_hash"}, &iteratorForInsertRecoveryCodes{rows: arg}) +} diff --git a/internal/store/db.go b/internal/store/db.go index 24023a5..949da91 100644 --- a/internal/store/db.go +++ b/internal/store/db.go @@ -15,6 +15,7 @@ type DBTX interface { Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) Query(context.Context, string, ...interface{}) (pgx.Rows, error) QueryRow(context.Context, string, ...interface{}) pgx.Row + CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) } func New(db DBTX) *Queries { diff --git a/internal/store/models.go b/internal/store/models.go index d54331e..c4adace 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -26,6 +26,13 @@ type Org struct { RequireTotp bool } +type RecoveryCode struct { + UserID uuid.UUID + CodeHash []byte + UsedAt *time.Time + CreatedAt time.Time +} + type SsoProvider struct { ID uuid.UUID OrgID uuid.UUID diff --git a/internal/store/querier.go b/internal/store/querier.go index 1fc7a89..267932a 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -13,11 +13,13 @@ import ( type Querier interface { AddMembership(ctx context.Context, arg AddMembershipParams) error AnyUserExists(ctx context.Context) (bool, error) + CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) + DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DisableTOTP(ctx context.Context, id uuid.UUID) error @@ -29,6 +31,7 @@ type Querier interface { GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error) + InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) @@ -42,6 +45,7 @@ type Querier interface { SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) + UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/recovery_codes.sql b/internal/store/queries/recovery_codes.sql new file mode 100644 index 0000000..9e1abde --- /dev/null +++ b/internal/store/queries/recovery_codes.sql @@ -0,0 +1,12 @@ +-- name: DeleteRecoveryCodes :exec +DELETE FROM recovery_codes WHERE user_id = $1; + +-- name: InsertRecoveryCodes :copyfrom +INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2); + +-- name: UseRecoveryCode :execrows +UPDATE recovery_codes SET used_at = now() +WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL; + +-- name: CountUnusedRecoveryCodes :one +SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL; diff --git a/internal/store/recovery_codes.sql.go b/internal/store/recovery_codes.sql.go new file mode 100644 index 0000000..c296d9a --- /dev/null +++ b/internal/store/recovery_codes.sql.go @@ -0,0 +1,55 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: recovery_codes.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const countUnusedRecoveryCodes = `-- name: CountUnusedRecoveryCodes :one +SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL +` + +func (q *Queries) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) { + row := q.db.QueryRow(ctx, countUnusedRecoveryCodes, userID) + var count int64 + err := row.Scan(&count) + return count, err +} + +const deleteRecoveryCodes = `-- name: DeleteRecoveryCodes :exec +DELETE FROM recovery_codes WHERE user_id = $1 +` + +func (q *Queries) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error { + _, err := q.db.Exec(ctx, deleteRecoveryCodes, userID) + return err +} + +type InsertRecoveryCodesParams struct { + UserID uuid.UUID + CodeHash []byte +} + +const useRecoveryCode = `-- name: UseRecoveryCode :execrows +UPDATE recovery_codes SET used_at = now() +WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL +` + +type UseRecoveryCodeParams struct { + UserID uuid.UUID + CodeHash []byte +} + +func (q *Queries) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) { + result, err := q.db.Exec(ctx, useRecoveryCode, arg.UserID, arg.CodeHash) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +}