feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders

- feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(cli): add check and audit commands
- feat(api): add api framework, login, page routes and account, user, delegation and audit handlers
- test(auth): cover passwords, sessions, rate limiter, authorization and audit builders
- test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal
- test(api): cover account, user, delegation and audit handlers and the authorization matrix
- test(ui): cover login, logout, page routes and the page authorization matrix
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 23bec143e3
commit 99fa5de747
28 files changed
+6591 -243

No files matched your search

+319
View File
@@ -5,16 +5,23 @@ package main
import (
"bytes"
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"html/template"
"io/fs"
"maps"
"net/http"
"net/url"
"path"
"slices"
"strconv"
"strings"
"github.com/gorilla/mux"
)
//go:embed templates/html
@@ -207,3 +214,315 @@ func (p *pageRenderer) staticHandler() http.Handler {
}
})
}
const (
loginFormLimit = 64 << 10
msgInvalidLogin = "invalid username or password"
msgTooManyLogins = "too many failed login attempts, try again later"
msgLoginUnavailable = "login is temporarily unavailable, try again later"
msgInvalidLoginForm = "the login form is invalid"
msgPageUnavailable = "service unavailable"
msgPageInternalError = "internal server error"
)
func validNextPath(next string) bool {
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.ContainsAny(next, "\\") {
return false
}
for _, r := range next {
if r < 0x20 || r == 0x7f {
return false
}
}
u, err := url.Parse(next)
return err == nil && u.Scheme == "" && u.Host == "" && u.User == nil
}
func safeNext(next string) string {
if validNextPath(next) {
return next
}
return "/"
}
func loginLocation(r *http.Request) string {
return "/login?next=" + url.QueryEscape(r.URL.RequestURI())
}
func (s *WebServer) basePageData() pageData {
return pageData{AppName: s.cfg.AppName}
}
func sessionPageData(base pageData, p principal) pageData {
base.Username, base.Role = p.User.Username, p.User.Role
return base
}
func (s *WebServer) renderPage(w http.ResponseWriter, status int, page string, data pageData) {
if s.pages == nil {
http.Error(w, msgPageInternalError, http.StatusInternalServerError)
return
}
s.pages.render(w, status, page, data)
}
func (s *WebServer) pageFailure(w http.ResponseWriter, r *http.Request, err error) {
s.log.ErrorContext(r.Context(), "page request failed", "path", r.URL.Path, "error", err)
if isDatabaseUnavailable(err) {
http.Error(w, msgPageUnavailable, http.StatusServiceUnavailable)
return
}
http.Error(w, msgPageInternalError, http.StatusInternalServerError)
}
func (s *WebServer) optionalPageData(r *http.Request) pageData {
data := s.basePageData()
if p, err := s.authenticate(r); err == nil {
data = sessionPageData(data, p)
}
return data
}
func (s *WebServer) handleNotFoundPage(w http.ResponseWriter, r *http.Request) {
s.renderPage(w, http.StatusNotFound, "not_found", s.optionalPageData(r))
}
func (s *WebServer) handleMethodNotAllowed(allow string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Allow", allow)
http.Error(w, msgMethodNotAllowed, http.StatusMethodNotAllowed)
}
}
func (s *WebServer) servePage(route pageRoute) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
p, err := s.authenticate(r)
if errors.Is(err, errNoSession) {
http.Redirect(w, r, loginLocation(r), http.StatusSeeOther)
return
}
if err != nil {
s.pageFailure(w, r, err)
return
}
data := sessionPageData(s.basePageData(), p)
if authorize(route.Access, &p, true) == accessForbidden {
s.log.WarnContext(ctx, "admin page refused", "path", r.URL.Path, "user", p.User.Username)
s.renderPage(w, http.StatusForbidden, "forbidden", data)
return
}
vars := mux.Vars(r)
if username, ok := vars["username"]; ok {
if !validUsernameSyntax(username) {
s.renderPage(w, http.StatusNotFound, "not_found", data)
return
}
data.TargetUser = username
}
if routeHasZone(route.Path) {
zone, err := normalizeZone(vars["zone"])
if err != nil {
s.renderPage(w, http.StatusNotFound, "not_found", data)
return
}
delegated := false
if needsDelegation(route.Access, p) {
if delegated, err = s.store.HasDelegation(ctx, zone, p.User.ID); err != nil {
s.pageFailure(w, r, err)
return
}
}
if authorize(route.Access, &p, delegated) == accessNotFound {
s.log.WarnContext(ctx, "zone not delegated", "path", r.URL.Path, "zone", zone, "user", p.User.Username)
s.renderPage(w, http.StatusNotFound, "not_found", data)
return
}
data.Zone = zone
}
s.renderPage(w, http.StatusOK, route.Page, data)
}
}
func (s *WebServer) renderLogin(w http.ResponseWriter, r *http.Request, status int, next, message string) {
data := s.basePageData()
data.Next = safeNext(next)
data.Error = message
if s.store != nil {
hasAdmin, err := s.store.HasActiveAdmin(r.Context())
if err != nil {
s.log.ErrorContext(r.Context(), "active admin lookup failed", "error", err)
}
data.NoActiveAdmin = err == nil && !hasAdmin
}
s.renderPage(w, status, "login", data)
}
func (s *WebServer) handleLoginPage(w http.ResponseWriter, r *http.Request) {
s.renderLogin(w, r, http.StatusOK, r.URL.Query().Get("next"), "")
}
func (s *WebServer) loginAttemptAudit(ctx context.Context, e auditEntry, status int, message string) error {
finishAuditEntry(&e, status, message)
if err := s.insertAudit(ctx, e); err != nil {
s.log.ErrorContext(ctx, "audit insert failed", "operation", e.Operation, "status", status, "error", err)
return err
}
return nil
}
func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
r.Body = http.MaxBytesReader(w, r.Body, loginFormLimit)
if err := r.ParseForm(); err != nil {
s.log.DebugContext(ctx, "invalid login form", "error", err)
s.renderLogin(w, r, http.StatusBadRequest, "", msgInvalidLoginForm)
return
}
username, password, next := r.PostForm.Get("username"), r.PostForm.Get("password"), safeNext(r.PostForm.Get("next"))
origin := clientOrigin(r, s.cfg.TrustedProxies)
actor := loginActor(username)
now := s.now().UTC()
if s.store == nil {
s.pageFailure(w, r, errDatabase)
return
}
var user *userRow
if validUsernameSyntax(username) {
u, err := s.store.UserByUsername(ctx, username)
switch {
case err == nil:
user = &u
case !errors.Is(err, errRowNotFound):
s.log.ErrorContext(ctx, "login user lookup failed", "error", err)
status, msg := failureStatus(err)
_ = s.loginAttemptAudit(ctx, loginAuditEntry(now, opLogin, username, nil, origin), status, msg)
s.renderLogin(w, r, status, next, msgLoginUnavailable)
return
}
}
entry := loginAuditEntry(now, opLogin, username, user, origin)
if !s.limiter.allow(actor, origin) {
s.log.WarnContext(ctx, "login rate limited", "actor", actor, "origin", origin)
if err := s.loginAttemptAudit(ctx, entry, http.StatusTooManyRequests, msgTooManyLogins); err != nil {
s.renderLogin(w, r, http.StatusInternalServerError, next, msgLoginUnavailable)
return
}
s.renderLogin(w, r, http.StatusTooManyRequests, next, msgTooManyLogins)
return
}
if !verifyLogin(s.verifyPassword, user, password) {
s.limiter.fail(actor, origin)
s.log.WarnContext(ctx, "login failed", "actor", actor, "origin", origin)
if err := s.loginAttemptAudit(ctx, entry, http.StatusUnauthorized, msgInvalidLogin); err != nil {
s.renderLogin(w, r, http.StatusInternalServerError, next, msgLoginUnavailable)
return
}
s.renderLogin(w, r, http.StatusUnauthorized, next, msgInvalidLogin)
return
}
token, hash, err := newSessionToken(s.random)
if err == nil {
err = s.store.InTx(ctx, func(tx webTx) error {
if old, ok := requestSessionToken(r); ok {
if _, err := tx.DeleteSession(ctx, sessionTokenHash(old)); err != nil {
return err
}
}
if err := tx.CreateSession(ctx, newSessionRow(hash, user.ID, now, s.cfg.SessionMaxAge, origin, r.UserAgent())); err != nil {
return err
}
if err := tx.TouchLastLogin(ctx, user.ID, now); err != nil {
return err
}
e := entry
finishAuditEntry(&e, http.StatusSeeOther, "")
_, err := tx.InsertAudit(ctx, e)
return err
})
}
if err != nil {
s.log.ErrorContext(ctx, "login failed with an internal error", "actor", actor, "error", err)
status, msg := failureStatus(err)
_ = s.loginAttemptAudit(ctx, entry, status, msg)
s.renderLogin(w, r, status, next, msgLoginUnavailable)
return
}
s.limiter.succeed(actor)
s.log.InfoContext(ctx, "change committed", "operation", opLogin, "actor", user.Username)
setRequestUser(r, principal{User: *user})
http.SetCookie(w, sessionCookie(token, s.cfg.CookieSecure))
http.Redirect(w, r, next, http.StatusSeeOther)
}
func (s *WebServer) handleLogout(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
p, err := s.authenticate(r)
if errors.Is(err, errNoSession) {
http.SetCookie(w, expiredSessionCookie(s.cfg.CookieSecure))
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if err != nil {
s.pageFailure(w, r, err)
return
}
entry := apiAuditEntry(s.now().UTC(), p, clientOrigin(r, s.cfg.TrustedProxies), opLogout, "")
err = s.store.InTx(ctx, func(tx webTx) error {
if _, err := tx.DeleteSession(ctx, p.TokenHash); err != nil {
return err
}
e := entry
finishAuditEntry(&e, http.StatusSeeOther, "")
_, err := tx.InsertAudit(ctx, e)
return err
})
if err != nil {
status, msg := failureStatus(err)
_ = s.loginAttemptAudit(ctx, entry, status, msg)
s.pageFailure(w, r, err)
return
}
s.log.InfoContext(ctx, "change committed", "operation", opLogout, "actor", p.User.Username)
http.SetCookie(w, expiredSessionCookie(s.cfg.CookieSecure))
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
func (s *WebServer) registerPageRoutes(r *mux.Router) {
special := map[string]http.HandlerFunc{
"GET /login": s.handleLoginPage,
"POST /login": s.handleLogin,
"POST /logout": s.handleLogout,
}
if s.pages != nil {
r.PathPrefix("/static/").Handler(s.pages.staticHandler())
}
byPath := map[string]map[string]http.HandlerFunc{}
var paths []string
for _, route := range pageRoutes {
h := special[route.Method+" "+route.Path]
if h == nil && route.Page != "" {
h = s.servePage(route)
}
if h == nil {
continue
}
if byPath[route.Path] == nil {
byPath[route.Path] = map[string]http.HandlerFunc{}
paths = append(paths, route.Path)
}
byPath[route.Path][route.Method] = h
}
for _, path := range paths {
methods := byPath[path]
notAllowed := s.handleMethodNotAllowed(strings.Join(slices.Sorted(maps.Keys(methods)), ", "))
r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
if h, ok := methods[req.Method]; ok {
h(w, req)
return
}
notAllowed(w, req)
})
}
r.NotFoundHandler = http.HandlerFunc(s.handleNotFoundPage)
}