Skip to content
Open
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
17 changes: 17 additions & 0 deletions backend/pkg/server/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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/") {
Expand Down
78 changes: 78 additions & 0 deletions backend/pkg/server/cache_control_test.go
Original file line number Diff line number Diff line change
@@ -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("<html></html>"), 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)
}
}
62 changes: 62 additions & 0 deletions frontend/src/api/__tests__/workspace-create.spec.tsx
Original file line number Diff line number Diff line change
@@ -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 }) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
);

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');
});
Loading