sonda/internal/api/http/middleware.go
tgiachi dbe9338af3 feat(auth): add refresh tokens, admin role and user management
- feat(auth): short-lived access tokens plus rotating refresh tokens stored as
  SHA-256 hashes; replaying a spent token revokes every session of that user
- feat(auth): is_admin flag; the first registered user is the admin and the
  last admin can be neither demoted nor deleted
- feat(api): POST /auth/refresh, /auth/logout, /auth/password and GET /auth/me
- feat(api): admin-only GET/POST /users, PATCH /users/{id}, PUT
  /users/{id}/password and DELETE /users/{id}; the admin check reads the role
  from the database on every call
- feat(api): starting a library scan is now admin-only
- feat(storage): users and refresh token repositories for SQLite and
  PostgreSQL (migration 0004; the oldest existing account becomes admin)
- feat(config): auth.access_ttl_minutes and auth.refresh_ttl_hours replace
  auth.token_ttl_hours
- test: rotation, reuse detection, concurrent rotation with a single winner,
  admin rules, role changes taking effect immediately
2026-11-11 12:38:42 +01:00

94 lines
2.5 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()
logger.Info("http request",
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)),
)
}
}
// 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 accepts only "Authorization: Bearer <jwt>".
func requireAuth(tokens tokenParser) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
token, ok := strings.CutPrefix(header, "Bearer ")
if !ok || 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()
}
}