From 9d28a8a99c9c42b99bb468e8e9bfcc79da20627e Mon Sep 17 00:00:00 2001 From: tgiachi Date: Wed, 11 Nov 2026 14:35:16 +0100 Subject: [PATCH] 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 --- README.md | 10 +- go.mod | 7 + go.sum | 22 + internal/api/http/api_test.go | 20 +- internal/api/http/contract_test.go | 322 +++++++++ internal/api/http/docs.go | 29 + internal/api/http/docs_test.go | 213 ++++++ internal/api/http/router.go | 1 + internal/api/openapi/openapi.go | 13 + internal/api/openapi/openapi.yaml | 1077 ++++++++++++++++++++++++++++ 10 files changed, 1710 insertions(+), 4 deletions(-) create mode 100644 internal/api/http/contract_test.go create mode 100644 internal/api/http/docs.go create mode 100644 internal/api/http/docs_test.go create mode 100644 internal/api/openapi/openapi.go create mode 100644 internal/api/openapi/openapi.yaml diff --git a/README.md b/README.md index 49cbebd..45169e1 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr - **Scanner.** Reads MP3 and FLAC tags and audio properties with several workers in parallel. Rescans are incremental, renamed files keep their identity, vanished files are flagged (never deleted), and a library whose folder looks empty or unreadable (an unmounted NAS) is left alone instead of being wiped. Audio in other formats (m4a, ogg, opus, wav, wma and similar) is not read yet, but it is counted as `unsupported` in the scan result instead of disappearing silently. NAS housekeeping folders (`@Recycle`, `#recycle`, `@eaDir`, `.@__thumb`, `$RECYCLE.BIN`) are skipped. - **Catalog.** Browse and search artists, albums and tracks, with paging, by library, artist or album. Only tracks you can actually play are listed. - **Streaming.** `GET` and `HEAD` with `Range` support, so players can seek. Opening or prefetching a stream does not record a listen. +- **API documentation.** The full API is described in OpenAPI and browsable with Swagger UI, served by Sonda itself. The UI is embedded in the binary, so opening it contacts no other server. - **Listening history.** Clients report explicit `play`, `complete` and `skip` events. They stay in your database; nothing is sent anywhere. Sonda makes no outbound network requests at all. ## What is not there yet @@ -170,6 +171,8 @@ curl -s -X POST $BASE/users -H "$AUTH" -d '{"username":"bob","password":"another Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"error":{"code":"...","message":"..."}}`. +**Interactive documentation:** open `http://127.0.0.1:8080/api/docs/` in a browser. Use *Authorize* with the `access_token` from the login to try the protected operations. The OpenAPI file itself is at `/api/v1/openapi.yaml`. Both are public, since they describe the API and contain no data. + | Who | Method and path | What it does | |---|---|---| | anyone | `GET /health` | Liveness check. | @@ -222,7 +225,8 @@ Layout: ``` cmd/sondad/ the server: wiring, config, logging, shutdown -internal/api/http/ the REST API (thin handlers) +internal/api/http/ the REST API (thin handlers) and the docs routes +internal/api/openapi/ the OpenAPI spec, embedded in the binary internal/auth/ users, roles, passwords, access and refresh tokens internal/catalog/ browsing and searching artists, albums, tracks internal/library/ libraries, the scanner, the event hub, the tag reader @@ -232,8 +236,10 @@ internal/streaming/ opening a track's file safely migrations/ SQL migrations, one folder per database ``` +The API description is `internal/api/openapi/openapi.yaml`, written by hand and embedded in the binary. Two tests keep it in step with the code: one fails when a route and the spec disagree in either direction, and a contract test sends real requests through every operation and validates each response (status, headers, JSON body) against the spec. Adding or changing an endpoint therefore means updating the spec in the same change. Response objects are closed (`additionalProperties: false`), so a field added in the code and forgotten in the spec fails the build. + Migrations are plain SQL files in `migrations/sqlite` and `migrations/postgres`. They must describe the same schema, and a test checks that both folders hold the same files. Add a new numbered file to both whenever the schema changes. ## Third-party code -Audio tags are read with `go.senan.xyz/taglib`, which embeds [TagLib](https://github.com/taglib/taglib) compiled to WebAssembly and is licensed under the LGPL 2.1. The other dependencies are listed in `go.mod`. +Audio tags are read with `go.senan.xyz/taglib`, which embeds [TagLib](https://github.com/taglib/taglib) compiled to WebAssembly and is licensed under the LGPL 2.1. The Swagger UI assets come from `github.com/swaggest/swgui` (Apache-2.0), which embeds [Swagger UI](https://github.com/swagger-api/swagger-ui) (Apache-2.0). The other dependencies are listed in `go.mod`. diff --git a/go.mod b/go.mod index 1d89fc3..87e3b38 100644 --- a/go.mod +++ b/go.mod @@ -3,10 +3,12 @@ module codeberg.org/squidd/sonda go 1.27.1 require ( + github.com/getkin/kin-openapi v0.153.0 github.com/gin-gonic/gin v1.12.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.12.0 github.com/pelletier/go-toml/v2 v2.4.3 + github.com/swaggest/swgui v1.8.9 github.com/uptrace/bun v1.3.0 github.com/uptrace/bun/dialect/pgdialect v1.3.0 github.com/uptrace/bun/dialect/sqlitedialect v1.3.0 @@ -24,6 +26,8 @@ require ( github.com/dustin/go-humanize v1.1.0 // indirect github.com/gabriel-vasile/mimetype v1.4.12 // indirect github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-openapi/jsonpointer v0.22.5 // indirect + github.com/go-openapi/swag/jsonname v0.25.5 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.30.1 // indirect @@ -45,14 +49,17 @@ require ( github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect github.com/tetratelabs/wazero v1.11.1-0.20260428013916-2bbd517b7633 // indirect github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect + github.com/vearutop/statigz v1.4.0 // indirect github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/multierr v1.11.0 // indirect + go.yaml.in/yaml/v4 v4.0.0 // indirect golang.org/x/arch v0.22.0 // indirect golang.org/x/net v0.60.0 // indirect golang.org/x/sync v0.24.0 // indirect diff --git a/go.sum b/go.sum index 59a8911..8985edb 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,7 @@ +github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= +github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/bool64/dev v0.2.45 h1:3nLKhAS/6Oklk3Mt2lHYSN/Cb4tdAD77KLwzeP+6eYE= +github.com/bool64/dev v0.2.45/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg= github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= @@ -9,14 +13,24 @@ github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gE github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/getkin/kin-openapi v0.153.0 h1:Qo4qWW+Pj8o90LUTE6MDyG5TJAtWnfvrcWOBcWg7eBw= +github.com/getkin/kin-openapi v0.153.0/go.mod h1:mEZ6Ip3gyqPDokUsJsttZhv3r46/NeH3tGwrFUMcoSE= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA= +github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0= +github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo= +github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= +github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM= +github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -77,6 +91,8 @@ github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SA github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -89,6 +105,8 @@ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/swaggest/swgui v1.8.9 h1:cxAgIwouPpZPlvX68jY5fpwarzLbkc8/IL6DMj+H460= +github.com/swaggest/swgui v1.8.9/go.mod h1:eTJfgwudbyw9xMwqO26vs82ei2u6//JnUAofx2vGB3M= github.com/tetratelabs/wazero v1.11.1-0.20260428013916-2bbd517b7633 h1:6GN/lazdqr69FIzz1U6c4TF/ppE2dInMR4GzU9QKxjg= github.com/tetratelabs/wazero v1.11.1-0.20260428013916-2bbd517b7633/go.mod h1:3ghOSSWYnzX0zd/3Ns4ni2tKxcXDE9/QgkwuH1PW3Rs= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= @@ -103,6 +121,8 @@ github.com/uptrace/bun/dialect/pgdialect v1.3.0 h1:0ZkGqGugxaPCxko4DV2f4d7i+FnM2 github.com/uptrace/bun/dialect/pgdialect v1.3.0/go.mod h1:kP5HGEpAX8iJCqj3WHm04XnoeBPacdCN1P2HiwMtHpg= github.com/uptrace/bun/dialect/sqlitedialect v1.3.0 h1:XzxkORYksxkLsIQLJHFYUb3yDvqSQHzTungyKpJhHTw= github.com/uptrace/bun/dialect/sqlitedialect v1.3.0/go.mod h1:x2D1sY50Itio0I/FVdNe30oMUT2ObiAS+oILcMR+Wys= +github.com/vearutop/statigz v1.4.0 h1:RQL0KG3j/uyA/PFpHeZ/L6l2ta920/MxlOAIGEOuwmU= +github.com/vearutop/statigz v1.4.0/go.mod h1:LYTolBLiz9oJISwiVKnOQoIwhO1LWX1A7OECawGS8XE= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= @@ -121,6 +141,8 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw= +go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index d126c34..8a3bfdf 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/uptrace/bun" "go.uber.org/zap" "codeberg.org/squidd/sonda/internal/auth" @@ -39,6 +40,21 @@ func newTestAPIWithScan(t *testing.T, scan scanService) http.Handler { // newTestAPIWith wires real services and lets a test replace parts of Deps. func newTestAPIWith(t *testing.T, mutate func(*Deps)) http.Handler { + t.Helper() + h, _ := newTestEnv(t, mutate) + return h +} + +// newTestEnv is newTestAPIWith that also returns the database, for tests that +// need to look at or seed it. +func newTestEnv(t *testing.T, mutate func(*Deps)) (http.Handler, *bun.DB) { + t.Helper() + return newTestEnvDB(t, func(d *Deps, _ *bun.DB) { mutate(d) }) +} + +// newTestEnvDB lets the mutate function see the database as well, for tests +// that build services on top of it. +func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun.DB) { t.Helper() db, err := storage.Open(storage.DriverSQLite, filepath.Join(t.TempDir(), "api.db")) if err != nil { @@ -66,8 +82,8 @@ func newTestAPIWith(t *testing.T, mutate func(*Deps)) http.Handler { Libraries: library.NewLibraries(storage.NewLibraryRepo(db)), Streams: streaming.NewService(noFiles{}), } - mutate(&deps) - return NewRouter(deps) + mutate(&deps, db) + return NewRouter(deps), db } // noFiles is a streaming source with nothing to play. diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go new file mode 100644 index 0000000..a5f7515 --- /dev/null +++ b/internal/api/http/contract_test.go @@ -0,0 +1,322 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/getkin/kin-openapi/openapi3filter" + "github.com/getkin/kin-openapi/routers" + "github.com/getkin/kin-openapi/routers/legacy" + "github.com/uptrace/bun" + + "codeberg.org/squidd/sonda/internal/catalog" + "codeberg.org/squidd/sonda/internal/library" + "codeberg.org/squidd/sonda/internal/storage" + "codeberg.org/squidd/sonda/internal/streaming" +) + +// Contract tests: real requests against the real services, with every response +// checked against openapi.yaml (status, headers, JSON body). A field that is +// added, renamed or dropped in the code without the spec fails here. + +// contractReader gives the two files of the fixture their tags without real audio. +type contractReader struct{} + +func (contractReader) Read(path string) (library.Metadata, error) { + m := library.Metadata{ + Tags: library.Tags{Artists: []string{"Artist X"}, Album: "Album Y", AlbumArtist: "Artist X", DiscNo: 1}, + Properties: library.Properties{DurationMs: 180000, SampleRate: 44100}, + } + switch filepath.Base(path) { + case "a.mp3": + m.Title, m.TrackNo, m.Format = "Song A", 1, "mpeg" + case "b.flac": + m.Title, m.TrackNo, m.Format = "Song B", 2, "flac" + default: + return library.Metadata{}, library.ErrUnreadable + } + return m, nil +} + +// scanAdapter lets the API start scans on a real manager. +type scanAdapter struct{ m *library.Manager } + +func (a scanAdapter) Start() error { return a.m.Start(context.Background()) } +func (a scanAdapter) StartLibrary(id int64) error { return a.m.StartLibrary(context.Background(), id) } +func (a scanAdapter) Status() library.Status { return a.m.Status() } + +type contract struct { + t *testing.T + h http.Handler + router routers.Router + seen map[string]bool // "METHOD /path" of every operation exercised + music string +} + +func newContract(t *testing.T) *contract { + t.Helper() + h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) { + repo := storage.NewLibraryRepo(db) + mgr := library.NewManager(library.NewScanner(repo, contractReader{}, library.NewHub(), 2), repo) + libs := library.NewLibraries(repo) + libs.SetBusy(func() bool { return mgr.Status().Running }) + d.Scan = scanAdapter{mgr} + d.Libraries = libs + d.Catalog = catalog.NewService(storage.NewCatalogRepo(db)) + d.Streams = streaming.NewService(repo) + }) + + router, err := legacy.NewRouter(loadSpec(t)) + if err != nil { + t.Fatal(err) + } + + music := t.TempDir() + for _, f := range []string{"a.mp3", "b.flac"} { + if err := os.WriteFile(filepath.Join(music, f), bytes.Repeat([]byte{0xAB}, 400), 0o644); err != nil { + t.Fatal(err) + } + } + return &contract{t: t, h: h, router: router, seen: map[string]bool{}, music: music} +} + +// call sends a request to /api/v1, checks the answer against the spec and +// returns it. headers are extra request headers. +func (c *contract) call(method, path, token string, body any, headers ...string) *httptest.ResponseRecorder { + c.t.Helper() + var buf bytes.Buffer + if body != nil { + if err := json.NewEncoder(&buf).Encode(body); err != nil { + c.t.Fatal(err) + } + } + req := httptest.NewRequest(method, "/api/v1"+path, &buf) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + for i := 0; i+1 < len(headers); i += 2 { + req.Header.Set(headers[i], headers[i+1]) + } + rec := httptest.NewRecorder() + c.h.ServeHTTP(rec, req) + c.validate(req, rec) + return rec +} + +func (c *contract) validate(req *http.Request, rec *httptest.ResponseRecorder) { + c.t.Helper() + route, params, err := c.router.FindRoute(req) + if err != nil { + c.t.Errorf("%s %s is not in the spec: %v", req.Method, req.URL.Path, err) + return + } + c.seen[req.Method+" "+route.Path] = true + + in := &openapi3filter.RequestValidationInput{ + Request: req, PathParams: params, Route: route, + Options: &openapi3filter.Options{AuthenticationFunc: openapi3filter.NoopAuthenticationFunc}, + } + out := &openapi3filter.ResponseValidationInput{ + RequestValidationInput: in, + Status: rec.Code, + Header: rec.Header(), + Options: &openapi3filter.Options{ + IncludeResponseStatus: true, // a status the spec does not list is a failure + // Audio and YAML bodies are not JSON, and HEAD has no body to check. + ExcludeResponseBody: req.Method == http.MethodHead || route.Path == "/openapi.yaml" || + (route.Path == "/tracks/{id}/stream" && rec.Code/100 == 2), + }, + } + out.SetBodyBytes(rec.Body.Bytes()) + if err := openapi3filter.ValidateResponse(context.Background(), out); err != nil { + c.t.Errorf("%s %s -> %d does not match the spec: %v\nbody: %.300s", req.Method, req.URL.Path, rec.Code, err, rec.Body.String()) + } +} + +func (c *contract) expect(rec *httptest.ResponseRecorder, want int, what string) map[string]any { + c.t.Helper() + if rec.Code != want { + c.t.Fatalf("%s: status %d, want %d: %s", what, rec.Code, want, rec.Body.String()) + } + out := map[string]any{} + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return out +} + +func idOf(m map[string]any) string { return strconv.FormatInt(int64(m["id"].(float64)), 10) } + +func TestResponsesMatchTheSpec(t *testing.T) { + c := newContract(t) + + // ---- system ---- + c.expect(c.call("GET", "/health", "", nil), 200, "health") + c.expect(c.call("GET", "/openapi.yaml", "", nil), 200, "openapi.yaml") + + // ---- auth ---- + creds := map[string]string{"username": "alice", "password": "correct horse"} + c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "x", "password": "short"}), 400, "register invalid") + c.expect(c.call("POST", "/auth/register", "", creds), 201, "register") + c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "eve", "password": "correct horse"}), 403, "register closed") + + c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "alice", "password": "wrong password"}), 401, "login wrong") + c.expect(c.call("POST", "/auth/login", "", nil), 400, "login without body") + session := c.expect(c.call("POST", "/auth/login", "", creds), 200, "login") + token := session["access_token"].(string) + refresh := session["refresh_token"].(string) + + c.expect(c.call("GET", "/auth/me", "", nil), 401, "me without token") + c.expect(c.call("GET", "/auth/me", token, nil), 200, "me") + + renewed := c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 200, "refresh") + c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 401, "refresh replay") + c.expect(c.call("POST", "/auth/refresh", "", "not an object"), 400, "refresh bad body") + c.expect(c.call("POST", "/auth/logout", "", map[string]string{"refresh_token": renewed["refresh_token"].(string)}), 204, "logout") + c.expect(c.call("POST", "/auth/logout", "", "not an object"), 400, "logout bad body") + + c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "nope nope nope", "new_password": "brand new pass"}), 403, "password wrong current") + c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "correct horse", "new_password": "x"}), 400, "password weak") + c.expect(c.call("POST", "/auth/password", "", map[string]string{}), 401, "password without token") + c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "correct horse", "new_password": "brand new pass"}), 204, "password changed") + creds["password"] = "brand new pass" + token = c.expect(c.call("POST", "/auth/login", "", creds), 200, "login again")["access_token"].(string) + + // ---- users ---- + bob := c.expect(c.call("POST", "/users", token, map[string]any{"username": "bob", "password": "bobs long pass"}), 201, "create user") + c.expect(c.call("POST", "/users", token, map[string]any{"username": "BOB", "password": "bobs long pass"}), 409, "create duplicate") + c.expect(c.call("POST", "/users", token, map[string]any{"username": "x", "password": "bobs long pass"}), 400, "create invalid") + bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "bob", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string) + c.expect(c.call("GET", "/users", bobToken, nil), 403, "users as non-admin") + c.expect(c.call("GET", "/users", token, nil), 200, "list users") + bobID := idOf(bob) + c.expect(c.call("PATCH", "/users/"+bobID, token, map[string]bool{"is_admin": true}), 200, "promote") + c.expect(c.call("PATCH", "/users/"+bobID, token, map[string]bool{"is_admin": false}), 200, "demote") + c.expect(c.call("PATCH", "/users/999", token, map[string]bool{"is_admin": true}), 404, "patch unknown user") + aliceID := idOf(c.expect(c.call("GET", "/auth/me", token, nil), 200, "me again")) + c.expect(c.call("PATCH", "/users/"+aliceID, token, map[string]bool{"is_admin": false}), 409, "demote the last admin") + c.expect(c.call("PUT", "/users/"+bobID+"/password", token, map[string]string{"password": "reset password"}), 204, "reset password") + c.expect(c.call("PUT", "/users/999/password", token, map[string]string{"password": "reset password"}), 404, "reset unknown") + c.expect(c.call("DELETE", "/users/"+bobID, token, nil), 204, "delete user") + c.expect(c.call("DELETE", "/users/"+bobID, token, nil), 404, "delete twice") + c.expect(c.call("DELETE", "/users/"+aliceID, token, nil), 409, "delete the last admin") + + // ---- libraries and scan ---- + c.expect(c.call("POST", "/library/scan", token, nil), 409, "scan with no library") + lib := c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Music", "path": c.music}), 201, "create library") + libID := idOf(lib) + c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "music", "path": c.music}), 409, "duplicate library") + c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Bad", "path": "relative/path"}), 400, "invalid library") + c.expect(c.call("GET", "/libraries", token, nil), 200, "list libraries") + c.expect(c.call("PATCH", "/libraries/"+libID, token, map[string]string{"name": "My music"}), 200, "rename library") + c.expect(c.call("PATCH", "/libraries/999", token, map[string]string{"name": "x"}), 404, "patch unknown library") + + c.expect(c.call("POST", "/libraries/999/scan", token, nil), 404, "scan unknown library") + c.expect(c.call("POST", "/libraries/"+libID+"/scan", token, nil), 202, "scan one library") + c.scanDone(token) + c.expect(c.call("POST", "/library/scan", token, nil), 202, "scan everything") + c.scanDone(token) + status := c.expect(c.call("GET", "/library/scan", token, nil), 200, "scan status") + last, _ := status["last"].(map[string]any) + if last["found"] != float64(2) || last["added"] != float64(0) || last["unchanged"] != float64(2) { + t.Fatalf("second scan = %v, want 2 files, all unchanged", last) + } + + extra := c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Extra", "path": t.TempDir()}), 201, "second library") + c.expect(c.call("DELETE", "/libraries/"+idOf(extra), token, nil), 204, "delete library") + c.expect(c.call("DELETE", "/libraries/"+idOf(extra), token, nil), 404, "delete library twice") + + // ---- catalog ---- + artists := c.expect(c.call("GET", "/artists?q=artist&limit=10&library_id="+libID, token, nil), 200, "artists") + artistID := idOf(artists["items"].([]any)[0].(map[string]any)) + c.expect(c.call("GET", "/artists?limit=abc", token, nil), 400, "artists bad limit") + c.expect(c.call("GET", "/artists/"+artistID, token, nil), 200, "artist") + c.expect(c.call("GET", "/artists/999", token, nil), 404, "artist unknown") + + albums := c.expect(c.call("GET", "/albums?artist_id="+artistID, token, nil), 200, "albums") + albumID := idOf(albums["items"].([]any)[0].(map[string]any)) + c.expect(c.call("GET", "/albums?offset=-1", token, nil), 400, "albums bad offset") + c.expect(c.call("GET", "/albums/"+albumID, token, nil), 200, "album") + c.expect(c.call("GET", "/albums/999", token, nil), 404, "album unknown") + + tracks := c.expect(c.call("GET", "/tracks?album_id="+albumID+"&artist_id="+artistID, token, nil), 200, "tracks") + items := tracks["items"].([]any) + if len(items) != 2 || tracks["total"] != float64(2) { + t.Fatalf("tracks = %v, want the two scanned files", tracks) + } + trackID := idOf(items[0].(map[string]any)) + c.expect(c.call("GET", "/tracks?q="+string(rune(0x41))+"&limit=-1", token, nil), 400, "tracks bad limit") + c.expect(c.call("GET", "/tracks/"+trackID, token, nil), 200, "track") + c.expect(c.call("GET", "/tracks/999", token, nil), 404, "track unknown") + + // ---- playback ---- + stream := "/tracks/" + trackID + "/stream" + c.expect(c.call("GET", stream, "", nil), 401, "stream without token") + if rec := c.call("GET", stream, token, nil); rec.Code != 200 || rec.Body.Len() != 400 { + t.Fatalf("stream: %d, %d bytes", rec.Code, rec.Body.Len()) + } + if rec := c.call("GET", stream+"?access_token="+token, "", nil); rec.Code != 200 { + t.Fatalf("stream with a query token: %d", rec.Code) + } + if rec := c.call("GET", stream, token, nil, "Range", "bytes=0-99"); rec.Code != 206 || rec.Body.Len() != 100 { + t.Fatalf("stream range: %d, %d bytes", rec.Code, rec.Body.Len()) + } + if rec := c.call("GET", stream, token, nil, "Range", "bytes=5000-"); rec.Code != 416 { + t.Fatalf("stream range past the end: %d", rec.Code) + } + if rec := c.call("GET", stream, token, nil, "If-Modified-Since", time.Now().Add(time.Hour).UTC().Format(http.TimeFormat)); rec.Code != 304 { + t.Fatalf("stream conditional: %d", rec.Code) + } + if rec := c.call("HEAD", stream, token, nil); rec.Code != 200 || rec.Body.Len() != 0 { + t.Fatalf("stream HEAD: %d, %d bytes", rec.Code, rec.Body.Len()) + } + if rec := c.call("HEAD", stream, token, nil, "Range", "bytes=0-9"); rec.Code != 206 { + t.Fatalf("stream HEAD with a range: %d", rec.Code) + } + c.expect(c.call("GET", "/tracks/999/stream", token, nil), 404, "stream unknown track") + + tid, _ := strconv.Atoi(trackID) + listen := map[string]any{"track_id": tid, "event_type": "complete", "duration_played_ms": 1000, "idempotency_key": "k1", "occurred_at": "2026-01-02T03:04:05Z"} + c.expect(c.call("POST", "/listens", token, listen), 201, "listen") + c.expect(c.call("POST", "/listens", token, listen), 200, "listen again") + c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": 999, "event_type": "play", "idempotency_key": "k2"}), 404, "listen unknown track") + c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": tid, "event_type": "dance", "idempotency_key": "k3"}), 400, "listen invalid") + + // ---- every operation in the spec was exercised ---- + var missing []string + for _, op := range specOperations(loadSpec(t)) { + if !c.seen[op] { + missing = append(missing, op) + } + } + if len(missing) > 0 { + t.Errorf("operations the contract test never called (add a request for each):\n %v", missing) + } +} + +// scanDone waits for the running scan to finish. +func (c *contract) scanDone(token string) { + c.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/api/v1/library/scan", nil) + req.Header.Set("Authorization", "Bearer "+token) + c.h.ServeHTTP(rec, req) + var st struct { + Running bool `json:"running"` + } + _ = json.Unmarshal(rec.Body.Bytes(), &st) + if !st.Running { + return + } + time.Sleep(20 * time.Millisecond) + } + c.t.Fatal("the scan did not finish in time") +} diff --git a/internal/api/http/docs.go b/internal/api/http/docs.go new file mode 100644 index 0000000..49d6cf8 --- /dev/null +++ b/internal/api/http/docs.go @@ -0,0 +1,29 @@ +package httpapi + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/swaggest/swgui/v5emb" + + "codeberg.org/squidd/sonda/internal/api/openapi" +) + +const ( + specPath = "/api/v1/openapi.yaml" + docsPath = "/api/docs/" +) + +// registerDocs serves the OpenAPI spec and a Swagger UI for it. Both are public: +// they describe the API and contain no data. The UI's assets are embedded in the +// binary, so opening it never contacts another server. +func registerDocs(r *gin.Engine, v1 *gin.RouterGroup) { + v1.GET("/openapi.yaml", func(c *gin.Context) { + c.Header("Cache-Control", "no-cache") + c.Data(http.StatusOK, "application/yaml; charset=utf-8", openapi.Spec) + }) + + ui := v5emb.New("Sonda API", specPath, docsPath) + r.GET("/api/docs", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, docsPath) }) + r.GET("/api/docs/*any", gin.WrapH(ui)) +} diff --git a/internal/api/http/docs_test.go b/internal/api/http/docs_test.go new file mode 100644 index 0000000..7a84da5 --- /dev/null +++ b/internal/api/http/docs_test.go @@ -0,0 +1,213 @@ +package httpapi + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "sort" + "strings" + "testing" + + "github.com/getkin/kin-openapi/openapi3" + "github.com/gin-gonic/gin" + + "codeberg.org/squidd/sonda/internal/api/openapi" +) + +func loadSpec(t *testing.T) *openapi3.T { + t.Helper() + loader := openapi3.NewLoader() + doc, err := loader.LoadFromData(openapi.Spec) + if err != nil { + t.Fatalf("the spec does not load: %v", err) + } + return doc +} + +func TestSpecIsValidOpenAPI(t *testing.T) { + if err := loadSpec(t).Validate(context.Background()); err != nil { + t.Fatalf("the spec is not valid OpenAPI: %v", err) + } +} + +// specOperations lists "METHOD /path" for every operation in the spec. +func specOperations(doc *openapi3.T) []string { + var out []string + for path, item := range doc.Paths.Map() { + for method := range item.Operations() { + out = append(out, method+" "+path) + } + } + sort.Strings(out) + return out +} + +// routerOperations lists "METHOD /path" for every /api/v1 route the router serves, +// written the way the spec writes them: relative to /api/v1, with {id}. +func routerOperations(t *testing.T, h http.Handler) []string { + t.Helper() + engine, ok := h.(*gin.Engine) + if !ok { + t.Fatalf("handler is a %T, want *gin.Engine", h) + } + param := regexp.MustCompile(`:([A-Za-z_]+)`) + var out []string + for _, r := range engine.Routes() { + rest, ok := strings.CutPrefix(r.Path, "/api/v1") + if !ok { + continue // the docs UI lives outside /api/v1 + } + out = append(out, r.Method+" "+param.ReplaceAllString(rest, "{$1}")) + } + sort.Strings(out) + return out +} + +func diff(a, b []string) []string { + in := map[string]bool{} + for _, x := range b { + in[x] = true + } + var out []string + for _, x := range a { + if !in[x] { + out = append(out, x) + } + } + return out +} + +// The spec and the router must describe the same API, in both directions. +func TestSpecAndRoutesAgree(t *testing.T) { + h := newTestAPI(t) + spec, routes := specOperations(loadSpec(t)), routerOperations(t, h) + + if missing := diff(routes, spec); len(missing) > 0 { + t.Errorf("routes that are not in the spec (add them to openapi.yaml):\n %s", strings.Join(missing, "\n ")) + } + if extra := diff(spec, routes); len(extra) > 0 { + t.Errorf("operations in the spec that no route serves (remove them or add the route):\n %s", strings.Join(extra, "\n ")) + } + if len(spec) == 0 { + t.Fatal("the spec has no operations") + } +} + +func TestSpecOperationsAreWellFormed(t *testing.T) { + doc := loadSpec(t) + declared := map[string]bool{} + for _, tag := range doc.Tags { + declared[tag.Name] = true + } + + seen := map[string]string{} + for path, item := range doc.Paths.Map() { + for method, op := range item.Operations() { + where := method + " " + path + if op.OperationID == "" { + t.Errorf("%s has no operationId", where) + } else if other, dup := seen[op.OperationID]; dup { + t.Errorf("%s and %s share the operationId %q", where, other, op.OperationID) + } + seen[op.OperationID] = where + + if strings.TrimSpace(op.Summary) == "" { + t.Errorf("%s has no summary", where) + } + if len(op.Tags) == 0 { + t.Errorf("%s has no tag", where) + } + for _, tag := range op.Tags { + if !declared[tag] { + t.Errorf("%s uses the undeclared tag %q", where, tag) + } + } + // An operation that needs a token must say what a missing one looks like, + // and an admin-only one must say what a normal user gets. + if op.Security != nil && len(*op.Security) > 0 && op.Responses.Value("401") == nil { + t.Errorf("%s needs authentication but does not document 401", where) + } + if strings.HasPrefix(op.Description, "Admin only") && op.Responses.Value("403") == nil { + t.Errorf("%s is admin only but does not document 403", where) + } + } + } +} + +// ---- serving ---- + +func TestSpecIsServedWithoutAuthentication(t *testing.T) { + h := newTestAPI(t) + req := httptest.NewRequest("GET", "/api/v1/openapi.yaml", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/yaml") { + t.Errorf("Content-Type = %q", ct) + } + if rec.Body.String() != string(openapi.Spec) { + t.Error("the served spec differs from the embedded one") + } +} + +func fetch(h http.Handler, path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) + return rec +} + +func TestDocsRedirectToTheTrailingSlash(t *testing.T) { + rec := fetch(newTestAPI(t), "/api/docs") + if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/api/docs/" { + t.Fatalf("status %d, Location %q", rec.Code, rec.Header().Get("Location")) + } +} + +// Opening the docs must never contact another server: the page and every asset +// it needs come from Sonda itself. +func TestSwaggerUIWorksOffline(t *testing.T) { + h := newTestAPI(t) + page := fetch(h, "/api/docs/") + if page.Code != http.StatusOK || !strings.HasPrefix(page.Header().Get("Content-Type"), "text/html") { + t.Fatalf("docs page: %d %q", page.Code, page.Header().Get("Content-Type")) + } + html := page.Body.String() + if !strings.Contains(html, "/api/v1/openapi.yaml") { + t.Error("the page does not point at the spec") + } + // The page's own script builds addresses from window.location, so look at what + // it loads (src and href), not at every "//" in the text. + refs := regexp.MustCompile(`(?:src|href)="([^"]+)"`).FindAllStringSubmatch(html, -1) + if len(refs) == 0 { + t.Fatal("the page references no assets") + } + base, _ := url.Parse("http://sonda.local/api/docs/") + for _, m := range refs { + u, err := base.Parse(m[1]) + if err != nil { + t.Fatalf("bad reference %q: %v", m[1], err) + } + if u.Host != base.Host { + t.Errorf("asset %q is served from another host", m[1]) + continue + } + asset := fetch(h, u.Path) + if asset.Code != http.StatusOK || asset.Body.Len() == 0 { + t.Errorf("asset %s: status %d, %d bytes", u.Path, asset.Code, asset.Body.Len()) + } + } +} + +func TestDocsAreAvailableWithoutAToken(t *testing.T) { + h := newTestAPI(t) + for _, path := range []string{"/api/docs/", "/api/v1/openapi.yaml"} { + if rec := fetch(h, path); rec.Code != http.StatusOK { + t.Errorf("%s without a token: %d", path, rec.Code) + } + } +} diff --git a/internal/api/http/router.go b/internal/api/http/router.go index f23b5cb..1e7d0f9 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -89,6 +89,7 @@ func NewRouter(d Deps) *gin.Engine { v1 := r.Group("/api/v1") v1.GET("/health", health) + registerDocs(r, v1) a := &authHandlers{svc: d.Auth} v1.POST("/auth/register", a.register) diff --git a/internal/api/openapi/openapi.go b/internal/api/openapi/openapi.go new file mode 100644 index 0000000..0c98b01 --- /dev/null +++ b/internal/api/openapi/openapi.go @@ -0,0 +1,13 @@ +// Package openapi holds the OpenAPI description of the Sonda API. +// +// The spec is written by hand and embedded in the binary. Tests keep it honest: +// they fail when a route and the spec disagree, and they validate real +// responses against it. +package openapi + +import _ "embed" + +// Spec is the OpenAPI 3.0 document, in YAML. +// +//go:embed openapi.yaml +var Spec []byte diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml new file mode 100644 index 0000000..b26cc71 --- /dev/null +++ b/internal/api/openapi/openapi.yaml @@ -0,0 +1,1077 @@ +openapi: 3.0.3 +info: + title: Sonda API + version: 0.1.0 + description: | + Sonda is a privacy-first, self-hosted music server. This is its first-party REST API. + + **Authentication.** Log in with `POST /auth/login` and send the access token as + `Authorization: Bearer `. Access tokens are short-lived; renew the session with + `POST /auth/refresh`. Each refresh token works once. + + **Roles.** Operations marked *admin* need an account with the admin role. The first user + who registers is the admin. + + **Errors.** Every error has the same shape: `{"error": {"code": "...", "message": "..."}}`. + The `code` is stable and meant for programs; the `message` is for people. + + **Paging.** Lists take `limit` (default 50, at most 200; a larger value is lowered to 200) + and `offset`, and answer with `items`, `total`, `limit` and `offset`. +servers: + - url: /api/v1 +tags: + - name: System + - name: Auth + description: Accounts and sessions. + - name: Users + description: User management (admin). + - name: Libraries + description: Named folders of music (admin). + - name: Scan + description: Indexing the libraries. + - name: Catalog + description: Browsing and searching what can be played. + - name: Playback + description: Streaming and listening history. + +paths: + /health: + get: + tags: [System] + operationId: getHealth + summary: Liveness check + responses: + '200': + description: The server is up. + content: + application/json: + schema: + type: object + additionalProperties: false + required: [status] + properties: + status: {type: string, enum: [ok]} + + /openapi.yaml: + get: + tags: [System] + operationId: getOpenAPI + summary: This document + responses: + '200': + description: The OpenAPI description of the API. + content: + application/yaml: + schema: {type: string} + + /auth/register: + post: + tags: [Auth] + operationId: register + summary: Create the first user + description: | + Only works while no user exists. The new user is the admin. Afterwards registration is + closed and admins create accounts with `POST /users`. + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/Credentials'} + responses: + '201': + description: The admin account. + content: + application/json: + schema: {$ref: '#/components/schemas/User'} + '400': {$ref: '#/components/responses/InvalidInput'} + '403': + description: A user already exists (`registration_closed`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + '409': + description: The username is taken (`username_taken`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /auth/login: + post: + tags: [Auth] + operationId: login + summary: Open a session + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/Credentials'} + responses: + '200': + description: A new session. + content: + application/json: + schema: {$ref: '#/components/schemas/Session'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': + description: Wrong username or password (`invalid_credentials`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /auth/refresh: + post: + tags: [Auth] + operationId: refresh + summary: Renew a session + description: | + Exchanges a refresh token for a new access token and a new refresh token. The old refresh + token stops working. Presenting a spent one again, more than ten seconds after it was used, + ends every session of that user; inside those ten seconds it only fails, so two tabs + refreshing together do not log each other out. + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/RefreshRequest'} + responses: + '200': + description: A new session. + content: + application/json: + schema: {$ref: '#/components/schemas/Session'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': + description: The refresh token is unknown, expired or already used (`invalid_refresh_token`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /auth/logout: + post: + tags: [Auth] + operationId: logout + summary: End a session + description: Revokes one refresh token. Always answers 204, so it never reveals whether the token existed. + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/RefreshRequest'} + responses: + '204': {description: Done.} + '400': {$ref: '#/components/responses/InvalidInput'} + + /auth/me: + get: + tags: [Auth] + operationId: getMe + summary: The signed-in account + security: [{bearerAuth: []}] + responses: + '200': + description: Your account. + content: + application/json: + schema: {$ref: '#/components/schemas/User'} + '401': {$ref: '#/components/responses/Unauthorized'} + + /auth/password: + post: + tags: [Auth] + operationId: changePassword + summary: Change your password + description: "Signs you out everywhere: every refresh token of the account is revoked." + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/PasswordChange'} + responses: + '204': {description: Password changed.} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': + description: The current password is wrong (`invalid_credentials`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /users: + get: + tags: [Users] + operationId: listUsers + summary: List users + description: Admin only. + security: [{bearerAuth: []}] + responses: + '200': + description: Every account, oldest first. + content: + application/json: + schema: + type: object + additionalProperties: false + required: [users] + properties: + users: + type: array + items: {$ref: '#/components/schemas/User'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + post: + tags: [Users] + operationId: createUser + summary: Create a user + description: Admin only. + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/CreateUser'} + responses: + '201': + description: The new account. + content: + application/json: + schema: {$ref: '#/components/schemas/User'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '409': + description: The username is taken (`username_taken`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /users/{id}: + parameters: + - {$ref: '#/components/parameters/Id'} + patch: + tags: [Users] + operationId: updateUser + summary: Grant or remove the admin role + description: Admin only. The last admin cannot be demoted. + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [is_admin] + properties: + is_admin: {type: boolean} + responses: + '200': + description: The updated account. + content: + application/json: + schema: {$ref: '#/components/schemas/User'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': + description: No such user (`user_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + '409': + description: This is the last admin (`last_admin`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + delete: + tags: [Users] + operationId: deleteUser + summary: Delete a user + description: Admin only. Removes the account and its sessions. The last admin cannot be deleted. + security: [{bearerAuth: []}] + responses: + '204': {description: Deleted.} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': + description: No such user (`user_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + '409': + description: This is the last admin (`last_admin`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /users/{id}/password: + parameters: + - {$ref: '#/components/parameters/Id'} + put: + tags: [Users] + operationId: resetUserPassword + summary: Reset a user's password + description: Admin only. Signs that user out everywhere. + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [password] + properties: + password: {type: string, format: password, minLength: 8, maxLength: 256} + responses: + '204': {description: Password reset.} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': + description: No such user (`user_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /libraries: + get: + tags: [Libraries] + operationId: listLibraries + summary: List libraries + description: Admin only. + security: [{bearerAuth: []}] + responses: + '200': + description: Every library, oldest first. + content: + application/json: + schema: + type: object + additionalProperties: false + required: [libraries] + properties: + libraries: + type: array + items: {$ref: '#/components/schemas/Library'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + post: + tags: [Libraries] + operationId: createLibrary + summary: Add a library + description: | + Admin only. The path must be an absolute, existing directory, never the filesystem root, + and never inside or around another library. Names are unique ignoring case. + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/NewLibrary'} + responses: + '201': + description: The new library. + content: + application/json: + schema: {$ref: '#/components/schemas/Library'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '409': + description: Another library has this name or path (`library_exists`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /libraries/{id}: + parameters: + - {$ref: '#/components/parameters/Id'} + patch: + tags: [Libraries] + operationId: updateLibrary + summary: Rename or move a library + description: | + Admin only. Send `name`, `path` or both. Files keep their identity when the path changes. + Changing the path is refused while a scan runs. + security: [{bearerAuth: []}] + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/LibraryUpdate'} + responses: + '200': + description: The updated library. + content: + application/json: + schema: {$ref: '#/components/schemas/Library'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': {$ref: '#/components/responses/LibraryNotFound'} + '409': + description: The name or path is used by another library (`library_exists`), or a scan is running (`scan_running`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + delete: + tags: [Libraries] + operationId: deleteLibrary + summary: Remove a library + description: | + Admin only. Removes the library and its index entries. Tracks and listening history stay; + the music on disk is never touched. Refused while a scan runs. + security: [{bearerAuth: []}] + responses: + '204': {description: Removed.} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': {$ref: '#/components/responses/LibraryNotFound'} + '409': + description: A scan is running (`scan_running`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /libraries/{id}/scan: + parameters: + - {$ref: '#/components/parameters/Id'} + post: + tags: [Scan] + operationId: scanLibrary + summary: Scan one library + description: Admin only. Starts a scan in the background; follow it with `GET /library/scan`. + security: [{bearerAuth: []}] + responses: + '202': {$ref: '#/components/responses/ScanStarted'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '404': {$ref: '#/components/responses/LibraryNotFound'} + '409': + description: A scan is already running (`scan_running`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /library/scan: + get: + tags: [Scan] + operationId: getScanStatus + summary: Scan status + description: Whether a scan is running and how the last one ended. + security: [{bearerAuth: []}] + responses: + '200': + description: The current state. + content: + application/json: + schema: {$ref: '#/components/schemas/ScanStatus'} + '401': {$ref: '#/components/responses/Unauthorized'} + post: + tags: [Scan] + operationId: scanAll + summary: Scan every library + description: | + Admin only. Starts a scan in the background. Only MP3 and FLAC files are read; other audio + formats are counted as `unsupported`. Housekeeping folders of NAS boxes (`@Recycle`, + `#recycle`, `@eaDir`, `.@__thumb`, `$RECYCLE.BIN`) are skipped. + security: [{bearerAuth: []}] + responses: + '202': {$ref: '#/components/responses/ScanStarted'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/AdminRequired'} + '409': + description: A scan is already running (`scan_running`), or there is no library yet (`no_libraries`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /artists: + get: + tags: [Catalog] + operationId: listArtists + summary: List artists + description: | + Artists credited on a playable track, or that are the album artist of an album with one. + Sorted by name. + security: [{bearerAuth: []}] + parameters: + - {$ref: '#/components/parameters/Q'} + - {$ref: '#/components/parameters/Limit'} + - {$ref: '#/components/parameters/Offset'} + - {$ref: '#/components/parameters/LibraryId'} + responses: + '200': + description: A page of artists. + content: + application/json: + schema: {$ref: '#/components/schemas/ArtistPage'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + + /artists/{id}: + parameters: + - {$ref: '#/components/parameters/Id'} + get: + tags: [Catalog] + operationId: getArtist + summary: One artist + security: [{bearerAuth: []}] + responses: + '200': + description: The artist. + content: + application/json: + schema: {$ref: '#/components/schemas/Artist'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '404': + description: No such artist, or nothing of it can be played (`artist_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /albums: + get: + tags: [Catalog] + operationId: listAlbums + summary: List albums + description: | + Albums with a playable track, sorted by title. `artist_id` matches the albums an artist + owns plus those where it is credited on a playable track, the same set as its `album_count`. + security: [{bearerAuth: []}] + parameters: + - {$ref: '#/components/parameters/Q'} + - {$ref: '#/components/parameters/Limit'} + - {$ref: '#/components/parameters/Offset'} + - {$ref: '#/components/parameters/LibraryId'} + - {$ref: '#/components/parameters/ArtistId'} + responses: + '200': + description: A page of albums. + content: + application/json: + schema: {$ref: '#/components/schemas/AlbumPage'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + + /albums/{id}: + parameters: + - {$ref: '#/components/parameters/Id'} + get: + tags: [Catalog] + operationId: getAlbum + summary: One album + security: [{bearerAuth: []}] + responses: + '200': + description: The album. + content: + application/json: + schema: {$ref: '#/components/schemas/Album'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '404': + description: No such album, or nothing of it can be played (`album_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /tracks: + get: + tags: [Catalog] + operationId: listTracks + summary: List tracks + description: | + Tracks with at least one file that is not flagged missing; a track with several files + appears once. Grouped by album, then disc and track number. + security: [{bearerAuth: []}] + parameters: + - {$ref: '#/components/parameters/Q'} + - {$ref: '#/components/parameters/Limit'} + - {$ref: '#/components/parameters/Offset'} + - {$ref: '#/components/parameters/LibraryId'} + - {$ref: '#/components/parameters/ArtistId'} + - {$ref: '#/components/parameters/AlbumId'} + responses: + '200': + description: A page of tracks. + content: + application/json: + schema: {$ref: '#/components/schemas/TrackPage'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + + /tracks/{id}: + parameters: + - {$ref: '#/components/parameters/Id'} + get: + tags: [Catalog] + operationId: getTrack + summary: One track + security: [{bearerAuth: []}] + responses: + '200': + description: The track. + content: + application/json: + schema: {$ref: '#/components/schemas/Track'} + '400': {$ref: '#/components/responses/InvalidInput'} + '401': {$ref: '#/components/responses/Unauthorized'} + '404': + description: No such track, or it has no playable file (`track_not_found`). + content: + application/json: + schema: {$ref: '#/components/schemas/Error'} + + /tracks/{id}/stream: + parameters: + - {$ref: '#/components/parameters/Id'} + get: + tags: [Playback] + operationId: streamTrack + summary: Stream a track + description: | + Serves the original audio file. Supports `Range` requests, so players can seek, and + conditional requests. Streaming never records a listen; report one with `POST /listens`. + + An `