test(ui): avoid a literal em dash in the em dash check

- test(ui): avoid a literal em dash in the em dash check
- fix(cli): accept any positive int64 audit count and share the last active admin rule
- fix(api): limit audit before_id to 2^53-1
- fix(api): audit unmatched api requests, bound every request body and record audit write failures
- fix(ui): recheck the account in the login transaction and require existing zones on zone pages
- fix(api): recheck the acting admin and the stored password hash in change transactions
- fix(db): keep committed outcomes on lock release failure, narrow the records contract and trace sql statements
- fix(db): make the initial migration restartable and verify the application schema
- fix(auth): never move last_seen_at backwards on concurrent session touches
- test(api): cover lock release failure after commit and handler tracing without secrets
- fix(test): redact credentials from mysql setup errors
- fix(audit): retain addressed objects on admin refusals
- test(db): cover migration restarts and records contract ranges in mysql
- test(api): verify account races and audit rollback in mysql
- fix(auth): reject password changes after account deletion
- docs: document unknown api audit entries
- fix(audit): bound failure retries and redact sensitive sql parameters
- fix(test): isolate docker resources and cover image cli commands
- test(auth): expect unauthorized after an account deletion race
- fix(db): verify application column widths and foreign keys
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 5f17aab6ca
commit 53444bec7a
40 files changed
+2332 -254

No files matched your search

