sonda/internal/api/http/middleware.go
tgiachi def20731be fix(streaming): open files through os.Root and tighten token parsing
- fix: open the audio file through os.Root with O_NONBLOCK. A FIFO under a
  stored path used to block the request forever in open(2) before the
  regular-file check could run; now it is refused immediately
- fix: os.Root also removes the gap between checking the path and opening it,
  so a symlink swapped in at the last moment cannot leave the library
  (absolute symlinks are refused even when they point back inside)
- fix(api): only "Authorization: Bearer <token>" is accepted again. The query
  token change had made a bare token in the header pass on every route
- fix(config): library.roots must be absolute paths; a relative root made
  every stream fail and depended on the directory sondad started in
- test: FIFO and symlink-to-FIFO without hanging, bare and non-Bearer headers
  on a normal route and on the stream route, relative roots
2026-11-11 13:00:17 +01:00

112 lines
3.3 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 != "" {
var ok bool
if token, ok = strings.CutPrefix(header, "Bearer "); !ok {
// Any other scheme, or a bare token, is not accepted.
writeError(c, http.StatusUnauthorized, "unauthorized", "missing bearer token")
return
}
} 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()
}
}