Phase 10, part 1: users, sessions and form tokens

Schema 32 adds users, memberships and sessions, on both databases.
internal/users keeps accounts (Argon2id passwords), roles and modules,
and sessions whose rows hold only a hash of the cookie's value; they end
after a week unused or 30 days. On the server edition, every page but the
public ones needs a session and sends others to /signin. Every edition's
forms now carry a CSRF token (a cookie repeated in each form, added as
pages render; htmx sends it as a header), besides the same-origin check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 08:49:45 -07:00
co-authored by Claude Opus 5.5
parent d537fb367f
commit 96404a3580
21 changed files with 1475 additions and 21 deletions
+330
View File
@@ -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)<form\b[^>]*>`)
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(`<input type="hidden" name="` + csrfField + `" value="` + html.EscapeString(token) + `">`)
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
}
+229
View File
@@ -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, `<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)
// 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)
}
}
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 {
+2 -2
View File
@@ -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 ---
+1 -1
View File
@@ -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))
}
+20 -6
View File
@@ -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.
+14 -1
View File
@@ -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)
+3 -3
View File
@@ -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
}
}
+2 -2
View File
@@ -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.
+5
View File
@@ -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;
});
})();
+1
View File
@@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{.CSRF}}">
<meta name="htmx-config" content='{"includeIndicatorStyles": false}'>
<title>{{.Title}} · Supermarket</title>
<link rel="icon" href="/favicon.ico" sizes="any">
+1 -1
View File
@@ -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.