Sandbox home and artifact files served on the app origin (H1)
GET /files and /artifacts/ now send the artifact sandbox CSP and nosniff through one helper, and /files serves HTML, XHTML, SVG, XML, XSL, JavaScript and multipart/x-mixed-replace as attachments, including when the type is sniffed from an extensionless file. The web proxy adds the same headers to every proxied /files and /artifacts/ response (defence in depth against an older server), and the peer relay shares the helper. show_html previews are unchanged by operator decision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
// 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,
|
// a new tab must be as safe as the embedded sandboxed preview. No scripts,
|
||||||
// network calls, forms, same-origin authority or top-level navigation.
|
// 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'")
|
setUntrustedContentHeaders(w.Header())
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
http.ServeContent(w, req, path.Base(name), opened.ModTime(), file)
|
http.ServeContent(w, req, path.Base(name), opened.ModTime(), file)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,7 +65,9 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
|
|||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
w.Header().Set("Cache-Control", "private, no-cache")
|
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))
|
contentType := mime.TypeByExtension(filepath.Ext(realTarget))
|
||||||
if contentType == "" {
|
if contentType == "" {
|
||||||
var sample [512]byte
|
var sample [512]byte
|
||||||
@@ -85,7 +87,7 @@ func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
|
|||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", contentType)
|
w.Header().Set("Content-Type", contentType)
|
||||||
disposition := "inline"
|
disposition := "inline"
|
||||||
if r.URL.Query().Get("download") == "1" {
|
if r.URL.Query().Get("download") == "1" || scriptCapableType(contentType) {
|
||||||
disposition = "attachment"
|
disposition = "attachment"
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
|
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
|
||||||
|
|||||||
@@ -86,3 +86,54 @@ func TestServeHomeFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestServeHomeFileSandboxesScriptCapableTypes(t *testing.T) {
|
||||||
|
home := t.TempDir()
|
||||||
|
files := map[string]string{
|
||||||
|
"page.html": "<script>fetch('/connect')</script>",
|
||||||
|
"image.svg": `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`,
|
||||||
|
"page.xhtml": "<html xmlns='http://www.w3.org/1999/xhtml'></html>",
|
||||||
|
"feed.xml": "<?xml version='1.0'?><x/>",
|
||||||
|
"noext": "<!DOCTYPE html><html><script>alert(1)</script></html>",
|
||||||
|
"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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
|
}
|
||||||
+11
-2
@@ -45,6 +45,7 @@ import {
|
|||||||
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
|
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
|
||||||
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
|
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
|
||||||
import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.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.
|
// The proxy's own directory holds the sign-in page's icons.
|
||||||
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
|
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
|
||||||
@@ -465,7 +466,8 @@ async function serveIndex(res) {
|
|||||||
function proxyArtifact(req, res) {
|
function proxyArtifact(req, res) {
|
||||||
let headers;
|
let headers;
|
||||||
// An upload is gated by the session's elevation on the server.
|
// 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 {
|
try {
|
||||||
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
|
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
|
||||||
} catch {
|
} catch {
|
||||||
@@ -477,7 +479,14 @@ function proxyArtifact(req, res) {
|
|||||||
const upstream = request(
|
const upstream = request(
|
||||||
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
|
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
|
||||||
(reply) => {
|
(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);
|
reply.pipe(res);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+11
-15
@@ -8,11 +8,9 @@ import {
|
|||||||
import { PeerRegistry } from "./peerRegistry.js";
|
import { PeerRegistry } from "./peerRegistry.js";
|
||||||
import { withServerToken } from "./serverToken.js";
|
import { withServerToken } from "./serverToken.js";
|
||||||
import { rememberDiscovered } from "./peerAddress.js";
|
import { rememberDiscovered } from "./peerAddress.js";
|
||||||
|
// Peer files are untrusted content, never privileged control-UI documents:
|
||||||
// Peer files are untrusted content, never privileged control-UI documents.
|
// the sandbox applies even for older peers whose /files has no such header.
|
||||||
// Apply this even for older peers whose /files endpoint has no sandbox header.
|
import { untrustedHeaders } from "./untrustedContent.js";
|
||||||
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'";
|
|
||||||
|
|
||||||
const allowed = (path) =>
|
const allowed = (path) =>
|
||||||
path === "/files" ||
|
path === "/files" ||
|
||||||
@@ -98,23 +96,21 @@ export class PeerRelay extends PeerRegistry {
|
|||||||
"content-range",
|
"content-range",
|
||||||
"accept-ranges",
|
"accept-ranges",
|
||||||
"content-disposition",
|
"content-disposition",
|
||||||
|
"content-security-policy",
|
||||||
])
|
])
|
||||||
if (response.headers[name]) safe[name] = response.headers[name];
|
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(
|
res.writeHead(
|
||||||
response.statusCode >= 300 && response.statusCode < 400
|
response.statusCode >= 300 && response.statusCode < 400
|
||||||
? 502
|
? 502
|
||||||
: response.statusCode,
|
: response.statusCode,
|
||||||
{
|
{
|
||||||
...safe,
|
...untrustedHeaders(safe, {
|
||||||
"Cache-Control": "private, no-store",
|
download: target.url.pathname === "/files",
|
||||||
// Multiple CSP policies intersect: preserve a peer's stricter
|
}),
|
||||||
// restrictions while always imposing the local sandbox boundary.
|
"cache-control": "private, no-store",
|
||||||
"Content-Security-Policy": response.headers[
|
|
||||||
"content-security-policy"
|
|
||||||
]
|
|
||||||
? [response.headers["content-security-policy"], contentPolicy]
|
|
||||||
: contentPolicy,
|
|
||||||
"X-Content-Type-Options": "nosniff",
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
response.pipe(res);
|
response.pipe(res);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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("<script>alert(1)</script>");
|
||||||
|
}).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) => {
|
test("file uploads require sign-in and reach the server with their name header", async (t) => {
|
||||||
const requests = [];
|
const requests = [];
|
||||||
const upstream = createServer(async (req, res) => {
|
const upstream = createServer(async (req, res) => {
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user