Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion pkg/server/swagger.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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),
)
}
84 changes: 84 additions & 0 deletions pkg/server/swagger_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
49 changes: 49 additions & 0 deletions pkg/server/swaggerui/swagger-initializer.js
Original file line number Diff line number Diff line change
@@ -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;
},
});
};
Loading