+166 -35
View File
@@ -19,10 +19,12 @@ import (
"net"
"net/http"
"net/netip"
"path"
"reflect"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
@@ -61,6 +63,8 @@ type apiContext struct {
Server *WebServer
auditDone bool
bodyLimit int64
bodyRead bool
body []byte
}
type apiResponse struct {
@@ -76,6 +80,7 @@ type apiError struct {
Message string
Fields map[string]string
Extra map[string]any
Header http.Header
}
func (e *apiError) Error() string { return e.Message }
@@ -181,13 +186,33 @@ func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status in
func (c *apiContext) writeChangeAuditWith(ctx context.Context, ins auditInserter, status int) error {
finishAuditEntry(c.Entry, status, "")
if _, err := ins.InsertAudit(ctx, *c.Entry); err != nil {
if err := insertAuditRow(ctx, ins, *c.Entry); err != nil {
return err
}
c.auditDone = true
return nil
}
type auditWriteError struct {
err error
}
func (e *auditWriteError) Error() string { return "audit write failed: " + e.err.Error() }
func (e *auditWriteError) Unwrap() error { return e.err }
func isAuditWriteError(err error) bool {
var auditErr *auditWriteError
return errors.As(err, &auditErr)
}
func insertAuditRow(ctx context.Context, ins auditInserter, e auditEntry) error {
if _, err := ins.InsertAudit(ctx, e); err != nil {
return &auditWriteError{err: err}
}
return nil
}
func isJSONContentType(ct string) bool {
mt, _, err := mime.ParseMediaType(ct)
return err == nil && mt == "application/json"
@@ -218,29 +243,55 @@ func jsonTypeMessage(e *json.UnmarshalTypeError) string {
return "has the wrong type"
}
func (c *apiContext) decodeJSON(dst any) error {
func requestHasBody(r *http.Request) bool {
return r.ContentLength != 0 || len(r.TransferEncoding) > 0
}
func (c *apiContext) readBody() error {
if c.bodyRead {
return nil
}
c.bodyRead = true
r := c.Request
if !requestHasBody(r) {
return nil
}
limit := c.bodyLimit
if limit <= 0 {
limit = defaultBodyLimit
}
body, err := io.ReadAll(io.LimitReader(c.Request.Body, limit+1))
if !isJSONContentType(r.Header.Get("Content-Type")) {
return &apiError{Status: http.StatusUnsupportedMediaType, Message: "content type must be application/json"}
}
if r.ContentLength > limit {
return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"}
}
body, err := io.ReadAll(io.LimitReader(r.Body, limit+1))
if err != nil {
return &apiError{Status: http.StatusBadRequest, Message: "cannot read the request body"}
}
trimmed := bytes.TrimLeft(body, " \t\r\n")
if len(trimmed) == 0 {
return &apiError{Status: http.StatusBadRequest, Message: "request body is required"}
}
if !isJSONContentType(c.Request.Header.Get("Content-Type")) {
return &apiError{Status: http.StatusUnsupportedMediaType, Message: "content type must be application/json"}
}
if int64(len(body)) > limit {
return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"}
}
if !utf8.Valid(body) {
return &apiError{Status: http.StatusBadRequest, Message: "request body must be valid UTF-8"}
}
c.body = body
return nil
}
func (c *apiContext) decodeJSON(dst any) error {
if err := c.readBody(); err != nil {
return err
}
trimmed := bytes.TrimLeft(c.body, " \t\r\n")
if len(trimmed) == 0 {
return &apiError{Status: http.StatusBadRequest, Message: "request body is required"}
}
if trimmed[0] != '{' {
return &apiError{Status: http.StatusBadRequest, Message: "request body must be a JSON object"}
}
dec := json.NewDecoder(bytes.NewReader(body))
dec := json.NewDecoder(bytes.NewReader(c.body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
var te *json.UnmarshalTypeError
@@ -258,19 +309,6 @@ func (c *apiContext) decodeJSON(dst any) error {
return nil
}
func precheckBody(r *http.Request, limit int64) error {
if r.ContentLength <= 0 {
return nil
}
if !isJSONContentType(r.Header.Get("Content-Type")) {
return &apiError{Status: http.StatusUnsupportedMediaType, Message: "content type must be application/json"}
}
if r.ContentLength > limit {
return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"}
}
return nil
}
func parseForwardedAddr(s string) (netip.Addr, error) {
s = strings.TrimSpace(s)
if ap, err := netip.ParseAddrPort(s); err == nil {
@@ -353,7 +391,8 @@ func requestLogMiddleware(s *WebServer, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
info := &requestInfo{}
r = r.WithContext(context.WithValue(r.Context(), requestInfoKey{}, info))
ctx := withTraceLogger(r.Context(), s.log)
r = r.WithContext(context.WithValue(ctx, requestInfoKey{}, info))
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
level := slog.LevelInfo
@@ -447,6 +486,9 @@ func (s *WebServer) authenticate(r *http.Request) (principal, error) {
}
func failureStatus(err error) (int, string) {
if isAuditWriteError(err) {
return http.StatusInternalServerError, msgInternalError
}
if isDatabaseUnavailable(err) {
return http.StatusServiceUnavailable, msgDatabaseDown
}
@@ -509,9 +551,8 @@ func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler {
s.log.Error("API route has no handler", "operation", op)
}
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
writeJSONError(w, http.StatusNotFound, msgNotFound)
})
r.SkipClean(true)
r.NotFoundHandler = s.serveUnknownAPI(http.StatusNotFound, "")
byPath := map[string]map[string]apiRoute{}
var paths []string
for _, route := range apiRoutes {
@@ -533,21 +574,32 @@ func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler {
}
served[method] = s.serveAPI(route, h)
}
notAllowed := s.serveUnknownAPI(http.StatusMethodNotAllowed, allow)
r.HandleFunc(apiPrefix+path, func(w http.ResponseWriter, req *http.Request) {
if h, ok := served[req.Method]; ok {
h(w, req)
return
}
w.Header().Set("Allow", allow)
writeJSONError(w, http.StatusMethodNotAllowed, msgMethodNotAllowed)
notAllowed(w, req)
})
}
return r
}
func (s *WebServer) serveUnknownAPI(status int, allow string) http.HandlerFunc {
route := apiRoute{Operation: opAPIUnknown, Access: accessSession}
return s.serveAPI(route, func(ctx context.Context, c *apiContext) (apiResponse, error) {
if status == http.StatusMethodNotAllowed {
return apiResponse{}, &apiError{Status: status, Message: msgMethodNotAllowed, Header: http.Header{"Allow": {allow}}}
}
return apiResponse{}, &apiError{Status: http.StatusNotFound, Message: msgNotFound}
})
}
func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
defer traceFunc(ctx, s.log, "api."+route.Operation)()
p, err := s.authenticate(r)
if err != nil {
if errors.Is(err, errNoSession) {
@@ -563,12 +615,16 @@ func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc {
entry := apiAuditEntry(now, p, clientOrigin(r, s.cfg.TrustedProxies), route.Operation, "")
c := &apiContext{Request: r, Principal: p, Vars: mux.Vars(r), Now: now, Entry: &entry, Server: s, bodyLimit: route.BodyLimit}
resp, err := s.authorizeAPI(ctx, c, route)
if err == nil {
err = precheckBody(r, route.BodyLimit)
if err == nil && route.BodyLimit > 0 {
err = c.readBody()
}
if err == nil {
resp, err = h(ctx, c)
}
var refusal *apiError
if route.Access == accessAdmin && errors.As(err, &refusal) && refusal.Status == http.StatusForbidden {
s.recordAddressedObjects(ctx, c, route)
}
s.finishAPI(ctx, w, c, resp, err)
}
}
@@ -601,6 +657,32 @@ func (s *WebServer) authorizeAPI(ctx context.Context, c *apiContext, route apiRo
return apiResponse{}, nil
}
func (s *WebServer) recordAddressedObjects(ctx context.Context, c *apiContext, route apiRoute) {
rawZone := c.Vars["zone"]
if route.Operation == opZoneCreate && c.readBody() == nil {
var request struct {
Name string `json:"name"`
}
if json.Unmarshal(c.body, &request) == nil {
rawZone = request.Name
}
}
if zone, err := normalizeZone(rawZone); err == nil {
c.Entry.Zone = sql.NullString{String: zone, Valid: true}
}
username, ok := c.Vars["username"]
if c.Entry.TargetUserID.Valid || !ok || !validUsernameSyntax(username) {
return
}
u, err := s.store.UserByUsername(ctx, username)
switch {
case err == nil:
c.Entry.TargetUserID = sql.NullInt64{Int64: u.ID, Valid: true}
case !errors.Is(err, errRowNotFound):
s.log.ErrorContext(ctx, "target user lookup failed", "operation", c.Entry.Operation, "error", err)
}
}
func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error) (apiResponse, string) {
var ae *apiError
switch {
@@ -619,7 +701,7 @@ func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error)
default:
s.log.DebugContext(ctx, "request failed", "operation", c.Entry.Operation, "status", ae.Status, "error", ae.Message)
}
return apiResponse{Status: ae.Status, Body: body}, ae.Message
return apiResponse{Status: ae.Status, Body: body, Header: ae.Header}, ae.Message
case errors.Is(err, errLockTimeout):
s.log.WarnContext(ctx, "zone lock timeout", "operation", c.Entry.Operation, "zone", c.Zone)
return apiResponse{Status: http.StatusServiceUnavailable, Body: map[string]any{"error": msgZoneBusy}}, msgZoneBusy
@@ -666,6 +748,24 @@ func (s *WebServer) insertAudit(ctx context.Context, e auditEntry) error {
return err
}
func (s *WebServer) recordAudit(ctx context.Context, e auditEntry) bool {
err := s.insertAudit(ctx, e)
if err == nil {
return true
}
s.log.ErrorContext(ctx, "audit insert failed", "operation", e.Operation, "status", e.Status.Int64, "error", err)
s.recordInternalAudit(ctx, e)
return false
}
func (s *WebServer) recordInternalAudit(ctx context.Context, e auditEntry) {
e.Before, e.After = nil, nil
finishAuditEntry(&e, http.StatusInternalServerError, msgInternalError)
if err := s.insertAudit(ctx, e); err != nil {
s.log.ErrorContext(ctx, "audit insert of the internal error failed", "operation", e.Operation, "error", err)
}
}
func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *apiContext, resp apiResponse, err error) {
message := ""
if err != nil {
@@ -680,11 +780,13 @@ func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *api
if c.auditDone {
s.log.InfoContext(ctx, "change committed", "operation", c.Entry.Operation, "zone", c.Entry.Zone.String,
"record_id", c.Entry.RecordID.Int64, "target_user_id", c.Entry.TargetUserID.Int64, "actor", c.Entry.Actor)
} else if isAuditWriteError(err) {
s.recordInternalAudit(ctx, *c.Entry)
out = internalErrorResponse()
} else {
c.Entry.Before, c.Entry.After = nil, nil
finishAuditEntry(c.Entry, out.status, message)
if aerr := s.insertAudit(ctx, *c.Entry); aerr != nil {
s.log.ErrorContext(ctx, "audit insert failed", "operation", c.Entry.Operation, "status", out.status, "error", aerr)
if !s.recordAudit(ctx, *c.Entry) {
out = internalErrorResponse()
}
}
@@ -702,6 +804,35 @@ func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *api
}
}
func cleanPagePath(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !isAPIPath(r.URL.Path) {
if p := cleanURLPath(r.URL.Path); p != r.URL.Path {
u := *r.URL
u.Path = p
w.Header().Set("Location", u.String())
w.WriteHeader(http.StatusMovedPermanently)
return
}
}
next.ServeHTTP(w, r)
})
}
func cleanURLPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
func registerAppRoutes(s *WebServer, r *mux.Router) {
r.PathPrefix("/api/").Handler(s.apiRouter(s.apiHandlers()))
s.registerPageRoutes(r)