Files
supermarket/internal/web/signin_test.go
T
davidandClaude Opus 5.5 47a504b7b2 Phase 10, part 4: inviting users, and what admins can change
Settings → Users lists everyone with their access and status. Admins
invite people by email (a link for 7 days), as admins or as members with
modules each to view or edit; the invitation's page sets the password,
profile and emails wanted. Admins can resend or withdraw invitations,
change access, turn accounts off and on, unlock, reset two-factor, sign
someone out, and remove them; never the owner, nor themselves. Your
account gets the emails wanted and a photo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:07:32 -07:00

376 lines
16 KiB
Go

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)<pre id="codes">(.*?)</pre>`).FindStringSubmatch(body)
if m == nil {
return nil
}
return strings.Fields(m[1])
}