sonda/internal/api/http/docs.go
tgiachi 2ae4aedac0 fix(api): make the spec say what the code does, and make the tests prove it
- fix(spec): album.artist and track.album are real nullable objects (OpenAPI
  3.0 only honours nullable next to a type); the stream documents 304 on HEAD,
  412, If-Unmodified-Since and multipart/byteranges answers
- fix(spec): passwords and idempotency keys are measured in bytes, an overlap
  between libraries is a 400, a library PATCH needs a name or a path, limit 0
  means the default, login has no format rules of its own, and the wording about
  signing out says that issued access tokens live until they expire
- fix(auth): the Bearer scheme is matched ignoring case (RFC 7235)
- fix(listening): a listen with the access token of a deleted account is a 401
  instead of a database error
- fix(docs): the docs pages answer HEAD and carry X-Frame-Options, a CSP
  frame-ancestors, nosniff and no-referrer, since people paste their token there
- test: error codes are asserted in every error case; every accepted request is
  validated against the spec too; HEAD and 3xx answers are checked by hand
  because the validator skips them; the stream Content-Type must be one the
  spec lists; a scan held mid-way proves the scan_running conflicts; null album
  and null album artist, a vanished file, multi-range, 412 and HEAD 304 are
  exercised. Verified by breaking the code and the spec on purpose
2026-11-11 14:46:28 +01:00

40 lines
1.3 KiB
Go

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 := gin.WrapH(v5emb.New("Sonda API", specPath, docsPath))
r.GET("/api/docs", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, docsPath) })
r.GET("/api/docs/*any", docsHeaders, ui)
r.HEAD("/api/docs/*any", docsHeaders, ui)
}
// docsHeaders protects the page where people paste their token: it cannot be
// framed by another site, and the browser must not guess content types.
func docsHeaders(c *gin.Context) {
h := c.Writer.Header()
h.Set("X-Frame-Options", "DENY")
h.Set("Content-Security-Policy", "frame-ancestors 'none'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
}