Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/2496-validate-allow-host.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@schlessera/brain-render-puppeteer": patch
"@schlessera/brain-render-template": patch
"@schlessera/brain": patch
---

`brain render --allow-host` and the renderer's `allowHosts` now refuse any value that is not a plain host name or IP address. Before, `--allow-host '*'` exempted every host from the renderer's DNS blackhole, and a value with a comma could inject another resolver rule. A wildcard, comma, space, scheme, port or path is now a usage error that names the value, before anything renders. An allowed host also admits only its `http:` and `https:` requests.
2 changes: 2 additions & 0 deletions api-report/render-template.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ export "." (./src/index.ts)
lintDocument

export "./internal" (./src/internal.ts)
allowHostProblem
applyExportLinkPolicy
documentTitle
isFullDocument
normalizeAllowHosts
prepareStaticDocument
protectExportLinkDestinations

Expand Down
5 changes: 4 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ Chrome available. Without it the command explains what is missing and

The page resolves no hostname by default, so remote images become a visible
`[alt — not embedded]` placeholder. `--allow-host <host>` opens specific image
hosts; `data:` URIs always render.
hosts over `http:` and `https:`; `data:` URIs always render. Each value must be
a plain host name or IP address. A wildcard, comma, space, scheme, port or path
is a usage error before anything renders, because each host becomes one
exception in the renderer's DNS blackhole.

The shell's stylesheet lays a PDF out as full-bleed A4, with the title and
"2 / 5" in the footer from page 2, and styles plain markdown into a finished
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/cli/commands/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
lintDocument,
type RenderContentType,
} from "@schlessera/brain-render-template";
import { documentTitle, isFullDocument, prepareStaticDocument } from "@schlessera/brain-render-template/internal";
import { allowHostProblem, documentTitle, isFullDocument, prepareStaticDocument } from "@schlessera/brain-render-template/internal";
import { DOCUMENT_KINDS, readSkeleton, resolveKind } from "@schlessera/brain-render-template/kinds";

import { collectModuleRenderers } from "../../lib/module-renderers.js";
Expand Down Expand Up @@ -292,6 +292,12 @@ export const renderCommand: CoreCommand = {
}

const allowHosts = repeatedValues(args, "allow-host");
// Each host becomes a renderer DNS rule: refuse anything but a plain host
// before building or rendering anything (#2496).
for (const host of allowHosts) {
const problem = allowHostProblem(host);
if (problem) throw new UsageError(`--allow-host ${problem}`);
}
const width = flags.width !== undefined ? Number(flags.width) : undefined;
if (width !== undefined && !Number.isFinite(width)) {
throw new UsageError(`--width must be a number, got "${String(flags.width)}"`);
Expand Down
16 changes: 16 additions & 0 deletions packages/core/tests/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,22 @@ describe("brain render", () => {
});
});

describe("--allow-host takes only a plain host (#2496)", () => {
for (const format of ["html", "pdf"]) test(`--allow-host '*' is a usage error naming the value, before any render (${format})`, async () => {
const out = `notes/allow-star.${format}`;
const res = await render(["notes/trip.md", "--format", format, "--out", out, "--allow-host", "*", "--json"]);
expect(res.code).toBe(1);
expect(res.stderr + res.stdout).toContain('--allow-host "*" is not a plain host name or IP address');
expect(existsSync(join(root, out))).toBe(false);
});

test("an entry that would inject a resolver rule is refused", async () => {
const res = await render(["notes/trip.md", "--format", "html", "--out", "notes/allow-comma.html", "--allow-host", "upload.wikimedia.org, MAP * 10.0.0.1", "--json"]);
expect(res.code).toBe(1);
expect(res.stderr + res.stdout).toContain("upload.wikimedia.org, MAP * 10.0.0.1");
});
});

