sonda/internal/api/http/docs_test.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

238 lines
6.9 KiB
Go

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)
}
}
}
func TestDocsPageIsHardenedAndAnswersHead(t *testing.T) {
h := newTestAPI(t)
page := fetch(h, "/api/docs/")
for header, want := range map[string]string{
"X-Frame-Options": "DENY",
"Content-Security-Policy": "frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
} {
if got := page.Header().Get(header); got != want {
t.Errorf("%s = %q, want %q", header, got, want)
}
}
// The assets carry the same protection.
if got := fetch(h, "/api/docs/swagger-ui.css").Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Errorf("asset X-Content-Type-Options = %q", got)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("HEAD", "/api/docs/", nil))
if rec.Code != http.StatusOK {
t.Errorf("HEAD /api/docs/: %d", rec.Code)
}
}