Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

public artifacts are origin-isolated and a revoked share is refused on the next read (#368)

github-actions[bot]207385b3ddd6
diff --git a/gateway/app.py b/gateway/app.py
index 67d7608a..3dd4536d 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -48,6 +48,7 @@ from pydantic import AliasChoices, BaseModel, ConfigDict, Field
import backing # pluggable graph/blob/secret stores (vg | local)
import media_plane # the media plane (capability catalog, provider adapters, ffmpeg)
import plugs_plane # the plugs surface: the vendor tools behind the hosted plugs server
+from public_artifacts import public_artifact_headers
import browser_plane # the browser surface: a cloud browser over CDP behind the browser plug
import sql_plane # the read-only SQL data plane (gate, row cap, introspection)
import control_store # durable transactional control state (idempotency / lease / monotonic cancel)
@@ -392,6 +393,11 @@ async def _harness_path_prefix(request: Request, call_next):
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
resp.headers.setdefault("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
resp.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
+ # Revocable public views must recheck authorization at the gateway, including metadata
+ # and 404s. Do not let a CDN or browser retain a share after its owner revokes it.
+ if request.url.path.startswith(("/share/", "/w/")):
+ resp.headers["Cache-Control"] = "private, no-store"
+ resp.headers["Referrer-Policy"] = "no-referrer"
return resp
# NOTE: do NOT add GZipMiddleware globally — it buffers StreamingResponse to compress, which kills
# the /v1/responses SSE (no live progress reaches the browser until the turn ends). Trace payloads
@@ -478,9 +484,8 @@ def _reap_spool_dir() -> None:
os.unlink(f)
except OSError:
pass
-_SHARE_STATE_CACHE: dict[str, tuple[float, bool]] = {} # sid -> (ts, shared)
_SHARE_TOKEN_CACHE: dict[str, tuple[float, str]] = {} # token -> (ts, sid)
-_SHARE_TTL = 10.0 # revocation latency ceiling
+_SHARE_TTL = 10.0 # lookup optimization only; never caches permission to read
# Extracting one member from a tar.gz means decompressing the archive up to that member —
# ~seconds of CPU on a big checkpoint, paid PER CLICK before this cache. One pass now
# extracts every user-visible file (node_modules etc. are already hidden, so this is the
@@ -4666,11 +4671,8 @@ async def delete_trace(sid: str, request: Request) -> dict:
await _vg_upsert("HarnessSession", sid, {"status": "deleted", "shared": "0"})
except Exception: # noqa: BLE001
pass
- # The share resolver caches token -> session and session -> shared for _SHARE_TTL seconds; a
- # link opened inside that window after the delete still answered (R-07 of the conformance
- # suite, intermittent by timing). The tombstone is not enough: the caches go with it, as they
- # do on every revoke.
- _SHARE_STATE_CACHE.pop(sid, None)
+ # Clear local token lookups as well. Every public read checks durable share state, so
+ # sibling replicas with warm token lookups cannot keep authorizing a deleted session.
_SHARE_TOKEN_CACHE.clear()
# §6: a session is deleted with nothing still writing into it. A live turn is stopped first,
# the same way cancel stops it, so the sandbox cannot repopulate storage that has no owner.
@@ -4714,7 +4716,6 @@ async def delete_trace(sid: str, request: Request) -> dict:
pass
await _media_session_purge(sid)
# 3) drop in-process state (the vertex was tombstoned first, above)
- _SHARE_STATE_CACHE.pop(sid, None)
_SHARE_TOKEN_CACHE.clear()
_session_trace.pop(sid, None)
return {"id": sid, "object": "session", "deleted": True}
@@ -8791,7 +8792,7 @@ def _preview_media(path: str, media: str, data: bytes) -> str:
return media or "application/octet-stream"
-async def _serve_workspace_path(sid: str, path: str) -> Response:
+async def _serve_workspace_path(sid: str, path: str, *, public: bool = False) -> Response:
path = path.lstrip("/")
if not path or not _ws_visible(path):
raise HTTPException(404, "file not found")
@@ -8800,29 +8801,26 @@ async def _serve_workspace_path(sid: str, path: str) -> Response:
raise HTTPException(404, "file not found")
data, media, fname = got
media = _preview_media(path, media, data)
- return Response(data, media_type=media, headers=_artifact_headers(media, fname))
+ headers = _artifact_headers(media, fname)
+ if public:
+ headers.update(public_artifact_headers())
+ return Response(data, media_type=media, headers=headers)
async def _session_shared(sid: str) -> bool:
- """Single cached flag check — one vertex prop read on miss, no traversal."""
- now = time.time()
- hit = _SHARE_STATE_CACHE.get(sid)
- if hit and now - hit[0] < _SHARE_TTL:
- return hit[1]
+ """Read durable authorization on every request, including on sibling replicas."""
v = await _vertex_get(sid)
- shared = bool(v) and str(v.get("shared") or "") == "1"
- _SHARE_STATE_CACHE[sid] = (now, shared)
- return shared
+ return bool(v) and str(v.get("shared") or "") == "1" and v.get("status") != "deleted"
@app.get("/w/{harness_id}/{sid}/workspace/{path:path}")
async def workspace_by_path(harness_id: str, sid: str, path: str) -> Response:
- """Canonical artifact URL: /{harness}/{session}/workspace/{path}. Access is ONE cached
+ """Canonical artifact URL: /{harness}/{session}/workspace/{path}. Access is one fresh
session-level check: is the session shared? (The console BFF maps its same-shaped route
here.) harness_id is part of the address, not the auth — the sid is the lookup key."""
if not await _session_shared(sid):
raise HTTPException(404, "file not found")
- return await _serve_workspace_path(sid, path)
+ return await _serve_workspace_path(sid, path, public=True)
@app.get("/a/{sid}/{path:path}")
@@ -8870,11 +8868,9 @@ async def set_session_share(sid: str, request: Request, body: ShareBody | None =
token = str(v.get("share_token") or "") or ("shr" + uuid.uuid4().hex)
await _vertex_upsert(sid, {"share_token": token, "shared": "1",
"shared_at": str(time.time())})
- _SHARE_STATE_CACHE.pop(sid, None)
_SHARE_TOKEN_CACHE.clear()
return _share_out(True, token)
await _vertex_upsert(sid, {"shared": "0"})
- _SHARE_STATE_CACHE.pop(sid, None)
_SHARE_TOKEN_CACHE.clear()
return _share_out(False, str(v.get("share_token") or ""))
@@ -8889,7 +8885,6 @@ async def revoke_session_share(sid: str, request: Request) -> dict:
if not v or str(v.get("tenant") or "") != p.get("org"):
raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")
await _vertex_upsert(sid, {"shared": "0"})
- _SHARE_STATE_CACHE.pop(sid, None)
_SHARE_TOKEN_CACHE.clear()
return _share_out(False, str(v.get("share_token") or "")) | {"deleted": True}
@@ -8913,13 +8908,20 @@ async def _share_sid(token: str) -> str | None:
# box resolve to "not found" while the console happily minted them.
hit = _SHARE_TOKEN_CACHE.get(tok)
if hit and time.time() - hit[0] < _SHARE_TTL:
- return hit[1] or None
- rows = await BACKING.graph.find("HarnessSession", {"share_token": tok, "shared": "1"})
- if not rows:
- _SHARE_TOKEN_CACHE[tok] = (time.time(), "")
+ sid = hit[1]
+ else:
+ rows = await BACKING.graph.find("HarnessSession", {"share_token": tok, "shared": "1"})
+ sid = str(rows[0].get("id") or "") if rows else ""
+ _SHARE_TOKEN_CACHE[tok] = (time.time(), sid)
+ if not sid:
+ return None
+ # A token lookup is not an authorization grant: another replica may have revoked the
+ # share since this one populated its cache (or a graph index may lag the point read).
+ v = await _vertex_get(sid)
+ if (not v or str(v.get("shared") or "") != "1" or v.get("status") == "deleted"
+ or str(v.get("share_token") or "") != tok):
+ _SHARE_TOKEN_CACHE.pop(tok, None)
return None
- sid = str(rows[0].get("id") or "")
- _SHARE_TOKEN_CACHE[tok] = (time.time(), sid)
return sid
@@ -8978,9 +8980,7 @@ async def share_file(token: str, path: str) -> Response:
sid = await _share_sid(token)
if not sid:
raise HTTPException(404, "share not found")
- resp = await _serve_workspace_path(sid, path)
- resp.headers["Cache-Control"] = "public, max-age=300"
- return resp
+ return await _serve_workspace_path(sid, path, public=True)
@app.get("/v1/responses/{response_id}/input_items")
diff --git a/gateway/public_artifacts.py b/gateway/public_artifacts.py
new file mode 100644
index 00000000..31f6f6a7
--- /dev/null
+++ b/gateway/public_artifacts.py
@@ -0,0 +1,22 @@
+"""Response policy for untrusted, revocable public workspace files.
+
+This is an interim origin boundary until artifacts have a separate serving site. A response
+sandbox applies to direct navigation as well as frames. Never add allow-same-origin: scripts
+must not inherit the console/API origin or its browser storage. Basic classic-script previews
+still work; storage, forms, popups and origin-dependent module/fetch apps deliberately do not.
+Apply regardless of MIME so SVG, XHTML and future renderable formats cannot bypass the gate.
+"""
+
+PUBLIC_ARTIFACT_CSP = (
+ "sandbox allow-scripts; base-uri 'none'; object-src 'none'; "
+ "form-action 'none'; frame-ancestors 'none'"
+)
+
+
+def public_artifact_headers() -> dict[str, str]:
+ return {
+ "Content-Security-Policy": PUBLIC_ARTIFACT_CSP,
+ "Cache-Control": "private, no-store",
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ }
diff --git a/gateway/tests/test_public_artifacts.py b/gateway/tests/test_public_artifacts.py
new file mode 100644
index 00000000..a1f5bf74
--- /dev/null
+++ b/gateway/tests/test_public_artifacts.py
@@ -0,0 +1,120 @@
+"""Public active documents are origin-isolated; revocation is checked beyond local caches."""
+import sys
+from pathlib import Path
+
+import httpx
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+
+def shared(monkeypatch):
+ state = {"id": "session1", "tenant": "org1", "share_token": "shrtest", "shared": "1", "status": "done"}
+
+ async def get(sid):
+ return dict(state) if sid == state["id"] else None
+
+ async def find(label, props):
+ # Deliberately emulate an eventually consistent index: the point read must be
+ # authoritative even when the lookup still returns a revoked session.
+ return [{"id": state["id"]}]
+
+ async def upsert(sid, props):
+ state.update(props)
+
+ async def principal(request):
+ return {"org": "org1"}
+
+ async def file_bytes(sid, fid):
+ path = gw._wf_path(fid)
+ media = {"page.html": "text/html", "image.svg": "image/svg+xml",
+ "page.xhtml": "application/xhtml+xml", "style.css": "text/css",
+ "code.js": "text/javascript", "photo.png": "image/png"}.get(path, "application/octet-stream")
+ return b"<script>window.canary = 1</script>\x00\xff", media, path
+
+ async def trace_base(sid):
+ return None
+
+ async def turns(sid):
+ return {"turns": []}
+
+ async def files(sid):
+ return {"page.html": b"example"}
+
+ monkeypatch.setattr(gw, "VG_GATEWAY_URL", "http://unused.test")
+ monkeypatch.setattr(gw, "_vertex_get", get)
+ monkeypatch.setattr(gw, "_vertex_upsert", upsert)
+ monkeypatch.setattr(gw.BACKING.graph, "find", find)
+ monkeypatch.setattr(gw, "_principal", principal)
+ monkeypatch.setattr(gw, "_container_file_bytes", file_bytes)
+ monkeypatch.setattr(gw, "_trace_base", trace_base)
+ monkeypatch.setattr(gw, "_session_turns_data", turns)
+ monkeypatch.setattr(gw, "_ws_files", files)
+ monkeypatch.setattr(gw, "_SHARE_TOKEN_CACHE", {})
+ return state
+
+
+def client():
+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=gw.app), base_url="https://gateway.test")
+
+
[email protected]("file", ["page.html", "image.svg", "page.xhtml", "style.css", "code.js", "photo.png", "unknown.bin"])
[email protected]("prefix", ["/share/shrtest/f/", "/w/h/session1/workspace/"])
+async def test_public_file_document_policy_and_bytes(shared, prefix, file):
+ async with client() as http:
+ response = await http.get(prefix + file)
+ assert response.status_code == 200
+ assert response.content == b"<script>window.canary = 1</script>\x00\xff"
+ csp = response.headers["content-security-policy"]
+ assert "sandbox allow-scripts" in csp
+ assert "allow-same-origin" not in csp
+ assert "form-action 'none'" in csp
+ assert response.headers["cache-control"] == "private, no-store"
+ assert response.headers["x-content-type-options"] == "nosniff"
+ assert response.headers["referrer-policy"] == "no-referrer"
+
+
[email protected]("path", ["/share/shrtest", "/share/shrtest/meta", "/share/shrtest/turns", "/share/shrtest/files"])
+async def test_share_metadata_and_revoked_errors_are_not_cached(shared, path):
+ async with client() as http:
+ response = await http.get(path)
+ assert response.status_code == 200
+ assert response.headers["cache-control"] == "private, no-store"
+ shared["shared"] = "0"
+ response = await http.get(path)
+ assert response.status_code == 404
+ assert response.headers["cache-control"] == "private, no-store"
+
+
[email protected]("method", ["DELETE", "POST"])
+async def test_revoke_denies_a_sibling_with_a_warm_token_lookup(shared, method):
+ async with client() as http:
+ assert (await http.get("/share/shrtest/f/page.html")).status_code == 200
+ sibling_cache = dict(gw._SHARE_TOKEN_CACHE)
+ response = await http.request(method, "/v1/sessions/session1/share",
+ **({"json": {"enabled": False}} if method == "POST" else {}))
+ assert response.status_code == 200
+ # Local invalidation cannot touch another replica. Restore its warmed lookup.
+ gw._SHARE_TOKEN_CACHE.update(sibling_cache)
+ for path in ["/share/shrtest/f/page.html", "/w/h/session1/workspace/page.html"]:
+ response = await http.get(path)
+ assert response.status_code == 404
+ assert response.headers["cache-control"] == "private, no-store"
+
+
[email protected]("update", [{"status": "deleted"}, {"share_token": "rotated"}])
+async def test_cached_lookup_cannot_outlive_deletion_or_token_rotation(shared, update):
+ async with client() as http:
+ assert (await http.get("/share/shrtest/f/page.html")).status_code == 200
+ shared.update(update)
+ assert (await http.get("/share/shrtest/f/page.html")).status_code == 404
+
+
+async def test_authenticated_artifact_behavior_is_not_changed(shared):
+ async with client() as http:
+ response = await http.get("/a/session1/page.html")
+ assert response.status_code == 200
+ assert "sandbox" not in response.headers["content-security-policy"]
+ assert response.headers["cache-control"] == "private, max-age=60"
diff --git a/gateway/tests/test_share_selfhost.py b/gateway/tests/test_share_selfhost.py
index 684f1519..3cd0467d 100644
--- a/gateway/tests/test_share_selfhost.py
+++ b/gateway/tests/test_share_selfhost.py
@@ -25,7 +25,6 @@ def api(monkeypatch):
return {"org": ORG, "member": "me@local"}
monkeypatch.setattr(gw, "_principal", principal)
gw._SHARE_TOKEN_CACHE.clear()
- gw._SHARE_STATE_CACHE.clear()
return TestClient(gw.app)
diff --git a/ui/jest.config.js b/ui/jest.config.js
new file mode 100644
index 00000000..cbc787b2
--- /dev/null
+++ b/ui/jest.config.js
@@ -0,0 +1,6 @@
+const nextJest = require('next/jest');
+
+module.exports = nextJest({ dir: './' })({
+ testEnvironment: 'node',
+ moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' },
+});
diff --git a/ui/next.config.ts b/ui/next.config.ts
index 40d29bbd..1b881a64 100644
--- a/ui/next.config.ts
+++ b/ui/next.config.ts
@@ -25,17 +25,31 @@ const nextConfig: NextConfig = {
// and a locked-down permissions policy. The console renders no third-party iframes and is
// never meant to be embedded, so 'none' is safe and has no functional regression.
async headers() {
- return [{
- source: "/:path*",
- headers: [
- { key: "X-Frame-Options", value: "DENY" },
- { key: "Content-Security-Policy", value: "frame-ancestors 'none'" },
- { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
- { key: "X-Content-Type-Options", value: "nosniff" },
- { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
- { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
- ],
- }];
+ const baseline = [
+ { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
+ { key: "X-Content-Type-Options", value: "nosniff" },
+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
+ { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
+ ];
+ return [
+ {
+ // Public artifact proxies set their own stricter CSP and referrer policy. Next's
+ // configured headers can overwrite route response headers, so exclude them here.
+ source: "/((?!api/share/|[^/]+/[^/]+/workspace/).*)",
+ headers: [
+ { key: "X-Frame-Options", value: "DENY" },
+ { key: "Content-Security-Policy", value: "frame-ancestors 'none'" },
+ ...baseline,
+ ],
+ },
+ ...["/api/share/:path*", "/:harness/:sid/workspace/:path*"].map((source) => ({
+ source,
+ headers: [
+ { key: "X-Frame-Options", value: "DENY" },
+ ...baseline.filter(({ key }) => key !== "Referrer-Policy"),
+ ],
+ })),
+ ];
},
webpack: (config) => {
// NOTE: do NOT alias react/react-dom here — Next.js installs its own layer-aware react
diff --git a/ui/src/app/[harness]/[sid]/workspace/[...fpath]/route.ts b/ui/src/app/[harness]/[sid]/workspace/[...fpath]/route.ts
index 1e715a0e..011d262a 100644
--- a/ui/src/app/[harness]/[sid]/workspace/[...fpath]/route.ts
+++ b/ui/src/app/[harness]/[sid]/workspace/[...fpath]/route.ts
@@ -1,8 +1,9 @@
// Canonical artifact URL: /{harness}/{session}/workspace/{path}, proxies to the gateway's
-// same-shaped /w/ route. Access is the gateway's single cached session-level shared flag
+// same-shaped /w/ route. Access is the gateway's fresh session-level shared flag
// (no auth headers injected; the unguessable session id is the lookup key, the flag is the
// gate). Binary-safe passthrough so html/css/js/img/pdf preview inline with relative assets.
import type { NextRequest } from 'next/server';
+import { publicShareResponseHeaders } from '@/lib/public-artifact-response';
export const dynamic = 'force-dynamic';
@@ -15,17 +16,11 @@ export async function GET(req: NextRequest,
`/workspace/${(fpath || []).map(encodeURIComponent).join('/')}`;
try {
const res = await fetch(target, { cache: 'no-store' });
- const out: Record<string, string> = {
- 'content-type': res.headers.get('content-type') || 'application/octet-stream',
- };
- for (const h of ['content-disposition', 'cache-control', 'x-content-type-options']) {
- const v = res.headers.get(h);
- if (v) out[h] = v;
- }
+ const out = publicShareResponseHeaders(res.headers, true);
return new Response(res.body, { status: res.status, headers: out });
} catch {
return new Response(JSON.stringify({ detail: 'workspace upstream unreachable' }), {
- status: 502, headers: { 'content-type': 'application/json' },
+ status: 502, headers: publicShareResponseHeaders(new Headers({ 'content-type': 'application/json' }), true),
});
}
}
diff --git a/ui/src/app/api/share/[...path]/route.ts b/ui/src/app/api/share/[...path]/route.ts
index 4524d947..793a6ac8 100644
--- a/ui/src/app/api/share/[...path]/route.ts
+++ b/ui/src/app/api/share/[...path]/route.ts
@@ -3,6 +3,7 @@
// serves sessions whose sharing is currently enabled. Binary-safe passthrough so html/css/js/
// images/pdf render inline in the browser.
import type { NextRequest } from 'next/server';
+import { publicShareResponseHeaders } from '@/lib/public-artifact-response';
export const dynamic = 'force-dynamic';
@@ -15,19 +16,11 @@ export async function GET(req: NextRequest, ctx: { params: Promise<{ path: strin
const res = await fetch(target, { cache: 'no-store' });
// Stream the body through (HR-INF-015): shared artifacts (rendered sites, PDFs, media) can be
// large, pass res.body byte-exact so the BFF never materializes the whole payload in memory.
- const out: Record<string, string> = {
- 'content-type': res.headers.get('content-type') || 'application/octet-stream',
- };
- const cd = res.headers.get('content-disposition');
- if (cd) out['content-disposition'] = cd;
- const cc = res.headers.get('cache-control');
- if (cc) out['cache-control'] = cc;
- const cl = res.headers.get('content-length');
- if (cl) out['content-length'] = cl;
+ const out = publicShareResponseHeaders(res.headers, path[1] === 'f');
return new Response(res.body, { status: res.status, headers: out });
} catch {
return new Response(JSON.stringify({ detail: 'share upstream unreachable' }), {
- status: 502, headers: { 'content-type': 'application/json' },
+ status: 502, headers: publicShareResponseHeaders(new Headers({ 'content-type': 'application/json' }), path[1] === 'f'),
});
}
}
diff --git a/ui/src/lib/public-artifact-response.test.ts b/ui/src/lib/public-artifact-response.test.ts
new file mode 100644
index 00000000..330cb1b7
--- /dev/null
+++ b/ui/src/lib/public-artifact-response.test.ts
@@ -0,0 +1,66 @@
+import { GET as shareGET } from '@/app/api/share/[...path]/route';
+import { GET as workspaceGET } from '@/app/[harness]/[sid]/workspace/[...fpath]/route';
+import { publicShareResponseHeaders } from './public-artifact-response';
+import type { NextRequest } from 'next/server';
+
+const request = new Request('https://console.test/') as NextRequest;
+const originalFetch = global.fetch;
+afterEach(() => { global.fetch = originalFetch; });
+
+function expectIsolated(headers: Headers) {
+ const csp = headers.get('content-security-policy')!;
+ const sandbox = csp.split(';').find((part) => part.trim().startsWith('sandbox'))!;
+ expect(sandbox).toContain('allow-scripts');
+ expect(sandbox).not.toContain('allow-same-origin');
+ expect(headers.get('cache-control')).toBe('private, no-store');
+ expect(headers.get('x-content-type-options')).toBe('nosniff');
+}
+
+test.each(['text/html', 'image/svg+xml', 'application/xhtml+xml', 'text/plain', 'text/css'])('%s public artifacts are isolated even from an older gateway', async (media) => {
+ const bytes = new Uint8Array([60, 115, 99, 114, 105, 112, 116, 62, 0, 255]);
+ const fetchMock = jest.fn().mockImplementation(async () => new Response(bytes, {
+ headers: { 'content-type': media, 'cache-control': 'public, max-age=300', 'set-cookie': 'unexpected=value' },
+ }));
+ global.fetch = fetchMock;
+ const share = await shareGET(request, { params: Promise.resolve({ path: ['token', 'f', 'file'] }) });
+ const workspace = await workspaceGET(request, { params: Promise.resolve({ harness: 'h', sid: 's', fpath: ['file'] }) });
+ for (const response of [share, workspace]) {
+ expect(response.status).toBe(200);
+ expectIsolated(response.headers);
+ expect(response.headers.get('content-type')).toBe(media);
+ expect(response.headers.has('set-cookie')).toBe(false);
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes);
+ }
+ for (const [, options] of fetchMock.mock.calls) {
+ expect(options).toEqual({ cache: 'no-store' });
+ }
+});
+
+test('an upstream restrictive CSP survives in addition to the local sandbox', () => {
+ const headers = publicShareResponseHeaders(new Headers({
+ 'content-security-policy': "default-src 'none'",
+ 'content-length': '100',
+ 'access-control-allow-origin': '*',
+ }), true);
+ expect(headers.get('content-security-policy')).toContain("default-src 'none', sandbox allow-scripts");
+ expect(headers.has('content-length')).toBe(false);
+ expect(headers.has('access-control-allow-origin')).toBe(false);
+});
+
+test.each([200, 404])('public metadata status %s remains JSON and cannot be cached', async (status) => {
+ global.fetch = jest.fn().mockResolvedValue(new Response('{"detail":"view"}', {
+ status, headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=300' },
+ }));
+ const response = await shareGET(request, { params: Promise.resolve({ path: ['token', 'meta'] }) });
+ expect(response.status).toBe(status);
+ expect(response.headers.get('cache-control')).toBe('private, no-store');
+ expect(await response.json()).toEqual({ detail: 'view' });
+});
+
+test('unreachable public artifact upstream produces an uncached error', async () => {
+ global.fetch = jest.fn().mockRejectedValue(new Error('unreachable'));
+ const response = await shareGET(request, { params: Promise.resolve({ path: ['token', 'f', 'index.html'] }) });
+ expect(response.status).toBe(502);
+ expectIsolated(response.headers);
+ expect(await response.json()).toEqual({ detail: 'share upstream unreachable' });
+});
diff --git a/ui/src/lib/public-artifact-response.ts b/ui/src/lib/public-artifact-response.ts
new file mode 100644
index 00000000..2c9a2849
--- /dev/null
+++ b/ui/src/lib/public-artifact-response.ts
@@ -0,0 +1,25 @@
+// The gateway and console both enforce the boundary so a rolling deployment cannot leave
+// an older gateway's active content running with the console's origin. No allow-same-origin.
+export const PUBLIC_ARTIFACT_CSP =
+ "sandbox allow-scripts; base-uri 'none'; object-src 'none'; form-action 'none'; frame-ancestors 'none'";
+
+export function publicShareResponseHeaders(upstream: Headers, artifact: boolean): Headers {
+ const out = new Headers({
+ 'content-type': upstream.get('content-type') || 'application/octet-stream',
+ 'cache-control': 'private, no-store',
+ 'x-content-type-options': 'nosniff',
+ 'referrer-policy': 'no-referrer',
+ });
+ for (const name of ['content-disposition', 'content-security-policy']) {
+ const value = upstream.get(name);
+ if (value) out.set(name, value);
+ }
+ if (artifact) {
+ // Separate policies intersect; an upstream policy must never weaken this sandbox.
+ const upstreamPolicy = out.get('content-security-policy');
+ out.set('content-security-policy', upstreamPolicy
+ ? `${upstreamPolicy}, ${PUBLIC_ARTIFACT_CSP}` : PUBLIC_ARTIFACT_CSP);
+ }
+ // Do not forward Set-Cookie, CORS grants, or Content-Length (fetch may decompress bytes).
+ return out;
+}