From 4471a270163d350e0d0978c803571af6f1a72b52 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 11:08:52 +0000 Subject: [PATCH] fix(render): accept only plain hosts in --allow-host (#2496) Each allowHosts entry becomes one EXCLUDE in the renderer's Chrome DNS blackhole, whose rule list is comma-separated with wildcard patterns. `*` exempted every host, and a comma injected another rule. A shared render-template check now accepts only a plain host name or IP literal: createRenderer throws before any launch, and `brain render --allow-host` turns it into a usage error naming the value. An allowed host also admits only http and https requests. Co-Authored-By: Claude Opus 5.5 --- .changeset/2496-validate-allow-host.md | 7 +++ api-report/render-template.txt | 2 + docs/cli.md | 5 +- packages/core/src/cli/commands/render.ts | 8 ++- packages/core/tests/render.test.ts | 16 ++++++ packages/render-template/src/allow-hosts.ts | 34 +++++++++++++ packages/render-template/src/internal.ts | 1 + packages/ui-render-puppeteer/README.md | 2 +- packages/ui-render-puppeteer/src/renderer.ts | 29 ++++++----- .../tests/renderer.test.ts | 49 ++++++++++++++++++- 10 files changed, 138 insertions(+), 15 deletions(-) create mode 100644 .changeset/2496-validate-allow-host.md create mode 100644 packages/render-template/src/allow-hosts.ts diff --git a/.changeset/2496-validate-allow-host.md b/.changeset/2496-validate-allow-host.md new file mode 100644 index 0000000000..c1c33c43f0 --- /dev/null +++ b/.changeset/2496-validate-allow-host.md @@ -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. diff --git a/api-report/render-template.txt b/api-report/render-template.txt index f00a8870e4..0a767b6e0c 100644 --- a/api-report/render-template.txt +++ b/api-report/render-template.txt @@ -16,9 +16,11 @@ export "." (./src/index.ts) lintDocument export "./internal" (./src/internal.ts) + allowHostProblem applyExportLinkPolicy documentTitle isFullDocument + normalizeAllowHosts prepareStaticDocument protectExportLinkDestinations diff --git a/docs/cli.md b/docs/cli.md index 2618bc1c66..c628f5503f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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 ` 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 diff --git a/packages/core/src/cli/commands/render.ts b/packages/core/src/cli/commands/render.ts index c0864e2454..81ec2dab58 100644 --- a/packages/core/src/cli/commands/render.ts +++ b/packages/core/src/cli/commands/render.ts @@ -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"; @@ -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)}"`); diff --git a/packages/core/tests/render.test.ts b/packages/core/tests/render.test.ts index cc476f7cc0..899cab0cf3 100644 --- a/packages/core/tests/render.test.ts +++ b/packages/core/tests/render.test.ts @@ -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`); diff --git a/packages/render-template/src/allow-hosts.ts b/packages/render-template/src/allow-hosts.ts new file mode 100644 index 0000000000..754db4827d --- /dev/null +++ b/packages/render-template/src/allow-hosts.ts @@ -0,0 +1,34 @@ +/** + * Image host allowlist entries (#2496). The renderer turns each entry into one + * `EXCLUDE ` 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(); + }); +} diff --git a/packages/render-template/src/internal.ts b/packages/render-template/src/internal.ts index fd912ad06c..82cc9d925a 100644 --- a/packages/render-template/src/internal.ts +++ b/packages/render-template/src/internal.ts @@ -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"; diff --git a/packages/ui-render-puppeteer/README.md b/packages/ui-render-puppeteer/README.md index 2892a5b7e9..2948182156 100644 --- a/packages/ui-render-puppeteer/README.md +++ b/packages/ui-render-puppeteer/README.md @@ -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), diff --git a/packages/ui-render-puppeteer/src/renderer.ts b/packages/ui-render-puppeteer/src/renderer.ts index 00c7d9b6e0..efb1108650 100644 --- a/packages/ui-render-puppeteer/src/renderer.ts +++ b/packages/ui-render-puppeteer/src/renderer.ts @@ -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"; @@ -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): 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; @@ -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 { @@ -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; diff --git a/packages/ui-render-puppeteer/tests/renderer.test.ts b/packages/ui-render-puppeteer/tests/renderer.test.ts index fa615b46cf..6f1ffb96c0 100644 --- a/packages/ui-render-puppeteer/tests/renderer.test.ts +++ b/packages/ui-render-puppeteer/tests/renderer.test.ts @@ -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)", () => { @@ -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: "

Ithaca

" }).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: "

Ithaca

" }).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); + }); +});