From 8040512a18677addf9bf55d844b2a17d32dc6e9f Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 09:01:29 -0700 Subject: [PATCH] Phase 10, part 3: signing in and out, resets, locks and two-factor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- PLAN.md | 36 +++ cmd/supermarket/main.go | 11 + go.mod | 1 + go.sum | 2 + internal/appmail/appmail.go | 173 ++++++++++ internal/config/config.go | 4 +- internal/config/config_test.go | 5 +- internal/db/migrations.go | 16 + internal/transfer/transfer.go | 2 +- internal/users/links.go | 2 + internal/users/signin.go | 87 ++++++ internal/users/totp.go | 175 +++++++++++ internal/users/users.go | 23 +- internal/users/users_test.go | 118 +++++++ internal/web/account.go | 358 +++++++++++++++++++++ internal/web/auth.go | 6 +- internal/web/auth_test.go | 2 + internal/web/server.go | 28 +- internal/web/signin.go | 417 +++++++++++++++++++++++++ internal/web/signin_test.go | 375 ++++++++++++++++++++++ internal/web/static/app.css | 5 + internal/web/templates/account.html | 70 +++++ internal/web/templates/forgot.html | 29 ++ internal/web/templates/layout.html | 4 + internal/web/templates/signin.html | 25 ++ internal/web/templates/two-factor.html | 29 ++ 26 files changed, 1991 insertions(+), 12 deletions(-) create mode 100644 internal/appmail/appmail.go create mode 100644 internal/users/signin.go create mode 100644 internal/users/totp.go create mode 100644 internal/web/account.go create mode 100644 internal/web/signin.go create mode 100644 internal/web/signin_test.go create mode 100644 internal/web/templates/account.html create mode 100644 internal/web/templates/forgot.html create mode 100644 internal/web/templates/signin.html create mode 100644 internal/web/templates/two-factor.html diff --git a/PLAN.md b/PLAN.md index 24767bb..4ed8a24 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2203,6 +2203,42 @@ This makes the server edition usable by a team. A commit after each part. - The server edition still won't start (`config.Ready`): signing in comes in part 3. +**Part 3 built 2026-11-25** on `phase10`. **The server edition now +starts** (multi-tenant still doesn't). +- `/signin`, `/signout`, `/forgot`, `/reset/`, without the sidebar. + A wrong password and an unknown address get the same answer, in the + same time (a dummy Argon2 check); only with the right password does the + page say an account is locked, turned off, or out of the team. `next` + is followed only to a path in the app. +- Limits (schema 34, a `throttle` table, so every copy of the app shares + them): 5 failures per address and 20 per IP in 15 minutes, then sign-ins + from them wait out the window. 10 failures in a row lock the account and + email its owner; resetting the password (which proves the email) or an + admin unlocks it. A wrong current password on Your account counts too. +- Reset links (an hour, once) are emailed in the background, the same page + shown whether or not there's an account; 3 per address and 10 per IP in + 15 minutes. A reset ends every session; signing in after still asks for + the two-factor code. +- `internal/appmail` sends the app's own mail through + `SUPERMARKET_MAIL_URL` (STARTTLS required, or smtps). +- Settings → Your account (every signed-in user): name, title, time zone; + password (needs the current one, ends the other sessions); where you're + signed in (browser, IP, when), signing out one or all the others. +- Two-factor: TOTP (SHA-1, 6 digits, 30 s, a step either side), set up + from a QR code (`rsc.io/qr`, a `data:` PNG) or the key typed in, and + confirmed by a code before it's on. The secret is in the secrets store + (`totp:`, encrypted on the server), never in the users table. Each + code works once (the last step is kept). Ten recovery codes + (`xxxx-xxxx-xxxx`, kept as SHA-256s), each once; new ones, and turning + it off, need the password. Sign-in with it on is two steps: the password, + then the code, joined by a 5-minute one-time link. Fewer than 3 codes + left: told so after signing in. The admin's reset comes with Users + (part 4). +- The sidebar shows who's signed in, with *Sign out*. An hourly job + (`job:accounts`) forgets ended sessions, links and old counts. +- Sign-ins, failures, locks, resets and two-factor changes are logged; + they move to the audit log in part 8. + 1. **Users and sessions.** - Tables: - `users`: email, name, kind (person or agent), status (invited, diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 4dd13c2..7eabfd8 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -36,6 +36,7 @@ import ( "time" "supermarket/internal/ai" + "supermarket/internal/appmail" "supermarket/internal/backup" "supermarket/internal/config" "supermarket/internal/content" @@ -320,6 +321,7 @@ func run(log *slog.Logger) error { MCPToken: token, MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)), MCP: mcpserver.Handler(database, token, version), + Mail: appMail(cfg), Log: log, ImportStatus: status, ImportErr: importErr, @@ -364,6 +366,7 @@ func run(log *slog.Logger) error { go srv.RunSEO(ctx) go srv.RunMetrics(ctx) go srv.RunBackups(ctx) + go srv.RunAccounts(ctx) // A sync falls due, and a claim times out, without anything being // written: refresh the state file each minute. go func() { @@ -401,6 +404,14 @@ func run(log *slog.Logger) error { return nil } +// appMail sends the app's own mail, where there's a mail server. +func appMail(cfg *config.Config) appmail.Sender { + if cfg.Mail == nil { + return nil + } + return &appmail.SMTP{Conf: cfg.Mail} +} + // setupLink makes a new one-time link to create the owner, or returns "" // if there's an owner already. func setupLink(d *db.DB, publicURL string) (string, error) { diff --git a/go.mod b/go.mod index 863e06c..98b3ebb 100644 --- a/go.mod +++ b/go.mod @@ -65,4 +65,5 @@ require ( modernc.org/libc v1.80.1 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect + rsc.io/qr v0.2.0 // indirect ) diff --git a/go.sum b/go.sum index 1efacb6..ee9dd6e 100644 --- a/go.sum +++ b/go.sum @@ -277,3 +277,5 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY= +rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs= diff --git a/internal/appmail/appmail.go b/internal/appmail/appmail.go new file mode 100644 index 0000000..385ad55 --- /dev/null +++ b/internal/appmail/appmail.go @@ -0,0 +1,173 @@ +// Package appmail sends the app's own mail on the server editions: +// invitations, password-reset links, and notices about someone's account. +// It goes through the mail server in SUPERMARKET_MAIL_URL, not the +// outreach mailbox a team sets up under Settings → Email. +package appmail + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/tls" + "encoding/hex" + "errors" + "fmt" + "mime" + "mime/quotedprintable" + "net" + "net/mail" + "net/smtp" + "strings" + "sync" + "time" + + "supermarket/internal/config" +) + +// Message is a plain-text email to one person. +type Message struct { + To string // an address + ToName string + Subject string + Body string +} + +// Sender sends messages. +type Sender interface { + Send(ctx context.Context, m Message) error +} + +// SMTP sends through a mail server. +type SMTP struct { + Conf *config.Mail +} + +// Send hands one message to the mail server. +func (s *SMTP) Send(ctx context.Context, m Message) error { + from, err := mail.ParseAddress(s.Conf.From) + if err != nil { + return err + } + raw, err := compose(from, m, time.Now()) + if err != nil { + return err + } + host, _, err := net.SplitHostPort(s.Conf.Host) + if err != nil { + return err + } + dialer := &net.Dialer{Timeout: 30 * time.Second} + tlsConf := &tls.Config{ServerName: host} + var conn net.Conn + if s.Conf.TLS { + conn, err = (&tls.Dialer{NetDialer: dialer, Config: tlsConf}).DialContext(ctx, "tcp", s.Conf.Host) + } else { + conn, err = dialer.DialContext(ctx, "tcp", s.Conf.Host) + } + if err != nil { + return fmt.Errorf("connecting to %s: %w", s.Conf.Host, err) + } + _ = conn.SetDeadline(time.Now().Add(time.Minute)) + c, err := smtp.NewClient(conn, host) + if err != nil { + conn.Close() + return err + } + defer c.Close() + if !s.Conf.TLS { + ok, _ := c.Extension("STARTTLS") + if !ok { + return fmt.Errorf("%s doesn't offer STARTTLS: use smtps:// (port 465) or a server that does", s.Conf.Host) + } + if err := c.StartTLS(tlsConf); err != nil { + return fmt.Errorf("starting TLS with %s: %w", s.Conf.Host, err) + } + } + if s.Conf.User != "" { + if err := c.Auth(smtp.PlainAuth("", s.Conf.User, s.Conf.Password, host)); err != nil { + return fmt.Errorf("signing in to %s: %w", s.Conf.Host, err) + } + } + if err := c.Mail(from.Address); err != nil { + return err + } + if err := c.Rcpt(m.To); err != nil { + return fmt.Errorf("the mail server refused %s: %w", m.To, err) + } + w, err := c.Data() + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + return c.Quit() +} + +func compose(from *mail.Address, m Message, now time.Time) ([]byte, error) { + to, err := mail.ParseAddress(m.To) + if err != nil { + return nil, err + } + to.Name = m.ToName + if strings.ContainsAny(m.Subject, "\r\n") { + return nil, errors.New("a subject has one line") + } + id := make([]byte, 12) + _, _ = rand.Read(id) + domain := from.Address[strings.LastIndex(from.Address, "@")+1:] + var b bytes.Buffer + h := func(k, v string) { b.WriteString(k + ": " + v + "\r\n") } + h("From", from.String()) + h("To", to.String()) + h("Subject", mime.QEncoding.Encode("utf-8", m.Subject)) + h("Date", now.Format(time.RFC1123Z)) + h("Message-ID", "<"+hex.EncodeToString(id)+"@"+domain+">") + h("Auto-Submitted", "auto-generated") + h("MIME-Version", "1.0") + h("Content-Type", "text/plain; charset=utf-8") + h("Content-Transfer-Encoding", "quoted-printable") + b.WriteString("\r\n") + text := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(m.Body), "\r\n", "\n"), "\n", "\r\n") + "\r\n" + qp := quotedprintable.NewWriter(&b) + _, _ = qp.Write([]byte(text)) + _ = qp.Close() + return b.Bytes(), nil +} + +// Outbox keeps messages instead of sending them: for tests. +type Outbox struct { + mu sync.Mutex + Sent []Message +} + +// Send keeps the message. +func (o *Outbox) Send(_ context.Context, m Message) error { + o.mu.Lock() + defer o.mu.Unlock() + o.Sent = append(o.Sent, m) + return nil +} + +// Last is the last message sent to an address, or nil. +func (o *Outbox) Last(to string) *Message { + o.mu.Lock() + defer o.mu.Unlock() + for i := len(o.Sent) - 1; i >= 0; i-- { + if strings.EqualFold(o.Sent[i].To, to) { + m := o.Sent[i] + return &m + } + } + return nil +} + +// Count is how many messages were sent. +func (o *Outbox) Count() int { + o.mu.Lock() + defer o.mu.Unlock() + return len(o.Sent) +} diff --git a/internal/config/config.go b/internal/config/config.go index c6893c6..c8a4541 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -307,10 +307,10 @@ func NewKey() (string, error) { // server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and // come in steps; until they're built, only the settings are checked. func (c *Config) Ready() error { - if c.Edition == Local { + if c.Edition != Multi { return nil } - return fmt.Errorf("This version of Supermarket runs only the local edition: the %s edition isn't built yet. Its settings are fine", c.Edition.Name()) + return fmt.Errorf("This version of Supermarket runs the local and server editions: the %s edition isn't built yet. Its settings are fine", c.Edition.Name()) } // Item is one line of the settings, to show. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index e35a270..ea20318 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -83,7 +83,7 @@ func TestServer(t *testing.T) { if m.Host != "mail.example.com:587" || m.TLS || m.User != "sm@example.com" || m.Password != "pw" || m.From != "Supermarket " { t.Fatalf("%+v", m) } - if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") { + if err := c.Ready(); err != nil { t.Fatal(err) } // The summary never shows a password. @@ -121,6 +121,9 @@ func TestMulti(t *testing.T) { if err != nil { t.Fatal(err) } + if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") { + t.Fatal(err) + } s := c.Storage if s.Bucket != "supermarket" || s.Prefix != "prod" || s.Endpoint != "https://s3.example.com" || s.Region != "garage" || s.String() != "s3://supermarket/prod at https://s3.example.com" { t.Fatalf("%+v", s) diff --git a/internal/db/migrations.go b/internal/db/migrations.go index 84c6108..40cc403 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -104,6 +104,22 @@ CREATE TABLE links ( expires_at TEXT NOT NULL ); CREATE INDEX links_user ON links(user_id, purpose); +`, + }, + // 34 + { + Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries", + SQLite: ` +ALTER TABLE users ADD COLUMN failed_signins INTEGER NOT NULL DEFAULT 0; -- in a row, since the last sign-in +ALTER TABLE users ADD COLUMN locked_at TEXT NOT NULL DEFAULT ''; -- locked after too many; '' when not +ALTER TABLE users ADD COLUMN two_factor INTEGER NOT NULL DEFAULT 0; -- an authenticator app is on (its secret is in secrets, totp:) +ALTER TABLE users ADD COLUMN totp_step INTEGER NOT NULL DEFAULT 0; -- the last code's time step: each code works once +ALTER TABLE users ADD COLUMN recovery_codes TEXT NOT NULL DEFAULT '[]'; -- SHA-256s of the unused recovery codes +CREATE TABLE throttle ( + key TEXT PRIMARY KEY, -- what's counted, e.g. signin:ip:203.0.113.5 + count INTEGER NOT NULL DEFAULT 0, + since TEXT NOT NULL -- when the count started +); `, }, } diff --git a/internal/transfer/transfer.go b/internal/transfer/transfer.go index f2e3861..953701c 100644 --- a/internal/transfer/transfer.go +++ b/internal/transfer/transfer.go @@ -42,7 +42,7 @@ type Manifest struct { // company's data. Secrets go in secrets.json, opened, if asked for. var skipped = map[string]bool{ "instances": true, "locks": true, "schema_version": true, "schema_migrations": true, "secrets": true, - "sessions": true, "links": true, + "sessions": true, "links": true, "throttle": true, } // startupSettings are settings a new install writes when it first starts: diff --git a/internal/users/links.go b/internal/users/links.go index 1c08345..fa34faf 100644 --- a/internal/users/links.go +++ b/internal/users/links.go @@ -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. diff --git a/internal/users/signin.go b/internal/users/signin.go new file mode 100644 index 0000000..5a67757 --- /dev/null +++ b/internal/users/signin.go @@ -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 +} diff --git a/internal/users/totp.go b/internal/users/totp.go new file mode 100644 index 0000000..7b14cab --- /dev/null +++ b/internal/users/totp.go @@ -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 +} diff --git a/internal/users/users.go b/internal/users/users.go index 26a1021..ca1ca8e 100644 --- a/internal/users/users.go +++ b/internal/users/users.go @@ -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 } diff --git a/internal/users/users_test.go b/internal/users/users_test.go index 97738e6..af3ae32 100644 --- a/internal/users/users_test.go +++ b/internal/users/users_test.go @@ -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) + } +} diff --git a/internal/web/account.go b/internal/web/account.go new file mode 100644 index 0000000..3574fe7 --- /dev/null +++ b/internal/web/account.go @@ -0,0 +1,358 @@ +package web + +import ( + "encoding/base64" + "html/template" + "net/http" + "net/url" + "strings" + "time" + + "rsc.io/qr" + + "supermarket/internal/users" +) + +// Settings → Your account, on the server edition: each person's profile, +// password, two-factor sign-in, and where they're signed in. + +type accountData struct { + U *users.User + Role users.Role + Sessions []sessionRow + Zones []string + Problem string // under the form it's about + Section string // which form: profile, password, two-factor + + // Setting up two-factor sign-in. + Secret string + QR template.URL + // Recovery codes, shown once. + Codes []string +} + +type sessionRow struct { + *users.Session + This bool +} + +// commonZones are offered for the time zone; any IANA name is accepted. +var commonZones = []string{ + "UTC", "Europe/London", "Europe/Dublin", "Europe/Lisbon", "Europe/Paris", "Europe/Berlin", "Europe/Madrid", "Europe/Rome", + "Europe/Amsterdam", "Europe/Stockholm", "Europe/Warsaw", "Europe/Athens", "Europe/Helsinki", "Europe/Istanbul", + "America/New_York", "America/Toronto", "America/Chicago", "America/Denver", "America/Phoenix", "America/Los_Angeles", + "America/Anchorage", "Pacific/Honolulu", "America/Mexico_City", "America/Sao_Paulo", "America/Buenos_Aires", + "Africa/Lagos", "Africa/Johannesburg", "Africa/Nairobi", "Asia/Dubai", "Asia/Kolkata", "Asia/Singapore", + "Asia/Shanghai", "Asia/Tokyo", "Asia/Seoul", "Australia/Perth", "Australia/Sydney", "Pacific/Auckland", +} + +// me is the signed-in user, or a 404 on the local edition, which has no +// accounts. +func (s *Server) me(w http.ResponseWriter, r *http.Request) *viewer { + v := viewerOf(r) + if v.User == nil { + http.NotFound(w, r) + return nil + } + return v +} + +func (s *Server) accountPage(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + s.renderAccount(w, r, v, &accountData{}, http.StatusOK) +} + +func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer, d *accountData, code int) { + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + list, err := users.Sessions(s.DB, u.ID, time.Now()) + if err != nil { + s.serverError(w, err) + return + } + d.U, d.Role, d.Zones = u, v.Member.Role, commonZones + for _, ss := range list { + d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID}) + } + if code != http.StatusOK { + w.WriteHeader(code) + } + s.render(w, r, "account", page{Title: "Your account", Nav: "settings/account", Data: d}) +} + +func (s *Server) accountProfile(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + u := *v.User + u.Name = strings.TrimSpace(r.PostFormValue("name")) + u.Title = strings.TrimSpace(r.PostFormValue("title")) + u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone")) + switch { + case u.Name == "": + s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "Give your name."}, http.StatusUnprocessableEntity) + return + case u.TimeZone != "" && !validZone(u.TimeZone): + s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "That isn't a time zone: choose one from the list, such as Europe/Paris."}, http.StatusUnprocessableEntity) + return + } + if err := users.SaveProfile(s.DB, &u); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/settings/account", "saved") +} + +func validZone(z string) bool { + if z == "Local" || len(z) > 64 { + return false + } + _, err := time.LoadLocation(z) + return err == nil +} + +func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + fail := func(msg string) { + s.renderAccount(w, r, v, &accountData{Section: "password", Problem: msg}, http.StatusUnprocessableEntity) + } + if !users.CheckPassword(u, r.PostFormValue("current")) { + s.accountWrongPassword(r, u) + fail("Your current password isn't right.") + return + } + pw := r.PostFormValue("password") + if err := users.CheckNewPassword(pw, u.Email); err != nil { + fail(sentence(err.Error()) + ".") + return + } + if pw != r.PostFormValue("password2") { + fail("The two new passwords aren't the same.") + return + } + if err := users.SetPassword(s.DB, u, pw); err != nil { + s.serverError(w, err) + return + } + n, err := users.EndOtherSessions(s.DB, u.ID, v.Session.ID) + if err != nil { + s.serverError(w, err) + return + } + s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n) + redirect(w, r, "/settings/account", "password-changed") +} + +// accountWrongPassword counts a wrong current password like a failed +// sign-in: someone at an open laptop can't guess at it for ever. +func (s *Server) accountWrongPassword(r *http.Request, u *users.User) { + now := time.Now() + s.countFailure("signin:ip:"+clientIP(r), "signin:email:"+u.Email, u, now) +} + +func (s *Server) accountEndSession(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + id := r.PathValue("id") + if id == v.Session.ID { + s.signout(w, r) + return + } + if err := users.EndSessionByID(s.DB, v.User.ID, id); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/settings/account#sessions", "session-ended") +} + +func (s *Server) accountEndOthers(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + if _, err := users.EndOtherSessions(s.DB, v.User.ID, v.Session.ID); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/settings/account#sessions", "sessions-ended") +} + +// Two-factor sign-in. + +// twoFactorPage starts setting up an authenticator app: a new secret, +// kept aside until a code from the app confirms it. +func (s *Server) twoFactorPage(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + if v.User.TwoFactor { + http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther) + return + } + secret := s.Secrets.Get(users.TOTPPendingName(v.User.ID)) + if secret == "" || r.URL.Query().Get("new") != "" { + var err error + if secret, err = users.NewTOTPSecret(); err != nil { + s.serverError(w, err) + return + } + if err := s.Secrets.Set(map[string]string{users.TOTPPendingName(v.User.ID): secret}); err != nil { + s.serverError(w, err) + return + } + } + s.renderTwoFactor(w, r, v, secret, "", http.StatusOK) +} + +func (s *Server) renderTwoFactor(w http.ResponseWriter, r *http.Request, v *viewer, secret, problem string, code int) { + d := &accountData{U: v.User, Secret: spaced(secret), Problem: problem} + if c, err := qr.Encode(users.TOTPURL(s.issuer(), v.User.Email, secret), qr.M); err == nil { + c.Scale = 6 + d.QR = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(c.PNG())) + } + if code != http.StatusOK { + w.WriteHeader(code) + } + s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Data: d}) +} + +// issuer is the name the authenticator app shows: Supermarket and where. +func (s *Server) issuer() string { + if u, err := url.Parse(s.PublicURL); err == nil && u.Hostname() != "" { + return "Supermarket (" + u.Hostname() + ")" + } + return "Supermarket" +} + +// spaced writes a secret in groups of four, to type it in. +func spaced(secret string) string { + var b strings.Builder + for i, c := range secret { + if i > 0 && i%4 == 0 { + b.WriteByte(' ') + } + b.WriteRune(c) + } + return b.String() +} + +func (s *Server) twoFactorOn(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + secret := s.Secrets.Get(users.TOTPPendingName(u.ID)) + if u.TwoFactor || secret == "" { + http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther) + return + } + step, ok := users.CheckTOTP(secret, r.PostFormValue("code"), 0, time.Now()) + if !ok { + s.renderTwoFactor(w, r, v, secret, "That code isn't right. Check the app shows Supermarket's code, and that your phone's clock is right, then try the code showing now.", http.StatusUnprocessableEntity) + return + } + codes, hashes, err := users.NewRecoveryCodes() + if err != nil { + s.serverError(w, err) + return + } + if err := s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): secret, users.TOTPPendingName(u.ID): ""}); err != nil { + s.serverError(w, err) + return + } + if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil { + s.serverError(w, err) + return + } + _ = users.UseTOTPStep(s.DB, u, step) + s.Log.Info("account: two-factor sign-in on", "user", u.Email) + s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "Two-factor sign-in is on.", Data: &accountData{U: u, Codes: codes}}) +} + +func (s *Server) twoFactorOff(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + if !users.CheckPassword(u, r.PostFormValue("current")) { + s.accountWrongPassword(r, u) + s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity) + return + } + if err := turnOffTwoFactor(s, u); err != nil { + s.serverError(w, err) + return + } + s.Log.Info("account: two-factor sign-in off", "user", u.Email) + redirect(w, r, "/settings/account#two-factor", "two-factor-off") +} + +// turnOffTwoFactor removes a user's authenticator and recovery codes. +func turnOffTwoFactor(s *Server, u *users.User) error { + if err := users.SetTwoFactor(s.DB, u, false, nil); err != nil { + return err + } + return s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): "", users.TOTPPendingName(u.ID): ""}) +} + +func (s *Server) recoveryCodes(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + if !u.TwoFactor { + http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther) + return + } + if !users.CheckPassword(u, r.PostFormValue("current")) { + s.accountWrongPassword(r, u) + s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity) + return + } + codes, hashes, err := users.NewRecoveryCodes() + if err != nil { + s.serverError(w, err) + return + } + step := u.TOTPStep() + if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil { + s.serverError(w, err) + return + } + _ = users.UseTOTPStep(s.DB, u, step) + s.Log.Info("account: new recovery codes", "user", u.Email) + s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "New recovery codes: the old ones no longer work.", Data: &accountData{U: u, Codes: codes}}) +} diff --git a/internal/web/auth.go b/internal/web/auth.go index fa926de..f73128b 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -84,8 +84,8 @@ func publicPath(p string) bool { switch { case p == "/healthz", p == "/favicon.ico", p == "/mcp", strings.HasPrefix(p, "/static/"), - p == "/signin", p == "/signout", - strings.HasPrefix(p, "/setup"): + p == "/signin", p == "/signin/code", p == "/signout", p == "/forgot", + strings.HasPrefix(p, "/reset/"), strings.HasPrefix(p, "/setup/"): return true } return false @@ -99,7 +99,7 @@ func (s *Server) sessions(next http.Handler) http.Handler { next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner))) return } - if !publicPath(r.URL.Path) || r.URL.Path == "/signin" { + if !publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin") { if done, err := s.hasOwner(); err != nil { s.serverError(w, err) return diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go index 5713a32..68936f7 100644 --- a/internal/web/auth_test.go +++ b/internal/web/auth_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "supermarket/internal/appmail" "supermarket/internal/config" "supermarket/internal/users" ) @@ -17,6 +18,7 @@ func newServerEdition(t *testing.T) (*Server, http.Handler) { t.Helper() s, h := newTestServer(t, nil) s.Config = &config.Config{Edition: config.Server} + s.Mail = &appmail.Outbox{} return s, h } diff --git a/internal/web/server.go b/internal/web/server.go index e646863..95fad77 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -27,6 +27,7 @@ import ( "supermarket/internal/api/reddit" "supermarket/internal/api/twitter" + "supermarket/internal/appmail" "supermarket/internal/core" "supermarket/internal/db" "supermarket/internal/legacy" @@ -59,7 +60,8 @@ type Server struct { MCPToken string MCPSocket string // the MCP socket's path on the host, for Hermes' config MCP http.Handler - Restart func() // stops the app so Docker starts it again; nil in tests + Mail appmail.Sender // the app's own mail (invitations, resets); nil on local + Restart func() // stops the app so Docker starts it again; nil in tests Log *slog.Logger // What the legacy import did at startup, or why it failed. @@ -140,6 +142,23 @@ func (s *Server) Handler() (http.Handler, error) { // Signing in (the server edition). mux.HandleFunc("GET /setup/{token}", s.setupPage) mux.HandleFunc("POST /setup/{token}", s.setupSave) + mux.HandleFunc("GET /signin", s.signinPage) + mux.HandleFunc("POST /signin", s.signin) + mux.HandleFunc("POST /signin/code", s.signinCode) + mux.HandleFunc("POST /signout", s.signout) + mux.HandleFunc("GET /forgot", s.forgotPage) + mux.HandleFunc("POST /forgot", s.forgot) + mux.HandleFunc("GET /reset/{token}", s.resetPage) + mux.HandleFunc("POST /reset/{token}", s.reset) + mux.HandleFunc("GET /settings/account", s.accountPage) + mux.HandleFunc("POST /settings/account/profile", s.accountProfile) + mux.HandleFunc("POST /settings/account/password", s.accountPassword) + mux.HandleFunc("POST /settings/account/sessions/end-others", s.accountEndOthers) + mux.HandleFunc("POST /settings/account/sessions/{id}/end", s.accountEndSession) + mux.HandleFunc("GET /settings/account/two-factor", s.twoFactorPage) + mux.HandleFunc("POST /settings/account/two-factor", s.twoFactorOn) + mux.HandleFunc("POST /settings/account/two-factor/off", s.twoFactorOff) + mux.HandleFunc("POST /settings/account/recovery-codes", s.recoveryCodes) mux.HandleFunc("GET /search", s.searchPage) @@ -609,6 +628,13 @@ func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name str var flashes = map[string]string{ "saved": "Saved.", "welcome": "Welcome: you're the owner. Start with the company's profile.", + "signed-out": "Signed out.", + "password-reset": "Your new password is saved: sign in with it.", + "password-changed": "Password changed. You're signed out everywhere else.", + "session-ended": "Signed out there.", + "sessions-ended": "Signed out everywhere else.", + "two-factor-off": "Two-factor sign-in is off.", + "codes-low": "You're running out of recovery codes: make new ones below.", "deleted": "Deleted.", "x-connected": "X is connected.", "li-connected": "LinkedIn is connected.", diff --git a/internal/web/signin.go b/internal/web/signin.go new file mode 100644 index 0000000..49bc182 --- /dev/null +++ b/internal/web/signin.go @@ -0,0 +1,417 @@ +package web + +import ( + "context" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "supermarket/internal/appmail" + "supermarket/internal/users" +) + +// Signing in and out, and resetting a password by email (the server +// edition). + +// signinForm is what the sign-in pages show. +type signinForm struct { + Email, Next string + Code bool // the second step: the authenticator's code + Token string // the sign-in waiting for its code + Problem string + Sent bool // a reset link went out (or would have) + Reset string +} + +// safeNext is where to go after signing in: a path in this app, else the +// Overview. +func safeNext(next string) string { + if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, `/\`) || strings.ContainsAny(next, "\r\n") { + return "/" + } + return next +} + +func (s *Server) signinPage(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + next := safeNext(r.URL.Query().Get("next")) + if v, _ := s.lookupSession(r); v != nil { + http.Redirect(w, r, next, http.StatusSeeOther) + return + } + s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: signinForm{Next: next, Email: r.URL.Query().Get("email")}}) +} + +func (s *Server) signinFail(w http.ResponseWriter, r *http.Request, f signinForm, code int) { + w.WriteHeader(code) + s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f}) +} + +const badSignIn = "That email address and password don't match an account." + +func (s *Server) signin(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + now := time.Now() + email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email"))) + f := signinForm{Email: email, Next: safeNext(r.PostFormValue("next"))} + ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+email + if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) { + f.Problem = "Too many failed sign-ins: wait a quarter of an hour, then try again. If you've forgotten your password, reset it." + s.signinFail(w, r, f, http.StatusTooManyRequests) + return + } + u, err := users.ByEmail(s.DB, email) + if err != nil && !errors.Is(err, users.ErrNotFound) { + s.serverError(w, err) + return + } + if err != nil { + u = nil + } + ok := users.CheckPassword(u, r.PostFormValue("password")) + if !ok { + s.countFailure(ipKey, emailKey, u, now) + f.Problem = badSignIn + s.signinFail(w, r, f, http.StatusUnauthorized) + return + } + // The password is right: now it's safe to say what else stops them. + if msg := s.cannotSignIn(u); msg != "" { + f.Problem = msg + s.signinFail(w, r, f, http.StatusForbidden) + return + } + if u.TwoFactor { + token, err := users.NewLink(s.DB, users.CodeLink, u.ID, now) + if err != nil { + s.serverError(w, err) + return + } + f.Code, f.Token = true, token + s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f}) + return + } + s.finishSignIn(w, r, u, ipKey, emailKey, f.Next) +} + +// cannotSignIn says why a user with the right password still can't sign +// in, or "". +func (s *Server) cannotSignIn(u *users.User) string { + switch { + case u.Locked(): + return "This account is locked after too many failed sign-ins. To unlock it, reset your password (below), or ask an admin." + case u.Status == users.Disabled: + return "This account is turned off. Ask an admin if you need it again." + case u.Status != users.Active || u.Kind != users.Person: + return badSignIn + } + if _, err := users.MembershipOf(s.DB, users.Team, u.ID); err != nil { + return "This account isn't part of the team any more. Ask an admin if you need it again." + } + return "" +} + +// signinCode is the second step, with the authenticator's code or a +// recovery code. +func (s *Server) signinCode(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + now := time.Now() + token := r.PostFormValue("token") + f := signinForm{Next: safeNext(r.PostFormValue("next")), Code: true, Token: token} + id, err := users.PeekLink(s.DB, token, users.CodeLink, now) + if err != nil { + if !errors.Is(err, users.ErrBadLink) { + s.serverError(w, err) + return + } + f = signinForm{Next: f.Next, Problem: "That took too long: sign in again."} + s.signinFail(w, r, f, http.StatusUnauthorized) + return + } + u, err := users.ByID(s.DB, id) + if err != nil { + s.serverError(w, err) + return + } + ipKey, emailKey := "signin:ip:"+clientIP(r), "signin:email:"+u.Email + if s.throttled(ipKey, users.MaxFailsPerIP, now) || s.throttled(emailKey, users.MaxFailsPerEmail, now) { + _ = users.DropLinks(s.DB, users.CodeLink, u.ID) + f = signinForm{Next: f.Next, Problem: "Too many failed sign-ins: wait a quarter of an hour, then try again."} + s.signinFail(w, r, f, http.StatusTooManyRequests) + return + } + if msg := s.cannotSignIn(u); msg != "" { + _ = users.DropLinks(s.DB, users.CodeLink, u.ID) + s.signinFail(w, r, signinForm{Next: f.Next, Problem: msg}, http.StatusForbidden) + return + } + code := strings.TrimSpace(r.PostFormValue("code")) + ok := false + if step, good := users.CheckTOTP(s.Secrets.Get(users.TOTPSecretName(u.ID)), code, u.TOTPStep(), now); good { + if err := users.UseTOTPStep(s.DB, u, step); err != nil { + s.serverError(w, err) + return + } + ok = true + } else if len(code) > 6 { + if ok, err = users.UseRecoveryCode(s.DB, u, code); err != nil { + s.serverError(w, err) + return + } + if ok { + s.Log.Info("signin: a recovery code was used", "user", u.Email, "left", u.RecoveryLeft) + } + } + if !ok { + s.countFailure(ipKey, emailKey, u, now) + f.Problem = "That code isn't right. Codes change every 30 seconds; enter the one showing now, or a recovery code." + s.signinFail(w, r, f, http.StatusUnauthorized) + return + } + if _, err := users.UseLink(s.DB, token, users.CodeLink, now); err != nil { + s.signinFail(w, r, signinForm{Next: f.Next, Problem: "That took too long: sign in again."}, http.StatusUnauthorized) + return + } + s.finishSignIn(w, r, u, ipKey, emailKey, f.Next) +} + +// finishSignIn starts the session, clears the failures, and goes on. +func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.User, ipKey, emailKey, next string) { + if err := users.Unlock(s.DB, u.ID); err != nil { + s.serverError(w, err) + return + } + _ = users.ClearFails(s.DB, emailKey) + if err := s.startSession(w, r, u); err != nil { + s.serverError(w, err) + return + } + s.Log.Info("signin", "user", u.Email, "ip", clientIP(r)) + if u.TwoFactor && u.RecoveryLeft < 3 { + redirect(w, r, "/settings/account#two-factor", "codes-low") + return + } + http.Redirect(w, r, next, http.StatusSeeOther) +} + +// throttled says whether key has failed too often lately. +func (s *Server) throttled(key string, max int, now time.Time) bool { + n, _ := users.Fails(s.DB, key, users.ThrottleWindow, now) + return n >= max +} + +// countFailure counts a failed sign-in against the IP, the address and +// the account, which locks after too many; its owner is told. +func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Time) { + for _, k := range []string{ipKey, emailKey} { + if err := users.Fail(s.DB, k, users.ThrottleWindow, now); err != nil { + s.Log.Warn("signin: counting a failure", "err", err) + } + } + if u == nil { + s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", strings.TrimPrefix(ipKey, "signin:ip:")) + return + } + s.Log.Info("signin: failed", "user", u.Email, "ip", strings.TrimPrefix(ipKey, "signin:ip:")) + locked, err := users.FailedSignIn(s.DB, u, now) + if err != nil { + s.Log.Warn("signin: counting a failure", "err", err) + return + } + if locked { + s.Log.Warn("signin: account locked", "user", u.Email) + s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked", + Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + + "Your account at " + s.PublicURL + " was locked after " + strconv.Itoa(users.LockAfter) + " failed sign-ins in a row.\n\n" + + "To unlock it, reset your password:\n" + s.PublicURL + "/forgot\n\nor ask an admin to unlock it.\n\n" + + "If those sign-ins weren't you, someone may be guessing your password. A long password used nowhere else, " + + "and two-factor sign-in (Settings → Your account), keep them out.\n"}) + } +} + +func (s *Server) signout(w http.ResponseWriter, r *http.Request) { + if err := s.endSession(w, r); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/signin", "signed-out") +} + +// Resetting a password. + +func (s *Server) forgotPage(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: signinForm{Email: r.URL.Query().Get("email")}}) +} + +func (s *Server) forgot(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + now := time.Now() + email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email"))) + f := signinForm{Email: email, Sent: true} + // The same answer whether or not there's an account, and the email is + // sent in the background, so the page can't tell anyone which + // addresses have one. Limited per IP and per address. + ipKey, emailKey := "reset:ip:"+clientIP(r), "reset:email:"+email + if s.throttled(ipKey, 10, now) || s.throttled(emailKey, 3, now) { + f.Sent, f.Problem = false, "Several links were sent already: check your email (and its spam folder), or wait a quarter of an hour." + w.WriteHeader(http.StatusTooManyRequests) + s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f}) + return + } + _ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now) + _ = users.Fail(s.DB, emailKey, users.ThrottleWindow, now) + if u, err := users.ByEmail(s.DB, email); err == nil && u.Kind == users.Person && (u.Status == users.Active) { + token, err := users.NewLink(s.DB, users.ResetLink, u.ID, now) + if err != nil { + s.serverError(w, err) + return + } + s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r)) + s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password", + Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + + "Someone, probably you, asked to reset your password at " + s.PublicURL + ".\n\n" + + "Choose a new one here, within an hour:\n" + s.PublicURL + "/reset/" + token + "\n\n" + + "If it wasn't you, ignore this email: your password stays as it is.\n"}) + } else if err != nil && !errors.Is(err, users.ErrNotFound) { + s.serverError(w, err) + return + } + s.render(w, r, "forgot", page{Title: "Reset your password", Bare: true, Data: f}) +} + +func (s *Server) resetPage(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + token := r.PathValue("token") + f := signinForm{Reset: token} + if _, err := users.PeekLink(s.DB, token, users.ResetLink, time.Now()); err != nil { + f.Reset, f.Problem = "", "This reset link has expired or was already used. Ask for a new one below." + w.WriteHeader(http.StatusNotFound) + } + s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f}) +} + +func (s *Server) reset(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + http.NotFound(w, r) + return + } + now := time.Now() + token := r.PathValue("token") + f := signinForm{Reset: token} + id, err := users.PeekLink(s.DB, token, users.ResetLink, now) + if err != nil { + s.resetPage(w, r) + return + } + u, err := users.ByID(s.DB, id) + if err != nil { + s.serverError(w, err) + return + } + pw := r.PostFormValue("password") + if err := users.CheckNewPassword(pw, u.Email); err != nil { + f.Problem = sentence(err.Error()) + "." + } else if pw != r.PostFormValue("password2") { + f.Problem = "The two passwords aren't the same." + } + if f.Problem != "" { + w.WriteHeader(http.StatusUnprocessableEntity) + s.render(w, r, "forgot", page{Title: "Choose a new password", Bare: true, Data: f}) + return + } + if _, err := users.UseLink(s.DB, token, users.ResetLink, now); err != nil { + s.resetPage(w, r) + return + } + if err := users.SetPassword(s.DB, u, pw); err != nil { + s.serverError(w, err) + return + } + // The email proved who they are: the lock goes, and so does every + // session, in case someone else had one. + if err := users.Unlock(s.DB, u.ID); err != nil { + s.serverError(w, err) + return + } + if _, err := users.EndOtherSessions(s.DB, u.ID, ""); err != nil { + s.serverError(w, err) + return + } + _ = users.ClearFails(s.DB, "signin:email:"+u.Email) + s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r)) + redirect(w, r, "/signin?email="+url.QueryEscape(u.Email), "password-reset") +} + +// sendMail sends the app's own mail in the background, so how long it +// takes says nothing to the person waiting. +func (s *Server) sendMail(m appmail.Message) { + if s.Mail == nil { + s.Log.Error("mail: no mail server (SUPERMARKET_MAIL_URL): not sent", "to", m.To, "subject", m.Subject) + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + if err := s.Mail.Send(ctx, m); err != nil { + s.Log.Error("mail: not sent", "to", m.To, "subject", m.Subject, "err", err) + } + }() +} + +func nameSuffix(name string) string { + if name = strings.TrimSpace(name); name != "" { + return " " + strings.Fields(name)[0] + } + return "" +} + +// RunAccounts forgets ended sessions, used-up links and old counts of +// failed sign-ins, every hour (the server edition). +func (s *Server) RunAccounts(ctx context.Context) { + if !s.signsIn() { + return + } + tick := time.NewTicker(time.Hour) + defer tick.Stop() + for { + s.jobDo(ctx, "accounts", func(context.Context) { + now := time.Now() + if _, err := users.PruneSessions(s.DB, now); err != nil { + s.Log.Warn("accounts: pruning sessions", "err", err) + } + if err := users.PruneLinks(s.DB, now); err != nil { + s.Log.Warn("accounts: pruning links", "err", err) + } + if err := users.PruneThrottle(s.DB, now); err != nil { + s.Log.Warn("accounts: pruning counts", "err", err) + } + }) + select { + case <-ctx.Done(): + return + case <-tick.C: + } + } +} diff --git a/internal/web/signin_test.go b/internal/web/signin_test.go new file mode 100644 index 0000000..474fa5a --- /dev/null +++ b/internal/web/signin_test.go @@ -0,0 +1,375 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "strings" + "testing" + "time" + + "supermarket/internal/appmail" + "supermarket/internal/users" +) + +// signin posts the sign-in form, from an IP. +func signin(h http.Handler, ip string, form url.Values) *httptest.ResponseRecorder { + return signinPost(h, ip, "/signin", form) +} + +func signinPost(h http.Handler, ip, path string, form url.Values) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) + req.Host = "localhost:8470" + req.RemoteAddr = ip + ":40000" + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Origin", "http://localhost:8470") + req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF}) + req.Header.Set(csrfHeader, testCSRF) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func cookieOf(rec *httptest.ResponseRecorder, name string) *http.Cookie { + for _, c := range rec.Result().Cookies() { + if c.Name == name && c.MaxAge >= 0 { + return c + } + } + return nil +} + +// waitMail waits for the app's mail (sent in the background). +func waitMail(t *testing.T, s *Server, to string, n int) *appmail.Message { + t.Helper() + ob := s.Mail.(*appmail.Outbox) + for i := 0; i < 200; i++ { + if ob.Count() >= n { + if m := ob.Last(to); m != nil { + return m + } + } + time.Sleep(5 * time.Millisecond) + } + t.Fatalf("no mail to %s (%d sent)", to, ob.Count()) + return nil +} + +func TestSignInAndOut(t *testing.T) { + s, h := newServerEdition(t) + addUser(t, s, "owner@example.com", users.Owner, nil) + + rec := do(h, http.MethodGet, "/signin?next=/seo/check", nil, nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `name="next" value="/seo/check"`) { + t.Fatalf("page: %d", rec.Code) + } + // Wrong password, unknown address: the same answer. + for _, f := range []url.Values{ + {"email": {"owner@example.com"}, "password": {"wrong password"}}, + {"email": {"nobody@example.com"}, "password": {"a long enough one"}}, + } { + rec := signin(h, "203.0.113.1", f) + if rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "match an account") || cookieOf(rec, sessionCookie) != nil { + t.Errorf("%v: %d", f, rec.Code) + } + } + rec = signin(h, "203.0.113.1", url.Values{"email": {"Owner@Example.com"}, "password": {"a long enough one"}, "next": {"/seo/check"}}) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo/check" { + t.Fatalf("sign in: %d %s", rec.Code, rec.Header().Get("Location")) + } + c := cookieOf(rec, sessionCookie) + if c == nil { + t.Fatal("no session") + } + if u, _ := users.ByEmail(s.DB, "owner@example.com"); u.FailedSignIns != 0 { + t.Errorf("failures not cleared: %d", u.FailedSignIns) + } + // Signed in, the sign-in page moves on. + if rec := as(h, c, http.MethodGet, "/signin", nil); rec.Code != http.StatusSeeOther { + t.Errorf("signed in, /signin: %d", rec.Code) + } + // Somewhere else: a path only. + rec = signin(h, "203.0.113.1", url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}, "next": {"//evil.example/"}}) + if rec.Header().Get("Location") != "/" { + t.Errorf("open redirect: %s", rec.Header().Get("Location")) + } + // The sidebar shows who's signed in. + if rec := as(h, c, http.MethodGet, "/", nil); !strings.Contains(rec.Body.String(), `action="/signout"`) { + t.Error("no sign-out button") + } + + rec = as(h, c, http.MethodPost, "/signout", url.Values{}) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?msg=signed-out" { + t.Errorf("sign out: %d %s", rec.Code, rec.Header().Get("Location")) + } + if rec := as(h, c, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther { + t.Errorf("after signing out: %d", rec.Code) + } +} + +func TestSignInLimitsAndLocks(t *testing.T) { + s, h := newServerEdition(t) + u := addUser(t, s, "owner@example.com", users.Owner, nil) + addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"seo": users.View}) + bad := url.Values{"email": {"owner@example.com"}, "password": {"wrong password"}} + good := url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}} + + // Five failures for an address, and it waits, even with the password. + for i := 0; i < users.MaxFailsPerEmail; i++ { + signin(h, "203.0.113.1", bad) + } + if rec := signin(h, "203.0.113.2", good); rec.Code != http.StatusTooManyRequests { + t.Errorf("address limit: %d", rec.Code) + } + // Another address from the same IP still works. + if rec := signin(h, "203.0.113.1", url.Values{"email": {"jo@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusSeeOther { + t.Errorf("other address: %d", rec.Code) + } + // An IP that fails often waits too. + for i := 0; i < users.MaxFailsPerIP; i++ { + signin(h, "198.51.100.7", url.Values{"email": {"x" + string(rune('a'+i)) + "@example.com"}, "password": {"nope nope nope"}}) + } + if rec := signin(h, "198.51.100.7", url.Values{"email": {"jo@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusTooManyRequests { + t.Errorf("IP limit: %d", rec.Code) + } + + // Ten failures in a row lock the account, and its owner is told. + s.DB.Exec(`DELETE FROM throttle`) + for i := 0; i < users.LockAfter; i++ { + if i%users.MaxFailsPerEmail == 0 { + s.DB.Exec(`DELETE FROM throttle`) + } + signin(h, "203.0.113.3", bad) + } + m := waitMail(t, s, "owner@example.com", 1) + if !strings.Contains(m.Subject, "locked") || !strings.Contains(m.Body, "/forgot") { + t.Errorf("mail %+v", m) + } + s.DB.Exec(`DELETE FROM throttle`) + rec := signin(h, "203.0.113.3", good) + if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "locked") { + t.Errorf("locked, right password: %d", rec.Code) + } + // With the wrong password, it doesn't say. + if rec := signin(h, "203.0.113.3", bad); strings.Contains(rec.Body.String(), "locked") { + t.Error("told a guesser it's locked") + } + users.Unlock(s.DB, u.ID) + s.DB.Exec(`DELETE FROM throttle`) + if rec := signin(h, "203.0.113.3", good); rec.Code != http.StatusSeeOther { + t.Errorf("unlocked: %d", rec.Code) + } + + // A disabled account, with the right password, is told so. + users.SetStatus(s.DB, u.ID, users.Disabled) + if rec := signin(h, "203.0.113.3", good); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "turned off") { + t.Errorf("disabled: %d", rec.Code) + } +} + +var linkRe = regexp.MustCompile(`http://localhost:8470(/reset/[A-Za-z0-9_-]+)`) + +func TestPasswordReset(t *testing.T) { + s, h := newServerEdition(t) + u := addUser(t, s, "owner@example.com", users.Owner, nil) + old := sessionFor(t, s, u) + users.FailedSignIn(s.DB, u, time.Now()) + + // The same page whether or not there's an account. + for _, email := range []string{"nobody@example.com", "Owner@example.com"} { + rec := postForm(h, "/forgot", url.Values{"email": {email}}) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Check your email") { + t.Errorf("%s: %d", email, rec.Code) + } + } + m := waitMail(t, s, "owner@example.com", 1) + if s.Mail.(*appmail.Outbox).Count() != 1 { + t.Errorf("mail to an unknown address") + } + path := linkRe.FindStringSubmatch(m.Body) + if path == nil { + t.Fatalf("no link: %s", m.Body) + } + if rec := do(h, http.MethodGet, path[1], nil, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Choose a new password") { + t.Errorf("reset page: %d", rec.Code) + } + if rec := postForm(h, path[1], url.Values{"password": {"short"}, "password2": {"short"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("short: %d", rec.Code) + } + rec := postForm(h, path[1], url.Values{"password": {"a brand new password"}, "password2": {"a brand new password"}}) + if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signin?email=owner%40example.com") { + t.Fatalf("reset: %d %s", rec.Code, rec.Header().Get("Location")) + } + got, _ := users.ByID(s.DB, u.ID) + if !users.CheckPassword(got, "a brand new password") || got.FailedSignIns != 0 { + t.Error("not reset") + } + if rec := as(h, old, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther { + t.Error("an old session survived the reset") + } + if rec := postForm(h, path[1], url.Values{"password": {"a brand new password"}, "password2": {"a brand new password"}}); rec.Code != http.StatusNotFound { + t.Errorf("used twice: %d", rec.Code) + } + + // Limited per address. + for i := 0; i < 3; i++ { + postForm(h, "/forgot", url.Values{"email": {"jo@example.com"}}) + } + if rec := postForm(h, "/forgot", url.Values{"email": {"jo@example.com"}}); rec.Code != http.StatusTooManyRequests { + t.Errorf("limit: %d", rec.Code) + } +} + +// codeFor signs a user in up to the two-factor step and returns its token. +func codeStep(t *testing.T, h http.Handler, email string) string { + t.Helper() + rec := signin(h, "203.0.113.9", url.Values{"email": {email}, "password": {"a long enough one"}}) + m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(rec.Body.String()) + if rec.Code != http.StatusOK || m == nil || cookieOf(rec, sessionCookie) != nil { + t.Fatalf("first step: %d %s", rec.Code, rec.Body.String()) + } + return m[1] +} + +func TestTwoFactor(t *testing.T) { + s, h := newServerEdition(t) + u := addUser(t, s, "owner@example.com", users.Owner, nil) + c := sessionFor(t, s, u) + + rec := as(h, c, http.MethodGet, "/settings/account", nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Turn it on") { + t.Fatalf("account: %d", rec.Code) + } + rec = as(h, c, http.MethodGet, "/settings/account/two-factor", nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `src="data:image/png;base64,`) { + t.Fatalf("setup: %d %s", rec.Code, rec.Body.String()) + } + secret := s.Secrets.Get(users.TOTPPendingName(u.ID)) + if secret == "" || !strings.Contains(rec.Body.String(), spaced(secret)) { + t.Fatal("no pending secret") + } + // Reloading keeps the same secret (the app may have it already). + as(h, c, http.MethodGet, "/settings/account/two-factor", nil) + if s.Secrets.Get(users.TOTPPendingName(u.ID)) != secret { + t.Error("secret changed on reload") + } + if rec := as(h, c, http.MethodPost, "/settings/account/two-factor", url.Values{"code": {"000000"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("wrong code: %d", rec.Code) + } + now := time.Now() + rec = as(h, c, http.MethodPost, "/settings/account/two-factor", url.Values{"code": {users.TOTPCode(secret, now)}}) + codes := recoveryCodesIn(rec.Body.String()) + if rec.Code != http.StatusOK || len(codes) != 10 { + t.Fatalf("on: %d %d codes", rec.Code, len(codes)) + } + if s.Secrets.Get(users.TOTPSecretName(u.ID)) != secret || s.Secrets.Get(users.TOTPPendingName(u.ID)) != "" { + t.Error("secret not moved") + } + + // Signing in now asks for the code. + token := codeStep(t, h, "owner@example.com") + // The code just used to turn it on doesn't work again. + if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now)}}); rec.Code != http.StatusUnauthorized { + t.Errorf("reused code: %d", rec.Code) + } + rec = signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now.Add(30 * time.Second))}, "next": {"/seo"}}) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo" || cookieOf(rec, sessionCookie) == nil { + t.Fatalf("code: %d %s", rec.Code, rec.Body.String()) + } + // The step is used up. + if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {"123456"}}); rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "took too long") { + t.Errorf("token reused: %d", rec.Code) + } + // A recovery code works once. + token = codeStep(t, h, "owner@example.com") + if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {strings.ToUpper(codes[0])}}); rec.Code != http.StatusSeeOther { + t.Errorf("recovery code: %d", rec.Code) + } + token = codeStep(t, h, "owner@example.com") + if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {codes[0]}}); rec.Code != http.StatusUnauthorized { + t.Errorf("recovery code twice: %d", rec.Code) + } + + // New codes and turning it off need the password. + if rec := as(h, c, http.MethodPost, "/settings/account/recovery-codes", url.Values{"current": {"wrong one"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("codes, wrong password: %d", rec.Code) + } + rec = as(h, c, http.MethodPost, "/settings/account/recovery-codes", url.Values{"current": {"a long enough one"}}) + if n := len(recoveryCodesIn(rec.Body.String())); n != 10 { + t.Errorf("new codes: %d", n) + } + if rec := as(h, c, http.MethodPost, "/settings/account/two-factor/off", url.Values{"current": {"a long enough one"}}); rec.Code != http.StatusSeeOther { + t.Errorf("off: %d", rec.Code) + } + if got, _ := users.ByID(s.DB, u.ID); got.TwoFactor || s.Secrets.Get(users.TOTPSecretName(u.ID)) != "" { + t.Error("still on") + } + if rec := signin(h, "203.0.113.9", url.Values{"email": {"owner@example.com"}, "password": {"a long enough one"}}); rec.Code != http.StatusSeeOther { + t.Errorf("sign in without a code: %d", rec.Code) + } +} + +func TestAccountPage(t *testing.T) { + s, h := newServerEdition(t) + u := addUser(t, s, "owner@example.com", users.Owner, nil) + c := sessionFor(t, s, u) + other := sessionFor(t, s, u) + third := sessionFor(t, s, u) + + rec := as(h, c, http.MethodPost, "/settings/account/profile", url.Values{"name": {"Olu A."}, "title": {"CEO"}, "time_zone": {"Mars/Base"}}) + if rec.Code != http.StatusUnprocessableEntity { + t.Errorf("bad zone: %d", rec.Code) + } + as(h, c, http.MethodPost, "/settings/account/profile", url.Values{"name": {"Olu A."}, "title": {"CEO"}, "time_zone": {"Europe/Paris"}}) + if got, _ := users.ByID(s.DB, u.ID); got.Name != "Olu A." || got.TimeZone != "Europe/Paris" { + t.Errorf("profile %+v", got) + } + rec = as(h, c, http.MethodGet, "/settings/account", nil) + if strings.Count(rec.Body.String(), "/end\"") != 3 || !strings.Contains(rec.Body.String(), "this one") { + t.Errorf("sessions: %s", rec.Body.String()) + } + + // Signing out one other session. + sess, _, err := users.Lookup(s.DB, other.Value, time.Now()) + if err != nil { + t.Fatal(err) + } + otherID := sess.ID + if rec := as(h, c, http.MethodPost, "/settings/account/sessions/"+otherID+"/end", url.Values{}); rec.Code != http.StatusSeeOther { + t.Errorf("end one: %d", rec.Code) + } + if rec := as(h, other, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther { + t.Error("ended session still works") + } + + // Changing the password ends the others, not this one. + if rec := as(h, c, http.MethodPost, "/settings/account/password", url.Values{"current": {"wrong"}, "password": {"a brand new password"}, "password2": {"a brand new password"}}); rec.Code != http.StatusUnprocessableEntity { + t.Errorf("wrong current: %d", rec.Code) + } + rec = as(h, c, http.MethodPost, "/settings/account/password", url.Values{"current": {"a long enough one"}, "password": {"a brand new password"}, "password2": {"a brand new password"}}) + if rec.Code != http.StatusSeeOther { + t.Errorf("change: %d %s", rec.Code, rec.Body.String()) + } + if rec := as(h, third, http.MethodGet, "/", nil); rec.Code != http.StatusSeeOther { + t.Error("other session survived the change") + } + if rec := as(h, c, http.MethodGet, "/", nil); rec.Code != http.StatusOK { + t.Error("this session ended") + } + + // The local edition has no account page. + _, lh := newTestServer(t, nil) + if rec := do(lh, http.MethodGet, "/settings/account", nil, nil); rec.Code != http.StatusNotFound { + t.Errorf("local: %d", rec.Code) + } +} + +// recoveryCodesIn finds the codes shown on the page. +func recoveryCodesIn(body string) []string { + m := regexp.MustCompile(`(?s)
(.*?)
`).FindStringSubmatch(body) + if m == nil { + return nil + } + return strings.Fields(m[1]) +} diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 8163a1a..4a2091b 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -496,3 +496,8 @@ dl.facts dd { margin: 0; overflow-wrap: anywhere; } .bare-main .card { padding: 1.5rem; } .bare-main button[type="submit"] { width: 100%; } .bare-shell .version { margin-top: auto; padding-top: 2rem; font-size: 0.8rem; color: hsl(var(--muted-foreground)); } +.pill.ok { background: hsl(var(--ok-bg)); border-color: hsl(var(--ok) / 0.35); color: hsl(var(--ok)); } +img.qr { image-rendering: pixelated; background: #fff; padding: 0.5rem; border-radius: var(--radius-sm); border: 1px solid hsl(var(--border)); } +.sidebar-foot .who { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; padding: 0.35rem 0.9rem; font-size: 0.85rem; color: hsl(var(--muted-foreground)); } +.sidebar-foot .who form { margin: 0; } +.sidebar-foot .who button { padding: 0.15rem 0.5rem; font-size: 0.8rem; } diff --git a/internal/web/templates/account.html b/internal/web/templates/account.html new file mode 100644 index 0000000..d15388b --- /dev/null +++ b/internal/web/templates/account.html @@ -0,0 +1,70 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}} +

Your account

+

{{.U.Email}} · {{.Role}}{{if not .U.SignedIn.IsZero}} · signed in {{ago .U.SignedIn}}{{end}}

+ +
+

About you

+ {{if eq .Section "profile"}}{{end}} +
+ + +
+ + {{range .Zones}} + +
+ +
+

Password

+ {{if eq .Section "password"}}{{end}} + + +
+ + +
+

Changing it signs you out everywhere else.

+ +
+ +
+

Two-factor sign-in

+ {{if eq .Section "two-factor"}}{{end}} + {{if .U.TwoFactor}} +

On Signing in asks for a code from your authenticator app. + {{if lt .U.RecoveryLeft 3}}{{.U.RecoveryLeft}} recovery codes left: make new ones below.{{else}}{{.U.RecoveryLeft}} recovery codes left.{{end}}

+
+
+ + + +
+
+ + + +
+
+ {{else}} +

Off. With it on, signing in asks for your password and a code from an authenticator app on your phone (such as Aegis, 2FAS, Google Authenticator or 1Password), so a stolen password isn't enough.

+ Turn it on + {{end}} +
+ +
+

Where you're signed in

+ + + + {{range .Sessions}} + + + + {{end}} + +
BrowserFromSigned inLast used
{{if .UserAgent}}{{truncate 60 .UserAgent}}{{else}}unknown{{end}}{{if .This}} this one{{end}}{{.IP}}{{ago .Created}}{{ago .Seen}}
+ {{if gt (len .Sessions) 1}}
{{end}} +
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/forgot.html b/internal/web/templates/forgot.html new file mode 100644 index 0000000..fd3546b --- /dev/null +++ b/internal/web/templates/forgot.html @@ -0,0 +1,29 @@ +{{define "content"}}{{with .Data}} +{{if .Reset}} +

Choose a new password

+{{with .Problem}}{{end}} +
+ + + +
+

Every place you're signed in is signed out; then you sign in with the new password.

+{{else if .Sent}} +

Check your email

+
+

If there's an account for {{.Email}}, a link to choose a new password is on its way. It works once, for an hour.

+

Nothing after a few minutes? Check the spam folder, and that the address is the one you sign in with.

+
+

Back to signing in

+{{else}} +

Reset your password

+{{with .Problem}}{{end}} +
+ + +
+

Back to signing in

+{{end}} +{{end}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 205807b..73cd363 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -102,6 +102,8 @@ @@ -136,6 +138,8 @@