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:
1 parent
23bec143e3
commit
99fa5de747
28 files changed
+6591
-243
No files matched your search
+699
@@ -0,0 +1,699 @@
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
// Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
const (
|
||||
contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
|
||||
auditInsertTimeout = 5 * time.Second
|
||||
msgAuthRequired = "authentication required"
|
||||
msgAdminRequired = "admin role required"
|
||||
msgZoneNotFound = "zone not found"
|
||||
msgUserNotFound = "user not found"
|
||||
msgInternalError = "internal error"
|
||||
msgDatabaseDown = "database unavailable"
|
||||
msgZoneBusy = "zone busy"
|
||||
msgNotFound = "not found"
|
||||
msgMethodNotAllowed = "method not allowed"
|
||||
msgCrossOrigin = "cross-origin request refused"
|
||||
msgNotImplemented = "not implemented"
|
||||
)
|
||||
|
||||
type principal struct {
|
||||
User userRow
|
||||
TokenHash []byte
|
||||
}
|
||||
|
||||
func (p principal) isAdmin() bool { return p.User.Role == "admin" }
|
||||
|
||||
type apiContext struct {
|
||||
Request *http.Request
|
||||
Principal principal
|
||||
Zone string
|
||||
Vars map[string]string
|
||||
Now time.Time
|
||||
Entry *auditEntry
|
||||
Server *WebServer
|
||||
auditDone bool
|
||||
bodyLimit int64
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
Status int
|
||||
Body any
|
||||
Raw []byte
|
||||
ContentType string
|
||||
Header http.Header
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Status int
|
||||
Message string
|
||||
Fields map[string]string
|
||||
Extra map[string]any
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.Message }
|
||||
|
||||
type apiHandler func(ctx context.Context, c *apiContext) (apiResponse, error)
|
||||
|
||||
func errZoneNotFound() *apiError {
|
||||
return &apiError{Status: http.StatusNotFound, Message: msgZoneNotFound}
|
||||
}
|
||||
|
||||
func errUserNotFound() *apiError {
|
||||
return &apiError{Status: http.StatusNotFound, Message: msgUserNotFound}
|
||||
}
|
||||
|
||||
func fieldError(field, message string) *apiError {
|
||||
return &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid " + field, Fields: map[string]string{field: message}}
|
||||
}
|
||||
|
||||
type auditInserter interface {
|
||||
InsertAudit(ctx context.Context, e auditEntry) (int64, error)
|
||||
}
|
||||
|
||||
type webTx interface {
|
||||
auditInserter
|
||||
CreateSession(ctx context.Context, row sessionRow) error
|
||||
DeleteSession(ctx context.Context, tokenHash []byte) (bool, error)
|
||||
DeleteUserSessions(ctx context.Context, userID int64) (int64, error)
|
||||
DeleteUserSessionsExcept(ctx context.Context, userID int64, keepTokenHash []byte) (int64, error)
|
||||
TouchLastLogin(ctx context.Context, id int64, now time.Time) error
|
||||
CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error)
|
||||
UserByIDForUpdate(ctx context.Context, id int64) (userRow, error)
|
||||
UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error)
|
||||
LockActiveAdmins(ctx context.Context) ([]userRow, error)
|
||||
SetRole(ctx context.Context, id int64, role string, now time.Time) error
|
||||
SetPassword(ctx context.Context, id int64, passwordHash string, now time.Time) error
|
||||
MarkDeleted(ctx context.Context, id int64, now time.Time) error
|
||||
ZoneExists(ctx context.Context, zone string) (bool, error)
|
||||
GrantDelegation(ctx context.Context, zone string, userID, createdBy int64, now time.Time) (bool, error)
|
||||
RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error)
|
||||
}
|
||||
|
||||
type webStore interface {
|
||||
auditInserter
|
||||
SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error)
|
||||
TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error
|
||||
UserByUsername(ctx context.Context, username string) (userRow, error)
|
||||
HasActiveAdmin(ctx context.Context) (bool, error)
|
||||
HasDelegation(ctx context.Context, zone string, userID int64) (bool, error)
|
||||
ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error)
|
||||
UserZones(ctx context.Context, userID int64) ([]userZone, error)
|
||||
ZoneUsers(ctx context.Context, zone string) ([]userRow, error)
|
||||
ZoneExists(ctx context.Context, zone string) (bool, error)
|
||||
ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error)
|
||||
InTx(ctx context.Context, fn func(tx webTx) error) error
|
||||
}
|
||||
|
||||
type sqlWebTx struct {
|
||||
userStore
|
||||
sessionStore
|
||||
delegationStore
|
||||
auditStore
|
||||
recordStore
|
||||
}
|
||||
|
||||
func newSQLWebTx(q dbtx, t tableNames) sqlWebTx {
|
||||
return sqlWebTx{
|
||||
userStore: newUserStore(q, t),
|
||||
sessionStore: newSessionStore(q, t),
|
||||
delegationStore: newDelegationStore(q, t),
|
||||
auditStore: newAuditStore(q, t),
|
||||
recordStore: newRecordStore(q, t),
|
||||
}
|
||||
}
|
||||
|
||||
type sqlWebStore struct {
|
||||
sqlWebTx
|
||||
db *sql.DB
|
||||
tables tableNames
|
||||
}
|
||||
|
||||
func newSQLWebStore(db *sql.DB, t tableNames) *sqlWebStore {
|
||||
return &sqlWebStore{sqlWebTx: newSQLWebTx(db, t), db: db, tables: t}
|
||||
}
|
||||
|
||||
func (s *sqlWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error {
|
||||
return runInTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
return fn(newSQLWebTx(tx, s.tables))
|
||||
})
|
||||
}
|
||||
|
||||
func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status int) error {
|
||||
return c.writeChangeAuditWith(ctx, newAuditStore(tx, c.Server.tables), status)
|
||||
}
|
||||
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
c.auditDone = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func isJSONContentType(ct string) bool {
|
||||
mt, _, err := mime.ParseMediaType(ct)
|
||||
return err == nil && mt == "application/json"
|
||||
}
|
||||
|
||||
func jsonTypeMessage(e *json.UnmarshalTypeError) string {
|
||||
if e.Type == nil {
|
||||
return "has the wrong type"
|
||||
}
|
||||
switch e.Type.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
if strings.HasPrefix(e.Value, "number") {
|
||||
return "must be an integer in range"
|
||||
}
|
||||
return "must be a number"
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return "must be a number"
|
||||
case reflect.String:
|
||||
return "must be a string"
|
||||
case reflect.Bool:
|
||||
return "must be a boolean"
|
||||
case reflect.Slice, reflect.Array:
|
||||
return "must be an array"
|
||||
case reflect.Map, reflect.Struct:
|
||||
return "must be an object"
|
||||
}
|
||||
return "has the wrong type"
|
||||
}
|
||||
|
||||
func (c *apiContext) decodeJSON(dst any) error {
|
||||
limit := c.bodyLimit
|
||||
if limit <= 0 {
|
||||
limit = defaultBodyLimit
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.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 trimmed[0] != '{' {
|
||||
return &apiError{Status: http.StatusBadRequest, Message: "request body must be a JSON object"}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
var te *json.UnmarshalTypeError
|
||||
if errors.As(err, &te) && te.Field != "" {
|
||||
return &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid field type", Fields: map[string]string{te.Field: jsonTypeMessage(te)}}
|
||||
}
|
||||
if strings.HasPrefix(err.Error(), "json: unknown field") {
|
||||
return &apiError{Status: http.StatusBadRequest, Message: "request body has an unknown field"}
|
||||
}
|
||||
return &apiError{Status: http.StatusBadRequest, Message: "malformed JSON"}
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return &apiError{Status: http.StatusBadRequest, Message: "request body has trailing data"}
|
||||
}
|
||||
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 {
|
||||
return ap.Addr(), nil
|
||||
}
|
||||
return netip.ParseAddr(strings.TrimSuffix(strings.TrimPrefix(s, "["), "]"))
|
||||
}
|
||||
|
||||
func clientOrigin(r *http.Request, trusted []netip.Prefix) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
peer, err := netip.ParseAddr(host)
|
||||
if err != nil {
|
||||
return printableText(host, auditMaxOriginRunes)
|
||||
}
|
||||
origin := peer.Unmap().WithZone("")
|
||||
if !addrTrusted(origin, trusted) {
|
||||
return origin.String()
|
||||
}
|
||||
var hops []string
|
||||
for _, v := range r.Header.Values("X-Forwarded-For") {
|
||||
hops = append(hops, strings.Split(v, ",")...)
|
||||
}
|
||||
for i := len(hops) - 1; i >= 0; i-- {
|
||||
hop, err := parseForwardedAddr(hops[i])
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
origin = hop.Unmap().WithZone("")
|
||||
if !addrTrusted(origin, trusted) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return origin.String()
|
||||
}
|
||||
|
||||
func addrTrusted(addr netip.Addr, trusted []netip.Prefix) bool {
|
||||
for _, p := range trusted {
|
||||
if p.Contains(addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type requestInfoKey struct{}
|
||||
|
||||
type requestInfo struct {
|
||||
user string
|
||||
role string
|
||||
}
|
||||
|
||||
func setRequestUser(r *http.Request, p principal) {
|
||||
if info, ok := r.Context().Value(requestInfoKey{}).(*requestInfo); ok {
|
||||
info.user, info.role = p.User.Username, p.User.Role
|
||||
}
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusRecorder) Unwrap() http.ResponseWriter {
|
||||
return s.ResponseWriter
|
||||
}
|
||||
|
||||
func quietPath(path string) bool {
|
||||
return path == "/health" || strings.HasPrefix(path, "/static/")
|
||||
}
|
||||
|
||||
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))
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
level := slog.LevelInfo
|
||||
if quietPath(r.URL.Path) {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
s.log.Log(r.Context(), level, "request", "method", r.Method, "path", r.URL.Path, "status", rec.status,
|
||||
"duration", time.Since(start), "user", info.user, "role", info.role, "origin", clientOrigin(r, s.cfg.TrustedProxies))
|
||||
})
|
||||
}
|
||||
|
||||
func securityHeadersMiddleware(s *WebServer, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", contentSecurityPolicy)
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func isAPIPath(path string) bool {
|
||||
return path == "/api" || strings.HasPrefix(path, "/api/")
|
||||
}
|
||||
|
||||
func crossOriginMiddleware(s *WebServer, next http.Handler) http.Handler {
|
||||
cop := http.NewCrossOriginProtection()
|
||||
cop.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
s.log.WarnContext(r.Context(), "cross-origin request refused", "method", r.Method, "path", r.URL.Path,
|
||||
"origin", clientOrigin(r, s.cfg.TrustedProxies))
|
||||
if isAPIPath(r.URL.Path) {
|
||||
writeJSONError(w, http.StatusForbidden, msgCrossOrigin)
|
||||
return
|
||||
}
|
||||
http.Error(w, msgCrossOrigin, http.StatusForbidden)
|
||||
}))
|
||||
return cop.Handler(next)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body []byte) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func errorBody(message string) []byte {
|
||||
b, _ := json.Marshal(map[string]string{"error": message})
|
||||
return b
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, errorBody(message))
|
||||
}
|
||||
|
||||
func isDatabaseUnavailable(err error) bool {
|
||||
var ne net.Error
|
||||
return errors.Is(err, errDatabase) || errors.Is(err, driver.ErrBadConn) || errors.Is(err, mysql.ErrInvalidConn) ||
|
||||
errors.Is(err, sql.ErrConnDone) || errors.As(err, &ne)
|
||||
}
|
||||
|
||||
func (s *WebServer) authenticate(r *http.Request) (principal, error) {
|
||||
token, ok := requestSessionToken(r)
|
||||
if !ok {
|
||||
return principal{}, errNoSession
|
||||
}
|
||||
if s.store == nil {
|
||||
return principal{}, errDatabase
|
||||
}
|
||||
ctx := r.Context()
|
||||
hash := sessionTokenHash(token)
|
||||
sw, err := s.store.SessionByTokenHash(ctx, hash)
|
||||
if errors.Is(err, errRowNotFound) {
|
||||
return principal{}, errNoSession
|
||||
}
|
||||
if err != nil {
|
||||
return principal{}, err
|
||||
}
|
||||
now := s.now()
|
||||
if !sessionValid(sw.Session, sw.User, now, s.cfg.SessionIdleTimeout, s.cfg.SessionMaxAge) {
|
||||
return principal{}, errNoSession
|
||||
}
|
||||
if sessionTouchDue(sw.Session, now) {
|
||||
if err := s.store.TouchSession(ctx, hash, now); err != nil {
|
||||
s.log.ErrorContext(ctx, "session touch failed", "error", err)
|
||||
}
|
||||
}
|
||||
p := principal{User: sw.User, TokenHash: hash}
|
||||
setRequestUser(r, p)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func failureStatus(err error) (int, string) {
|
||||
if isDatabaseUnavailable(err) {
|
||||
return http.StatusServiceUnavailable, msgDatabaseDown
|
||||
}
|
||||
return http.StatusInternalServerError, msgInternalError
|
||||
}
|
||||
|
||||
func (s *WebServer) apiHandlers() map[string]apiHandler {
|
||||
if s.apiHandlerSet != nil {
|
||||
return s.apiHandlerSet
|
||||
}
|
||||
handlers, duplicates := mergeAPIHandlers(frameworkAPIHandlers(s), zoneAPIHandlers(s))
|
||||
for _, op := range duplicates {
|
||||
s.log.Error("API operation has two handlers", "operation", op)
|
||||
}
|
||||
return handlers
|
||||
}
|
||||
|
||||
func mergeAPIHandlers(sets ...map[string]apiHandler) (map[string]apiHandler, []string) {
|
||||
merged := map[string]apiHandler{}
|
||||
var duplicates []string
|
||||
for _, set := range sets {
|
||||
for _, op := range slices.Sorted(maps.Keys(set)) {
|
||||
if _, dup := merged[op]; dup {
|
||||
duplicates = append(duplicates, op)
|
||||
continue
|
||||
}
|
||||
merged[op] = set[op]
|
||||
}
|
||||
}
|
||||
return merged, duplicates
|
||||
}
|
||||
|
||||
func missingAPIHandlers(handlers map[string]apiHandler) []string {
|
||||
var missing []string
|
||||
for _, route := range apiRoutes {
|
||||
if handlers[route.Operation] == nil {
|
||||
missing = append(missing, route.Operation)
|
||||
}
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
func (s *WebServer) checkAPIHandlers() error {
|
||||
if missing := missingAPIHandlers(s.apiHandlers()); len(missing) > 0 {
|
||||
return fmt.Errorf("API operations without a handler: %s", strings.Join(missing, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func notImplementedHandler(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
return apiResponse{}, &apiError{Status: http.StatusNotImplemented, Message: msgNotImplemented}
|
||||
}
|
||||
|
||||
func routeVariables(path string) int {
|
||||
return strings.Count(path, "{")
|
||||
}
|
||||
|
||||
func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler {
|
||||
for _, op := range missingAPIHandlers(handlers) {
|
||||
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)
|
||||
})
|
||||
byPath := map[string]map[string]apiRoute{}
|
||||
var paths []string
|
||||
for _, route := range apiRoutes {
|
||||
if byPath[route.Path] == nil {
|
||||
byPath[route.Path] = map[string]apiRoute{}
|
||||
paths = append(paths, route.Path)
|
||||
}
|
||||
byPath[route.Path][route.Method] = route
|
||||
}
|
||||
slices.SortStableFunc(paths, func(a, b string) int { return cmp.Compare(routeVariables(a), routeVariables(b)) })
|
||||
for _, path := range paths {
|
||||
methods := byPath[path]
|
||||
allow := strings.Join(slices.Sorted(maps.Keys(methods)), ", ")
|
||||
served := map[string]http.HandlerFunc{}
|
||||
for method, route := range methods {
|
||||
h := handlers[route.Operation]
|
||||
if h == nil {
|
||||
h = notImplementedHandler
|
||||
}
|
||||
served[method] = s.serveAPI(route, h)
|
||||
}
|
||||
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)
|
||||
})
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
p, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, errNoSession) {
|
||||
writeJSONError(w, http.StatusUnauthorized, msgAuthRequired)
|
||||
return
|
||||
}
|
||||
s.log.ErrorContext(ctx, "session lookup failed", "error", err)
|
||||
status, msg := failureStatus(err)
|
||||
writeJSONError(w, status, msg)
|
||||
return
|
||||
}
|
||||
now := s.now().UTC()
|
||||
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 {
|
||||
resp, err = h(ctx, c)
|
||||
}
|
||||
s.finishAPI(ctx, w, c, resp, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WebServer) authorizeAPI(ctx context.Context, c *apiContext, route apiRoute) (apiResponse, error) {
|
||||
if authorize(route.Access, &c.Principal, true) == accessForbidden {
|
||||
s.log.WarnContext(ctx, "admin route refused", "operation", route.Operation, "user", c.Principal.User.Username)
|
||||
return apiResponse{}, &apiError{Status: http.StatusForbidden, Message: msgAdminRequired}
|
||||
}
|
||||
if !routeHasZone(route.Path) {
|
||||
return apiResponse{}, nil
|
||||
}
|
||||
zone, err := normalizeZone(c.Vars["zone"])
|
||||
if err != nil {
|
||||
return apiResponse{}, errZoneNotFound()
|
||||
}
|
||||
c.Zone = zone
|
||||
c.Entry.Zone = sql.NullString{String: zone, Valid: true}
|
||||
if !needsDelegation(route.Access, c.Principal) {
|
||||
return apiResponse{}, nil
|
||||
}
|
||||
delegated, err := s.store.HasDelegation(ctx, zone, c.Principal.User.ID)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if authorize(route.Access, &c.Principal, delegated) == accessNotFound {
|
||||
s.log.WarnContext(ctx, "zone not delegated", "operation", route.Operation, "zone", zone, "user", c.Principal.User.Username)
|
||||
return apiResponse{}, errZoneNotFound()
|
||||
}
|
||||
return apiResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error) (apiResponse, string) {
|
||||
var ae *apiError
|
||||
switch {
|
||||
case errors.As(err, &ae):
|
||||
body := map[string]any{}
|
||||
for k, v := range ae.Extra {
|
||||
body[k] = v
|
||||
}
|
||||
body["error"] = ae.Message
|
||||
if ae.Fields != nil {
|
||||
body["fields"] = ae.Fields
|
||||
}
|
||||
switch ae.Status {
|
||||
case http.StatusForbidden, http.StatusConflict, http.StatusPreconditionFailed, http.StatusTooManyRequests:
|
||||
s.log.WarnContext(ctx, "request refused", "operation", c.Entry.Operation, "status", ae.Status, "error", ae.Message)
|
||||
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
|
||||
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
|
||||
}
|
||||
s.log.ErrorContext(ctx, "request failed", "operation", c.Entry.Operation, "error", err)
|
||||
status, msg := failureStatus(err)
|
||||
return apiResponse{Status: status, Body: map[string]any{"error": msg}}, msg
|
||||
}
|
||||
|
||||
type preparedResponse struct {
|
||||
status int
|
||||
contentType string
|
||||
header http.Header
|
||||
body []byte
|
||||
}
|
||||
|
||||
func prepareResponse(resp apiResponse) (preparedResponse, error) {
|
||||
p := preparedResponse{status: cmp.Or(resp.Status, http.StatusOK), header: resp.Header}
|
||||
switch {
|
||||
case p.status == http.StatusNoContent:
|
||||
case resp.Raw != nil:
|
||||
p.contentType, p.body = resp.ContentType, resp.Raw
|
||||
default:
|
||||
b, err := json.Marshal(resp.Body)
|
||||
if err != nil {
|
||||
return preparedResponse{}, err
|
||||
}
|
||||
p.contentType, p.body = "application/json", b
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func internalErrorResponse() preparedResponse {
|
||||
return preparedResponse{status: http.StatusInternalServerError, contentType: "application/json", body: errorBody(msgInternalError)}
|
||||
}
|
||||
|
||||
func (s *WebServer) insertAudit(ctx context.Context, e auditEntry) error {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), auditInsertTimeout)
|
||||
defer cancel()
|
||||
if s.store == nil {
|
||||
return errDatabase
|
||||
}
|
||||
_, err := s.store.InsertAudit(ctx, e)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *apiContext, resp apiResponse, err error) {
|
||||
message := ""
|
||||
if err != nil {
|
||||
resp, message = s.errorResponse(ctx, c, err)
|
||||
c.auditDone = false
|
||||
}
|
||||
out, perr := prepareResponse(resp)
|
||||
if perr != nil {
|
||||
s.log.ErrorContext(ctx, "encode response failed", "operation", c.Entry.Operation, "error", perr)
|
||||
out, message, c.auditDone = internalErrorResponse(), msgInternalError, false
|
||||
}
|
||||
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 {
|
||||
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)
|
||||
out = internalErrorResponse()
|
||||
}
|
||||
}
|
||||
for k, vs := range out.header {
|
||||
for _, v := range vs {
|
||||
w.Header().Add(k, v)
|
||||
}
|
||||
}
|
||||
if out.contentType != "" {
|
||||
w.Header().Set("Content-Type", out.contentType)
|
||||
}
|
||||
w.WriteHeader(out.status)
|
||||
if out.body != nil {
|
||||
_, _ = w.Write(out.body)
|
||||
}
|
||||
}
|
||||
|
||||
func registerAppRoutes(s *WebServer, r *mux.Router) {
|
||||
r.PathPrefix("/api/").Handler(s.apiRouter(s.apiHandlers()))
|
||||
s.registerPageRoutes(r)
|
||||
}
|
||||
Reference in new issue
Block a user