From d31705030261d6074359a996cf204647c66c29e8 Mon Sep 17 00:00:00 2001 From: Gage Krumbach Date: Sun, 15 Nov 2026 10:00:39 -0600 Subject: [PATCH] fix(bff): mark API responses no-store Every /api/v1 response now carries Cache-Control: no-store, set by a middleware on the API router before the handler runs. A cache in the deployment path could otherwise replay a list read after a write, which is how the workspace count stayed stale after a create (#129): the hooks invalidate and refetch the unfiltered list, and the gateway writes the workspace synchronously. The logs stream keeps its own "no-cache, no-transform"; static frontend assets are not affected. Fixes #129 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Gage Krumbach --- backend/pkg/server/app.go | 17 ++++ backend/pkg/server/cache_control_test.go | 78 +++++++++++++++++++ .../api/__tests__/workspace-create.spec.tsx | 62 +++++++++++++++ 3 files changed, 157 insertions(+) create mode 100644 backend/pkg/server/cache_control_test.go create mode 100644 frontend/src/api/__tests__/workspace-create.spec.tsx diff --git a/backend/pkg/server/app.go b/backend/pkg/server/app.go index 4c5aa63c..c9d31864 100644 --- a/backend/pkg/server/app.go +++ b/backend/pkg/server/app.go @@ -144,6 +144,8 @@ func (app *App) Routes() http.Handler { r.Use(chimiddleware.Recoverer) r.Route("/api/v1", func(r chi.Router) { + r.Use(noStore) + // Public: frontend bootstrap config, no token needed. r.Get("/auth/config", app.GetAuthConfig) // BFF liveness (does not call the gateway). @@ -282,6 +284,21 @@ func (app *App) Routes() http.Handler { return r } +// noStore marks every API response uncacheable. Answers depend on the bearer +// and change with every write, so a cache between the browser and the BFF (a +// proxy, a CDN, the browser's own heuristic cache) must never replay one: a +// list read again after a create would come back without the new item. It is +// set before the handler runs, so a handler that sets its own Cache-Control +// keeps it (the logs stream sends "no-cache, no-transform", which already +// forbids reuse without revalidation and also keeps proxies from buffering +// the stream). The static frontend is not under /api/v1 and is not affected. +func noStore(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + next.ServeHTTP(w, r) + }) +} + // serveStatic serves the built frontend with SPA fallback to index.html. func (app *App) serveStatic(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { diff --git a/backend/pkg/server/cache_control_test.go b/backend/pkg/server/cache_control_test.go new file mode 100644 index 00000000..8c0a4d85 --- /dev/null +++ b/backend/pkg/server/cache_control_test.go @@ -0,0 +1,78 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake" + + "github.com/ai-openshell/console/backend/pkg/auth" + "github.com/ai-openshell/console/backend/pkg/models" +) + +// A cache between the browser and the BFF must never replay an API answer: +// a list read again after a create came back without the new workspace +// (issue #129). Every /api/v1 response says no-store, public or not, success +// or error; the static frontend does not. +func TestAPIResponsesAreNoStore(t *testing.T) { + static := t.TempDir() + if err := os.WriteFile(filepath.Join(static, "index.html"), []byte(""), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(static, "app.js"), []byte("console.log(1)"), 0o600); err != nil { + t.Fatal(err) + } + app := NewApp(fake.NewClient(), nil, auth.New(auth.Config{Disabled: true}), static, models.AuthConfigResponse{AuthDisabled: true}) + router := app.Routes() + + apiTests := []struct { + name string + method string + path string + }{ + {name: "public", method: http.MethodGet, path: "/api/v1/auth/config"}, + {name: "health", method: http.MethodGet, path: "/api/v1/healthz"}, + {name: "workspace list", method: http.MethodGet, path: "/api/v1/workspaces"}, + {name: "handler error", method: http.MethodGet, path: "/api/v1/workspaces/team-a/sandboxes/sb1/policy/revisions/0"}, + {name: "unknown API route", method: http.MethodGet, path: "/api/v1/no-such-route"}, + } + for _, tc := range apiTests { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil)) + if got := recorder.Header().Get("Cache-Control"); got != "no-store" { + t.Errorf("%s %s (status %d): Cache-Control = %q, want no-store", tc.method, tc.path, recorder.Code, got) + } + }) + } + + for _, path := range []string{"/", "/app.js", "/workspaces/team-a"} { + t.Run("static "+path, func(t *testing.T) { + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + if recorder.Code != http.StatusOK { + t.Fatalf("GET %s = %d, want 200", path, recorder.Code) + } + if got := recorder.Header().Get("Cache-Control"); got != "" { + t.Errorf("GET %s: Cache-Control = %q, want none", path, got) + } + }) + } +} + +// The header is set before the handler runs, so a handler with a policy of +// its own (the logs stream's "no-cache, no-transform") keeps it. +func TestNoStoreLeavesAHandlersOwnCacheControl(t *testing.T) { + handler := noStore(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Cache-Control", "no-cache, no-transform") + w.WriteHeader(http.StatusOK) + })) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if got := recorder.Header().Get("Cache-Control"); got != "no-cache, no-transform" { + t.Errorf("Cache-Control = %q, want the handler's own", got) + } +} diff --git a/frontend/src/api/__tests__/workspace-create.spec.tsx b/frontend/src/api/__tests__/workspace-create.spec.tsx new file mode 100644 index 00000000..95247c62 --- /dev/null +++ b/frontend/src/api/__tests__/workspace-create.spec.tsx @@ -0,0 +1,62 @@ +import React from 'react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, renderHook, waitFor } from '@testing-library/react'; + +import { get, post } from '../client'; +import { workspaceKeys } from '../queryKeys'; +import { useCreateWorkspace, useWorkspaces } from '../workspaces'; + +// The hooks are the real ones, on a real query client; only the HTTP calls +// under them are stubbed. +jest.mock('../client', () => ({ + apiFetch: jest.fn(), + get: jest.fn(), + post: jest.fn(), + put: jest.fn(), + del: jest.fn(), +})); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +// Issue #129: the workspace count in the navigation, which reads the +// unfiltered list, stayed stale after a workspace was created. Creating one +// has to read that list again, and the count has to follow it. +it('reads the unfiltered workspace list again after creating a workspace', async () => { + const listed = [{ metadata: { name: 'default' } }]; + (get as jest.Mock).mockImplementation(() => Promise.resolve([...listed])); + (post as jest.Mock).mockImplementation(() => { + const created = { metadata: { name: 'team-a' } }; + listed.push(created); + return Promise.resolve(created); + }); + + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const wrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => ( + {children} + ); + + const { result } = renderHook( + () => ({ + // What the navigation mounts for its count. + workspaces: useWorkspaces(undefined, { refetchInterval: 0 }), + create: useCreateWorkspace(), + }), + { wrapper }, + ); + await waitFor(() => expect(result.current.workspaces.data).toHaveLength(1)); + expect(client.getQueryData(workspaceKeys.list())).toHaveLength(1); + expect(get).toHaveBeenCalledTimes(1); + expect(get).toHaveBeenLastCalledWith('/api/v1/workspaces'); + + await act(async () => { + await result.current.create.mutateAsync({ name: 'team-a' }); + }); + + await waitFor(() => expect(result.current.workspaces.data).toHaveLength(2)); + expect(get).toHaveBeenCalledTimes(2); + expect(get).toHaveBeenLastCalledWith('/api/v1/workspaces'); +});