Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(server): restore immutable cache and gzip on /assets/* [BYT-9339] (#20117)

h3n4l5a6008bd5b4f
diff --git a/backend/server/server_frontend_embed.go b/backend/server/server_frontend_embed.go
index 8735c7b40b..4c581e26c2 100644
--- a/backend/server/server_frontend_embed.go
+++ b/backend/server/server_frontend_embed.go
@@ -10,9 +10,6 @@ import (
"sync"
"github.com/labstack/echo/v5"
- "github.com/labstack/echo/v5/middleware"
-
- "github.com/bytebase/bytebase/backend/common"
)
//go:embed dist/assets/*
@@ -74,37 +71,5 @@ func getFileSystem(path string) fs.FS {
}
func embedFrontend(e *echo.Echo) {
- // Use echo static middleware to serve the built dist folder
- // refer: https://github.com/labstack/echo/blob/master/middleware/static.go
- e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
- Skipper: defaultAPIRequestSkipper,
- HTML5: true,
- Filesystem: getFileSystem("dist"),
- }))
-
- g := e.Group("assets")
- // Use echo gzip middleware to compress the response.
- // refer: https://echo.labstack.com/docs/middleware/gzip
- g.Use(middleware.GzipWithConfig(middleware.GzipConfig{
- Skipper: defaultAPIRequestSkipper,
- Level: 5,
- }))
-
- g.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
- return func(c *echo.Context) error {
- c.Response().Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
- return next(c)
- }
- })
- g.Use(middleware.StaticWithConfig(middleware.StaticConfig{
- Skipper: defaultAPIRequestSkipper,
- HTML5: true,
- Filesystem: getFileSystem("dist/assets"),
- }))
-}
-
-// defaultAPIRequestSkipper is echo skipper for api requests.
-func defaultAPIRequestSkipper(c *echo.Context) bool {
- path := c.Request().URL.Path
- return common.HasPrefixes(path, "/api", "/v1", "/.well-known", webhookAPIPrefix)
+ registerFrontendRoutes(e, getFileSystem("dist"))
}
diff --git a/backend/server/server_frontend_routes.go b/backend/server/server_frontend_routes.go
new file mode 100644
index 0000000000..ecc9b4fb46
--- /dev/null
+++ b/backend/server/server_frontend_routes.go
@@ -0,0 +1,70 @@
+package server
+
+import (
+ "io/fs"
+ "net/http"
+ "net/url"
+ "path"
+ "strings"
+
+ "github.com/labstack/echo/v5"
+ "github.com/labstack/echo/v5/middleware"
+
+ "github.com/bytebase/bytebase/backend/common"
+)
+
+// registerFrontendRoutes wires up static file serving for the embedded frontend
+// against the given filesystem (typically the embedded dist tree). It is extracted
+// from embedFrontend so the behavior can be exercised in tests with an in-memory fs.FS.
+//
+// Layout:
+// - Global static middleware serves the SPA shell (index.html) with HTML5 fallback
+// for client-side routes, but skips /assets/* so the dedicated route below wins.
+// - /assets/* is served by a real route that returns a true 404 for missing files
+// (no HTML5 fallback) and attaches long-cache + gzip middleware.
+func registerFrontendRoutes(e *echo.Echo, distFS fs.FS) {
+ e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
+ Skipper: func(c *echo.Context) bool {
+ return defaultAPIRequestSkipper(c) || strings.HasPrefix(c.Request().URL.Path, "/assets/")
+ },
+ HTML5: true,
+ Filesystem: distFS,
+ }))
+
+ assetsFS, err := fs.Sub(distFS, "assets")
+ if err != nil {
+ panic(err)
+ }
+ cacheImmutable := func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c *echo.Context) error {
+ // Only mark an asset immutable once we've confirmed it exists. In an HA
+ // rolling deploy, an older replica can 404 a new hashed asset briefly;
+ // we must not let browsers or CDNs cache "does not exist" for a year.
+ p := c.Param("*")
+ if unescaped, err := url.PathUnescape(p); err == nil {
+ p = unescaped
+ }
+ name := path.Clean(strings.TrimPrefix(p, "/"))
+ if info, err := fs.Stat(assetsFS, name); err == nil && !info.IsDir() {
+ c.Response().Header().Set(echo.HeaderCacheControl, "public, max-age=31536000, immutable")
+ }
+ return next(c)
+ }
+ }
+ // Register GET + HEAD so the dedicated asset route matches HEAD requests too
+ // (curl -I, CDN health checks, cache revalidation). Before this fix, the global
+ // StaticWithConfig middleware served any method; a GET-only route would 405 on HEAD.
+ e.Match([]string{http.MethodGet, http.MethodHead}, "/assets/*",
+ echo.StaticDirectoryHandler(assetsFS, false),
+ middleware.GzipWithConfig(middleware.GzipConfig{Level: 5}),
+ cacheImmutable,
+ )
+}
+
+// defaultAPIRequestSkipper is echo skipper for api requests. /bytebase.v1 covers
+// Connect-go gRPC handlers so unknown gRPC paths return a structured 404 instead
+// of falling through to the SPA's HTML5 fallback (which would return index.html).
+func defaultAPIRequestSkipper(c *echo.Context) bool {
+ path := c.Request().URL.Path
+ return common.HasPrefixes(path, "/api", "/v1", "/bytebase.v1", "/.well-known", webhookAPIPrefix)
+}
diff --git a/backend/server/server_frontend_routes_test.go b/backend/server/server_frontend_routes_test.go
new file mode 100644
index 0000000000..d72aca8c23
--- /dev/null
+++ b/backend/server/server_frontend_routes_test.go
@@ -0,0 +1,153 @@
+package server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "testing/fstest"
+
+ "github.com/labstack/echo/v5"
+)
+
+func newFrontendTestFS() fstest.MapFS {
+ return fstest.MapFS{
+ "index.html": &fstest.MapFile{Data: []byte("<!doctype html><html>APP</html>")},
+ "assets/app-1234.js": &fstest.MapFile{Data: []byte("console.log('hi')")},
+ }
+}
+
+func TestRegisterFrontendRoutes_AssetCacheHeaders(t *testing.T) {
+ const wantImmutable = "public, max-age=31536000, immutable"
+ cases := []struct {
+ name string
+ path string
+ wantStatus int
+ wantCacheCtrl string // "" = asserts no Cache-Control header
+ wantBodyContains string
+ bodyMustNotBe string
+ }{
+ {
+ name: "real asset gets immutable cache",
+ path: "/assets/app-1234.js",
+ wantStatus: http.StatusOK,
+ wantCacheCtrl: wantImmutable,
+ },
+ {
+ // 404 must NOT carry the immutable Cache-Control header. In an HA
+ // rolling deploy, an older replica can 404 a new hashed asset briefly;
+ // browsers/CDNs caching that 404 for a year would wedge users on a
+ // broken app long after the deploy completes.
+ name: "missing asset returns 404 with no immutable cache",
+ path: "/assets/this-does-not-exist.js",
+ wantStatus: http.StatusNotFound,
+ wantCacheCtrl: "",
+ bodyMustNotBe: "<!doctype html",
+ },
+ {
+ name: "spa route falls back to index.html with no immutable",
+ path: "/projects/foo",
+ wantStatus: http.StatusOK,
+ wantCacheCtrl: "",
+ wantBodyContains: "APP",
+ },
+ {
+ name: "root serves index.html",
+ path: "/",
+ wantStatus: http.StatusOK,
+ wantCacheCtrl: "",
+ wantBodyContains: "APP",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ e := echo.New()
+ registerFrontendRoutes(e, newFrontendTestFS())
+
+ req := httptest.NewRequest(http.MethodGet, tc.path, nil)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+
+ if rec.Code != tc.wantStatus {
+ t.Fatalf("status = %d, want %d; body=%q", rec.Code, tc.wantStatus, rec.Body.String())
+ }
+ if got := rec.Header().Get(echo.HeaderCacheControl); got != tc.wantCacheCtrl {
+ t.Errorf("Cache-Control = %q, want %q", got, tc.wantCacheCtrl)
+ }
+ body := rec.Body.String()
+ if tc.wantBodyContains != "" && !strings.Contains(body, tc.wantBodyContains) {
+ t.Errorf("body = %q, want to contain %q", body, tc.wantBodyContains)
+ }
+ if tc.bodyMustNotBe != "" && strings.Contains(strings.ToLower(body), tc.bodyMustNotBe) {
+ t.Errorf("body should not contain %q (HTML5 fallback regression): %q", tc.bodyMustNotBe, body)
+ }
+ })
+ }
+}
+
+func TestRegisterFrontendRoutes_AssetHeadRequest(t *testing.T) {
+ e := echo.New()
+ registerFrontendRoutes(e, newFrontendTestFS())
+
+ req := httptest.NewRequest(http.MethodHead, "/assets/app-1234.js", nil)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("HEAD /assets/app-1234.js status = %d, want 200; body=%q", rec.Code, rec.Body.String())
+ }
+ if got, want := rec.Header().Get(echo.HeaderCacheControl), "public, max-age=31536000, immutable"; got != want {
+ t.Errorf("Cache-Control = %q, want %q", got, want)
+ }
+}
+
+func TestDefaultAPIRequestSkipper(t *testing.T) {
+ cases := map[string]bool{
+ // API-ish prefixes that must be skipped (fall through to registered handlers).
+ "/api/v1/login": true,
+ "/v1/projects": true,
+ "/v1:adminExecute": true,
+ "/bytebase.v1.AuthService/Login": true,
+ "/bytebase.v1.ProjectService/GetProject": true,
+ "/.well-known/oauth-authorization-server": true,
+ "/hook/gitlab": true,
+ // Paths that must NOT be skipped (they're meant for the static handler).
+ "/assets/main-abc.js": false,
+ "/projects/foo": false,
+ "/": false,
+ }
+ for reqPath, want := range cases {
+ t.Run(reqPath, func(t *testing.T) {
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodGet, reqPath, nil)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+ if got := defaultAPIRequestSkipper(c); got != want {
+ t.Errorf("defaultAPIRequestSkipper(%q) = %v, want %v", reqPath, got, want)
+ }
+ })
+ }
+}
+
+func TestRegisterFrontendRoutes_AssetGzip(t *testing.T) {
+ body := strings.Repeat("console.log('hello gzip');\n", 100)
+ distFS := fstest.MapFS{
+ "index.html": &fstest.MapFile{Data: []byte("<!doctype html>")},
+ "assets/big-1234.js": &fstest.MapFile{Data: []byte(body)},
+ }
+ e := echo.New()
+ registerFrontendRoutes(e, distFS)
+
+ req := httptest.NewRequest(http.MethodGet, "/assets/big-1234.js", nil)
+ req.Header.Set(echo.HeaderAcceptEncoding, "gzip")
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%q", rec.Code, rec.Body.String())
+ }
+ if got := rec.Header().Get(echo.HeaderContentEncoding); got != "gzip" {
+ t.Errorf("Content-Encoding = %q, want gzip", got)
+ }
+}