From caff396264f5aca4d624e9d40ffa577f1cf5e795 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH] feat(auth): add argon2id passwords, replay-safe totp and redis rate limits Refs #3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/password.go | 82 ++++++++++++++++++++++++++++++++++ internal/auth/password_test.go | 41 +++++++++++++++++ internal/auth/ratelimit.go | 32 +++++++++++++ internal/auth/session.go | 6 +-- internal/auth/totp.go | 42 +++++++++++++++++ internal/auth/totp_test.go | 43 ++++++++++++++++++ 6 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 internal/auth/password.go create mode 100644 internal/auth/password_test.go create mode 100644 internal/auth/ratelimit.go create mode 100644 internal/auth/totp.go create mode 100644 internal/auth/totp_test.go diff --git a/internal/auth/password.go b/internal/auth/password.go new file mode 100644 index 0000000..8e1ebb1 --- /dev/null +++ b/internal/auth/password.go @@ -0,0 +1,82 @@ +package auth + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +// OWASP 2024 baseline for argon2id. +type argonParams struct { + memory uint32 + time uint32 + threads uint8 + keyLen uint32 +} + +var current = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32} + +const MinPasswordLength = 12 + +var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength) + +func HashPassword(pw string) (string, error) { + if len([]rune(pw)) < MinPasswordLength { + return "", ErrPasswordTooShort + } + salt := make([]byte, 16) + _, _ = rand.Read(salt) + p := current + hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen) + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, p.memory, p.time, p.threads, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(hash)), nil +} + +// VerifyPassword reports whether pw matches and whether the stored hash uses +// outdated parameters and should be replaced on this successful login. +func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) { + p, salt, want, err := decodeHash(encoded) + if err != nil { + return false, false, err + } + got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want))) + ok = subtle.ConstantTimeCompare(got, want) == 1 + return ok, ok && p != current, nil +} + +// dummyHash keeps the response time of unknown accounts equal to known ones. +var dummyHash, _ = HashPassword("not-a-real-password-for-timing") + +func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash, pw) } + +func decodeHash(s string) (argonParams, []byte, []byte, error) { + var p argonParams + parts := strings.Split(s, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return p, nil, nil, errors.New("auth: unsupported password hash") + } + var v int + if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version { + return p, nil, nil, errors.New("auth: unsupported argon2 version") + } + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.threads); err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + hash, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + p.keyLen = uint32(len(hash)) + return p, salt, hash, nil +} diff --git a/internal/auth/password_test.go b/internal/auth/password_test.go new file mode 100644 index 0000000..cb85041 --- /dev/null +++ b/internal/auth/password_test.go @@ -0,0 +1,41 @@ +package auth + +import ( + "strings" + "testing" +) + +func TestPasswordHash(t *testing.T) { + h, err := HashPassword("correct horse battery") + if err != nil { + t.Fatal(err) + } + if ok, rehash, err := VerifyPassword(h, "correct horse battery"); !ok || rehash || err != nil { + t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) + } + if ok, _, _ := VerifyPassword(h, "correct horse batterz"); ok { + t.Fatal("wrong password accepted") + } + if _, err := HashPassword("short"); err != ErrPasswordTooShort { + t.Fatalf("got %v", err) + } +} + +func TestPasswordRehashOnWeakerParams(t *testing.T) { + saved := current + current = argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32} + h, _ := HashPassword("correct horse battery") + current = saved + ok, rehash, err := VerifyPassword(h, "correct horse battery") + if !ok || !rehash || err != nil { + t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) + } +} + +func TestPasswordHashRejectsForeignFormats(t *testing.T) { + for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash, "argon2id", "argon2i", 1)} { + if _, _, err := VerifyPassword(h, "x"); err == nil { + t.Errorf("accepted %q", h) + } + } +} diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go new file mode 100644 index 0000000..c4410d4 --- /dev/null +++ b/internal/auth/ratelimit.go @@ -0,0 +1,32 @@ +package auth + +import ( + "context" + "time" + + "github.com/redis/go-redis/v9" +) + +type Limiter struct { + rdb redis.UniversalClient +} + +func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } + +var incrWithTTL = redis.NewScript(` +local n = redis.call("INCR", KEYS[1]) +if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end +return n`) + +// Allow counts one attempt in a fixed window shared by all replicas. +func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error) { + n, err := incrWithTTL.Run(ctx, l.rdb, []string{"rl:" + key}, window.Milliseconds()).Int() + if err != nil { + return false, err + } + return n <= limit, nil +} + +func (l *Limiter) Reset(ctx context.Context, key string) error { + return l.rdb.Del(ctx, "rl:"+key).Err() +} diff --git a/internal/auth/session.go b/internal/auth/session.go index 245e004..c7831dc 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -50,7 +50,7 @@ func key(token string) string { func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() } -func randomToken() string { +func RandomToken() string { b := make([]byte, 32) _, _ = rand.Read(b) return base64.RawURLEncoding.EncodeToString(b) @@ -58,10 +58,10 @@ func randomToken() string { func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, error) { sess := &Session{ - Token: randomToken(), + Token: RandomToken(), UserID: user, OrgID: org, - CSRF: randomToken(), + CSRF: RandomToken(), CreatedAt: s.now(), } k := key(sess.Token) diff --git a/internal/auth/totp.go b/internal/auth/totp.go new file mode 100644 index 0000000..1ea913d --- /dev/null +++ b/internal/auth/totp.go @@ -0,0 +1,42 @@ +package auth + +import ( + "context" + "time" + + "github.com/google/uuid" + "github.com/pquerna/otp" + "github.com/pquerna/otp/totp" + "github.com/redis/go-redis/v9" +) + +const totpIssuer = "uptimesebi" + +func NewTOTPKey(account string) (*otp.Key, error) { + return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) +} + +// TOTPVerifier rejects a code that was already accepted once, so an observed +// code cannot be replayed within its validity window. +type TOTPVerifier struct { + rdb redis.UniversalClient + now func() time.Time +} + +func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { + return &TOTPVerifier{rdb: rdb, now: time.Now} +} + +func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) { + ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ + Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, + }) + if err != nil || !ok { + return false, nil + } + fresh, err := v.rdb.SetNX(ctx, "totp_used:"+user.String()+":"+code, 1, 2*time.Minute).Result() + if err != nil { + return false, err + } + return fresh, nil +} diff --git a/internal/auth/totp_test.go b/internal/auth/totp_test.go new file mode 100644 index 0000000..d673ffc --- /dev/null +++ b/internal/auth/totp_test.go @@ -0,0 +1,43 @@ +package auth + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/pquerna/otp/totp" + "github.com/redis/go-redis/v9" +) + +func TestTOTPRejectsReplay(t *testing.T) { + url := os.Getenv("UPTIME_TEST_REDIS_URL") + if url == "" { + t.Skip("UPTIME_TEST_REDIS_URL not set") + } + opts, _ := redis.ParseURL(url) + rdb := redis.NewClient(opts) + defer rdb.Close() + + key, err := NewTOTPKey("a@example.test") + if err != nil { + t.Fatal(err) + } + now := time.Now() + code, _ := totp.GenerateCode(key.Secret(), now) + v := NewTOTPVerifier(rdb) + v.now = func() time.Time { return now } + user := uuid.New() + ctx := context.Background() + + if ok, err := v.Verify(ctx, user, key.Secret(), code); !ok || err != nil { + t.Fatalf("first use rejected: %v", err) + } + if ok, _ := v.Verify(ctx, user, key.Secret(), code); ok { + t.Fatal("replayed code accepted") + } + if ok, _ := v.Verify(ctx, user, key.Secret(), "000000"); ok { + t.Fatal("wrong code accepted") + } +}