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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
3f21361995
commit
dbea42e7a5
9 files changed
+248
No files matched your search
@@ -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[:]
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ type DBTX interface {
|
|||||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
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 {
|
func New(db DBTX) *Queries {
|
||||||
|
|||||||
@@ -26,6 +26,13 @@ type Org struct {
|
|||||||
RequireTotp bool
|
RequireTotp bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RecoveryCode struct {
|
||||||
|
UserID uuid.UUID
|
||||||
|
CodeHash []byte
|
||||||
|
UsedAt *time.Time
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
type SsoProvider struct {
|
type SsoProvider struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
OrgID uuid.UUID
|
OrgID uuid.UUID
|
||||||
|
|||||||
@@ -13,11 +13,13 @@ import (
|
|||||||
type Querier interface {
|
type Querier interface {
|
||||||
AddMembership(ctx context.Context, arg AddMembershipParams) error
|
AddMembership(ctx context.Context, arg AddMembershipParams) error
|
||||||
AnyUserExists(ctx context.Context) (bool, error)
|
AnyUserExists(ctx context.Context) (bool, error)
|
||||||
|
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||||
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
|
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
|
||||||
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
|
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
|
||||||
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
||||||
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
||||||
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, 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)
|
DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error)
|
||||||
DeleteUser(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
|
DisableTOTP(ctx context.Context, id uuid.UUID) error
|
||||||
@@ -29,6 +31,7 @@ type Querier interface {
|
|||||||
GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
|
GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
|
||||||
GetUser(ctx context.Context, id uuid.UUID) (User, error)
|
GetUser(ctx context.Context, id uuid.UUID) (User, error)
|
||||||
GetUserByEmail(ctx context.Context, email string) (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)
|
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
|
||||||
ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
|
ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
|
||||||
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
|
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
|
||||||
@@ -42,6 +45,7 @@ type Querier interface {
|
|||||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||||
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
||||||
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
|
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
|
||||||
|
UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ Querier = (*Queries)(nil)
|
var _ Querier = (*Queries)(nil)
|
||||||
@@ -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;
|
||||||
@@ -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
|
||||||
|
}
|
||||||
Reference in new issue
Block a user