sonda/internal/api/http/router.go
tgiachi 9d28a8a99c feat(api): OpenAPI spec and an offline Swagger UI
- feat: internal/api/openapi/openapi.yaml describes every operation (OpenAPI
  3.0.3), written by hand and embedded in the binary; GET /api/v1/openapi.yaml
  serves it
- feat: GET /api/docs/ serves Swagger UI from assets embedded in the binary
  (github.com/swaggest/swgui, v5emb), so opening it never contacts another
  server; both are public because they contain no data
- feat: response objects in the spec are closed (additionalProperties: false)
- test: the spec is valid OpenAPI; the router and the spec describe the same
  operations in both directions; every operation has an id, a summary, a tag,
  a documented 401 when it needs a token and a 403 when it is admin only
- test: a contract test drives every operation through the real services,
  including a real scan and real streaming, and validates each response
  (status, headers, JSON body) against the spec with kin-openapi; it fails if
  an operation was never exercised. Checked by breaking the code and the spec
  on purpose
- test: the docs page loads without any external address and every asset it
  references is served
- docs: README section on the interactive documentation and on keeping the
  spec in step with the code

Closes #15
2026-11-11 14:35:16 +01:00

146 lines
4.9 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/catalog"
"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
StartLibrary(id int64) error
Status() library.Status
}
type catalogService interface {
Artists(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error)
Albums(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error)
Tracks(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error)
Artist(ctx context.Context, id int64) (catalog.Artist, error)
Album(ctx context.Context, id int64) (catalog.Album, error)
Track(ctx context.Context, id int64) (catalog.Track, error)
}
type libraryService interface {
List(ctx context.Context) ([]library.Library, error)
Create(ctx context.Context, name, path string) (library.Library, error)
Update(ctx context.Context, id int64, name, path *string) (library.Library, error)
Delete(ctx context.Context, id int64) error
}
// Deps are the services the API needs.
type Deps struct {
Logger *zap.Logger
Auth authService
Tokens tokenParser
Listening listenService
Scan scanService
Libraries libraryService
Catalog catalogService
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)
registerDocs(r, v1)
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)
cat := &catalogHandlers{svc: d.Catalog}
protected.GET("/artists", cat.listArtists)
protected.GET("/artists/:id", cat.getArtist)
protected.GET("/albums", cat.listAlbums)
protected.GET("/albums/:id", cat.getAlbum)
protected.GET("/tracks", cat.listTracks)
protected.GET("/tracks/:id", cat.getTrack)
// 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)
libs := &librariesHandlers{svc: d.Libraries}
admin.GET("/libraries", libs.list)
admin.POST("/libraries", libs.create)
admin.PATCH("/libraries/:id", libs.update)
admin.DELETE("/libraries/:id", libs.remove)
admin.POST("/libraries/:id/scan", lib.startLibraryScan)
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"})
}