Files
supermarket/internal/web/auth.go
T
davidandClaude Opus 5.5 6d3eb18b5e Phase 14, parts 5 and 6: seats, and moving down to Free
Seats: inviting past the seats paid for offers the owner to add one
(Stripe prorates it); admins are told to ask the owner; Free has two.
Moving down: past the plan's seats, the owner and one other (the owner's
pick, or the first to join) edit and the rest read; storage is measured
hourly, and past the plan's, photo uploads and the SEO crawl stop.
Nothing is deleted. TEST.md section 18.

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

433 lines
13 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
Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS)
Viewing bool // a platform admin viewing a team, read-only
ReadOnly bool // the team's subscription has lapsed: nothing may change
// More people than the plan's seats, and not one kept: they read, and
// change nothing.
OverSeats bool
}
// 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 !s.multi() && (!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
}
if s.multi() && v.Session != nil && !publicPath(r.URL.Path) && !platformPath(r.URL.Path) {
// A platform admin outside any team: the platform's pages.
if v.Session.Team == 0 {
http.Redirect(w, r, "/platform", http.StatusSeeOther)
return
}
// A team that's suspended or being deleted is closed, but for
// switching teams, one's account, and the platform's admins.
if !v.Viewing && !strings.HasPrefix(r.URL.Path, "/teams/") {
if t, err := users.GetTeam(s.platform(), v.Session.Team); err == nil && t.Status != users.TeamActive {
s.teamClosed(w, r, t)
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
}
now := time.Now()
sess, u, err := users.Lookup(s.platform(), c.Value, now)
if err != nil {
return nil, err
}
pa := s.isPlatformAdmin(u)
if s.multi() && !sess.ViewUntil.IsZero() {
if pa && now.Before(sess.ViewUntil) {
return &viewer{User: u, Member: readOnly(sess.Team), Session: sess, Platform: true, Viewing: true}, nil
}
// Ran out: back to the platform.
if err := users.ViewAs(s.platform(), sess.ID, 0, time.Time{}, ""); err != nil {
return nil, err
}
sess.Team, sess.ViewUntil, sess.ViewReason = 0, time.Time{}, ""
}
if s.multi() && sess.Team == 0 {
if !pa {
return nil, users.ErrNoSession
}
return &viewer{User: u, Member: users.Membership{Team: 0, Role: users.Member}, Session: sess, Platform: true}, nil
}
m, err := users.MembershipOf(s.platform(), sess.Team, u.ID)
if errors.Is(err, users.ErrNotFound) {
return nil, users.ErrNoSession // no longer in the team
}
if err != nil {
return nil, err
}
v := &viewer{User: u, Member: m, Session: sess, Platform: pa}
if s.billingOn() {
if ts, err := s.forTeam(sess.Team); err == nil {
plan, ro := ts.teamPlan()
v.Member, v.ReadOnly = planned(m, plan, ro), ro
if kept, _ := ts.kept(); kept != nil && !kept[u.ID] {
v.Member, v.OverSeats = viewOnly(v.Member), true
}
}
}
return v, 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 {
team := s.team()
if s.multi() {
// The team they worked in last, else their first.
list, err := users.TeamsOf(s.platform(), u.ID)
if err != nil {
return err
}
team = 0
for _, t := range list {
if t.Status == users.TeamActive && (team == 0 || t.ID == lastTeam(s, u.ID)) {
team = t.ID
}
}
if team == 0 && !s.isPlatformAdmin(u) {
return errors.New("you aren't in any team that's open")
}
}
return s.startSessionIn(w, r, u, team, "password")
}
// startSessionIn signs a user in to a team, recording how (password, core).
func (s *Server) startSessionIn(w http.ResponseWriter, r *http.Request, u *users.User, team int64, via string) error {
token, sess, err := users.StartSessionIn(s.platform(), u.ID, team, clientIP(r), r.UserAgent(), time.Now())
if err != nil {
return err
}
if via != "password" {
if err := users.SetVia(s.platform(), sess.ID, via); err != nil {
return err
}
}
if err := users.SignedIn(s.platform(), u.ID, time.Now()); err != nil {
return err
}
s.setSessionCookie(w, token)
return nil
}
// lastTeam is the team a person's latest session worked in.
func lastTeam(s *Server, user int64) int64 {
var t int64
_ = s.platform().QueryRow(`SELECT team_id FROM sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1`, user).Scan(&t)
return t
}
// setSessionCookie gives the browser its session.
func (s *Server) setSessionCookie(w http.ResponseWriter, token string) {
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,
})
}
// 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" && !strings.HasPrefix(r.URL.Path, "/api/v1/") && r.URL.Path != "/billing/stripe" {
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
}
// teamServer is the Server for the request's team: the viewer's (the
// team their session works in), else this one.
func (s *Server) teamServer(r *http.Request) (*Server, error) {
if !s.multi() {
return s, nil
}
v := viewerOf(r)
if v.Session == nil {
return s, nil
}
return s.forTeam(v.Session.Team)
}
// team is the team this Server works for: 1 on the local and server
// editions.
func (s *Server) team() int64 {
if s.Team == 0 && !s.multi() {
return users.Team
}
return s.Team // 0: the multi-tenant edition's platform, no team's
}