Files

190 lines
8.8 KiB
TypeScript

import { describe, it, expect } from "vitest";
import fs from "node:fs";
import path from "node:path";
import ts from "typescript";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
// Spec (admin-portal-markup-safety), security finding F09: the admin portal never injects HTML into its own origin.
// Data HTML goes into <iframe sandbox="" srcDoc>. Allow-listing a file here is a security
// decision for review: only code-generated or escaped content may be injected, and the reason is written down.
const APP_DIR = path.resolve(__dirname, "..", "..");
const HTML_SINKS = [
"dangerouslySetInnerHTML",
"innerHTML",
"outerHTML",
"insertAdjacentHTML",
"document.write",
"createContextualFragment",
] as const;
type Sink = (typeof HTML_SINKS)[number];
const SINK_ALLOWED: Record<string, Sink[]> = {
// shadcn chart: a <style> built from the chart's own colour config (code constants), never from data.
"components/ui/chart.tsx": ["dangerouslySetInnerHTML"],
// add-landing-pages design decision 8: page authors' rich text, run through sanitize-html with a fixed allow-list
// (pageHtml.ts: no scripts, handlers, iframes, images or styles beyond text-align) on the server render.
"components/pages/SafeHtml.tsx": ["dangerouslySetInnerHTML"],
};
// add-custom-html-block: a Custom HTML block's frame loads its own address, whose response carries a `sandbox` CSP
// (opaque origin), and may run scripts but never as this origin: FRAME_SANDBOX holds no allow-same-origin.
// Only this file may give an iframe that one non-empty sandbox, and only as the named constant.
const SANDBOX_ALLOWED: Record<string, string> = {
"components/pages/HtmlFrame.tsx": "FRAME_SANDBOX",
};
// add-page-visual-editor design Decision 1: the editor canvas is a same-origin frame the editor renders its own React
// tree into by portal, so it cannot be sandboxed (that would also strip scripts from the Custom HTML frames nested in
// it). It holds no data HTML: its only document is this file's constant blank page, with no src.
const UNSANDBOXED_ALLOWED: Record<string, { srcDoc: string; html: string }> = {
"components/pages/CanvasFrame.tsx": { srcDoc: "BLANK", html: `const BLANK = "<!doctype html><html><head></head><body></body></html>";` },
};
function sourceFiles(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === ".next") continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
sourceFiles(full, out);
} else if (/\.(ts|tsx)$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
out.push(full);
}
}
return out;
}
/**
* Problems with iframes in one source file: every <iframe> must carry the literal sandbox="" and no spread props
* (a spread could override the sandbox), and iframes must not be created imperatively.
*/
function iframeProblems(fileName: string, src: string): string[] {
const problems: string[] = [];
const sf = ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const visit = (node: ts.Node) => {
if (
(ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) &&
node.tagName.getText(sf) === "iframe"
) {
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
const props = node.attributes.properties;
if (props.some(ts.isJsxSpreadAttribute)) problems.push(`${fileName}:${line} iframe with spread props`);
const sandbox = props.find(
(p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === "sandbox",
);
const value = sandbox?.initializer;
const allowed = SANDBOX_ALLOWED[fileName];
const named = !!allowed && !!value && ts.isJsxExpression(value) && value.expression?.getText(sf) === allowed;
const attr = (n: string) => props.find((p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === n);
const canvas = UNSANDBOXED_ALLOWED[fileName];
const srcDoc = attr("srcDoc")?.initializer;
const blank = !!canvas && !sandbox && !attr("src") && src.includes(canvas.html)
&& !!srcDoc && ts.isJsxExpression(srcDoc) && srcDoc.expression?.getText(sf) === canvas.srcDoc;
if (!named && !blank && (!value || !ts.isStringLiteral(value) || value.text !== "")) {
problems.push(`${fileName}:${line} iframe without sandbox=""`);
}
}
if (
ts.isCallExpression(node) &&
node.expression.getText(sf).endsWith("createElement") &&
node.arguments[0] &&
ts.isStringLiteral(node.arguments[0]) &&
node.arguments[0].text.toLowerCase() === "iframe"
) {
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
problems.push(`${fileName}:${line} iframe created imperatively`);
}
ts.forEachChild(node, visit);
};
visit(sf);
return problems;
}
const files = sourceFiles(APP_DIR).map((f) => ({
rel: path.relative(APP_DIR, f).split(path.sep).join("/"),
src: fs.readFileSync(f, "utf8"),
}));
describe("admin portal never injects HTML into its own origin", () => {
it("scans real source files", () => {
expect(files.length).toBeGreaterThan(20);
});
it("uses HTML sinks only where allow-listed", () => {
const offenders: string[] = [];
for (const f of files) {
for (const sink of HTML_SINKS) {
if (f.src.includes(sink) && !(SINK_ALLOWED[f.rel] ?? []).includes(sink)) offenders.push(`${f.rel}: ${sink}`);
}
}
expect(offenders).toEqual([]);
});
it("keeps the allow-list honest: every listed file still exists and still uses its sink", () => {
for (const [rel, sinks] of Object.entries(SINK_ALLOWED)) {
const file = files.find((f) => f.rel === rel);
expect(file, rel).toBeDefined();
for (const sink of sinks) expect(file!.src.includes(sink), `${rel}: ${sink}`).toBe(true);
}
});
it("lets the Custom HTML frame run scripts, never as this origin, submit forms or navigate the page", () => {
const grants = FRAME_SANDBOX.split(/\s+/);
for (const g of ["allow-same-origin", "allow-forms", "allow-top-navigation", "allow-top-navigation-by-user-activation", "allow-modals"]) {
expect(grants).not.toContain(g);
}
});
it("gives every iframe a literal empty sandbox", () => {
const problems = files.flatMap((f) => iframeProblems(f.rel, f.src));
expect(problems).toEqual([]);
});
});
describe("iframe checker", () => {
const check = (jsx: string) => iframeProblems("fixture.tsx", `export const X = () => ${jsx};`);
it("accepts a literal empty sandbox", () => {
expect(check(`<iframe title="t" sandbox="" srcDoc={html} />`)).toEqual([]);
});
it("is not fooled by '>' inside an attribute expression", () => {
expect(check(`<iframe onLoad={() => a > b} srcDoc={html} />`)).toHaveLength(1);
});
it("rejects a spread that could override the sandbox", () => {
expect(check(`<iframe sandbox="" {...props} srcDoc={html} />`)).toHaveLength(1);
});
it("accepts the named Custom HTML sandbox only in its allow-listed file", () => {
const src = `export const X = () => <iframe title="t" sandbox={FRAME_SANDBOX} src={u} />;`;
expect(iframeProblems("components/pages/HtmlFrame.tsx", src)).toEqual([]);
expect(iframeProblems("fixture.tsx", src)).toHaveLength(1);
expect(iframeProblems("components/pages/HtmlFrame.tsx", src.replace("FRAME_SANDBOX", "mode"))).toHaveLength(1);
});
it("accepts the editor canvas unsandboxed only in its file, with its constant blank document and no src", () => {
const blank = `const BLANK = "<!doctype html><html><head></head><body></body></html>";\n`;
const src = `${blank}export const X = () => <iframe title="t" srcDoc={BLANK} />;`;
expect(iframeProblems("components/pages/CanvasFrame.tsx", src)).toEqual([]);
expect(iframeProblems("fixture.tsx", src)).toHaveLength(1);
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("srcDoc={BLANK}", "srcDoc={html}"))).toHaveLength(1);
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("srcDoc={BLANK}", "srcDoc={BLANK} src={u}"))).toHaveLength(1);
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("<body></body>", "<body><script>x()</script></body>"))).toHaveLength(1);
});
it("rejects a non-empty or computed sandbox", () => {
expect(check(`<iframe sandbox="allow-scripts" srcDoc={html} />`)).toHaveLength(1);
expect(check(`<iframe sandbox={mode} srcDoc={html} />`)).toHaveLength(1);
});
it("rejects an unsandboxed frame loading a blob or any other src", () => {
expect(check(`<iframe src={URL.createObjectURL(blob)} />`)).toHaveLength(1);
});
it("rejects iframes created imperatively", () => {
expect(check(`React.createElement("iframe", { srcDoc: html })`)).toHaveLength(1);
expect(check(`document.createElement("iframe")`)).toHaveLength(1);
});
});