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

213 lines
6.1 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)
}
}
}