Files
supermarket/internal/web/auth.go
T
davidandClaude Opus 5.5 2b9d04297f 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>
2026-11-25 09:13:16 -07:00

322 lines
9.6 KiB
Go

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)
)
// 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
}
if !publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin") {
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
} else if !done {
s.setupUnfinished(w, r)
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 {
method, action, enctype := formAttrs(tag)
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
}
var v *viewer
if vv := viewerOf(r); !vv.Member.Admin() {
v = vv // forms they can't send are disabled
}
return rewriteForms(buf.Bytes(), csrfToken(r), r.URL.Path, v), nil
}