Phase 10, part 5: access enforced on every page, form and fragment

One table maps every address to an area (a module, Settings, anything
signed in, or public); each route is checked against it, and the app won't
start with a route missing from it. Changing needs edit on the module. For
members who may only view, forms that would change something are shown
disabled and htmx buttons hidden. The menu, the Overview, Search and the
SEO emails follow each person's modules; Settings is for admins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 09:13:16 -07:00
co-authored by Claude Opus 5.5
parent 47a504b7b2
commit 2b9d04297f
13 changed files with 578 additions and 41 deletions
+206
View File
@@ -0,0 +1,206 @@
package web
import (
"net/http"
"net/url"
"strings"
"testing"
"supermarket/internal/appmail"
"supermarket/internal/profile"
"supermarket/internal/users"
)
func TestEveryRouteHasAnArea(t *testing.T) {
// The app's own routes: Handler fails if one has no area.
s, _ := newTestServer(t, nil)
if _, err := s.Handler(); err != nil {
t.Fatal(err)
}
// A new route that isn't in the table is caught.
rt := &routes{s: s, mux: http.NewServeMux()}
rt.HandleFunc("GET /brand-new/{id}", func(http.ResponseWriter, *http.Request) {})
rt.HandleFunc("GET /seo/new-page", func(http.ResponseWriter, *http.Request) {})
if err := rt.err(); err == nil || !strings.Contains(err.Error(), "/brand-new/{id}") || strings.Contains(err.Error(), "/seo/new-page") {
t.Errorf("unmapped: %v", err)
}
for path, want := range map[string]string{
"/": areaSignedIn, "/seo": "seo", "/seo/check": "seo", "/seosomething": "", "/settings/account": areaSignedIn,
"/settings/account/two-factor": areaSignedIn, "/settings": areaSignedIn, "/settings/ai": areaAdmin,
"/market/1": "market", "/preview/0/x/index.html": "sites", "/static/app.css": areaPublic, "/mcp": areaPublic,
"/mcp/x": "", "/signin/code": areaPublic, "/{$}": areaSignedIn,
} {
got, ok := areaOf(path)
if got != want || ok != (want != "") {
t.Errorf("areaOf(%s) = %q %v, want %q", path, got, ok, want)
}
}
}
// pages are GET addresses across every area, for the access tests.
var accessPages = []string{"/", "/search?q=x", "/settings/account",
"/market", "/market/new", "/settings/profile", "/settings/ai", "/settings/accounts", "/settings/core", "/settings/users",
"/settings/email", "/settings/tracking", "/settings/search", "/settings/sources", "/settings/backups", "/settings/about",
"/content", "/posts", "/content/scheduled", "/content/published",
"/prospects", "/prospects/new", "/prospects/suppressed", "/outreach", "/crm", "/signals", "/signals/new",
"/seo", "/seo/check", "/seo/report", "/seo/next", "/seo/links", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
"/metrics", "/metrics/customers", "/metrics/spend", "/metrics/clv", "/metrics/publish",
"/sites", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new"}
func TestAccessEnforced(t *testing.T) {
s, h := newServerEdition(t)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
// The owner invites an admin and a member with only SEO.
adminLink := invite(t, s, h, oc, url.Values{"email": {"ada@example.com"}, "name": {"Ada"}, "role": {"admin"}})
memberLink := invite(t, s, h, oc, url.Values{"email": {"sam@example.com"}, "name": {"Sam"}, "role": {"member"}, "module:seo": {"edit"}})
for _, l := range []string{adminLink, memberLink} {
if rec := postForm(h, l, url.Values{"name": {"X"}, "password": {"a long enough one"}, "password2": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("join: %d", rec.Code)
}
}
// The member signs in.
rec := signin(h, "203.0.113.20", url.Values{"email": {"sam@example.com"}, "password": {"a long enough one"}})
sc := cookieOf(rec, sessionCookie)
if sc == nil {
t.Fatalf("member sign-in: %d", rec.Code)
}
ada, _ := users.ByEmail(s.DB, "ada@example.com")
ac := sessionFor(t, s, ada)
// The menu shows only SEO.
home := as(h, sc, http.MethodGet, "/", nil).Body.String()
for _, l := range []string{`href="/posts"`, `href="/signals"`, `href="/metrics"`, `href="/sites"`, `href="/market"`, `href="/settings/profile"`} {
if strings.Contains(home, l) {
t.Errorf("member's page links to %s", l)
}
}
if !strings.Contains(home, `href="/seo/check"`) || !strings.Contains(home, `href="/settings/account"`) {
t.Error("member's page lacks SEO or Your account")
}
for _, p := range accessPages {
area, _ := areaOf(strings.SplitN(p, "?", 2)[0])
want := http.StatusForbidden
if area == "seo" || area == areaSignedIn {
want = http.StatusOK
}
if rec := as(h, sc, http.MethodGet, p, nil); rec.Code != want {
t.Errorf("member GET %s: %d, want %d", p, rec.Code, want)
}
// The admin and the owner reach everything.
for who, c := range map[string]*http.Cookie{"admin": ac, "owner": oc} {
if rec := as(h, c, http.MethodGet, p, nil); rec.Code != http.StatusOK {
t.Errorf("%s GET %s: %d", who, p, rec.Code)
}
}
}
// Changes outside SEO, and htmx fragments, are refused too.
for _, p := range []string{"/settings/profile", "/market/save", "/metrics/sync", "/sites/sync", "/signals/new", "/drafts/1/publish", "/settings/users", "/settings/ai/test"} {
if rec := as(h, sc, http.MethodPost, p, url.Values{"name": {"x"}}); rec.Code != http.StatusForbidden {
t.Errorf("member POST %s: %d", p, rec.Code)
}
}
for _, p := range []string{"/settings/core/checks", "/crm/reach", "/settings/ai/models"} {
rec := do(h, http.MethodGet, p, nil, map[string]string{"HX-Request": "true", "Cookie": sessionCookie + "=" + sc.Value})
if rec.Code != http.StatusForbidden {
t.Errorf("member htmx %s: %d", p, rec.Code)
}
}
// Search shows only their modules.
if body := as(h, sc, http.MethodGet, "/search?q=company+profile", nil).Body.String(); strings.Contains(body, `href="/settings/profile"`) {
t.Error("search shows Settings to a member")
}
// What SEO changes, they can.
if rec := as(h, sc, http.MethodPost, "/seo/next/dismiss", url.Values{"page": {"/x"}}); rec.Code == http.StatusForbidden {
t.Errorf("member POST in SEO: %d", rec.Code)
}
}
func TestViewOnlyMember(t *testing.T) {
s, h := newServerEdition(t)
addUser(t, s, "owner@example.com", users.Owner, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
jo := addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"seo": users.View, "market": users.Edit})
c := sessionFor(t, s, jo)
rec := as(h, c, http.MethodGet, "/seo/audit", nil)
if rec.Code != http.StatusOK {
t.Fatalf("view: %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, `<fieldset class="readonly" disabled>`) {
t.Error("SEO's forms aren't disabled")
}
if strings.Contains(body, `<input type="hidden" name="csrf" value="`+testCSRF) && strings.Contains(body, `action="/seo/audit?site=0" class="card row wrap" data-busy="Starting…"><input`) {
t.Error("a disabled form carries the token")
}
if rec := as(h, c, http.MethodPost, "/seo/audit?site=0", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("view member POST: %d", rec.Code)
}
// The search box (GET) and sign-out still work; the Market, which they
// edit, keeps its forms.
if !strings.Contains(body, `action="/signout"><input type="hidden" name="csrf"`) {
t.Error("sign-out form disabled")
}
rec = as(h, c, http.MethodGet, "/market/new", nil)
if strings.Contains(rec.Body.String(), `class="readonly"`) {
t.Error("the Market's forms are disabled for an editor")
}
}
func TestRewriteForms(t *testing.T) {
v := &viewer{Member: users.Membership{Role: users.Member, Modules: map[string]users.Access{"seo": users.View, "market": users.Edit}}, User: &users.User{ID: 2}}
in := `<form method="post" action="/seo/keywords"><textarea>keep me</textarea><button>Find</button></form>` +
`<form method="post" action="/market/save"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><button>Here</button></form>` +
`<button hx-post="/seo/changes/suggest">Suggest</button><button hx-get="/seo/audit/status">Status</button>`
out := string(rewriteForms([]byte(in), "T", "/seo/check", v))
want := `<form method="post" action="/seo/keywords"><fieldset class="readonly" disabled><textarea>keep me</textarea><button>Find</button></fieldset></form>` +
`<form method="post" action="/market/save"><input type="hidden" name="csrf" value="T"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><fieldset class="readonly" disabled><button>Here</button></fieldset></form>` +
`<button hx-post="/seo/changes/suggest" hidden disabled>Suggest</button><button hx-get="/seo/audit/status">Status</button>`
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}
func TestLocalOwnerReachesEverything(t *testing.T) {
_, h := newTestServer(t, nil)
for _, p := range accessPages {
if p == "/settings/account" || p == "/settings/users" {
continue // there are no accounts on the local edition
}
if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK {
t.Errorf("local GET %s: %d", p, rec.Code)
}
}
if body := do(h, http.MethodGet, "/seo/keywords", nil, nil).Body.String(); strings.Contains(body, "readonly") {
t.Error("local forms disabled")
}
}
func TestMailTeam(t *testing.T) {
s, _ := newServerEdition(t)
a := addUser(t, s, "a@example.com", users.Member, map[string]users.Access{"seo": users.View})
b := addUser(t, s, "b@example.com", users.Member, map[string]users.Access{"metrics": users.Edit})
c := addUser(t, s, "c@example.com", users.Admin, nil)
d := addUser(t, s, "d@example.com", users.Admin, nil)
for _, u := range []*users.User{a, b, c} {
u.Emails = []string{"seo-check"}
users.SaveProfile(s.DB, u)
}
users.SetStatus(s.DB, c.ID, users.Disabled)
_ = d // didn't ask
if n := s.mailTeam(t.Context(), "seo-check", "Moved", "Text"); n != 1 {
t.Errorf("sent %d", n)
}
m := s.Mail.(interface{ Last(string) *appmail.Message }).Last("a@example.com")
if m == nil || !strings.Contains(m.Body, "/settings/account") {
t.Errorf("mail %+v", m)
}
}