diff --git a/internal/server/artifacts.go b/internal/server/artifacts.go
index 1e849a1f..368d3f89 100644
--- a/internal/server/artifacts.go
+++ b/internal/server/artifacts.go
@@ -291,8 +291,7 @@ func (r *runner) serveArtifact(w http.ResponseWriter, req *http.Request) {
// Enforce the boundary on the response itself: opening the raw HTML/SVG in
// a new tab must be as safe as the embedded sandboxed preview. No scripts,
// network calls, forms, same-origin authority or top-level navigation.
- w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'")
- w.Header().Set("X-Content-Type-Options", "nosniff")
+ setUntrustedContentHeaders(w.Header())
w.Header().Set("Cache-Control", "private, no-store")
http.ServeContent(w, req, path.Base(name), opened.ModTime(), file)
}
diff --git a/internal/server/home_files.go b/internal/server/home_files.go
index ab5bef59..744007e7 100644
--- a/internal/server/home_files.go
+++ b/internal/server/home_files.go
@@ -65,7 +65,9 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
defer file.Close()
w.Header().Set("Cache-Control", "private, no-cache")
- w.Header().Set("X-Content-Type-Options", "nosniff")
+ // A home file is untrusted content (a download, a cloned repository, an
+ // agent's output), never part of the control UI.
+ setUntrustedContentHeaders(w.Header())
contentType := mime.TypeByExtension(filepath.Ext(realTarget))
if contentType == "" {
var sample [512]byte
@@ -85,7 +87,7 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
}
w.Header().Set("Content-Type", contentType)
disposition := "inline"
- if r.URL.Query().Get("download") == "1" {
+ if r.URL.Query().Get("download") == "1" || scriptCapableType(contentType) {
disposition = "attachment"
}
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
diff --git a/internal/server/home_files_test.go b/internal/server/home_files_test.go
index c393defc..f8256b4e 100644
--- a/internal/server/home_files_test.go
+++ b/internal/server/home_files_test.go
@@ -86,3 +86,54 @@ func TestServeHomeFile(t *testing.T) {
}
})
}
+
+func TestServeHomeFileSandboxesScriptCapableTypes(t *testing.T) {
+ home := t.TempDir()
+ files := map[string]string{
+ "page.html": "",
+ "image.svg": ``,
+ "page.xhtml": "",
+ "feed.xml": "",
+ "noext": "",
+ "notes.txt": "plain",
+ "photo.png": "\x89PNG\r\n\x1a\n",
+ }
+ for name, body := range files {
+ if err := os.WriteFile(filepath.Join(home, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for name := range files {
+ t.Run(name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ serveHomeFileFrom(recorder, httptest.NewRequest(http.MethodGet, "/files?path=~/"+name, nil), home)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status = %d", recorder.Code)
+ }
+ header := recorder.Header()
+ if csp := header.Get("Content-Security-Policy"); csp != untrustedContentPolicy || !strings.HasPrefix(csp, "sandbox;") {
+ t.Fatalf("csp = %q", csp)
+ }
+ if header.Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("nosniff = %q", header.Get("X-Content-Type-Options"))
+ }
+ wantAttachment := name != "notes.txt" && name != "photo.png"
+ if got := strings.HasPrefix(header.Get("Content-Disposition"), "attachment;"); got != wantAttachment {
+ t.Fatalf("disposition = %q (type %q), want attachment %v", header.Get("Content-Disposition"), header.Get("Content-Type"), wantAttachment)
+ }
+ })
+ }
+}
+
+func TestScriptCapableType(t *testing.T) {
+ for _, contentType := range []string{"text/html; charset=utf-8", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml", "application/rss+xml", "TEXT/HTML"} {
+ if !scriptCapableType(contentType) {
+ t.Errorf("%q should be script-capable", contentType)
+ }
+ }
+ for _, contentType := range []string{"text/plain; charset=utf-8", "image/png", "application/pdf", "application/octet-stream", ""} {
+ if scriptCapableType(contentType) {
+ t.Errorf("%q should not be script-capable", contentType)
+ }
+ }
+}
diff --git a/internal/server/untrusted_content.go b/internal/server/untrusted_content.go
new file mode 100644
index 00000000..a6ac4b68
--- /dev/null
+++ b/internal/server/untrusted_content.go
@@ -0,0 +1,40 @@
+package server
+
+import (
+ "mime"
+ "net/http"
+ "strings"
+)
+
+// untrustedContentPolicy is the response boundary for every file the server
+// hands back that it did not write itself: run artifacts, files under the
+// operator's home and anything an agent produced. The `sandbox` directive gives
+// the document an opaque origin even when opened as a top-level page, so a
+// crafted HTML or SVG file cannot script the app origin, reach /connect or read
+// other files. The web proxy and the peer relay add the same policy.
+const untrustedContentPolicy = "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"
+
+// setUntrustedContentHeaders applies the sandbox policy and turns off MIME
+// sniffing, so a response is never interpreted as a more powerful type.
+func setUntrustedContentHeaders(h http.Header) {
+ h.Set("Content-Security-Policy", untrustedContentPolicy)
+ h.Set("X-Content-Type-Options", "nosniff")
+}
+
+// scriptCapableType reports whether a browser could run script in a document of
+// this content type when it is opened as a page: HTML, XHTML, SVG and every XML
+// flavour (XSLT and XML stylesheets can build HTML). Such files are served as
+// downloads; the sandbox policy is the second layer.
+func scriptCapableType(contentType string) bool {
+ media, _, err := mime.ParseMediaType(contentType)
+ if err != nil {
+ media = strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, ";", 2)[0]))
+ }
+ switch media {
+ case "text/html", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml",
+ "text/xsl", "application/xslt+xml", "application/javascript", "text/javascript",
+ "application/ecmascript", "text/ecmascript", "multipart/x-mixed-replace":
+ return true
+ }
+ return strings.HasSuffix(media, "+xml") || strings.HasSuffix(media, "/xml")
+}
diff --git a/web/serve.mjs b/web/serve.mjs
index a0ea542b..bdb4658f 100644
--- a/web/serve.mjs
+++ b/web/serve.mjs
@@ -45,6 +45,7 @@ import {
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.js";
+import { untrustedHeaders } from "./src/untrustedContent.js";
// The proxy's own directory holds the sign-in page's icons.
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
@@ -465,7 +466,8 @@ async function serveIndex(res) {
function proxyArtifact(req, res) {
let headers;
// An upload is gated by the session's elevation on the server.
- const upload = req.method === "POST" && (req.url ?? "").split("?")[0] === "/files";
+ const pathname = (req.url ?? "").split("?")[0];
+ const upload = req.method === "POST" && pathname === "/files";
try {
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
} catch {
@@ -477,7 +479,14 @@ function proxyArtifact(req, res) {
const upstream = request(
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
(reply) => {
- res.writeHead(reply.statusCode ?? 502, reply.headers);
+ // Served files are untrusted content: always sandboxed, and a home file
+ // a browser could script is a download. Defence in depth: the server
+ // sets the same headers.
+ const served = req.method === "GET" || req.method === "HEAD";
+ res.writeHead(
+ reply.statusCode ?? 502,
+ served ? untrustedHeaders(reply.headers, { download: pathname === "/files" }) : reply.headers,
+ );
reply.pipe(res);
},
);
diff --git a/web/src/peerRelay.js b/web/src/peerRelay.js
index 5d940a6a..5b62d2f7 100644
--- a/web/src/peerRelay.js
+++ b/web/src/peerRelay.js
@@ -8,11 +8,9 @@ import {
import { PeerRegistry } from "./peerRegistry.js";
import { withServerToken } from "./serverToken.js";
import { rememberDiscovered } from "./peerAddress.js";
-
-// Peer files are untrusted content, never privileged control-UI documents.
-// Apply this even for older peers whose /files endpoint has no sandbox header.
-const contentPolicy =
- "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
+// Peer files are untrusted content, never privileged control-UI documents:
+// the sandbox applies even for older peers whose /files has no such header.
+import { untrustedHeaders } from "./untrustedContent.js";
const allowed = (path) =>
path === "/files" ||
@@ -98,23 +96,21 @@ export class PeerRelay extends PeerRegistry {
"content-range",
"accept-ranges",
"content-disposition",
+ "content-security-policy",
])
if (response.headers[name]) safe[name] = response.headers[name];
+ // Multiple CSP policies intersect: preserve a peer's stricter
+ // restrictions while always imposing the local sandbox boundary. A
+ // peer home file a browser could script is a download.
res.writeHead(
response.statusCode >= 300 && response.statusCode < 400
? 502
: response.statusCode,
{
- ...safe,
- "Cache-Control": "private, no-store",
- // Multiple CSP policies intersect: preserve a peer's stricter
- // restrictions while always imposing the local sandbox boundary.
- "Content-Security-Policy": response.headers[
- "content-security-policy"
- ]
- ? [response.headers["content-security-policy"], contentPolicy]
- : contentPolicy,
- "X-Content-Type-Options": "nosniff",
+ ...untrustedHeaders(safe, {
+ download: target.url.pathname === "/files",
+ }),
+ "cache-control": "private, no-store",
},
);
response.pipe(res);
diff --git a/web/src/untrustedContent.js b/web/src/untrustedContent.js
new file mode 100644
index 00000000..7c839d5d
--- /dev/null
+++ b/web/src/untrustedContent.js
@@ -0,0 +1,50 @@
+// The response boundary for files the proxy relays but did not write: run
+// artifacts, files under a home directory and a peer's files. `sandbox` gives
+// such a document an opaque origin even when it is opened as a page, so a
+// crafted HTML or SVG file cannot script the app origin. The Go server sets the
+// same policy; the proxy adds it again so an older server, or a peer, cannot
+// serve a document with the app's authority.
+export const CONTENT_POLICY =
+ "sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
+
+const SCRIPT_CAPABLE = new Set([
+ "text/html",
+ "application/xhtml+xml",
+ "image/svg+xml",
+ "text/xml",
+ "application/xml",
+ "text/xsl",
+ "application/xslt+xml",
+ "application/javascript",
+ "text/javascript",
+ "application/ecmascript",
+ "text/ecmascript",
+ "multipart/x-mixed-replace",
+]);
+
+/** Whether a browser could run script in a page of this content type. */
+export function scriptCapable(contentType) {
+ const media = String(contentType ?? "").split(";")[0].trim().toLowerCase();
+ return SCRIPT_CAPABLE.has(media) || media.endsWith("+xml") || media.endsWith("/xml");
+}
+
+/**
+ * Copies [headers] (a Node response's headers, lower-case names) with the
+ * sandbox policy added. Multiple CSP headers intersect, so an upstream policy
+ * is kept beside the local one. With [download], a script-capable type is
+ * forced to an attachment, keeping any filename the upstream named.
+ */
+export function untrustedHeaders(headers, { download = false } = {}) {
+ const out = { ...headers };
+ const upstream = out["content-security-policy"];
+ out["content-security-policy"] = upstream
+ ? [...(Array.isArray(upstream) ? upstream : [upstream]), CONTENT_POLICY]
+ : CONTENT_POLICY;
+ out["x-content-type-options"] = "nosniff";
+ if (download && scriptCapable(out["content-type"])) {
+ const current = String(out["content-disposition"] ?? "").trim();
+ if (/^inline\b/i.test(current)) out["content-disposition"] = current.replace(/^inline/i, "attachment");
+ else if (!/^attachment\b/i.test(current)) out["content-disposition"] = "attachment";
+ }
+ return out;
+}
diff --git a/web/test/serve.test.mjs b/web/test/serve.test.mjs
index 7a2d9ea9..09cb5f61 100644
--- a/web/test/serve.test.mjs
+++ b/web/test/serve.test.mjs
@@ -214,6 +214,37 @@ test("files require sign-in and proxy query, ranges and attachment headers", asy
]);
});
+test("files and artifacts are sandboxed and home HTML is a download even from an old server", async (t) => {
+ // An older server that sets none of the boundary headers.
+ const upstream = createServer((req, res) => {
+ const html = req.url.startsWith("/files") || req.url.startsWith("/artifacts/");
+ res.writeHead(200, {
+ "Content-Type": html ? "text/html; charset=utf-8" : "text/plain",
+ "Content-Disposition": 'inline; filename="x.html"',
+ });
+ res.end("");
+ }).listen(0, "127.0.0.1");
+ await once(upstream, "listening");
+ t.after(() => new Promise((done) => upstream.close(done)));
+ const port = await freePort();
+ const child = spawn(process.execPath, ["serve.mjs", "--port", String(port),
+ "--pipelines", `127.0.0.1:${upstream.address().port}`], {
+ cwd: here,
+ env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
+ await once(child.stdout, "data");
+ const base = `http://127.0.0.1:${port}`;
+ const file = await fetch(base + "/files?path=~/Downloads/x.html");
+ assert.match(file.headers.get("content-security-policy"), /(^|, )sandbox; default-src 'none'; script-src 'none'/);
+ assert.equal(file.headers.get("x-content-type-options"), "nosniff");
+ assert.equal(file.headers.get("content-disposition"), 'attachment; filename="x.html"');
+ const artifact = await fetch(base + "/artifacts/r/s/report.html");
+ assert.match(artifact.headers.get("content-security-policy"), /sandbox; default-src 'none'/);
+ assert.equal(artifact.headers.get("content-disposition"), 'inline; filename="x.html"');
+});
+
test("file uploads require sign-in and reach the server with their name header", async (t) => {
const requests = [];
const upstream = createServer(async (req, res) => {
diff --git a/web/test/untrustedContent.test.mjs b/web/test/untrustedContent.test.mjs
new file mode 100644
index 00000000..5b0fe072
--- /dev/null
+++ b/web/test/untrustedContent.test.mjs
@@ -0,0 +1,34 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { CONTENT_POLICY, scriptCapable, untrustedHeaders } from "../src/untrustedContent.js";
+
+test("script-capable types cover HTML, SVG and every XML flavour", () => {
+ for (const type of [
+ "text/html; charset=utf-8",
+ "application/xhtml+xml",
+ "image/svg+xml",
+ "text/xml",
+ "application/xml",
+ "application/rss+xml",
+ "TEXT/HTML",
+ ])
+ assert.equal(scriptCapable(type), true, type);
+ for (const type of ["text/plain", "image/png", "application/pdf", "application/octet-stream", "", undefined])
+ assert.equal(scriptCapable(type), false, String(type));
+});
+
+test("untrusted headers add the sandbox beside an upstream policy", () => {
+ assert.equal(untrustedHeaders({})["content-security-policy"], CONTENT_POLICY);
+ const both = untrustedHeaders({ "content-security-policy": "img-src 'none'" });
+ assert.deepEqual(both["content-security-policy"], ["img-src 'none'", CONTENT_POLICY]);
+ assert.equal(both["x-content-type-options"], "nosniff");
+});
+
+test("downloads force script-capable types to attachments and keep the name", () => {
+ const html = { "content-type": "text/html", "content-disposition": 'inline; filename="a.html"' };
+ assert.equal(untrustedHeaders(html, { download: true })["content-disposition"], 'attachment; filename="a.html"');
+ assert.equal(untrustedHeaders({ "content-type": "image/svg+xml" }, { download: true })["content-disposition"], "attachment");
+ assert.equal(untrustedHeaders(html)["content-disposition"], 'inline; filename="a.html"');
+ const text = { "content-type": "text/plain", "content-disposition": "inline" };
+ assert.equal(untrustedHeaders(text, { download: true })["content-disposition"], "inline");
+});