describe("the temp directory is not scratch space (#310)", () => {
test("an output under the system temp directory is refused", async () => {
const out = join(tmpdir(), `brain-render-${Date.now()}.html`);
Expand Down
34 changes: 34 additions & 0 deletions packages/render-template/src/allow-hosts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Image host allowlist entries (#2496). The renderer turns each entry into one
* `EXCLUDE <host>` in Chrome's DNS blackhole (`--host-resolver-rules`), whose
* syntax is a comma-separated rule list with wildcard host patterns. So an
* entry must be a plain DNS host name or IP literal, nothing else: `*` would
* exempt every host, and a comma would inject another rule.
*/

/** Lowercase labels of letters, digits, `-` and `_`, dot-separated; or a bracketed IPv6 literal. */
const PLAIN_HOST = /^(?:[a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])$/;

/** Why `value` is not a plain host, or `null` when it is one. */
export function allowHostProblem(value: string): string | null {
const lower = value.toLowerCase();
let parsed: string | null = null;
try {
parsed = new URL(`http://${lower}`).hostname;
} catch {
parsed = null;
}
// The URL parser keeps `*` and `,` in a host name, so the pattern carries
// the refusal; the round trip catches what the parser would rewrite.
if (PLAIN_HOST.test(lower) && parsed === lower) return null;
return `"${value}" is not a plain host name or IP address (no wildcard, comma, space, scheme, port or path)`;
}

/** The entries lowercased, or a throw naming the first that is not a plain host. */
export function normalizeAllowHosts(values: readonly string[]): string[] {
return values.map((value) => {
const problem = allowHostProblem(value);
if (problem) throw new Error(problem);
return value.toLowerCase();
});
}
1 change: 1 addition & 0 deletions packages/render-template/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export { applyExportLinkPolicy, protectExportLinkDestinations } from "./link-pol
export { documentTitle, isFullDocument } from "./template.js";

export { prepareStaticDocument } from "./static.js";
export { allowHostProblem, normalizeAllowHosts } from "./allow-hosts.js";
2 changes: 1 addition & 1 deletion packages/ui-render-puppeteer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ select an unbounded full-page screenshot.
| `maxConcurrent` | `2` | Renders in flight; more queue. |
| `maxQueue` | `16` | Waiting renders beyond the cap before "renderer busy". |
| `idleTimeoutMs` | 5 min | Close the browser after this long without a render. |
| `allowHosts` | `[]` | Explicit host allowlist excluded from **both** the DNS blackhole and interception. A predicate was rejected by design — it could only gate the interceptable channels. |
| `allowHosts` | `[]` | Explicit host allowlist excluded from **both** the DNS blackhole and interception (`http:` and `https:` requests only). Each entry must be a plain host name or IP literal; anything else (a wildcard, comma, space, scheme, port or path) throws from `createRenderer` before any launch. A predicate was rejected by design — it could only gate the interceptable channels. |

The phases are sequential. A render rejects or returns within
`queueTimeoutMs + browserTimeoutMs + renderTimeoutMs` (120 s by default),
Expand Down
29 changes: 18 additions & 11 deletions packages/ui-render-puppeteer/src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import puppeteer, { type Browser, type HTTPRequest, type Page } from "puppeteer-
import { existsSync } from "node:fs";

import type { ExportLinkPolicy } from "@schlessera/brain-render-template";
import { applyExportLinkPolicy, protectExportLinkDestinations } from "@schlessera/brain-render-template/internal";
import { applyExportLinkPolicy, normalizeAllowHosts, protectExportLinkDestinations } from "@schlessera/brain-render-template/internal";

import { resolveEnv } from "./config/env.js";
import { Semaphore } from "./semaphore.js";
Expand Down Expand Up @@ -67,6 +67,18 @@ export function shouldAllowRequest(url: string): boolean {
return url.startsWith("data:") || url === "about:blank";
}

/** Whether a request is an http(s) fetch from one of the allowed image hosts. */
export function hostRequestAllowed(url: string, hosts: ReadonlySet<string>): boolean {
if (hosts.size === 0) return false;
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
return hosts.has(parsed.hostname.toLowerCase());
} catch {
return false;
}
}

export interface RendererOptions {
/** Chrome executable. Default: PUPPETEER_EXECUTABLE_PATH / BRAIN_UI_CHROME_PATH / well-known paths. */
executablePath?: string;
Expand Down Expand Up @@ -154,8 +166,10 @@ export function createRenderer(options: RendererOptions = {}): Renderer {
const semaphore = new Semaphore(options.maxConcurrent ?? 2, options.maxQueue ?? 16);
const noSandbox = options.noSandbox ?? false;
const allowScripts = options.allowScripts ?? false;
const allowHosts = options.allowHosts ?? [];
const allowedHostSet = new Set(allowHosts.map((h) => h.toLowerCase()));
// Refused before any launch: each entry becomes one EXCLUDE in the DNS
// blackhole below, so only a plain host may reach that rule (#2496).
const allowHosts = normalizeAllowHosts(options.allowHosts ?? []);
const allowedHostSet = new Set(allowHosts);
let closed = false;

interface BrowserLaunch {
Expand Down Expand Up @@ -262,14 +276,7 @@ export function createRenderer(options: RendererOptions = {}): Renderer {
(idleTimer as { unref?: () => void }).unref?.();
}

function hostAllowed(url: string): boolean {
if (allowedHostSet.size === 0) return false;
try {
return allowedHostSet.has(new URL(url).hostname.toLowerCase());
} catch {
return false;
}
}
const hostAllowed = (url: string): boolean => hostRequestAllowed(url, allowedHostSet);

function onRequest(request: HTTPRequest): void {
let allow = false;
Expand Down
49 changes: 48 additions & 1 deletion packages/ui-render-puppeteer/tests/renderer.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";

import { shouldAllowRequest } from "../src/renderer";
import { createRenderer, hostRequestAllowed, shouldAllowRequest } from "../src/renderer";
import { Semaphore } from "../src/semaphore";

describe("shouldAllowRequest (default network policy)", () => {
Expand Down Expand Up @@ -93,3 +93,50 @@ describe("Semaphore", () => {
(await p)();
});
});

describe("the image host allowlist (#2496)", () => {
// Each entry becomes one `EXCLUDE` in Chrome's DNS blackhole. A wildcard, a
// comma or anything but a plain host would widen or rewrite that rule.
for (const bad of ["*", "a.test, MAP * 10.0.0.1", "a.test b.test", "https://a.test", "a.test:8080", "a,b.test", "*.ithaca.test", "a.test/path", ""]) {
test(`createRenderer refuses ${JSON.stringify(bad)} before any launch`, () => {
let launches = 0;
expect(() => createRenderer({ allowHosts: [bad], executablePath: "/fake/chrome", launch: (async () => { launches++; throw new Error("no browser"); }) as never }))
.toThrow("not a plain host name or IP address");
expect(launches).toBe(0);
});
}

test("a valid list becomes exactly one EXCLUDE per entry in the blackhole, and no other rule", async () => {
const seen: string[][] = [];
const renderer = createRenderer({
allowHosts: ["img.example.test", "192.0.2.10"], executablePath: "/fake/chrome",
launch: (async (args: { args: string[] }) => { seen.push(args.args); throw new Error("no browser"); }) as never,
});
await renderer.renderPdf({ html: "<p>Ithaca</p>" }).catch(() => {});
await renderer.shutdown();
expect(seen.length).toBe(1);
expect(seen[0]!.filter((arg) => arg.startsWith("--host-resolver-rules="))).toEqual(["--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE img.example.test, EXCLUDE 192.0.2.10"]);
});

test("plain hosts pass: mixed case is lowercased, and IPv4 and bracketed IPv6 literals are kept", async () => {
const seen: string[][] = [];
const renderer = createRenderer({
allowHosts: ["IMG.Example.Test", "192.0.2.10", "[2001:db8::1]", "cdn_1.ithaca.test"], executablePath: "/fake/chrome",
launch: (async (args: { args: string[] }) => { seen.push(args.args); throw new Error("no browser"); }) as never,
});
await renderer.renderPdf({ html: "<p>Ithaca</p>" }).catch(() => {});
await renderer.shutdown();
expect(seen[0]!.find((arg) => arg.startsWith("--host-resolver-rules="))).toBe("--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE img.example.test, EXCLUDE 192.0.2.10, EXCLUDE [2001:db8::1], EXCLUDE cdn_1.ithaca.test");
});

test("an allowed host admits only its http and https requests", () => {
const hosts = new Set(["img.example.test"]);
expect(hostRequestAllowed("https://img.example.test/a.png", hosts)).toBe(true);
expect(hostRequestAllowed("http://IMG.example.test/a.png", hosts)).toBe(true);
for (const url of ["ws://img.example.test/live", "ftp://img.example.test/a.png", "file://img.example.test/etc/passwd", "wss://img.example.test/"]) {
expect(hostRequestAllowed(url, hosts), url).toBe(false);
}
expect(hostRequestAllowed("https://other.example.test/a.png", hosts)).toBe(false);
expect(hostRequestAllowed("https://img.example.test/a.png", new Set())).toBe(false);
});
});
Loading