sonda/internal/api/http/router.go
tgiachi 49f1051b3f feat(streaming): stream tracks with HTTP Range support
- feat(streaming): open a track's file only after checking it against the
  configured library roots: relative paths only, no "..", symlinks resolved on
  both sides so none can leave the root, regular files only
- feat(api): GET and HEAD /api/v1/tracks/{id}/stream via http.ServeContent
  (206, 416, Content-Length, conditional requests), MIME type from the
  extension, nosniff, no-referrer and private caching headers
- feat(api): the stream route also accepts the access token as access_token in
  the query string, because an audio element cannot send headers; no other
  route does, and the query string is never logged
- feat(storage): PlayableFile picks the oldest file of a track that is not
  flagged missing
- fix(api): internal errors set by handlers are now written to the request log
- test: range variants, HEAD, conditional requests, auth variants, traversal,
  symlink escape, symlinked root, missing file, directory instead of file
2026-11-11 12:56:20 +01:00

111 lines
3.4 KiB
Go

// Package httpapi is the first-party REST API (/api/v1).
//
// Handlers stay thin: they validate and serialize, then call services.
package httpapi
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"codeberg.org/squidd/sonda/internal/auth"
"codeberg.org/squidd/sonda/internal/library"
"codeberg.org/squidd/sonda/internal/listening"
"codeberg.org/squidd/sonda/internal/streaming"
)
// maxBodyBytes bounds every request body.
const maxBodyBytes = 64 << 10
type authService interface {
Register(ctx context.Context, username, password string) (auth.User, error)
Login(ctx context.Context, username, password string) (auth.Session, error)
Refresh(ctx context.Context, refreshToken string) (auth.Session, error)
Logout(ctx context.Context, refreshToken string) error
User(ctx context.Context, id int64) (auth.User, error)
ChangePassword(ctx context.Context, userID int64, current, next string) error
ListUsers(ctx context.Context) ([]auth.User, error)
CreateUser(ctx context.Context, username, password string, isAdmin bool) (auth.User, error)
SetAdmin(ctx context.Context, id int64, isAdmin bool) (auth.User, error)
ResetPassword(ctx context.Context, id int64, password string) error
DeleteUser(ctx context.Context, id int64) error
}
type tokenParser interface {
Parse(token string) (auth.Claims, error)
}
type listenService interface {
Record(ctx context.Context, e listening.Event) (bool, error)
}
type streamService interface {
Open(ctx context.Context, trackID int64) (*streaming.Stream, error)
}
type scanService interface {
Start() error
Status() library.Status
}
// Deps are the services the API needs.
type Deps struct {
Logger *zap.Logger
Auth authService
Tokens tokenParser
Listening listenService
Scan scanService
Streams streamService
}
// NewRouter builds the gin engine with all routes.
func NewRouter(d Deps) *gin.Engine {
r := gin.New()
_ = r.SetTrustedProxies(nil) // use the socket address; no forwarded-header trust yet
r.Use(gin.Recovery(), limitBody(maxBodyBytes), requestLog(d.Logger))
r.NoRoute(func(c *gin.Context) { writeError(c, http.StatusNotFound, "not_found", "no such route") })
v1 := r.Group("/api/v1")
v1.GET("/health", health)
a := &authHandlers{svc: d.Auth}
v1.POST("/auth/register", a.register)
v1.POST("/auth/login", a.login)
v1.POST("/auth/refresh", a.refresh)
v1.POST("/auth/logout", a.logout)
// Any signed-in user.
protected := v1.Group("", requireAuth(d.Tokens, false))
protected.GET("/auth/me", a.me)
protected.POST("/auth/password", a.changePassword)
l := &listenHandlers{svc: d.Listening}
protected.POST("/listens", l.record)
lib := &libraryHandlers{scan: d.Scan}
protected.GET("/library/scan", lib.scanStatus)
// Audio loaded by an <audio> element cannot send headers, so this route also
// takes the access token as a query parameter. It never records a listen.
st := &streamHandlers{svc: d.Streams}
audio := v1.Group("", requireAuth(d.Tokens, true))
audio.GET("/tracks/:id/stream", st.stream)
audio.HEAD("/tracks/:id/stream", st.stream)
// Admins only.
admin := protected.Group("", requireAdmin(d.Auth))
admin.POST("/library/scan", lib.startScan)
u := &usersHandlers{svc: d.Auth}
admin.GET("/users", u.list)
admin.POST("/users", u.create)
admin.PATCH("/users/:id", u.update)
admin.PUT("/users/:id/password", u.resetPassword)
admin.DELETE("/users/:id", u.remove)
return r
}
func health(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}