sonda/internal/api/http/docs_test.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +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"
"git.kmalloc.org/squid/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)
}
}