diff --git a/apps/docs/scripts/publish/publish-index.mjs b/apps/docs/scripts/publish/publish-index.mjs new file mode 100644 index 00000000..96411563 --- /dev/null +++ b/apps/docs/scripts/publish/publish-index.mjs @@ -0,0 +1,77 @@ +// Keeps artifact text from forming a `::cmd::` or `##[cmd]` workflow command in the publish job's output. +import { readFile } from "node:fs/promises"; +import { hasUnsafePathSegment } from "@coder/docs-manifest"; + +// Next names dynamic-route payloads `__next.$oc$slug.txt`. +const SAFE_PATH_CHARS = "A-Za-z0-9._/@$-"; +const SAFE_ARTIFACT_PATH = new RegExp(`^[${SAFE_PATH_CHARS}]+$`); +const UNSAFE_PATH_CHAR = new RegExp(`[^${SAFE_PATH_CHARS}]`, "g"); +const MAX_ARTIFACT_PATH_LENGTH = 1024; +const SHA256 = /^[0-9a-f]{64}$/; + +/** + * Quote artifact-derived text for a log line, truncated and with every + * character outside the path allowlist replaced by `?`. + * + * @param {unknown} value + * @param {number} [max] + */ +export function describeForLog(value, max = 80) { + const text = String(value).replace(UNSAFE_PATH_CHAR, "?"); + return JSON.stringify(text.length > max ? `${text.slice(0, max)}...` : text); +} + +/** + * Whether an archive key from the artifact may be uploaded and printed: the + * router's traversal rule plus an allowlist with no control characters. + * + * @param {unknown} key + */ +export function isSafeArtifactPath(key) { + return ( + typeof key === "string" && + key.length > 0 && + key.length <= MAX_ARTIFACT_PATH_LENGTH && + SAFE_ARTIFACT_PATH.test(key) && + !key.startsWith("/") && + !key.endsWith("/") && + !key.includes("//") && + !hasUnsafePathSegment(key) + ); +} + +/** + * Parse `_publish.json` and refuse it unless every entry is safe. Errors name + * the entry by position and never quote the artifact's text. + * + * @param {string} text + * @returns {{ version: 1; files: { path: string; sha256: string }[] }} + */ +export function parsePublishIndex(text) { + let index; + try { + index = JSON.parse(text); + } catch { + throw new Error("_publish.json is not valid JSON"); + } + if (index?.version !== 1 || !Array.isArray(index.files)) { + throw new Error("_publish.json has an unrecognised shape"); + } + index.files.forEach((file, i) => { + if (typeof file !== "object" || file === null) { + throw new Error(`_publish.json entry ${i} is not an object`); + } + if (!isSafeArtifactPath(file.path)) { + throw new Error(`_publish.json entry ${i} has an unsafe path: ${describeForLog(file.path)}`); + } + if (typeof file.sha256 !== "string" || !SHA256.test(file.sha256)) { + throw new Error(`_publish.json entry ${i} has no valid sha256`); + } + }); + return index; +} + +/** @param {string} file */ +export async function readPublishIndex(file) { + return parsePublishIndex(await readFile(file, "utf8")); +} diff --git a/apps/docs/scripts/publish/publish-index.test.mjs b/apps/docs/scripts/publish/publish-index.test.mjs new file mode 100644 index 00000000..d56dd8c9 --- /dev/null +++ b/apps/docs/scripts/publish/publish-index.test.mjs @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { + describeForLog, + isSafeArtifactPath, + parsePublishIndex, + readPublishIndex, +} from "./publish-index.mjs"; + +const sha256 = "a".repeat(64); +const indexOf = (...paths) => + JSON.stringify({ version: 1, files: paths.map((path) => ({ path, sha256, bytes: 1 })) }); + +test("isSafeArtifactPath accepts the key shapes a real export produces", () => { + for (const key of [ + "beta-docs/@main/index.html", + "beta-docs/@2.36/_next/static/chunks/0cz1d0mv5g_q7.js", + "beta-docs/@main/admin/__next.$oc$slug.__PAGE__.txt", + "beta-docs/@main/images/Screenshot.PNG", + "_redirects.json", + ]) { + assert.equal(isSafeArtifactPath(key), true, key); + } +}); + +test("isSafeArtifactPath refuses control characters, separators tricks, and traversal", () => { + for (const key of [ + "beta-docs/\n::error title=x::y\n::stop-commands::z/index.html", + "beta-docs/a\rb", + "beta-docs/a\u0000b", + "beta-docs/a b/index.html", + "beta-docs/a%2f..%2fb", + "beta-docs/../x", + "beta-docs/./x", + "beta-docs\\x", + "/beta-docs/x", + "beta-docs//x", + "beta-docs/x/", + "beta-docs/é.html", + "::error::x", + "beta-docs/##[error]x", + "beta-docs/a%0Ab", + "beta-docs/a\u2028b", + "beta-docs/a\u0005b", + "", + `beta-docs/${"a".repeat(1100)}`, + undefined, + 42, + ]) { + assert.equal(isSafeArtifactPath(key), false, JSON.stringify(key)); + } +}); + +const WORKFLOW_COMMAND_OR_LINE_BREAK = /##\[|::|%|[\r\n\u0085\u2028\u2029]/; +const hostileTexts = [ + "##[add-mask]x", + "##[error]x", + "beta-docs/##[error title=Publish compromised]rotate the token", + "::error::x", + "a\n::error::x", + "a\r\n##[stop-commands]t", + "\u2028::x", + "\u2029##[warning]x", + "\u0085::x", + "a%0A::error::x", + "x\u001b[31m", +]; + +test("describeForLog never prints text the runner could read as a workflow command", () => { + for (const hostile of hostileTexts) { + assert.doesNotMatch( + describeForLog(hostile), + WORKFLOW_COMMAND_OR_LINE_BREAK, + JSON.stringify(hostile), + ); + } + assert.equal(describeForLog("beta-docs/@main/a b.html"), '"beta-docs/@main/a?b.html"'); + assert.ok(describeForLog("a".repeat(500)).length < 120); +}); + +test("parsePublishIndex returns an index whose every path is safe", () => { + const index = parsePublishIndex(indexOf("beta-docs/index.html", "beta-docs/a/index.html")); + assert.deepEqual( + index.files.map((f) => f.path), + ["beta-docs/index.html", "beta-docs/a/index.html"], + ); +}); + +test("parsePublishIndex refuses an unsafe path without echoing it raw", () => { + const hostile = "beta-docs/v2.38/\n::error title=pwned::injected\n::stop-commands::x/index.html"; + assert.throws( + () => parsePublishIndex(indexOf("beta-docs/index.html", hostile)), + (error) => { + assert.match(error.message, /entry 1 has an unsafe path/); + assert.doesNotMatch(error.message, WORKFLOW_COMMAND_OR_LINE_BREAK); + return true; + }, + ); + for (const text of hostileTexts) { + assert.throws( + () => parsePublishIndex(indexOf(text)), + (error) => !WORKFLOW_COMMAND_OR_LINE_BREAK.test(error.message), + JSON.stringify(text), + ); + } +}); + +test("parsePublishIndex refuses a bad hash, a wrong shape, and invalid JSON without quoting the text", () => { + assert.throws( + () => + parsePublishIndex( + JSON.stringify({ version: 1, files: [{ path: "a.html", sha256: "z\n::error::x" }] }), + ), + (error) => /entry 0 has no valid sha256/.test(error.message) && !/::error/.test(error.message), + ); + assert.throws(() => parsePublishIndex(JSON.stringify({ version: 2, files: [] })), /unrecognised/); + assert.throws(() => parsePublishIndex(JSON.stringify({ version: 1, files: {} })), /unrecognised/); + assert.throws(() => parsePublishIndex(JSON.stringify({ version: 1, files: [null] })), /entry 0/); + assert.throws( + () => parsePublishIndex('{"files": "\n::error::injected'), + (error) => /not valid JSON/.test(error.message) && !/::error/.test(error.message), + ); +}); + +test("readPublishIndex reads and validates a file", async () => { + const dir = await mkdtemp(join(tmpdir(), "docs-index-")); + try { + await writeFile(join(dir, "_publish.json"), indexOf("beta-docs/index.html")); + assert.equal((await readPublishIndex(join(dir, "_publish.json"))).files.length, 1); + await writeFile(join(dir, "bad.json"), indexOf("a\nb")); + await assert.rejects(() => readPublishIndex(join(dir, "bad.json")), /unsafe path/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/apps/docs/scripts/publish/smoke.mjs b/apps/docs/scripts/publish/smoke.mjs index bf19e7a5..a6d653e8 100644 --- a/apps/docs/scripts/publish/smoke.mjs +++ b/apps/docs/scripts/publish/smoke.mjs @@ -18,6 +18,7 @@ // what the settle window in `probe` is for. import { readFile } from "node:fs/promises"; import { normalizeBasePath } from "../single-version.mjs"; +import { readPublishIndex } from "./publish-index.mjs"; import { expectedPrefixes, hasSitemapEntry } from "./verify.mjs"; /** @@ -175,7 +176,7 @@ if (process.argv[1]?.endsWith("smoke.mjs")) { process.exit(2); } const plan = JSON.parse(await readFile(planFile, "utf8")); - const index = JSON.parse(await readFile(indexFile, "utf8")); + const index = await readPublishIndex(indexFile); const targets = smokeTargets({ plan, basePath, siteUrl, index }); for (const target of targets) console.log(`checking ${target.label}: ${target.url}`); const result = await probe(targets, { diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index 09406c97..646639aa 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -14,6 +14,7 @@ import { import { copy, get, put } from "@vercel/blob"; import { contentTypeFor } from "../archive-layout-helpers.mjs"; import { logBlobRetry, withBlobRetry } from "./blob-retry.mjs"; +import { describeForLog, isSafeArtifactPath, readPublishIndex } from "./publish-index.mjs"; const ARCHIVE_PREFIX = /^versions\/(\d+\.\d+(\.\d+)?|main)\/[0-9a-f]{40}$/; @@ -135,7 +136,12 @@ async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { MAX_RECORDED_OBJECTS_BYTES, ); if (text === null) throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`); - const recorded = JSON.parse(text); + let recorded; + try { + recorded = JSON.parse(text); + } catch { + throw new Error("not valid JSON"); + } if (recorded?.version !== 1 || typeof recorded.files !== "object" || recorded.files === null) { throw new Error("unrecognised format"); } @@ -187,13 +193,24 @@ export async function uploadDir({ }) { assertArchivePrefix(prefix); if (reuseFrom !== undefined) assertArchivePrefix(reuseFrom); - const index = JSON.parse(await readFile(path.join(dir, "_publish.json"), "utf8")); + const index = await readPublishIndex(path.join(dir, "_publish.json")); const byPath = new Map(index.files.map((file) => [file.path, file])); const files = (await readdir(dir, { recursive: true, withFileTypes: true })) .filter((e) => e.isFile()) .map((e) => path.relative(dir, path.join(e.parentPath, e.name)).split(path.sep).join("/")) .filter((p) => p !== "_publish.json") .toSorted(); + for (const file of files) { + if (!isSafeArtifactPath(file)) { + throw new Error( + `upload: the artifact has a file with an unsafe path: ${describeForLog(file)}`, + ); + } + // Underscore-prefixed root keys are reserved for the publisher. + if (!file.includes("/") && file.startsWith("_") && file !== VERSION_REDIRECTS_KEY) { + throw new Error(`upload: the artifact carries a reserved root file: ${describeForLog(file)}`); + } + } if (files.length === 0) throw new Error(`upload: ${dir} has no files to upload (besides _publish.json)`); if (files.includes(VERSION_REDIRECTS_KEY)) { diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index d7163046..f5b9facb 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -610,6 +610,66 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined); }); +test("an artifact path with a newline stops the upload before any put, without echoing it", async () => { + const hostile = "beta-docs/v2.38/\n::error title=pwned::injected\n::stop-commands::x/index.html"; + const dir = await archiveFixture([entry("index.html"), entry(hostile)]); + await assert.rejects( + () => uploadDir({ dir, prefix: `versions/main/${sha}`, token: "t", blobPut: refusingBlobPut }), + (error) => /unsafe path/.test(error.message) && !/[\r\n]/.test(error.message), + ); +}); + +test("a file on disk with an unsafe name stops the upload, named without control characters", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + await writeFile(path.join(dir, "bad\n::error::x.html"), "x"); + await assert.rejects( + () => uploadDir({ dir, prefix: `versions/main/${sha}`, token: "t", blobPut: refusingBlobPut }), + (error) => /unsafe path/.test(error.message) && !/[\r\n]/.test(error.message), + ); +}); + +test("a file on disk named as a legacy workflow command is refused without printing the command", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + await writeFile(path.join(dir, "##[error title=Publish compromised]rotate the token"), "x"); + await assert.rejects( + () => uploadDir({ dir, prefix: `versions/main/${sha}`, token: "t", blobPut: refusingBlobPut }), + (error) => /unsafe path/.test(error.message) && !/##\[|::/.test(error.message), + ); +}); + +test("an artifact cannot ship publisher-owned root files such as _objects.json", async () => { + const dir = await archiveFixture([ + entry("index.html"), + entry("_next/static/chunks/a.js"), + entry("_objects.json"), + ]); + await writeFile( + path.join(dir, "_objects.json"), + JSON.stringify({ version: 1, files: { "index.html": { sha256: "b".repeat(64), bytes: 1 } } }), + ); + await assert.rejects( + () => uploadDir({ dir, prefix: `versions/main/${sha}`, token: "t", blobPut: refusingBlobPut }), + /reserved root file/, + ); +}); + +test("_redirects.json is the one underscore-prefixed root file an artifact may carry", async () => { + const dir = await archiveFixture([ + entry("index.html"), + entry("_next/static/chunks/a.js"), + entry("_redirects.json"), + ]); + await writeFile(path.join(dir, "_redirects.json"), "{}"); + const result = await uploadDir({ + dir, + prefix: `versions/main/${sha}`, + token: "t", + concurrency: 1, + blobPut: acceptingBlobPut, + }); + assert.equal(result.count, 3); +}); + test("a _redirects.json over the cap fails the upload before anything is put", async () => { const dir = await archiveFixture([entry("index.html"), entry("_redirects.json")]); await writeFile(path.join(dir, "_redirects.json"), "x".repeat(MAX_VERSION_REDIRECTS_BYTES + 1)); @@ -665,6 +725,33 @@ test("a recorded _objects.json that reports a size over the limit is not read, a assert.match(skipped[0], /larger than/); }); +test("an unparsable recorded _objects.json skips reuse without quoting its text", async () => { + const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); + const store = recordingStore(); + const body = new TextEncoder().encode('{"files": ##[error]x\n::error::y'); + store.blobGet = async () => ({ + blob: { size: body.byteLength }, + stream: new ReadableStream({ + start(controller) { + controller.enqueue(body); + controller.close(); + }, + }), + }); + const skipped = []; + await uploadDir({ + dir, + prefix: `versions/2.36/${sha}`, + token: "t", + concurrency: 1, + reuseFrom: previous, + onReuseSkipped: (info) => skipped.push(info.reason), + ...store, + }); + assert.equal(skipped.length, 1); + assert.doesNotMatch(skipped[0], /##\[|::|[\r\n]/); +}); + test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => { const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]); const prefix = `versions/main/${sha}`; diff --git a/apps/docs/scripts/publish/verify.mjs b/apps/docs/scripts/publish/verify.mjs index 38ad7245..f0a0f99a 100644 --- a/apps/docs/scripts/publish/verify.mjs +++ b/apps/docs/scripts/publish/verify.mjs @@ -25,6 +25,7 @@ import { get } from "@vercel/blob"; import { JSDOM } from "jsdom"; import { normalizeBasePath, versionAssetPrefix } from "../single-version.mjs"; import { withBlobRetry } from "./blob-retry.mjs"; +import { parsePublishIndex } from "./publish-index.mjs"; import { assertArchivePrefix } from "./upload.mjs"; const SITEMAP_NS = "http://www.sitemaps.org/schemas/sitemap/0.9"; @@ -134,7 +135,7 @@ export async function verifyPrefix({ prefix, plan, basePath, token, blobGet = ge checks: [{ ok: false, error: "FAIL _publish.json is missing; the upload did not complete" }], }; } - const index = JSON.parse(indexBytes.toString("utf8")); + const index = parsePublishIndex(indexBytes.toString("utf8")); const assets = checkAssetPrefix(index, assetPrefix); const checks = [ { diff --git a/apps/docs/scripts/publish/verify.test.mjs b/apps/docs/scripts/publish/verify.test.mjs index beb9c976..97e6edc4 100644 --- a/apps/docs/scripts/publish/verify.test.mjs +++ b/apps/docs/scripts/publish/verify.test.mjs @@ -333,3 +333,23 @@ test("hasSitemapEntry, given a prefix, needs every to sit under it", () => false, ); }); + +test("verifyPrefix refuses an index whose path could carry a workflow command", async () => { + const { blobGet } = fakeStore(); + const hostile = "beta-docs/v2.36/\n::error title=pwned::injected\n::stop-commands::x/index.html"; + const poisoned = async (key) => + key === `${prefix}/_publish.json` + ? { + stream: new Response( + JSON.stringify({ + version: 1, + files: [{ path: hostile, sha256: "a".repeat(64), bytes: 1 }], + }), + ).body, + } + : blobGet(key); + await assert.rejects( + () => verifyPrefix({ prefix, plan, basePath: "/beta-docs", token: "t", blobGet: poisoned }), + (error) => /unsafe path/.test(error.message) && !/[\r\n]/.test(error.message), + ); +});