The server edition now starts. Sign-in by email and password, limited per address and per IP; ten failures in a row lock the account and email its owner, and a reset by email (or an admin) unlocks it. Settings → Your account has the profile, the password, where you're signed in, and two-factor sign-in with an authenticator app (TOTP, from a QR code) and ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
384 lines
11 KiB
Go
384 lines
11 KiB
Go
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)
|
|
}
|
|
}
|
|
|
|
func TestLinks(t *testing.T) {
|
|
d := openDB(t)
|
|
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
|
|
a, err := NewLink(d, ResetLink, 7, now)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if u, err := PeekLink(d, a, ResetLink, now); err != nil || u != 7 {
|
|
t.Errorf("peek: %d %v", u, err)
|
|
}
|
|
if _, err := PeekLink(d, a, InviteLink, now); !errors.Is(err, ErrBadLink) {
|
|
t.Error("used for another purpose")
|
|
}
|
|
if exp, _ := LinkExpiry(d, ResetLink, 7, now); !exp.Equal(now.Add(time.Hour)) {
|
|
t.Errorf("expiry %v", exp)
|
|
}
|
|
if _, err := UseLink(d, a, ResetLink, now.Add(time.Hour)); !errors.Is(err, ErrBadLink) {
|
|
t.Error("used after an hour")
|
|
}
|
|
b, _ := NewLink(d, ResetLink, 7, now)
|
|
c, _ := NewLink(d, ResetLink, 7, now) // replaces b
|
|
if _, err := UseLink(d, b, ResetLink, now); !errors.Is(err, ErrBadLink) {
|
|
t.Error("replaced link worked")
|
|
}
|
|
if u, err := UseLink(d, c, ResetLink, now); err != nil || u != 7 {
|
|
t.Errorf("use: %d %v", u, err)
|
|
}
|
|
if _, err := UseLink(d, c, ResetLink, now); !errors.Is(err, ErrBadLink) {
|
|
t.Error("used twice")
|
|
}
|
|
i, _ := NewLink(d, InviteLink, 8, now)
|
|
if err := DropLinks(d, InviteLink, 8); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := PeekLink(d, i, InviteLink, now); !errors.Is(err, ErrBadLink) {
|
|
t.Error("withdrawn link worked")
|
|
}
|
|
if _, err := NewLink(d, "other", 1, now); err == nil {
|
|
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)
|
|
}
|
|
}
|