From 11d25f9f7db303c74a21dc79e46d36d38a0a1663 Mon Sep 17 00:00:00 2001 From: n30nex Date: Tue, 17 Nov 2026 17:31:33 -0500 Subject: [PATCH] docs(api): describe configured areas and geometry (#2401) Partial fix for #1670. Document the two public area configuration endpoints with reusable array response schemas. The descriptions distinguish labeled summaries from geometry entries, specify latitude/longitude order, and explain omitted fields and preserved zero bounds. Known route-description gaps decrease from 15 to 13. This changes generated API metadata only. Handler behavior, authentication, configuration and packet processing are unchanged; no new customizer settings or dependencies. Validation: - Tests-only RED `8f27f8ff0` builds and [fails the intended documentation assertions](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43828097551/job/133166654496). - GREEN `5966b8021` passes the byte-unchanged tests; [final CI passes](https://github.com/Kpa-clawbot/CoreScope/actions/runs/43830879045). - Handler fixtures cover absent/empty config, labeled/unlabeled and underscore keys, whitespace labels, normal/short/empty polygons, partial bounds and zero values without assuming entry order. - All 26 focused checks pass on final GREEN. Full native server/ingestor suites passed at `e19c49e26` (158.088s/160.279s); the final amendment only clarifies four descriptions, and final CI includes both suites. - Parent browser validation rendered both operations in Swagger UI and executed their actual public GETs, checking coordinate shape, omissions and zero values. - Three independent reviews completed with no remaining findings; parent read every report. The remaining 13 route-description gaps and broader parameter/schema work stay open under #1670. --------- Co-authored-by: n30nex <6686206+n30nex@users.noreply.github.com> --- cmd/server/openapi.go | 33 ++++++ cmd/server/openapi_areas_test.go | 184 +++++++++++++++++++++++++++++ cmd/server/openapi_known_gaps.json | 2 - 3 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 cmd/server/openapi_areas_test.go diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index a179e902..241b73d9 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -48,6 +48,8 @@ func routeDescriptions() map[string]routeMeta { "GET /api/config/theme": {Summary: "Get theme configuration", Description: "Returns color maps, CSS variables, and theme defaults.", Tag: "config"}, "GET /api/config/map": {Summary: "Get map configuration", Tag: "config"}, "GET /api/config/geo-filter": {Summary: "Get geo-filter configuration", Tag: "config"}, + "GET /api/config/areas": {Summary: "List configured areas", Description: "Returns an array of configured area keys and labels with a non-empty label. Labels are not trimmed and keys are not filtered by prefix. Returns an empty array when no entries qualify. Result order is unspecified. Public endpoint with no query parameters.", Tag: "config", Response: schemaRef("ConfigAreasResponse")}, + "GET /api/config/areas/polygons": {Summary: "Get configured area geometry", Description: "Returns an array of all configured areas, including unlabeled entries, with their raw polygon and bounding-box fields. Empty polygons and unset bounds are omitted; zero bounds are included. Each bound is independently optional, and polygons may coexist with bounds. Returns an empty array when no areas are configured. Result order is unspecified. Public endpoint with no query parameters.", Tag: "config", Response: schemaRef("ConfigAreaPolygonsResponse")}, // Admin / system "GET /api/health": {Summary: "Health check", Description: "Returns server health, uptime, and memory stats.", Tag: "admin"}, @@ -282,6 +284,8 @@ type openAPISchema struct { Nullable bool `json:"nullable,omitempty"` Enum []string `json:"enum,omitempty"` Items *openAPISchema `json:"items,omitempty"` + MinItems int `json:"minItems,omitempty"` + MaxItems int `json:"maxItems,omitempty"` Properties map[string]openAPISchema `json:"properties,omitempty"` Required []string `json:"required,omitempty"` AdditionalProperties *openAPISchema `json:"additionalProperties,omitempty"` @@ -314,6 +318,35 @@ func componentSchemas() map[string]interface{} { return m } return map[string]interface{}{ + "ConfigAreasResponse": openAPISchema{ + Type: "array", Items: &openAPISchema{ + Type: "object", Required: []string{"key", "label"}, + Properties: map[string]openAPISchema{ + "key": {Type: "string", Description: "Area configuration map key, preserved verbatim."}, + "label": {Type: "string", Description: "Non-empty configured display label, preserved verbatim."}, + }, + }, + }, + "ConfigAreaPolygonsResponse": openAPISchema{ + Type: "array", Items: &openAPISchema{ + Type: "object", Required: []string{"key", "label"}, + Properties: map[string]openAPISchema{ + "key": {Type: "string", Description: "Area configuration map key, preserved verbatim."}, + "label": {Type: "string", Description: "Configured display label; may be empty."}, + "polygon": { + Type: "array", MinItems: 1, Description: "Configured coordinates, unchanged; omitted when empty. The endpoint does not validate polygon geometry.", + Items: &openAPISchema{ + Type: "array", MinItems: 2, MaxItems: 2, Description: "[latitude, longitude] in degrees.", + Items: &openAPISchema{Type: "number"}, + }, + }, + "latMin": {Type: "number", Description: "Configured minimum latitude in degrees. Omitted when unset; included when set to zero."}, + "latMax": {Type: "number", Description: "Configured maximum latitude in degrees. Omitted when unset; included when set to zero."}, + "lonMin": {Type: "number", Description: "Configured minimum longitude in degrees. Omitted when unset; included when set to zero."}, + "lonMax": {Type: "number", Description: "Configured maximum longitude in degrees. Omitted when unset; included when set to zero."}, + }, + }, + }, "ReadinessResponse": openAPISchema{ Type: "object", Required: []string{"ready", "loadedTx", "loadedObs", "from_pubkey_backfill"}, Properties: map[string]openAPISchema{ diff --git a/cmd/server/openapi_areas_test.go b/cmd/server/openapi_areas_test.go new file mode 100644 index 00000000..32d00991 --- /dev/null +++ b/cmd/server/openapi_areas_test.go @@ -0,0 +1,184 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" +) + +// Inspect JSON served by /api/spec, independently of the production schema type. +func TestOpenAPIConfigAreasDocumentation(t *testing.T) { + spec := fetchSpec(t) + paths := asMap(t, spec["paths"], "paths") + schemas := asMap(t, asMap(t, spec["components"], "components")["schemas"], "schemas") + if spec["security"] != nil { + t.Fatal("area routes must not inherit a global authentication requirement") + } + for _, tc := range []struct { + path, schema string + geometry bool + terms []string + }{ + {"/api/config/areas", "ConfigAreasResponse", false, []string{"non-empty", "label"}}, + {"/api/config/areas/polygons", "ConfigAreaPolygonsResponse", true, []string{"unlabeled", "omitted", "zero"}}, + } { + t.Run(tc.path, func(t *testing.T) { + path := asMap(t, paths[tc.path], tc.path) + op := asMap(t, path["get"], "get") + if len(path) != 1 || op["summary"] == "" || op["summary"] == tc.path { + t.Errorf("expected a documented GET operation: %v", path) + } + if op["security"] != nil || !reflect.DeepEqual(op["tags"], []interface{}{"config"}) { + t.Errorf("expected a public config operation: %v", op) + } + if params, ok := op["parameters"]; ok && !reflect.DeepEqual(params, []interface{}{}) { + t.Errorf("area configuration endpoints have no parameters: %v", params) + } + description, _ := op["description"].(string) + for _, term := range append(tc.terms, "empty array", "order", "query parameters") { + if !strings.Contains(description, term) { + t.Errorf("description must explain %q: %q", term, description) + } + } + response := asMap(t, asMap(t, op["responses"], "responses")["200"], "200") + media := asMap(t, asMap(t, response["content"], "content")["application/json"], "JSON") + if asMap(t, media["schema"], "response schema")["$ref"] != "#/components/schemas/"+tc.schema { + t.Errorf("expected concrete %s response schema", tc.schema) + } + schema := asMap(t, schemas[tc.schema], tc.schema) + if schema["type"] != "array" || schema["nullable"] == true { + t.Errorf("expected a non-null array response: %v", schema) + } + item := asMap(t, schema["items"], "area entry") + props := asMap(t, item["properties"], "area properties") + required, _ := item["required"].([]interface{}) + if item["type"] != "object" || len(required) != 2 || !slices.Contains(required, interface{}("key")) || !slices.Contains(required, interface{}("label")) { + t.Errorf("area entry must require key and label: %v", item) + } + fields := map[string]string{"key": "string", "label": "string"} + if tc.geometry { + fields["polygon"] = "array" + for _, name := range []string{"latMin", "latMax", "lonMin", "lonMax"} { + fields[name] = "number" + } + } + if len(props) != len(fields) { + t.Errorf("unexpected area properties: %v", props) + } + for name, kind := range fields { + property := asMap(t, props[name], name) + if property["type"] != kind || property["nullable"] == true { + t.Errorf("wrong type or nullability for %s: %v", name, property) + } + } + if tc.geometry { + polygon := asMap(t, props["polygon"], "polygon") + if minimum, _ := polygon["minItems"].(float64); minimum > 1 { + t.Error("the geometry endpoint returns short configured polygons without validation") + } + pair := asMap(t, polygon["items"], "coordinate pair") + if pair["type"] != "array" || pair["minItems"] != float64(2) || pair["maxItems"] != float64(2) || asMap(t, pair["items"], "coordinate")["type"] != "number" { + t.Errorf("polygon coordinates must be pairs of exactly two numbers: %v", pair) + } + if desc, _ := pair["description"].(string); !strings.Contains(desc, "[latitude, longitude]") { + t.Errorf("coordinate order must be explicit: %q", desc) + } + } + if loadKnownGaps(t)[tc.path] { + t.Error("documented area route must leave the known-gap list") + } + }) + } +} + +func TestConfigAreasDocumentedResponses(t *testing.T) { + srv, router := setupTestServerWithAPIKey(t, "test-secret-key-strong-enough") + for _, tc := range []struct { + name, config, areas, polygons string + }{ + {"absent", `{}`, `{}`, `{}`}, + {"empty", `{"areas":{}}`, `{}`, `{}`}, + { + "configured", + `{"areas":{ + "polygon":{"label":"Polygon fixture","polygon":[[10,20],[11,20],[10,21]]}, + "box":{"label":"Box fixture","latMin":0,"latMax":2,"lonMin":0,"lonMax":3}, + "partial":{"label":"Partial fixture","latMax":0}, + "both":{"label":"Both fixture","polygon":[[10,20]],"lonMin":0}, + "unlabeled":{"label":"","polygon":[[1,2],[3,4]]}, + "_named":{"label":"Underscore fixture"}, + "_comment":{}, + "empty-polygon":{"label":"Empty polygon fixture","polygon":[]}, + "whitespace":{"label":" "} + }}`, + `{ + "polygon":{"key":"polygon","label":"Polygon fixture"}, + "box":{"key":"box","label":"Box fixture"}, + "partial":{"key":"partial","label":"Partial fixture"}, + "both":{"key":"both","label":"Both fixture"}, + "_named":{"key":"_named","label":"Underscore fixture"}, + "empty-polygon":{"key":"empty-polygon","label":"Empty polygon fixture"}, + "whitespace":{"key":"whitespace","label":" "} + }`, + `{ + "polygon":{"key":"polygon","label":"Polygon fixture","polygon":[[10,20],[11,20],[10,21]]}, + "box":{"key":"box","label":"Box fixture","latMin":0,"latMax":2,"lonMin":0,"lonMax":3}, + "partial":{"key":"partial","label":"Partial fixture","latMax":0}, + "both":{"key":"both","label":"Both fixture","polygon":[[10,20]],"lonMin":0}, + "unlabeled":{"key":"unlabeled","label":"","polygon":[[1,2],[3,4]]}, + "_named":{"key":"_named","label":"Underscore fixture"}, + "_comment":{"key":"_comment","label":""}, + "empty-polygon":{"key":"empty-polygon","label":"Empty polygon fixture"}, + "whitespace":{"key":"whitespace","label":" "} + }`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var cfg Config + if err := json.Unmarshal([]byte(tc.config), &cfg); err != nil { + t.Fatal(err) + } + srv.cfg.Areas = cfg.Areas + for _, endpoint := range []struct{ path, want string }{ + {"/api/config/areas", tc.areas}, + {"/api/config/areas/polygons", tc.polygons}, + } { + t.Run(endpoint.path, func(t *testing.T) { + // No credentials; unrelated query parameters must not filter config. + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, endpoint.path+"?area=unknown", nil)) + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/json" { + t.Fatalf("expected public JSON response, got %d %s: %s", w.Code, w.Header().Get("Content-Type"), w.Body.String()) + } + var rows []map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil { + t.Fatal(err) + } + if rows == nil { + t.Fatal("expected an array, not null") + } + // Map iteration order is not part of either endpoint's contract. + got := make(map[string]map[string]interface{}, len(rows)) + for _, row := range rows { + key, ok := row["key"].(string) + if !ok || got[key] != nil { + t.Fatalf("missing or duplicate key: %v", row) + } + got[key] = row + } + var want map[string]map[string]interface{} + if err := json.Unmarshal([]byte(endpoint.want), &want); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("response differs from the documented fields and omission rules:\ngot %v\nwant %v", got, want) + } + }) + } + }) + } +} diff --git a/cmd/server/openapi_known_gaps.json b/cmd/server/openapi_known_gaps.json index 98d6ad11..ed7b616c 100644 --- a/cmd/server/openapi_known_gaps.json +++ b/cmd/server/openapi_known_gaps.json @@ -6,8 +6,6 @@ "/api/admin/prune-geo-filter/status", "/api/analytics/relay-airtime-share", "/api/analytics/roles", - "/api/config/areas", - "/api/config/areas/polygons", "/api/docs", "/api/dropped-packets", "/api/nodes/{pubkey}/reach",