Files
supermarket/internal/web/auth_test.go
T
davidandClaude Opus 5.5 da2d56f8d2 Phase 11, part 1: agents and their keys
Agents are users of kind agent, each given modules to read, or to read
and act on, and the CRM scope. Admins make them under Settings → Agents,
on every edition; keys (sm_…) are shown once and kept as hashes, can
expire, be rotated (the old one works a day) or revoked, and record their
last use. /mcp takes agent keys and offers each agent only the tools its
scopes allow. On the local edition, mcp-token is the key of a built-in
Hermes agent with the CRM and the Market.

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

245 lines
8.7 KiB
Go

package web
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/appmail"
"supermarket/internal/config"
"supermarket/internal/storage"
"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}
// The server edition has no built-in Hermes.
var hermes int64
if ok, _ := s.DB.GetJSON(hermesKey, &hermes); ok {
users.Delete(s.DB, hermes)
s.DB.Exec(`DELETE FROM settings WHERE key = ?`, hermesKey)
s.DB.Exec(`DELETE FROM audit_log`)
}
s.Mail = &appmail.Outbox{}
files, err := storage.Open(config.Storage{Dir: t.TempDir()})
if err != nil {
t.Fatal(err)
}
s.Files = files
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, `<input type="hidden" name="csrf" value="`+token+`">`) {
t.Error("the form has no token")
}
if !strings.Contains(body, `<meta name="csrf-token" content="`+token+`">`) {
t.Error("no token for htmx")
}
if strings.Contains(body, `role="search"><input type="hidden" name="csrf"`) {
t.Error("the search form (GET) got the token")
}
post := func(cookie, field, header string) int {
f := url.Values{}
for k, v := range form {
f[k] = v
}
if field != "" {
f.Set(csrfField, field)
}
req := httptest.NewRequest(http.MethodPost, "/settings/profile", strings.NewReader(f.Encode()))
req.Host = "localhost:8470"
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", "http://localhost:8470")
if cookie != "" {
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: cookie})
}
if header != "" {
req.Header.Set(csrfHeader, header)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}
for _, c := range []struct {
name string
cookie, field, header string
want int
}{
{"no token at all", "", "", "", http.StatusForbidden},
{"cookie only", token, "", "", http.StatusForbidden},
{"field without a cookie", "", token, "", http.StatusForbidden},
{"wrong field", token, token + "x", "", http.StatusForbidden},
{"field", token, token, "", http.StatusSeeOther},
{"header", token, "", token, http.StatusSeeOther},
} {
if got := post(c.cookie, c.field, c.header); got != c.want {
t.Errorf("%s: %d, want %d", c.name, got, c.want)
}
}
// MCP has its own key.
if rec := do(h, http.MethodPost, "/mcp", strings.NewReader("{}"), map[string]string{csrfHeader: ""}); rec.Code == http.StatusForbidden {
t.Errorf("MCP asked for a form token: %d", rec.Code)
}
}
func TestAddCSRF(t *testing.T) {
in := `<form method="post" action="/a"><form method="get" action="/b"><form action="/c"><form method="POST" action="https://evil.example/x"><form method="post" action="//evil.example/"><form method="post" action="/up?x=1" enctype="multipart/form-data"><form method="post">`
out := string(addCSRF([]byte(in), "T0k"))
want := `<form method="post" action="/a"><input type="hidden" name="csrf" value="T0k"><form method="get" action="/b"><form action="/c"><form method="POST" action="https://evil.example/x"><form method="post" action="//evil.example/"><form method="post" action="/up?x=1&amp;csrf=T0k" enctype="multipart/form-data"><input type="hidden" name="csrf" value="T0k"><form method="post"><input type="hidden" name="csrf" value="T0k">`
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}
func TestServerEditionNeedsSignIn(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
// 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.
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)
}
}