Phase 10, part 3: signing in and out, resets, locks and two-factor
The server edition now starts. Sign-in by email and password, limited per address and per IP; ten failures in a row lock the account and email its owner, and a reset by email (or an admin) unlocks it. Settings → Your account has the profile, the password, where you're signed in, and two-factor sign-in with an authenticator app (TOTP, from a QR code) and ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,6 +15,7 @@ const (
|
||||
SetupLink Purpose = "setup" // creates the first owner
|
||||
ResetLink Purpose = "reset" // chooses a new password
|
||||
InviteLink Purpose = "invite" // joins the team
|
||||
CodeLink Purpose = "code" // a sign-in waiting for its two-factor code
|
||||
)
|
||||
|
||||
// How long each kind of link lasts.
|
||||
@@ -22,6 +23,7 @@ var linkTTL = map[Purpose]time.Duration{
|
||||
SetupLink: 24 * time.Hour,
|
||||
ResetLink: time.Hour,
|
||||
InviteLink: 7 * 24 * time.Hour,
|
||||
CodeLink: 5 * time.Minute,
|
||||
}
|
||||
|
||||
// ErrBadLink is a link that's unknown, used, replaced or out of date.
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Limits on signing in.
|
||||
const (
|
||||
// LockAfter failed sign-ins in a row lock an account, until its owner
|
||||
// resets the password or an admin unlocks it.
|
||||
LockAfter = 10
|
||||
// ThrottleWindow is how long failures are counted for the limits below.
|
||||
ThrottleWindow = 15 * time.Minute
|
||||
// Within the window, an address may fail this often, and an IP this
|
||||
// often, before sign-ins from them are refused for the rest of it.
|
||||
MaxFailsPerEmail = 5
|
||||
MaxFailsPerIP = 20
|
||||
)
|
||||
|
||||
// FailedSignIn counts a wrong password or code against the user, and locks
|
||||
// the account at LockAfter. It says whether this failure locked it.
|
||||
func FailedSignIn(d *db.DB, u *User, now time.Time) (lockedNow bool, err error) {
|
||||
if _, err := d.Exec(`UPDATE users SET failed_signins = failed_signins + 1 WHERE id = ?`, u.ID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
u.FailedSignIns++
|
||||
if u.FailedSignIns < LockAfter || u.Locked() {
|
||||
return false, nil
|
||||
}
|
||||
res, err := d.Exec(`UPDATE users SET locked_at = ? WHERE id = ? AND locked_at = ''`, ts(now), u.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
u.LockedAt = now
|
||||
return n == 1, nil
|
||||
}
|
||||
|
||||
// Unlock clears the failures and the lock: after a sign-in, a password
|
||||
// reset, or an admin's unlock.
|
||||
func Unlock(d *db.DB, id int64) error {
|
||||
_, err := d.Exec(`UPDATE users SET failed_signins = 0, locked_at = '' WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Throttle counts events (failed sign-ins, reset emails) by key within a
|
||||
// window.
|
||||
|
||||
// Fails is how many events key has had in the window so far.
|
||||
func Fails(d *db.DB, key string, window time.Duration, now time.Time) (int, error) {
|
||||
var n int
|
||||
var since string
|
||||
err := d.QueryRow(`SELECT count, since FROM throttle WHERE key = ?`, key).Scan(&n, &since)
|
||||
if err != nil {
|
||||
return 0, nil // none yet (or unreadable: the other checks still hold)
|
||||
}
|
||||
if !parseTS(since).After(now.Add(-window)) {
|
||||
return 0, nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Fail counts one event for key, starting a new window if the last one
|
||||
// has passed.
|
||||
func Fail(d *db.DB, key string, window time.Duration, now time.Time) error {
|
||||
old := ts(now.Add(-window))
|
||||
_, err := d.Exec(`INSERT INTO throttle (key, count, since) VALUES (?, 1, ?)
|
||||
ON CONFLICT (key) DO UPDATE SET
|
||||
count = CASE WHEN throttle.since <= ? THEN 1 ELSE throttle.count + 1 END,
|
||||
since = CASE WHEN throttle.since <= ? THEN excluded.since ELSE throttle.since END`,
|
||||
key, ts(now), old, old)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClearFails forgets key's events.
|
||||
func ClearFails(d *db.DB, key string) error {
|
||||
_, err := d.Exec(`DELETE FROM throttle WHERE key = ?`, key)
|
||||
return err
|
||||
}
|
||||
|
||||
// PruneThrottle forgets counts whose window passed a day ago.
|
||||
func PruneThrottle(d *db.DB, now time.Time) error {
|
||||
_, err := d.Exec(`DELETE FROM throttle WHERE since < ?`, ts(now.Add(-24*time.Hour)))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base32"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Two-factor sign-in with an authenticator app: TOTP (RFC 6238), six
|
||||
// digits every 30 seconds, as every app does by default. The secret is
|
||||
// kept in the secrets store (encrypted on the server editions), under
|
||||
// TOTPSecretName.
|
||||
|
||||
// TOTPSecretName is where a user's authenticator secret is kept; while it's
|
||||
// being set up, TOTPPendingName.
|
||||
func TOTPSecretName(user int64) string { return fmt.Sprintf("totp:%d", user) }
|
||||
func TOTPPendingName(user int64) string { return fmt.Sprintf("totp-pending:%d", user) }
|
||||
|
||||
const totpPeriod = 30
|
||||
|
||||
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
|
||||
|
||||
// NewTOTPSecret is a new authenticator secret, in base32 as apps take it.
|
||||
func NewTOTPSecret() (string, error) {
|
||||
b := make([]byte, 20)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return b32.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// TOTPURL is the otpauth:// address an app reads from the QR code.
|
||||
func TOTPURL(issuer, account, secret string) string {
|
||||
v := url.Values{"secret": {secret}, "issuer": {issuer}, "algorithm": {"SHA1"}, "digits": {"6"}, "period": {"30"}}
|
||||
return "otpauth://totp/" + url.PathEscape(issuer+":"+account) + "?" + v.Encode()
|
||||
}
|
||||
|
||||
// totpAt is the code for a time step.
|
||||
func totpAt(key []byte, step int64) string {
|
||||
var msg [8]byte
|
||||
binary.BigEndian.PutUint64(msg[:], uint64(step))
|
||||
mac := hmac.New(sha1.New, key)
|
||||
mac.Write(msg[:])
|
||||
sum := mac.Sum(nil)
|
||||
off := sum[len(sum)-1] & 0x0f
|
||||
n := binary.BigEndian.Uint32(sum[off:off+4]) & 0x7fffffff
|
||||
return fmt.Sprintf("%06d", n%1000000)
|
||||
}
|
||||
|
||||
// TOTPCode is the code for a time: for tests.
|
||||
func TOTPCode(secret string, t time.Time) string {
|
||||
key, _ := b32.DecodeString(strings.ToUpper(secret))
|
||||
return totpAt(key, t.Unix()/totpPeriod)
|
||||
}
|
||||
|
||||
// CheckTOTP checks a code against the secret, allowing a step either side
|
||||
// for clocks that differ. A code works only after the step last used
|
||||
// (after), so one seen over someone's shoulder can't be used again. It
|
||||
// returns the code's step.
|
||||
func CheckTOTP(secret, code string, after int64, now time.Time) (int64, bool) {
|
||||
code = strings.Join(strings.Fields(code), "")
|
||||
if len(code) != 6 {
|
||||
return 0, false
|
||||
}
|
||||
key, err := b32.DecodeString(strings.ToUpper(secret))
|
||||
if err != nil || len(key) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
cur := now.Unix() / totpPeriod
|
||||
for _, step := range []int64{cur - 1, cur, cur + 1} {
|
||||
if step > after && subtle.ConstantTimeCompare([]byte(totpAt(key, step)), []byte(code)) == 1 {
|
||||
return step, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// UseTOTPStep records the step of a code that was used.
|
||||
func UseTOTPStep(d *db.DB, u *User, step int64) error {
|
||||
_, err := d.Exec(`UPDATE users SET totp_step = ? WHERE id = ? AND totp_step < ?`, step, u.ID, step)
|
||||
if err == nil {
|
||||
u.totpStep = step
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// TOTPStep is the step of the last code used.
|
||||
func (u *User) TOTPStep() int64 { return u.totpStep }
|
||||
|
||||
// NewRecoveryCodes makes ten single-use codes, like 7kq2-m9xw-4tpd, and
|
||||
// returns them with the hashes to keep.
|
||||
func NewRecoveryCodes() (codes, hashes []string, err error) {
|
||||
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789" // no 0/o, 1/l/i
|
||||
for i := 0; i < 10; i++ {
|
||||
b := make([]byte, 12)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var sb strings.Builder
|
||||
for j, c := range b {
|
||||
if j > 0 && j%4 == 0 {
|
||||
sb.WriteByte('-')
|
||||
}
|
||||
sb.WriteByte(alphabet[int(c)%len(alphabet)])
|
||||
}
|
||||
codes = append(codes, sb.String())
|
||||
hashes = append(hashes, hashCode(sb.String()))
|
||||
}
|
||||
return codes, hashes, nil
|
||||
}
|
||||
|
||||
func hashCode(code string) string {
|
||||
code = strings.ToLower(strings.NewReplacer("-", "", " ", "").Replace(strings.TrimSpace(code)))
|
||||
sum := sha256.Sum256([]byte(code))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// SetTwoFactor turns two-factor sign-in on, with new recovery codes'
|
||||
// hashes, or off (hashes nil). The secret is the caller's to keep or drop.
|
||||
func SetTwoFactor(d *db.DB, u *User, on bool, hashes []string) error {
|
||||
if hashes == nil {
|
||||
hashes = []string{}
|
||||
}
|
||||
js, _ := json.Marshal(hashes)
|
||||
flag := 0
|
||||
if on {
|
||||
flag = 1
|
||||
}
|
||||
if _, err := d.Exec(`UPDATE users SET two_factor = ?, recovery_codes = ?, totp_step = 0 WHERE id = ?`, flag, string(js), u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
u.TwoFactor, u.recoveryCodes, u.RecoveryLeft, u.totpStep = on, hashes, len(hashes), 0
|
||||
return nil
|
||||
}
|
||||
|
||||
// UseRecoveryCode uses up one of the user's recovery codes, if code is one.
|
||||
func UseRecoveryCode(d *db.DB, u *User, code string) (bool, error) {
|
||||
h := hashCode(code)
|
||||
left := make([]string, 0, len(u.recoveryCodes))
|
||||
found := false
|
||||
for _, c := range u.recoveryCodes {
|
||||
if !found && subtle.ConstantTimeCompare([]byte(c), []byte(h)) == 1 {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
left = append(left, c)
|
||||
}
|
||||
if !found {
|
||||
return false, nil
|
||||
}
|
||||
js, _ := json.Marshal(left)
|
||||
old, _ := json.Marshal(u.recoveryCodes)
|
||||
// Only if no one else used a code meanwhile: each works once.
|
||||
res, err := d.Exec(`UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?`, string(js), u.ID, string(old))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return false, nil
|
||||
}
|
||||
u.recoveryCodes, u.RecoveryLeft = left, len(left)
|
||||
return true, nil
|
||||
}
|
||||
+19
-4
@@ -83,9 +83,19 @@ type User struct {
|
||||
SignedIn time.Time // their last sign-in; zero if never
|
||||
HasPassword bool
|
||||
|
||||
passwordHash string
|
||||
FailedSignIns int // failed in a row since the last sign-in
|
||||
LockedAt time.Time // zero unless locked after too many failures
|
||||
TwoFactor bool // signs in with an authenticator app's code too
|
||||
RecoveryLeft int // unused recovery codes
|
||||
|
||||
passwordHash string
|
||||
totpStep int64
|
||||
recoveryCodes []string
|
||||
}
|
||||
|
||||
// Locked says whether the account is locked after too many failures.
|
||||
func (u *User) Locked() bool { return !u.LockedAt.IsZero() }
|
||||
|
||||
// Membership is a user's place in a team.
|
||||
type Membership struct {
|
||||
Team int64
|
||||
@@ -127,12 +137,14 @@ func NormalEmail(s string) (string, error) {
|
||||
return strings.ToLower(s), nil
|
||||
}
|
||||
|
||||
const userCols = `id, email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at, signed_in_at`
|
||||
const userCols = `id, email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes`
|
||||
|
||||
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
||||
var u User
|
||||
var kind, status, emails, created, signedIn string
|
||||
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.TimeZone, &u.Photo, &emails, &created, &signedIn)
|
||||
var kind, status, emails, created, signedIn, locked, codes string
|
||||
var twoFactor int
|
||||
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
|
||||
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
@@ -143,6 +155,9 @@ func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
||||
_ = json.Unmarshal([]byte(emails), &u.Emails)
|
||||
u.Created, u.SignedIn = parseTS(created), parseTS(signedIn)
|
||||
u.HasPassword = u.passwordHash != ""
|
||||
u.LockedAt, u.TwoFactor = parseTS(locked), twoFactor != 0
|
||||
_ = json.Unmarshal([]byte(codes), &u.recoveryCodes)
|
||||
u.RecoveryLeft = len(u.recoveryCodes)
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -263,3 +263,121 @@ func TestLinks(t *testing.T) {
|
||||
t.Error("unknown purpose")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockAndThrottle(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
|
||||
u := &User{Email: "pat@example.com", Status: Active}
|
||||
Create(d, u, now)
|
||||
for i := 1; i <= LockAfter; i++ {
|
||||
locked, err := FailedSignIn(d, u, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if locked != (i == LockAfter) {
|
||||
t.Errorf("failure %d: locked %v", i, locked)
|
||||
}
|
||||
}
|
||||
if locked, _ := FailedSignIn(d, u, now); locked {
|
||||
t.Error("locked twice")
|
||||
}
|
||||
got, _ := ByID(d, u.ID)
|
||||
if !got.Locked() || got.FailedSignIns != LockAfter+1 {
|
||||
t.Errorf("after: %+v", got)
|
||||
}
|
||||
Unlock(d, u.ID)
|
||||
if got, _ = ByID(d, u.ID); got.Locked() || got.FailedSignIns != 0 {
|
||||
t.Error("still locked")
|
||||
}
|
||||
|
||||
key := "signin:ip:203.0.113.5"
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := Fail(d, key, ThrottleWindow, now.Add(time.Duration(i)*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if n, _ := Fails(d, key, ThrottleWindow, now.Add(5*time.Minute)); n != 3 {
|
||||
t.Errorf("fails %d", n)
|
||||
}
|
||||
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 0 {
|
||||
t.Errorf("after the window: %d", n)
|
||||
}
|
||||
Fail(d, key, ThrottleWindow, now.Add(ThrottleWindow)) // a new window
|
||||
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 1 {
|
||||
t.Errorf("new window: %d", n)
|
||||
}
|
||||
ClearFails(d, key)
|
||||
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 0 {
|
||||
t.Errorf("cleared: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOTP(t *testing.T) {
|
||||
// RFC 6238's test secret, at 59 seconds: 94287082, of which apps show
|
||||
// the last six digits.
|
||||
secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
||||
at := time.Unix(59, 0)
|
||||
if got := TOTPCode(secret, at); got != "287082" {
|
||||
t.Errorf("code %s", got)
|
||||
}
|
||||
step, ok := CheckTOTP(secret, "287 082", 0, at)
|
||||
if !ok || step != 1 {
|
||||
t.Errorf("check: %d %v", step, ok)
|
||||
}
|
||||
if _, ok := CheckTOTP(secret, "287082", 1, at); ok {
|
||||
t.Error("a used code worked again")
|
||||
}
|
||||
if _, ok := CheckTOTP(secret, "287082", 0, at.Add(30*time.Second)); !ok {
|
||||
t.Error("a step late: refused")
|
||||
}
|
||||
if _, ok := CheckTOTP(secret, "287082", 0, at.Add(90*time.Second)); ok {
|
||||
t.Error("three steps late: accepted")
|
||||
}
|
||||
if _, ok := CheckTOTP(secret, "000000", 0, at); ok {
|
||||
t.Error("wrong code")
|
||||
}
|
||||
s, _ := NewTOTPSecret()
|
||||
if len(s) != 32 {
|
||||
t.Errorf("secret %s", s)
|
||||
}
|
||||
if u := TOTPURL("Supermarket (acme.com)", "pat@example.com", s); !strings.HasPrefix(u, "otpauth://totp/Supermarket%20%28acme.com%29:pat@example.com?") {
|
||||
t.Errorf("url %s", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryCodes(t *testing.T) {
|
||||
d := openDB(t)
|
||||
u := &User{Email: "pat@example.com", Status: Active}
|
||||
Create(d, u, time.Now())
|
||||
codes, hashes, err := NewRecoveryCodes()
|
||||
if err != nil || len(codes) != 10 || len(codes[0]) != 14 {
|
||||
t.Fatalf("%v %v", codes, err)
|
||||
}
|
||||
if err := SetTwoFactor(d, u, true, hashes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ = ByID(d, u.ID)
|
||||
if !u.TwoFactor || u.RecoveryLeft != 10 {
|
||||
t.Errorf("%+v", u)
|
||||
}
|
||||
if ok, _ := UseRecoveryCode(d, u, strings.ToUpper(codes[3])); !ok {
|
||||
t.Error("code refused")
|
||||
}
|
||||
if ok, _ := UseRecoveryCode(d, u, codes[3]); ok {
|
||||
t.Error("used twice")
|
||||
}
|
||||
// A stale copy of the user can't use a code another request used.
|
||||
stale, _ := ByID(d, u.ID)
|
||||
UseRecoveryCode(d, u, codes[4])
|
||||
if ok, _ := UseRecoveryCode(d, stale, codes[4]); ok {
|
||||
t.Error("used twice, from a stale copy")
|
||||
}
|
||||
u, _ = ByID(d, u.ID)
|
||||
if u.RecoveryLeft != 8 {
|
||||
t.Errorf("left %d", u.RecoveryLeft)
|
||||
}
|
||||
SetTwoFactor(d, u, false, nil)
|
||||
if u, _ = ByID(d, u.ID); u.TwoFactor || u.RecoveryLeft != 0 {
|
||||
t.Errorf("off: %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user