From b0e7bdb87dba2658f90bf31566080ae5c53d157c Mon Sep 17 00:00:00 2001 From: hsinhoyeh Date: Mon, 17 Aug 2026 18:07:36 +0800 Subject: [PATCH] fix(swagger): the API doc served Swagger's demo API, not ours swagger-ui-dist ships a swagger-initializer.js whose spec URL is Swagger's public petstore demo, with a comment saying the line "will be replaced by docker/configurator, when it runs in a docker-container". We embed the assets rather than running that container, so nothing ever replaced it. The result: /swaggerui/ has always served somebody else's API. On an internal-only deployment - ubm01, where this was found - the browser cannot even reach that host, so the page renders an error instead. Two things had to be right, and neither can be known by this process: THE SPEC URL. Absolute paths break under a path prefix. A gateway that routes /reststore/ to us REWRITES THE PREFIX AWAY before the request arrives, so by the time any Go handler sees it the path is /swaggerui/ and the prefix is gone. The browser is the only party that still knows where the page came from, so the initializer derives it from window.location and asks for the spec relative to that. THE REQUEST BASE. The spec declares neither host nor basePath, so swagger-ui builds calls as origin + the path as written - https://host/v1/projects/... - which behind a prefix misses by exactly the prefix and 404s every "Try it out". Writing a basePath into the spec would bake one deployment's layout into an artifact all of them share, so a requestInterceptor re-adds the real mount instead. Overriding one file, not vendoring the directory: the bundles and CSS still come from the agent's embed, so there is no second copy to drift. The tests assert the failure, not the plumbing. A "200 OK" test would have passed throughout - the wrong file was being served perfectly well. One greps for the demo host by name, which is why the initializer's own comment must not mention it. pkg/storage/projects fails locally without a postgres on 5432; that is environmental and predates this. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01BSzNfcVc1FnDCfk9AF68Eh --- pkg/server/swagger.go | 47 +++++++++++- pkg/server/swagger_test.go | 84 +++++++++++++++++++++ pkg/server/swaggerui/swagger-initializer.js | 49 ++++++++++++ 3 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 pkg/server/swagger_test.go create mode 100644 pkg/server/swaggerui/swagger-initializer.js diff --git a/pkg/server/swagger.go b/pkg/server/swagger.go index f396be5..250d173 100644 --- a/pkg/server/swagger.go +++ b/pkg/server/swagger.go @@ -1,6 +1,10 @@ package server import ( + "embed" + "net/http" + "strings" + grpchttpgatewayserver "github.com/sdinsure/agent/pkg/grpc/server/httpgateway" api "github.com/footprintai/restcol/api" @@ -10,9 +14,50 @@ type GatewayRouteAdder interface { AddGatewayRoutes(routes ...*grpchttpgatewayserver.Route) error } +// Only the initializer. The rest of swagger-ui-dist - the bundles, the CSS, the +// fonts, several megabytes of it - stays in the agent's embed, because we have +// no reason to carry a second copy and every reason not to let the two drift. +// +//go:embed swaggerui/swagger-initializer.js +var initializerAssets embed.FS + +const initializerPath = "swagger-initializer.js" + +// swaggerUIHandler serves the agent's swagger-ui assets, with one file +// replaced. +// +// The agent embeds swagger-ui-dist verbatim, and dist's swagger-initializer.js +// points at https://petstore.swagger.io/v2/swagger.json. Its own comment says +// the line "will be replaced by docker/configurator, when it runs in a +// docker-container" - we embed the assets rather than running that container, +// so nothing replaced it, and every deployment has been serving Swagger's demo +// API where ours should be. +// +// Overriding one file rather than vendoring the whole directory keeps the fix +// the size of the defect. +func swaggerUIHandler() http.Handler { + assets := http.FileServer(http.FS(initializerAssets)) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/"+initializerPath) || + strings.TrimPrefix(r.URL.Path, "/") == initializerPath { + // http.FS serves from the embed root, where the file lives under + // swaggerui/. Ask for it by that name rather than by whatever + // prefix the request arrived on. + r2 := r.Clone(r.Context()) + r2.URL.Path = "/swaggerui/" + initializerPath + assets.ServeHTTP(w, r2) + return + } + grpchttpgatewayserver.NewSwaggerRoute().Handler.ServeHTTP(w, r) + }) +} + func AddSwaggerRoutes(s GatewayRouteAdder) error { return s.AddGatewayRoutes( - grpchttpgatewayserver.NewSwaggerRoute(), + &grpchttpgatewayserver.Route{ + Pattern: "/swaggerui/", + Handler: swaggerUIHandler(), + }, grpchttpgatewayserver.NewOpenAPIV2Route("/openapiv2/", api.OpenApiV2HttpHandler), ) } diff --git a/pkg/server/swagger_test.go b/pkg/server/swagger_test.go new file mode 100644 index 0000000..909ba26 --- /dev/null +++ b/pkg/server/swagger_test.go @@ -0,0 +1,84 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// The defect: swagger-ui-dist ships an initializer pointing at Swagger's demo +// API, and we embed the assets rather than running the configurator container +// that is supposed to rewrite it. A test that only asserted "200 OK" would +// have passed throughout - the wrong file was being served perfectly well. +func TestInitializerDoesNotServeThePetstoreDemo(t *testing.T) { + rr := httptest.NewRecorder() + swaggerUIHandler().ServeHTTP(rr, httptest.NewRequest( + http.MethodGet, "/swaggerui/swagger-initializer.js", nil)) + + if rr.Code != http.StatusOK { + t.Fatalf("initializer: got %d, want 200", rr.Code) + } + body := rr.Body.String() + if strings.Contains(body, "petstore.swagger.io") { + t.Error("still serving the swagger-ui-dist default, which points at " + + "petstore.swagger.io - the whole point of overriding this file") + } + if !strings.Contains(body, "openapiv2/restcol.swagger.json") { + t.Error("initializer does not load restcol's own spec") + } +} + +// The URL has to be built from the page's location, not hardcoded. A deployment +// mounted at /reststore/ and one mounted at / are served the SAME file, and the +// server cannot tell them apart - the gateway strips the prefix before any Go +// handler sees the request. +func TestInitializerResolvesTheSpecRelativeToItsMount(t *testing.T) { + rr := httptest.NewRecorder() + swaggerUIHandler().ServeHTTP(rr, httptest.NewRequest( + http.MethodGet, "/swaggerui/swagger-initializer.js", nil)) + body := rr.Body.String() + + if !strings.Contains(body, "window.location.pathname") { + t.Error("the spec URL is not derived from the page location, so it " + + "cannot be correct under both / and /reststore/") + } + // Without this, every "Try it out" goes to origin + /v1/... and misses by + // exactly the prefix. + if !strings.Contains(body, "requestInterceptor") { + t.Error("no requestInterceptor: the spec declares no basePath, so " + + "requests will not carry the mount prefix") + } +} + +// Everything except the one overridden file must still come from the agent's +// embed - the bundles, the CSS, the page itself. Getting this wrong would 404 +// the whole UI while the initializer test above still passed. +// +// Not /swaggerui/index.html: http.FileServer canonicalises that to ./ with a +// 301, which is correct behaviour and would make this assert the wrong thing. +func TestOtherAssetsStillComeFromTheAgent(t *testing.T) { + for _, path := range []string{ + "/swaggerui/", + "/swaggerui/swagger-ui-bundle.js", + "/swaggerui/swagger-ui.css", + } { + rr := httptest.NewRecorder() + swaggerUIHandler().ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil)) + if rr.Code != http.StatusOK { + t.Errorf("%s: got %d, want 200 - the UI is not being served", path, rr.Code) + } + } +} + +// The page has to reference the initializer for the override to matter at all. +// If a future swagger-ui-dist inlines its config instead, this fix becomes a +// no-op and everything above still passes. +func TestThePageActuallyLoadsTheInitializer(t *testing.T) { + rr := httptest.NewRecorder() + swaggerUIHandler().ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/swaggerui/", nil)) + if !strings.Contains(rr.Body.String(), "swagger-initializer.js") { + t.Error("index.html does not load swagger-initializer.js, so overriding " + + "that file configures nothing") + } +} diff --git a/pkg/server/swaggerui/swagger-initializer.js b/pkg/server/swaggerui/swagger-initializer.js new file mode 100644 index 0000000..fd71233 --- /dev/null +++ b/pkg/server/swaggerui/swagger-initializer.js @@ -0,0 +1,49 @@ +// Replaces the swagger-ui-dist default, which ships pointing at Swagger's own +// public demo API and carries a comment saying the line "will be replaced by +// docker/configurator, when it runs in a docker-container". We embed the assets +// instead of running that container, so nothing ever replaced it: every +// deployment served the demo API in place of ours, and on an air-gapped or +// internal-only site it could not even fetch that, so the page rendered an +// error. +// +// The test for this file greps for the demo host by name, so do not write it +// here - not even in a comment. +// +// Everything here is computed IN THE BROWSER, from the URL the page was served +// on. That is deliberate. The server cannot know where it is mounted: a gateway +// that routes /reststore/ to us rewrites the prefix away before the request +// arrives, so by the time any Go handler sees it the path is /swaggerui/ and +// the prefix is gone. The browser is the only party that still knows. +window.onload = function () { + // "/reststore/" behind a path-prefix gateway, "/" when run directly. + const mount = window.location.pathname.replace(/swaggerui\/.*$/, ""); + + window.ui = SwaggerUIBundle({ + // Relative to the mount, so this file needs no knowledge of the prefix. + url: mount + "openapiv2/restcol.swagger.json", + dom_id: "#swagger-ui", + deepLinking: true, + presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset], + plugins: [SwaggerUIBundle.plugins.DownloadUrl], + layout: "StandaloneLayout", + + // The spec declares neither `host` nor `basePath`, so swagger-ui builds + // request URLs as origin + the path as written - https://host/v1/projects/… + // - which behind a prefix misses by exactly the prefix and 404s every + // "Try it out". Putting a basePath in the spec would hardcode one + // deployment's layout into an artifact shared by all of them, so the fix + // belongs here, where the real mount point is known. + requestInterceptor: function (req) { + if (mount === "/" || !mount) { + return req; + } + const prefix = mount.replace(/\/$/, ""); + const u = new URL(req.url, window.location.origin); + if (u.origin === window.location.origin && !u.pathname.startsWith(prefix + "/")) { + u.pathname = prefix + u.pathname; + req.url = u.toString(); + } + return req; + }, + }); +};