sonda/internal/api/http/middleware.go
tgiachi 2ae4aedac0 fix(api): make the spec say what the code does, and make the tests prove it
- fix(spec): album.artist and track.album are real nullable objects (OpenAPI
  3.0 only honours nullable next to a type); the stream documents 304 on HEAD,
  412, If-Unmodified-Since and multipart/byteranges answers
- fix(spec): passwords and idempotency keys are measured in bytes, an overlap
  between libraries is a 400, a library PATCH needs a name or a path, limit 0
  means the default, login has no format rules of its own, and the wording about
  signing out says that issued access tokens live until they expire
- fix(auth): the Bearer scheme is matched ignoring case (RFC 7235)
- fix(listening): a listen with the access token of a deleted account is a 401
  instead of a database error
- fix(docs): the docs pages answer HEAD and carry X-Frame-Options, a CSP
  frame-ancestors, nosniff and no-referrer, since people paste their token there
- test: error codes are asserted in every error case; every accepted request is
  validated against the spec too; HEAD and 3xx answers are checked by hand
  because the validator skips them; the stream Content-Type must be one the
  spec lists; a scan held mid-way proves the scan_running conflicts; null album
  and null album artist, a vanished file, multi-range, 412 and HEAD 304 are
  exercised. Verified by breaking the code and the spec on purpose
2026-11-11 14:46:28 +01:00

114 lines
3.4 KiB
Go

package httpapi
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"codeberg.org/squidd/sonda/internal/auth"
)
const (
ctxUserID = "user_id"
ctxUsername = "username"
)
// limitBody caps the request body size.
func limitBody(max int64) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, max)
c.Next()
}
}
// requestLog logs one line per request. It never logs headers, query strings
// or bodies, so tokens and passwords cannot leak into the log.
func requestLog(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
fields := []zap.Field{
zap.String("method", c.Request.Method),
zap.String("path", c.Request.URL.Path),
zap.Int("status", c.Writer.Status()),
zap.Duration("latency", time.Since(start)),
}
if last := c.Errors.Last(); last != nil {
// Internal errors are hidden from the client; keep them in the log.
fields = append(fields, zap.String("error", last.Error()))
}
logger.Info("http request", fields...)
}
}
// currentUserID returns the authenticated user's id (set by requireAuth).
func currentUserID(c *gin.Context) int64 {
v, _ := c.Get(ctxUserID)
id, _ := v.(int64)
return id
}
// userLookup finds an account by id.
type userLookup interface {
User(ctx context.Context, id int64) (auth.User, error)
}
// requireAdmin runs after requireAuth. It reads the role from the database on
// every call, so a demoted or deleted admin loses access immediately instead
// of when the access token expires.
func requireAdmin(users userLookup) gin.HandlerFunc {
return func(c *gin.Context) {
user, err := users.User(c.Request.Context(), currentUserID(c))
switch {
case errors.Is(err, auth.ErrUserNotFound):
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
case !user.IsAdmin:
writeError(c, http.StatusForbidden, "admin_required", "this action needs an admin account")
default:
c.Next()
}
}
}
// requireAuth checks the access token. It reads "Authorization: Bearer <jwt>";
// when allowQuery is true and the header is absent it also accepts the
// access_token query parameter. That is for routes loaded by an <audio> element,
// which cannot send headers. A header that is present always wins, so a bad
// header is never rescued by a query token.
func requireAuth(tokens tokenParser, allowQuery bool) gin.HandlerFunc {
return func(c *gin.Context) {
token := ""
if header := c.GetHeader("Authorization"); header != "" {
// The scheme name is case-insensitive (RFC 7235). Any other scheme,
// or a bare token, is not accepted.
const scheme = "Bearer "
if len(header) < len(scheme) || !strings.EqualFold(header[:len(scheme)], scheme) {
writeError(c, http.StatusUnauthorized, "unauthorized", "missing bearer token")
return
}
token = header[len(scheme):]
} else if allowQuery {
token = c.Query("access_token")
}
if token == "" {
writeError(c, http.StatusUnauthorized, "unauthorized", "missing bearer token")
return
}
claims, err := tokens.Parse(token)
if err != nil {
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
return
}
c.Set(ctxUserID, claims.UserID)
c.Set(ctxUsername, claims.Username)
c.Next()
}
}