diff --git a/PLAN.md b/PLAN.md index 7fc77c4..f2bc31e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2159,6 +2159,32 @@ imported into Postgres, shows the same pages. This makes the server edition usable by a team. A commit after each part. +**Part 1 built 2026-11-25** on branch `phase10`. +- Schema 32 (both databases): `users` (email without case, kind, status, + an Argon2id hash in the PHC format, title, time zone, photo, emails + wanted, last sign-in), `memberships` (team 1 until Phase 13, role, a + member's modules as `{"seo":"edit"}`) and `sessions`. +- `internal/users`: accounts, memberships (`Can(module, write)`; owners and + admins can do everything) and sessions. A session's row keeps the + SHA-256 of the cookie's random value, never the value. A session ends + after 7 days unused or 30 days in all, or when its user is disabled or + leaves the team. Passwords need 10 characters, and can't be the email; + a sign-in for an unknown address takes as long as a real one. +- The cookie is `HttpOnly`, `SameSite=Lax`, and over https `Secure` with + the `__Host-` prefix. On the server edition every page but the public + ones (`/healthz`, `/static/`, `/mcp`, `/signin`, `/setup`) sends someone + not signed in to `/signin?next=…`; htmx gets a 401 with `HX-Redirect`. +- The local edition is unchanged: every request is the owner's. +- CSRF, on every edition: a random token in its own cookie, repeated in + every form (double-submit). Pages are rendered into a buffer and each + `method="post"` form to one of the app's own addresses gets a hidden + field (and a file upload, the token in its address, so its handler + still limits the body); htmx sends it as `X-CSRF-Token` (app.js). Forms + that post elsewhere never get it. `/mcp` has its key instead. The + same-origin check stays. +- Sessions aren't exported (`supermarket export`); users and memberships + are. + 1. **Users and sessions.** - Tables: - `users`: email, name, kind (person or agent), status (invited, diff --git a/go.mod b/go.mod index 70816b4..863e06c 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/jackc/pgx/v5 v5.13.0 github.com/minio/minio-go/v7 v7.4.1 github.com/modelcontextprotocol/go-sdk v1.8.0 + golang.org/x/crypto v0.59.0 golang.org/x/net v0.63.0 golang.org/x/text v0.44.0 gopkg.in/yaml.v3 v3.0.1 @@ -56,7 +57,6 @@ require ( go.opentelemetry.io/otel/trace v1.33.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect - golang.org/x/crypto v0.59.0 // indirect golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect diff --git a/internal/db/migrations.go b/internal/db/migrations.go index 284a073..4932063 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -52,6 +52,44 @@ CREATE TABLE locks ( taken_at TEXT NOT NULL DEFAULT '', expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it ); +`, + }, + // 32 + { + Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)", + SQLite: ` +CREATE TABLE users ( + id INTEGER PRIMARY KEY, + email TEXT NOT NULL UNIQUE COLLATE NOCASE, + name TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL DEFAULT 'person', -- person or agent + status TEXT NOT NULL DEFAULT 'invited', -- invited, active or disabled + password_hash TEXT NOT NULL DEFAULT '', -- Argon2id, in the PHC string format; '' for none + title TEXT NOT NULL DEFAULT '', + time_zone TEXT NOT NULL DEFAULT '', -- an IANA name, such as Europe/Paris + photo TEXT NOT NULL DEFAULT '', -- a name in the file storage + emails TEXT NOT NULL DEFAULT '[]', -- the emails they want, as a JSON list + created_at TEXT NOT NULL, + signed_in_at TEXT NOT NULL DEFAULT '' -- their last sign-in +); +CREATE TABLE memberships ( + team_id INTEGER NOT NULL DEFAULT 1, -- one team until the multi-tenant edition + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role TEXT NOT NULL, -- owner, admin or member + modules TEXT NOT NULL DEFAULT '{}', -- a member's modules: {"seo":"edit","metrics":"view"} + created_at TEXT NOT NULL, + PRIMARY KEY (team_id, user_id) +); +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, -- the SHA-256 of the cookie's random ID, never the ID itself + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at TEXT NOT NULL, + seen_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + ip TEXT NOT NULL DEFAULT '', + user_agent TEXT NOT NULL DEFAULT '' +); +CREATE INDEX sessions_user ON sessions(user_id); `, }, } diff --git a/internal/transfer/transfer.go b/internal/transfer/transfer.go index 21463a1..4c55c0c 100644 --- a/internal/transfer/transfer.go +++ b/internal/transfer/transfer.go @@ -42,6 +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, } // startupSettings are settings a new install writes when it first starts: diff --git a/internal/users/sessions.go b/internal/users/sessions.go new file mode 100644 index 0000000..972f96b --- /dev/null +++ b/internal/users/sessions.go @@ -0,0 +1,178 @@ +package users + +import ( + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "errors" + "time" + + "supermarket/internal/db" +) + +// Session lengths: a session ends after a week unused, and after 30 days +// whatever happens. +const ( + SessionIdle = 7 * 24 * time.Hour + SessionMax = 30 * 24 * time.Hour + // seenEvery is how often a session's last use is written down: not on + // every request. + seenEvery = time.Minute +) + +// Session is a signed-in browser. Its ID is the hash of the cookie's +// value: a copy of the database doesn't let anyone in. +type Session struct { + ID string + User int64 + Created time.Time + Seen time.Time + Expires time.Time + IP string + UserAgent string +} + +// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired, +// or its user can't sign in any more. +var ErrNoSession = errors.New("not signed in") + +func hashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// NewToken is 32 random bytes, for a cookie or a link. +func NewToken() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// StartSession signs a user in: it returns the token for the cookie. +func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (string, *Session, error) { + token, err := NewToken() + if err != nil { + return "", nil, err + } + if len(userAgent) > 300 { + userAgent = userAgent[:300] + } + s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent} + _, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)`, + s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent) + if err != nil { + return "", nil, err + } + return token, s, nil +} + +// expiry is when a session created at created, last used at seen, ends. +func expiry(created, seen time.Time) time.Time { + idle, max := seen.Add(SessionIdle), created.Add(SessionMax) + if idle.Before(max) { + return idle + } + return max +} + +const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent` + +func scanSession(row interface{ Scan(...any) error }) (*Session, error) { + var s Session + var created, seen, expires string + if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent); err != nil { + return nil, err + } + s.Created, s.Seen, s.Expires = parseTS(created), parseTS(seen), parseTS(expires) + return &s, nil +} + +// Lookup finds the session and user a cookie's token belongs to, and +// notes that it was used. Only active users have sessions that work. +func Lookup(d *db.DB, token string, now time.Time) (*Session, *User, error) { + if token == "" { + return nil, nil, ErrNoSession + } + s, err := scanSession(d.QueryRow(`SELECT `+sessionCols+` FROM sessions WHERE id = ?`, hashToken(token))) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil, ErrNoSession + } + if err != nil { + return nil, nil, err + } + if !now.Before(s.Expires) { + _, _ = d.Exec(`DELETE FROM sessions WHERE id = ?`, s.ID) + return nil, nil, ErrNoSession + } + u, err := ByID(d, s.User) + if errors.Is(err, ErrNotFound) { + return nil, nil, ErrNoSession + } + if err != nil { + return nil, nil, err + } + if u.Status != Active { + return nil, nil, ErrNoSession + } + if now.Sub(s.Seen) >= seenEvery { + s.Seen, s.Expires = now, expiry(s.Created, now) + if _, err := d.Exec(`UPDATE sessions SET seen_at = ?, expires_at = ? WHERE id = ?`, ts(s.Seen), ts(s.Expires), s.ID); err != nil { + return nil, nil, err + } + } + return s, u, nil +} + +// EndSession signs a cookie's session out. +func EndSession(d *db.DB, token string) error { + _, err := d.Exec(`DELETE FROM sessions WHERE id = ?`, hashToken(token)) + return err +} + +// EndSessionByID signs one of a user's sessions out, by its ID (from +// Sessions): only theirs. +func EndSessionByID(d *db.DB, user int64, id string) error { + _, err := d.Exec(`DELETE FROM sessions WHERE id = ? AND user_id = ?`, id, user) + return err +} + +// EndOtherSessions signs a user out everywhere but the session keep ("" +// for everywhere). It returns how many ended. +func EndOtherSessions(d *db.DB, user int64, keep string) (int64, error) { + res, err := d.Exec(`DELETE FROM sessions WHERE user_id = ? AND id <> ?`, user, keep) + if err != nil { + return 0, err + } + return res.RowsAffected() +} + +// Sessions are a user's sessions, the most recently used first. +func Sessions(d *db.DB, user int64, now time.Time) ([]*Session, error) { + rows, err := d.Query(`SELECT `+sessionCols+` FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY seen_at DESC`, user, ts(now)) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Session + for rows.Next() { + s, err := scanSession(rows) + if err != nil { + return nil, err + } + out = append(out, s) + } + return out, rows.Err() +} + +// PruneSessions deletes the sessions that have ended. +func PruneSessions(d *db.DB, now time.Time) (int64, error) { + res, err := d.Exec(`DELETE FROM sessions WHERE expires_at <= ?`, ts(now)) + if err != nil { + return 0, err + } + return res.RowsAffected() +} diff --git a/internal/users/users.go b/internal/users/users.go new file mode 100644 index 0000000..26a1021 --- /dev/null +++ b/internal/users/users.go @@ -0,0 +1,396 @@ +// Package users holds the people (and, from Phase 11, agents) who sign in +// to the server and multi-tenant editions: their accounts, their role and +// modules in the team, and their sessions. The local edition has none: +// whoever opens it is the owner. +package users + +import ( + "crypto/rand" + "crypto/subtle" + "database/sql" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/mail" + "strings" + "time" + + "golang.org/x/crypto/argon2" + + "supermarket/internal/db" +) + +// Kind is what signs in: a person, or an agent with a key (Phase 11). +type Kind string + +const ( + Person Kind = "person" + Agent Kind = "agent" +) + +// Status is where an account is. +type Status string + +const ( + Invited Status = "invited" // asked to join; hasn't chosen a password yet + Active Status = "active" // may sign in + Disabled Status = "disabled" // may not sign in; kept for the record +) + +// Role is what someone may do in the team. +type Role string + +const ( + Owner Role = "owner" // everything, and billing (multi-tenant) + Admin Role = "admin" // everything: users, connections, every module + Member Role = "member" // the modules they're given +) + +// Access is how much of a module a member has. +type Access string + +const ( + View Access = "view" // sees its pages + Edit Access = "edit" // and changes things +) + +// Team is the one team until the multi-tenant edition (Phase 13). +const Team int64 = 1 + +// timeFormat sorts as text: fixed width, UTC. +const timeFormat = "2006-01-02T15:04:05.000Z" + +func ts(t time.Time) string { return t.UTC().Format(timeFormat) } + +func parseTS(s string) time.Time { + t, _ := time.Parse(timeFormat, s) + return t +} + +// User is an account. +type User struct { + ID int64 + Email string + Name string + Kind Kind + Status Status + Title string + TimeZone string + Photo string + Emails []string // the emails they want (the daily SEO email, …) + Created time.Time + SignedIn time.Time // their last sign-in; zero if never + HasPassword bool + + passwordHash string +} + +// Membership is a user's place in a team. +type Membership struct { + Team int64 + User int64 + Role Role + Modules map[string]Access // a member's; admins and owners have them all +} + +// Admin says whether the role runs the whole system. +func (m Membership) Admin() bool { return m.Role == Owner || m.Role == Admin } + +// Can says whether the member may see a module (write false) or change +// things in it (write true). +func (m Membership) Can(module string, write bool) bool { + if m.Admin() { + return true + } + a, ok := m.Modules[module] + if !ok { + return false + } + return !write || a == Edit +} + +// Errors. +var ( + ErrNotFound = errors.New("no such user") + ErrExists = errors.New("someone already has that email address") +) + +// NormalEmail checks an email address and returns it trimmed, in lower +// case: addresses are compared without case. +func NormalEmail(s string) (string, error) { + s = strings.TrimSpace(s) + a, err := mail.ParseAddress(s) + if err != nil || a.Address != s || !strings.Contains(s, "@") { + return "", fmt.Errorf("%q isn't an email address", s) + } + return strings.ToLower(s), nil +} + +const userCols = `id, email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at, signed_in_at` + +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) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + u.Kind, u.Status = Kind(kind), Status(status) + _ = json.Unmarshal([]byte(emails), &u.Emails) + u.Created, u.SignedIn = parseTS(created), parseTS(signedIn) + u.HasPassword = u.passwordHash != "" + return &u, nil +} + +// Create adds a user. Its email is normalized; ID and Created are set. +func Create(d *db.DB, u *User, now time.Time) error { + email, err := NormalEmail(u.Email) + if err != nil { + return err + } + if _, err := ByEmail(d, email); err == nil { + return ErrExists + } else if !errors.Is(err, ErrNotFound) { + return err + } + u.Email = email + if u.Kind == "" { + u.Kind = Person + } + if u.Status == "" { + u.Status = Invited + } + if u.Emails == nil { + u.Emails = []string{} + } + emails, _ := json.Marshal(u.Emails) + u.Created = now + u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, u.TimeZone, u.Photo, string(emails), ts(now)) + return err +} + +// ByID finds a user. +func ByID(d *db.DB, id int64) (*User, error) { + return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE id = ?`, id)) +} + +// ByEmail finds a user by email address, whatever its case. +func ByEmail(d *db.DB, email string) (*User, error) { + return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE email = ? COLLATE NOCASE`, strings.TrimSpace(email))) +} + +// List is every user, people first, then by name. +func List(d *db.DB) ([]*User, error) { + rows, err := d.Query(`SELECT ` + userCols + ` FROM users ORDER BY kind DESC, name COLLATE NOCASE, email`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*User + for rows.Next() { + u, err := scanUser(rows) + if err != nil { + return nil, err + } + out = append(out, u) + } + return out, rows.Err() +} + +// Count is how many users there are. +func Count(d *db.DB) (int, error) { + var n int + err := d.QueryRow(`SELECT count(*) FROM users`).Scan(&n) + return n, err +} + +// SaveProfile writes the fields a user fills in about themselves. +func SaveProfile(d *db.DB, u *User) error { + if u.Emails == nil { + u.Emails = []string{} + } + emails, _ := json.Marshal(u.Emails) + _, err := d.Exec(`UPDATE users SET name = ?, title = ?, time_zone = ?, photo = ?, emails = ? WHERE id = ?`, + strings.TrimSpace(u.Name), strings.TrimSpace(u.Title), u.TimeZone, u.Photo, string(emails), u.ID) + return err +} + +// SetStatus activates, disables or re-invites a user. +func SetStatus(d *db.DB, id int64, s Status) error { + _, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id) + return err +} + +// SignedIn records a sign-in. +func SignedIn(d *db.DB, id int64, now time.Time) error { + _, err := d.Exec(`UPDATE users SET signed_in_at = ? WHERE id = ?`, ts(now), id) + return err +} + +// Delete removes a user, their memberships and their sessions. +func Delete(d *db.DB, id int64) error { + tx, err := d.Begin() + if err != nil { + return err + } + defer tx.Rollback() + // Not left to ON DELETE CASCADE: SQLite enforces it only with + // foreign_keys on, and an imported database may not have had them. + for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} { + if _, err := tx.Exec(q, id); err != nil { + return err + } + } + return tx.Commit() +} + +// Passwords. + +// MinPassword is the shortest password accepted. Length is what makes a +// password strong; there are no rules about kinds of characters. +const MinPassword = 10 + +// CheckNewPassword says what's wrong with a password someone chose. +func CheckNewPassword(pw, email string) error { + switch { + case len([]rune(pw)) < MinPassword: + return fmt.Errorf("the password needs at least %d characters", MinPassword) + case len(pw) > 1024: + return errors.New("the password is too long") + case strings.EqualFold(strings.TrimSpace(pw), strings.TrimSpace(email)): + return errors.New("the password can't be your email address") + } + return nil +} + +// Argon2id's cost: OWASP's suggestion of 19 MiB, two passes. +const ( + argonTime = 2 + argonMemory = 19 * 1024 + argonThreads = 1 + argonKeyLen = 32 +) + +// HashPassword hashes a password with Argon2id, in the PHC string format +// ($argon2id$v=19$m=…,t=…,p=…$salt$hash). +func HashPassword(pw string) (string, error) { + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + return "", err + } + key := argon2.IDKey([]byte(pw), salt, argonTime, argonMemory, argonThreads, argonKeyLen) + b64 := base64.RawStdEncoding + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil +} + +// VerifyPassword says whether pw matches a hash from HashPassword. It +// reads the cost from the hash, so older hashes still verify. +func VerifyPassword(hash, pw string) bool { + parts := strings.Split(hash, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return false + } + var v int + var m, t uint32 + var p uint8 + if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version { + return false + } + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil || m == 0 || m > 1<<20 || t == 0 || t > 16 || p == 0 { + return false + } + b64 := base64.RawStdEncoding + salt, err1 := b64.DecodeString(parts[4]) + want, err2 := b64.DecodeString(parts[5]) + if err1 != nil || err2 != nil || len(want) == 0 { + return false + } + got := argon2.IDKey([]byte(pw), salt, t, m, p, uint32(len(want))) + return subtle.ConstantTimeCompare(got, want) == 1 +} + +// dummyHash is checked against when there's no user, so a sign-in takes +// as long whether or not the address has an account. +var dummyHash, _ = HashPassword("not anyone's password") + +// CheckPassword says whether pw is the user's password. A user without +// one never matches. +func CheckPassword(u *User, pw string) bool { + if u == nil || u.passwordHash == "" { + VerifyPassword(dummyHash, pw) + return false + } + return VerifyPassword(u.passwordHash, pw) +} + +// SetPassword changes a user's password ("" removes it). +func SetPassword(d *db.DB, u *User, pw string) error { + hash := "" + if pw != "" { + var err error + if hash, err = HashPassword(pw); err != nil { + return err + } + } + if _, err := d.Exec(`UPDATE users SET password_hash = ? WHERE id = ?`, hash, u.ID); err != nil { + return err + } + u.passwordHash, u.HasPassword = hash, hash != "" + return nil +} + +// Memberships. + +// Join gives a user a role (and a member their modules) in the team, or +// changes it. +func Join(d *db.DB, team, user int64, role Role, modules map[string]Access, now time.Time) error { + switch role { + case Owner, Admin, Member: + default: + return fmt.Errorf("no role %q", role) + } + if role != Member || modules == nil { + modules = map[string]Access{} + } + for m, a := range modules { + if a != View && a != Edit { + return fmt.Errorf("module %s: no access %q", m, a) + } + } + js, _ := json.Marshal(modules) + _, err := d.Exec(`INSERT INTO memberships (team_id, user_id, role, modules, created_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (team_id, user_id) DO UPDATE SET role = excluded.role, modules = excluded.modules`, + team, user, string(role), string(js), ts(now)) + return err +} + +// MembershipOf is a user's place in the team; ErrNotFound if they have none. +func MembershipOf(d *db.DB, team, user int64) (Membership, error) { + m := Membership{Team: team, User: user} + var role, modules string + err := d.QueryRow(`SELECT role, modules FROM memberships WHERE team_id = ? AND user_id = ?`, team, user).Scan(&role, &modules) + if errors.Is(err, sql.ErrNoRows) { + return m, ErrNotFound + } + if err != nil { + return m, err + } + m.Role = Role(role) + m.Modules = map[string]Access{} + _ = json.Unmarshal([]byte(modules), &m.Modules) + return m, nil +} + +// HasOwner says whether the team has its owner yet: until then, the +// server edition is waiting to be set up. +func HasOwner(d *db.DB, team int64) (bool, error) { + var n int + err := d.QueryRow(`SELECT count(*) FROM memberships WHERE team_id = ? AND role = 'owner'`, team).Scan(&n) + return n > 0, err +} diff --git a/internal/users/users_test.go b/internal/users/users_test.go new file mode 100644 index 0000000..8ec976a --- /dev/null +++ b/internal/users/users_test.go @@ -0,0 +1,223 @@ +package users + +import ( + "errors" + "path/filepath" + "strings" + "testing" + "time" + + "supermarket/internal/db" +) + +func openDB(t *testing.T) *db.DB { + t.Helper() + d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Close() }) + return d +} + +func TestPasswords(t *testing.T) { + h, err := HashPassword("correct horse battery") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(h, "$argon2id$v=19$m=19456,t=2,p=1$") { + t.Errorf("hash %s", h) + } + if !VerifyPassword(h, "correct horse battery") || VerifyPassword(h, "correct horse batterY") { + t.Error("verify") + } + h2, _ := HashPassword("correct horse battery") + if h == h2 { + t.Error("no salt") + } + for _, bad := range []string{"", "x", "$argon2id$v=19$m=0,t=2,p=1$aa$bb", "$argon2i$v=19$m=19456,t=2,p=1$aa$bb", "$argon2id$v=19$m=99999999,t=2,p=1$aa$bb"} { + if VerifyPassword(bad, "x") { + t.Errorf("%q verified", bad) + } + } + if err := CheckNewPassword("short", "a@b.c"); err == nil { + t.Error("short password accepted") + } + if err := CheckNewPassword("Pat@Example.com", "pat@example.com"); err == nil { + t.Error("the email as a password accepted") + } + if err := CheckNewPassword("a long enough one", "pat@example.com"); err != nil { + t.Error(err) + } +} + +func TestUsersAndMemberships(t *testing.T) { + d := openDB(t) + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) + if ok, err := HasOwner(d, Team); err != nil || ok { + t.Fatalf("owner on a new database: %v %v", ok, err) + } + u := &User{Email: " Pat@Example.com ", Name: "Pat"} + if err := Create(d, u, now); err != nil { + t.Fatal(err) + } + if u.Email != "pat@example.com" || u.Status != Invited || u.Kind != Person { + t.Errorf("created %+v", u) + } + if err := Create(d, &User{Email: "PAT@example.com"}, now); !errors.Is(err, ErrExists) { + t.Errorf("same address again: %v", err) + } + if err := Create(d, &User{Email: "not an address"}, now); err == nil { + t.Error("bad address accepted") + } + got, err := ByEmail(d, "PAT@EXAMPLE.COM") + if err != nil || got.ID != u.ID || got.HasPassword { + t.Fatalf("by email: %+v %v", got, err) + } + if CheckPassword(got, "") || CheckPassword(nil, "x") { + t.Error("no password matched") + } + if err := SetPassword(d, got, "a long enough one"); err != nil { + t.Fatal(err) + } + got, _ = ByID(d, u.ID) + if !got.HasPassword || !CheckPassword(got, "a long enough one") || CheckPassword(got, "another one!") { + t.Error("password") + } + + if err := Join(d, Team, u.ID, Owner, nil, now); err != nil { + t.Fatal(err) + } + if ok, _ := HasOwner(d, Team); !ok { + t.Error("no owner") + } + m, err := MembershipOf(d, Team, u.ID) + if err != nil || !m.Admin() || !m.Can("metrics", true) { + t.Errorf("owner: %+v %v", m, err) + } + + jo := &User{Email: "jo@example.com", Name: "Jo"} + if err := Create(d, jo, now); err != nil { + t.Fatal(err) + } + if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) { + t.Errorf("no membership yet: %v", err) + } + if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": Edit, "metrics": View}, now); err != nil { + t.Fatal(err) + } + if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": "all"}, now); err == nil { + t.Error("bad access accepted") + } + m, _ = MembershipOf(d, Team, jo.ID) + for _, c := range []struct { + module string + write bool + want bool + }{{"seo", false, true}, {"seo", true, true}, {"metrics", false, true}, {"metrics", true, false}, {"content", false, false}} { + if got := m.Can(c.module, c.write); got != c.want { + t.Errorf("member Can(%s, %v) = %v", c.module, c.write, got) + } + } + // Changing the role. + if err := Join(d, Team, jo.ID, Admin, map[string]Access{"seo": View}, now); err != nil { + t.Fatal(err) + } + if m, _ = MembershipOf(d, Team, jo.ID); m.Role != Admin || len(m.Modules) != 0 { + t.Errorf("made admin: %+v", m) + } + + jo.Title, jo.TimeZone, jo.Emails = "Writer", "Europe/Paris", []string{"seo-daily"} + if err := SaveProfile(d, jo); err != nil { + t.Fatal(err) + } + list, err := List(d) + if err != nil || len(list) != 2 || list[0].Name != "Jo" || list[0].Title != "Writer" || len(list[0].Emails) != 1 { + t.Errorf("list: %+v %v", list, err) + } + if n, _ := Count(d); n != 2 { + t.Errorf("count %d", n) + } + if err := Delete(d, jo.ID); err != nil { + t.Fatal(err) + } + if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) { + t.Error("membership outlived its user") + } +} + +func TestSessions(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} + if err := Create(d, u, now); err != nil { + t.Fatal(err) + } + token, s, err := StartSession(d, u.ID, "203.0.113.5", "Firefox", now) + if err != nil { + t.Fatal(err) + } + if s.ID == token || len(token) < 40 { + t.Errorf("token %q, id %q", token, s.ID) + } + if _, _, err := Lookup(d, "nonsense", now); !errors.Is(err, ErrNoSession) { + t.Errorf("unknown token: %v", err) + } + if _, _, err := Lookup(d, "", now); !errors.Is(err, ErrNoSession) { + t.Errorf("empty token: %v", err) + } + got, who, err := Lookup(d, token, now.Add(time.Hour)) + if err != nil || who.ID != u.ID || got.IP != "203.0.113.5" { + t.Fatalf("lookup: %+v %+v %v", got, who, err) + } + if !got.Expires.Equal(now.Add(time.Hour + SessionIdle)) { + t.Errorf("expiry not slid: %v", got.Expires) + } + // Used every few days, it still ends after 30 days. + at := now + for i := 0; i < 9; i++ { + at = at.Add(3 * 24 * time.Hour) + if _, _, err := Lookup(d, token, at); err != nil { + t.Fatalf("day %d: %v", i*3, err) + } + } + if _, _, err := Lookup(d, token, now.Add(SessionMax)); !errors.Is(err, ErrNoSession) { + t.Errorf("after 30 days: %v", err) + } + + // Idle for a week. + t2, _, _ := StartSession(d, u.ID, "", "", now) + if _, _, err := Lookup(d, t2, now.Add(SessionIdle)); !errors.Is(err, ErrNoSession) { + t.Errorf("idle a week: %v", err) + } + + // A disabled user's sessions stop working. + t3, s3, _ := StartSession(d, u.ID, "", "", now) + t4, _, _ := StartSession(d, u.ID, "", "", now) + if err := SetStatus(d, u.ID, Disabled); err != nil { + t.Fatal(err) + } + if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) { + t.Errorf("disabled user: %v", err) + } + SetStatus(d, u.ID, Active) + if list, _ := Sessions(d, u.ID, now); len(list) != 2 { + t.Errorf("sessions: %d", len(list)) + } + if n, err := EndOtherSessions(d, u.ID, s3.ID); err != nil || n != 1 { + t.Errorf("end others: %d %v", n, err) + } + if _, _, err := Lookup(d, t4, now); !errors.Is(err, ErrNoSession) { + t.Error("another session survived") + } + if err := EndSession(d, t3); err != nil { + t.Fatal(err) + } + if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) { + t.Error("signed out, still in") + } + StartSession(d, u.ID, "", "", now) + if n, _ := PruneSessions(d, now.Add(SessionMax)); n != 1 { + t.Errorf("pruned %d", n) + } +} diff --git a/internal/web/auth.go b/internal/web/auth.go new file mode 100644 index 0000000..3b0d9cf --- /dev/null +++ b/internal/web/auth.go @@ -0,0 +1,330 @@ +package web + +import ( + "bytes" + "context" + "crypto/subtle" + "errors" + "html" + "net" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + "supermarket/internal/config" + "supermarket/internal/users" +) + +// The people using the app. On the local edition there is one, the +// owner, who never signs in: only this computer reaches the app. On the +// server edition each request carries a session cookie, and pages are +// shown to whoever it belongs to. + +// viewer is who a request comes from. +type viewer struct { + User *users.User // nil on the local edition + Member users.Membership + Session *users.Session // nil on the local edition +} + +// localOwner is the local edition's one user. +var localOwner = &viewer{Member: users.Membership{Team: users.Team, Role: users.Owner}} + +type ctxKey int + +const ( + viewerKey ctxKey = iota + csrfKey +) + +// viewerOf is who's asking. Requests that didn't go through the session +// check (tests calling a handler directly) are the local owner's. +func viewerOf(r *http.Request) *viewer { + if v, ok := r.Context().Value(viewerKey).(*viewer); ok { + return v + } + return localOwner +} + +// edition is how the app is run; tests without a Config are local. +func (s *Server) edition() config.Edition { + if s.Config == nil { + return config.Local + } + return s.Config.Edition +} + +// signsIn says whether people sign in: every edition but local. +func (s *Server) signsIn() bool { return s.edition() != config.Local } + +// secureCookies says whether cookies are marked Secure: when people reach +// the app over https. +func (s *Server) secureCookies() bool { return strings.HasPrefix(s.PublicURL, "https://") } + +// cookieName gives a cookie the __Host- prefix over https, so nothing on +// another subdomain can set it. +func (s *Server) cookieName(name string) string { + if s.secureCookies() { + return "__Host-" + name + } + return name +} + +const ( + sessionCookie = "sm_session" + csrfCookie = "sm_csrf" + csrfField = "csrf" // the forms' hidden field + csrfHeader = "X-CSRF-Token" // htmx sends it (app.js) +) + +// publicPaths are reached without signing in. +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"): + return true + } + return false +} + +// sessions finds who each request comes from. On the server edition, +// anyone not signed in is sent to sign in. +func (s *Server) sessions(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !s.signsIn() { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner))) + return + } + v, err := s.lookupSession(r) + if err != nil && !errors.Is(err, users.ErrNoSession) { + s.serverError(w, err) + return + } + if v == nil { + if publicPath(r.URL.Path) { + next.ServeHTTP(w, r) + return + } + s.toSignIn(w, r) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, v))) + }) +} + +// lookupSession is the signed-in viewer, or nil. +func (s *Server) lookupSession(r *http.Request) (*viewer, error) { + c, err := r.Cookie(s.cookieName(sessionCookie)) + if err != nil { + return nil, users.ErrNoSession + } + sess, u, err := users.Lookup(s.DB, c.Value, time.Now()) + if err != nil { + return nil, err + } + m, err := users.MembershipOf(s.DB, users.Team, u.ID) + if errors.Is(err, users.ErrNotFound) { + return nil, users.ErrNoSession // no longer in the team + } + if err != nil { + return nil, err + } + return &viewer{User: u, Member: m, Session: sess}, nil +} + +// toSignIn sends someone who isn't signed in to the sign-in page, and +// back here afterwards. htmx is told to load the whole page. +func (s *Server) toSignIn(w http.ResponseWriter, r *http.Request) { + target := "/signin" + if r.Method == http.MethodGet && r.URL.Path != "/" { + target += "?next=" + url.QueryEscape(r.URL.RequestURI()) + } + if r.Header.Get("HX-Request") != "" { + w.Header().Set("HX-Redirect", target) + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + http.Error(w, "Sign in first.", http.StatusUnauthorized) + return + } + http.Redirect(w, r, target, http.StatusSeeOther) +} + +// startSession signs a user in on this browser. +func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *users.User) error { + token, _, err := users.StartSession(s.DB, u.ID, clientIP(r), r.UserAgent(), time.Now()) + if err != nil { + return err + } + if err := users.SignedIn(s.DB, u.ID, time.Now()); err != nil { + return err + } + http.SetCookie(w, &http.Cookie{ + Name: s.cookieName(sessionCookie), Value: token, Path: "/", + MaxAge: int(users.SessionMax / time.Second), Secure: s.secureCookies(), + HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) + return nil +} + +// endSession signs this browser out. +func (s *Server) endSession(w http.ResponseWriter, r *http.Request) error { + if c, err := r.Cookie(s.cookieName(sessionCookie)); err == nil { + if err := users.EndSession(s.DB, c.Value); err != nil { + return err + } + } + http.SetCookie(w, &http.Cookie{ + Name: s.cookieName(sessionCookie), Value: "", Path: "/", MaxAge: -1, + Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) + return nil +} + +// clientIP is where a request came from: the proxy's X-Forwarded-For on +// the server edition (Caddy sets it, replacing what the client sent), +// else the connection's address. +func clientIP(r *http.Request) string { + if f := r.Header.Get("X-Forwarded-For"); f != "" { + parts := strings.Split(f, ",") + if ip := net.ParseIP(strings.TrimSpace(parts[len(parts)-1])); ip != nil { + return ip.String() + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +// CSRF: every form that changes something carries a token that a page on +// another site can't know, as well as the same-origin check (guard). The +// token is a random value in a cookie of its own, repeated in each form +// (the double-submit pattern): the forms get it as a hidden field, added +// as pages are rendered, and htmx sends it as a header. + +// csrf makes sure the browser has a token, and checks it on every request +// that changes something. +func (s *Server) csrf(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + name := s.cookieName(csrfCookie) + token := "" + if c, err := r.Cookie(name); err == nil && len(c.Value) >= 32 { + token = c.Value + } + if !safeMethod(r.Method) && r.URL.Path != "/mcp" { + if token == "" || !sameToken(token, sentToken(r)) { + http.Error(w, "This form has expired: reload the page and try again.", http.StatusForbidden) + return + } + } + if token == "" { + var err error + if token, err = users.NewToken(); err != nil { + s.serverError(w, err) + return + } + http.SetCookie(w, &http.Cookie{ + Name: name, Value: token, Path: "/", MaxAge: 365 * 24 * 3600, + Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), csrfKey, token))) + }) +} + +func safeMethod(m string) bool { + return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions +} + +func sameToken(a, b string) bool { + return b != "" && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +// sentToken is the token a request carries: htmx's header, a multipart +// form's address (its body is left for the handler, which limits its +// size), or a form's field. +func sentToken(r *http.Request) string { + if t := r.Header.Get(csrfHeader); t != "" { + return t + } + if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/") { + return r.URL.Query().Get(csrfField) + } + if err := r.ParseForm(); err != nil { + return "" + } + return r.PostForm.Get(csrfField) +} + +// csrfToken is the request's token, for the page. +func csrfToken(r *http.Request) string { + t, _ := r.Context().Value(csrfKey).(string) + return t +} + +var ( + formTag = regexp.MustCompile(`(?is)]*>`) + attrRe = regexp.MustCompile(`(?is)\b(method|action|enctype)\s*=\s*"([^"]*)"`) + actionArg = regexp.MustCompile(`(?is)\baction\s*=\s*"([^"]*)"`) +) + +// addCSRF puts the token into every form on a page that posts to this app: +// a hidden field, and for a file upload (multipart) also its address. +// Forms that post elsewhere never get it. +func addCSRF(page []byte, token string) []byte { + if token == "" { + return page + } + field := []byte(``) + return formTag.ReplaceAllFunc(page, func(tag []byte) []byte { + var method, action, enctype string + for _, m := range attrRe.FindAllSubmatch(tag, -1) { + switch strings.ToLower(string(m[1])) { + case "method": + method = strings.ToLower(string(m[2])) + case "action": + action = html.UnescapeString(string(m[2])) + case "enctype": + enctype = strings.ToLower(string(m[2])) + } + } + if method != "post" || !ownAddress(action) { + return tag + } + if strings.HasPrefix(enctype, "multipart/") { + sep := "?" + if strings.Contains(action, "?") { + sep = "&" + } + a := action + sep + csrfField + "=" + url.QueryEscape(token) + tag = actionArg.ReplaceAll(tag, []byte(`action="`+html.EscapeString(strings.ReplaceAll(a, "$", "$$"))+`"`)) + } + out := make([]byte, 0, len(tag)+len(field)) + return append(append(out, tag...), field...) + }) +} + +// ownAddress says whether a form's action is this app: empty, or a path. +func ownAddress(action string) bool { + if action == "" { + return true + } + return strings.HasPrefix(action, "/") && !strings.HasPrefix(action, "//") && !strings.HasPrefix(action, `/\`) +} + +// withCSRF renders a template into a buffer and adds the token to its +// forms. +func withCSRF(r *http.Request, exec func(*bytes.Buffer) error) ([]byte, error) { + var buf bytes.Buffer + if err := exec(&buf); err != nil { + return nil, err + } + return addCSRF(buf.Bytes(), csrfToken(r)), nil +} diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go new file mode 100644 index 0000000..683567e --- /dev/null +++ b/internal/web/auth_test.go @@ -0,0 +1,229 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "supermarket/internal/config" + "supermarket/internal/users" +) + +// newServerEdition is a test server run as the server edition. +func newServerEdition(t *testing.T) (*Server, http.Handler) { + t.Helper() + s, h := newTestServer(t, nil) + s.Config = &config.Config{Edition: config.Server} + return s, h +} + +// addUser makes an active user with a role and a password. +func addUser(t *testing.T, s *Server, email string, role users.Role, modules map[string]users.Access) *users.User { + t.Helper() + u := &users.User{Email: email, Name: strings.Split(email, "@")[0], Status: users.Active} + if err := users.Create(s.DB, u, time.Now()); err != nil { + t.Fatal(err) + } + if err := users.SetPassword(s.DB, u, "a long enough one"); err != nil { + t.Fatal(err) + } + if err := users.Join(s.DB, users.Team, u.ID, role, modules, time.Now()); err != nil { + t.Fatal(err) + } + return u +} + +// sessionFor signs a user in and returns their cookie. +func sessionFor(t *testing.T, s *Server, u *users.User) *http.Cookie { + t.Helper() + token, _, err := users.StartSession(s.DB, u.ID, "", "", time.Now()) + if err != nil { + t.Fatal(err) + } + return &http.Cookie{Name: sessionCookie, Value: token} +} + +// as makes a request with a session cookie. +func as(h http.Handler, c *http.Cookie, method, target string, form url.Values) *httptest.ResponseRecorder { + var req *http.Request + if form != nil { + req = httptest.NewRequest(method, target, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } else { + req = httptest.NewRequest(method, target, nil) + } + req.Host = "localhost:8470" + if c != nil { + req.AddCookie(c) + } + if !safeMethod(method) { + req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF}) + req.Header.Set(csrfHeader, testCSRF) + req.Header.Set("Origin", "http://localhost:8470") + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func TestCSRF(t *testing.T) { + _, h := newTestServer(t, nil) + form := url.Values{"name": {"Acme"}, "description": {"x"}} + + // A page sets the cookie and puts the token in its forms. + rec := do(h, http.MethodGet, "/settings/profile", nil, nil) + var token string + for _, c := range rec.Result().Cookies() { + if c.Name == csrfCookie { + token = c.Value + if !c.HttpOnly || c.SameSite != http.SameSiteLaxMode { + t.Errorf("cookie %+v", c) + } + } + } + if len(token) < 32 { + t.Fatalf("no token cookie: %v", rec.Result().Cookies()) + } + body := rec.Body.String() + if !strings.Contains(body, ``) { + t.Error("the form has no token") + } + if !strings.Contains(body, ``) { + t.Error("no token for htmx") + } + if strings.Contains(body, `role="search">
` + out := string(addCSRF([]byte(in), "T0k")) + want := `` + if out != want { + t.Errorf("got\n%s\nwant\n%s", out, want) + } +} + +func TestServerEditionNeedsSignIn(t *testing.T) { + s, h := newServerEdition(t) + // Not signed in: pages lead to the sign-in page; what's public stays so. + rec := do(h, http.MethodGet, "/seo/check?site=0", nil, nil) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?next=%2Fseo%2Fcheck%3Fsite%3D0" { + t.Errorf("page: %d %s", rec.Code, rec.Header().Get("Location")) + } + if rec := do(h, http.MethodGet, "/", nil, nil); rec.Header().Get("Location") != "/signin" { + t.Errorf("home: %s", rec.Header().Get("Location")) + } + if rec := do(h, http.MethodGet, "/seo/audit/status", nil, map[string]string{"HX-Request": "true"}); rec.Code != http.StatusUnauthorized || rec.Header().Get("HX-Redirect") == "" { + t.Errorf("htmx: %d %v", rec.Code, rec.Header()) + } + if rec := postForm(h, "/settings/profile", url.Values{"name": {"x"}}); rec.Code != http.StatusUnauthorized { + t.Errorf("post: %d", rec.Code) + } + for _, p := range []string{"/healthz", "/static/app.css", "/favicon.ico"} { + if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK { + t.Errorf("%s: %d", p, rec.Code) + } + } + + // Signed in. + owner := addUser(t, s, "owner@example.com", users.Owner, nil) + c := sessionFor(t, s, owner) + if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK { + t.Errorf("signed in: %d", rec.Code) + } + if rec := as(h, c, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme"}, "description": {"x"}}); rec.Code != http.StatusSeeOther { + t.Errorf("signed-in post: %d %s", rec.Code, rec.Body.String()) + } + // A made-up cookie, a disabled user, a user out of the team: not in. + if rec := as(h, &http.Cookie{Name: sessionCookie, Value: "made-up"}, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { + t.Errorf("made-up cookie: %d", rec.Code) + } + users.SetStatus(s.DB, owner.ID, users.Disabled) + if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { + t.Errorf("disabled: %d", rec.Code) + } + users.SetStatus(s.DB, owner.ID, users.Active) + s.DB.Exec(`DELETE FROM memberships WHERE user_id = ?`, owner.ID) + if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { + t.Errorf("out of the team: %d", rec.Code) + } +} + +func TestSessionCookiesOverHTTPS(t *testing.T) { + s, _ := newServerEdition(t) + s.PublicURL = "https://sm.example.com" + u := addUser(t, s, "pat@example.com", users.Owner, nil) + req := httptest.NewRequest(http.MethodPost, "/signin", nil) + rec := httptest.NewRecorder() + if err := s.startSession(rec, req, u); err != nil { + t.Fatal(err) + } + c := rec.Result().Cookies()[0] + if c.Name != "__Host-sm_session" || !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.Domain != "" { + t.Errorf("cookie %+v", c) + } + if got, _ := users.ByID(s.DB, u.ID); got.SignedIn.IsZero() { + t.Error("sign-in not recorded") + } +} + +func TestClientIP(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.RemoteAddr = "10.0.0.2:5555" + if got := clientIP(r); got != "10.0.0.2" { + t.Errorf("direct: %s", got) + } + r.Header.Set("X-Forwarded-For", "1.2.3.4, 203.0.113.9") + if got := clientIP(r); got != "203.0.113.9" { + t.Errorf("through the proxy: %s", got) + } +} diff --git a/internal/web/crm.go b/internal/web/crm.go index 616964a..97cc213 100644 --- a/internal/web/crm.go +++ b/internal/web/crm.go @@ -128,7 +128,7 @@ func (s *Server) crmReach(w http.ResponseWriter, r *http.Request) { } failure := unreachableError(actions) if s.Core == nil || failure == "" { - s.fragment(w, "crm", "reach", nil) + s.fragment(w, r, "crm", "reach", nil) return } check := probe(r.Context(), core.Service{Name: "EspoCRM", URL: espoCRMURL(s.Core)}) @@ -139,7 +139,7 @@ func (s *Server) crmReach(w http.ResponseWriter, r *http.Request) { break } } - s.fragment(w, "crm", "reach", map[string]any{ + s.fragment(w, r, "crm", "reach", map[string]any{ "Check": check, "Tried": tried, "Error": failure, diff --git a/internal/web/listmonk.go b/internal/web/listmonk.go index aef9904..de8ea18 100644 --- a/internal/web/listmonk.go +++ b/internal/web/listmonk.go @@ -112,7 +112,7 @@ func (s *Server) listmonkTest(w http.ResponseWriter, r *http.Request) { } else { data["Lists"] = lists } - s.fragment(w, "email", "listmonk-test", data) + s.fragment(w, r, "email", "listmonk-test", data) } // addToList adds a person to a mailing list. diff --git a/internal/web/outreach.go b/internal/web/outreach.go index 2717616..7f9bb15 100644 --- a/internal/web/outreach.go +++ b/internal/web/outreach.go @@ -141,7 +141,7 @@ func (s *Server) emailTest(w http.ResponseWriter, r *http.Request) { line{c.DMARC != "", "DMARC: " + or(c.DMARC, "none found. Add a DMARC record (start with p=none) so receivers trust your domain.")}, ) } - s.fragment(w, "email", "email-test", lines) + s.fragment(w, r, "email", "email-test", lines) } func or(a, b string) string { diff --git a/internal/web/pages.go b/internal/web/pages.go index a7748b5..7db8f9d 100644 --- a/internal/web/pages.go +++ b/internal/web/pages.go @@ -339,7 +339,7 @@ func probe(ctx context.Context, svc core.Service) serviceCheck { // fragment, loaded after the page so a slow service doesn't hold it up. func (s *Server) coreChecks(w http.ResponseWriter, r *http.Request) { if s.Core == nil { - s.fragment(w, "core", "checks", nil) + s.fragment(w, r, "core", "checks", nil) return } services := s.Core.Services() @@ -353,7 +353,7 @@ func (s *Server) coreChecks(w http.ResponseWriter, r *http.Request) { }(i, svc) } wg.Wait() - s.fragment(w, "core", "checks", checks) + s.fragment(w, r, "core", "checks", checks) } // --- AI servers CoreDesktop found --- diff --git a/internal/web/seo.go b/internal/web/seo.go index 8ebc969..ab1b83a 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -710,5 +710,5 @@ func (s *Server) weeklyAudits(now time.Time) { func (s *Server) giteaTest(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() - s.fragment(w, "sources", "test-result", s.testGitea(ctx)) + s.fragment(w, r, "sources", "test-result", s.testGitea(ctx)) } diff --git a/internal/web/server.go b/internal/web/server.go index 8fde0fe..f34cffa 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -2,6 +2,7 @@ package web import ( + "bytes" "context" "embed" "fmt" @@ -311,7 +312,7 @@ func (s *Server) Handler() (http.Handler, error) { }) } - return s.guard(mux), nil + return s.guard(s.csrf(s.sessions(mux))), nil } // guard protects the app, which has no login because only this machine can @@ -509,6 +510,9 @@ type page struct { NewProspects int // companies and people waiting for review, shown in the menu Drafts int // outreach drafts waiting, shown in the menu + + CSRF string // the form token, for htmx (app.js) + Viewer *viewer // who's looking } // Section is the top bar's first breadcrumb, from Nav. @@ -563,23 +567,33 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p p.Flash = flashText(r.URL.Query()) } p.Error = sentence(p.Error) - w.Header().Set("Content-Type", "text/html; charset=utf-8") - if err := t.ExecuteTemplate(w, "layout.html", p); err != nil { + p.CSRF = csrfToken(r) + p.Viewer = viewerOf(r) + out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) }) + if err != nil { s.Log.Error("render", "page", name, "err", err) + http.Error(w, "The page couldn't be shown: "+err.Error(), http.StatusInternalServerError) + return } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(out) } // fragment writes one named template (for htmx swaps). -func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) { +func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name string, data any) { t, ok := s.pages[page] if !ok { http.Error(w, "no template "+page, http.StatusInternalServerError) return } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - if err := t.ExecuteTemplate(w, name, data); err != nil { + out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, name, data) }) + if err != nil { s.Log.Error("render fragment", "page", page, "name", name, "err", err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(out) } // Messages shown after a redirect, by code, so no user text is reflected. diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 832adf5..7e14ebf 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -32,6 +32,9 @@ import ( const testToken = "0123456789abcdef0123456789abcdef" +// testCSRF is the form token test requests carry. +const testCSRF = "test-csrf-token-0123456789abcdef0123" + func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { t.Helper() dir := t.TempDir() @@ -63,8 +66,18 @@ func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) { func do(h http.Handler, method, target string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, target, body) req.Host = "localhost:8470" + // Requests that change something carry the form token, as the app's + // pages do; a test that sets X-CSRF-Token itself ("" for none) checks it. + if !safeMethod(method) { + req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF}) + if _, ok := hdr[csrfHeader]; !ok { + req.Header.Set(csrfHeader, testCSRF) + } + } for k, v := range hdr { - req.Header.Set(k, v) + if v != "" { + req.Header.Set(k, v) + } } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) diff --git a/internal/web/settings.go b/internal/web/settings.go index be10139..f666bd0 100644 --- a/internal/web/settings.go +++ b/internal/web/settings.go @@ -121,7 +121,7 @@ func (s *Server) aiTest(w http.ResponseWriter, r *http.Request) { if err != nil { result["Error"] = err.Error() } - s.fragment(w, "ai", "test-result", result) + s.fragment(w, r, "ai", "test-result", result) } // aiModels lists an OpenAI-compatible server's models (htmx fragment). @@ -139,7 +139,7 @@ func (s *Server) aiModels(w http.ResponseWriter, r *http.Request) { } data["Models"] = models } - s.fragment(w, "ai", "model-list", data) + s.fragment(w, r, "ai", "model-list", data) } // --- Secrets forms --- @@ -311,7 +311,7 @@ func (s *Server) accountsSave(w http.ResponseWriter, r *http.Request) { for _, n := range s.networks() { if n.Name == r.PostForm.Get("network") { n.Saved = true - s.fragment(w, "accounts", "network", n) + s.fragment(w, r, "accounts", "network", n) return } } diff --git a/internal/web/signals.go b/internal/web/signals.go index 08302c3..f85d9eb 100644 --- a/internal/web/signals.go +++ b/internal/web/signals.go @@ -450,7 +450,7 @@ func (s *Server) sourcesTest(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - s.fragment(w, "sources", "test-result", data) + s.fragment(w, r, "sources", "test-result", data) } // importSource runs one tool's import now. @@ -653,7 +653,7 @@ func (s *Server) signalRuns(w http.ResponseWriter, r *http.Request) { for _, run := range runs { running = running || run.Status == "running" } - s.fragment(w, "signal", "runs", map[string]any{"ID": id, "Runs": runs, "Running": running}) + s.fragment(w, r, "signal", "runs", map[string]any{"ID": id, "Runs": runs, "Running": running}) } // RunDiscovery searches for signals that ask to be searched on a schedule. diff --git a/internal/web/static/app.js b/internal/web/static/app.js index d02c29d..3ffbba6 100644 --- a/internal/web/static/app.js +++ b/internal/web/static/app.js @@ -177,4 +177,9 @@ }); }); })(); + // htmx's requests carry the form token, as forms do (a hidden field). + document.addEventListener("htmx:configRequest", function (e) { + var meta = document.querySelector('meta[name="csrf-token"]'); + if (meta && meta.content) e.detail.headers["X-CSRF-Token"] = meta.content; + }); })(); diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index a5104d4..e097fa0 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -3,6 +3,7 @@ + {{.Title}} · Supermarket diff --git a/internal/web/tracking.go b/internal/web/tracking.go index 05fd4b8..8c54a60 100644 --- a/internal/web/tracking.go +++ b/internal/web/tracking.go @@ -204,7 +204,7 @@ func (s *Server) trackingTest(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - s.fragment(w, "sources", "test-result", data) + s.fragment(w, r, "sources", "test-result", data) } // trackingRun imports from one source now.