From 0dfe811d673961928ae193391a46318e5998754c Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 17:47:54 +0000 Subject: [PATCH 1/3] fix(docs): refuse artifact paths that GitHub could read as workflow commands The secret-holding publish job printed paths and keys from the untrusted build artifact at the start of log lines, where the runner looks for workflow commands. Every _publish.json entry is now checked before use with the router's traversal rule plus an allowlist with no control characters, and an artifact that fails is refused with an error that never quotes its text. The same check covers the files found on disk, and the index is parsed with a generic error so a JSON snippet cannot leak. The uploader also refuses any underscore-prefixed root file other than _redirects.json, so an artifact cannot supply the publisher-owned _objects.json. The allowlist also admits the dollar sign, because Next names its dynamic-route payloads with it and every real export contains them. Assisted-by: AI --- apps/docs/scripts/publish/publish-index.mjs | 78 +++++++++++++ .../scripts/publish/publish-index.test.mjs | 104 ++++++++++++++++++ apps/docs/scripts/publish/smoke.mjs | 3 +- apps/docs/scripts/publish/upload.mjs | 15 ++- apps/docs/scripts/publish/upload.test.mjs | 51 +++++++++ apps/docs/scripts/publish/verify.mjs | 3 +- apps/docs/scripts/publish/verify.test.mjs | 20 ++++ 7 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 apps/docs/scripts/publish/publish-index.mjs create mode 100644 apps/docs/scripts/publish/publish-index.test.mjs diff --git a/apps/docs/scripts/publish/publish-index.mjs b/apps/docs/scripts/publish/publish-index.mjs new file mode 100644 index 00000000..7b79223c --- /dev/null +++ b/apps/docs/scripts/publish/publish-index.mjs @@ -0,0 +1,78 @@ +// The publish job treats the export artifact as data. Everything it prints or +// uploads from `_publish.json` goes through here first, because GitHub Actions +// reads `::command::` lines out of any step's output. +import { readFile } from "node:fs/promises"; +import { hasUnsafePathSegment } from "@coder/docs-manifest"; + +// `$` is in the set because Next names its dynamic-route payloads +// `__next.$oc$slug.txt`. +const SAFE_ARTIFACT_PATH = /^[A-Za-z0-9._/@$-]+$/; +const MAX_ARTIFACT_PATH_LENGTH = 1024; +const SHA256 = /^[0-9a-f]{64}$/; + +/** + * Quote artifact-derived text for a log line: printable ASCII only and + * truncated, so it can neither end the line it sits in nor start a new one. + * + * @param {unknown} value + * @param {number} [max] + */ +export function describeForLog(value, max = 80) { + const text = String(value).replace(/[^\x20-\x7e]/g, "?"); + 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..80fdd539 --- /dev/null +++ b/apps/docs/scripts/publish/publish-index.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +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", + "", + `beta-docs/${"a".repeat(1100)}`, + undefined, + 42, + ]) { + assert.equal(isSafeArtifactPath(key), false, JSON.stringify(key)); + } +}); + +test("describeForLog never lets artifact text start a line or carry a control character", () => { + const hostile = "x\n::add-mask::secret\r\n::stop-commands::t\u001b[31m"; + const printed = describeForLog(hostile); + assert.doesNotMatch(printed, /[\r\n]/); + assert.equal(printed.startsWith("::"), false); + 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, /[\r\n]/); + assert.doesNotMatch(error.message, /^::/m); + return true; + }, + ); +}); + +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 { mkdtemp, writeFile } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = await mkdtemp(join(tmpdir(), "docs-index-")); + 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/); +}); 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 2f058453..aedff1fc 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -7,6 +7,7 @@ import { DEV_KEY, lineKey, tagKey } from "@coder/docs-manifest"; 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}$/; @@ -109,6 +110,7 @@ export function liveArchivePrefix({ items, plan }) { // prefix. That is what makes it safe to copy from on the next publish: // `_publish.json` hashes are the untrusted build's claims. const OBJECTS_KEY = "_objects.json"; +const REDIRECTS_FILE = "_redirects.json"; async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { try { @@ -171,13 +173,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)}`, + ); + } + // The publisher writes every other underscore-prefixed root file itself. + if (!file.includes("/") && file.startsWith("_") && file !== REDIRECTS_FILE) { + 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)`); const reusable = diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index 63b216ac..2f3e0a2a 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -592,3 +592,54 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from", assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.36" } }), undefined); 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("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); +}); 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), + ); +}); From de1b7d32cb2ee9c5402360aeb7fbfaf2f3e49dc9 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:14:44 -0700 Subject: [PATCH 2/3] fix(docs): print refused artifact paths with only allowlisted characters describeForLog kept every printable ASCII character, so a refused path such as "##[error title=x]y" still reached the log with "##[" intact. The runner parses that legacy command syntax anywhere in a line once the "::" parser has failed, so quoting alone let an artifact forge annotations, add-mask or stop-commands through the new error messages. Every character outside the path allowlist now prints as "?", and the allowlist is defined once for both the check and the log form. The tests now assert the failure mode directly: no "##[", "::", "%" or line break of any kind in the printed text or the thrown errors. The upload check reuses VERSION_REDIRECTS_KEY from @coder/docs-manifest instead of a private copy of the name. Assisted-by: AI --- apps/docs/scripts/publish/publish-index.mjs | 17 +++-- .../scripts/publish/publish-index.test.mjs | 62 ++++++++++++++----- apps/docs/scripts/publish/upload.mjs | 7 +-- apps/docs/scripts/publish/upload.test.mjs | 9 +++ 4 files changed, 68 insertions(+), 27 deletions(-) diff --git a/apps/docs/scripts/publish/publish-index.mjs b/apps/docs/scripts/publish/publish-index.mjs index 7b79223c..96411563 100644 --- a/apps/docs/scripts/publish/publish-index.mjs +++ b/apps/docs/scripts/publish/publish-index.mjs @@ -1,24 +1,23 @@ -// The publish job treats the export artifact as data. Everything it prints or -// uploads from `_publish.json` goes through here first, because GitHub Actions -// reads `::command::` lines out of any step's output. +// 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"; -// `$` is in the set because Next names its dynamic-route payloads -// `__next.$oc$slug.txt`. -const SAFE_ARTIFACT_PATH = /^[A-Za-z0-9._/@$-]+$/; +// 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: printable ASCII only and - * truncated, so it can neither end the line it sits in nor start a new one. + * 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(/[^\x20-\x7e]/g, "?"); + const text = String(value).replace(UNSAFE_PATH_CHAR, "?"); return JSON.stringify(text.length > max ? `${text.slice(0, max)}...` : text); } diff --git a/apps/docs/scripts/publish/publish-index.test.mjs b/apps/docs/scripts/publish/publish-index.test.mjs index 80fdd539..d56dd8c9 100644 --- a/apps/docs/scripts/publish/publish-index.test.mjs +++ b/apps/docs/scripts/publish/publish-index.test.mjs @@ -1,4 +1,7 @@ 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, @@ -37,6 +40,11 @@ test("isSafeArtifactPath refuses control characters, separators tricks, and trav "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, @@ -46,11 +54,30 @@ test("isSafeArtifactPath refuses control characters, separators tricks, and trav } }); -test("describeForLog never lets artifact text start a line or carry a control character", () => { - const hostile = "x\n::add-mask::secret\r\n::stop-commands::t\u001b[31m"; - const printed = describeForLog(hostile); - assert.doesNotMatch(printed, /[\r\n]/); - assert.equal(printed.startsWith("::"), false); +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); }); @@ -68,11 +95,17 @@ test("parsePublishIndex refuses an unsafe path without echoing it raw", () => { () => parsePublishIndex(indexOf("beta-docs/index.html", hostile)), (error) => { assert.match(error.message, /entry 1 has an unsafe path/); - assert.doesNotMatch(error.message, /[\r\n]/); - assert.doesNotMatch(error.message, /^::/m); + 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", () => { @@ -93,12 +126,13 @@ test("parsePublishIndex refuses a bad hash, a wrong shape, and invalid JSON with }); test("readPublishIndex reads and validates a file", async () => { - const { mkdtemp, writeFile } = await import("node:fs/promises"); - const { tmpdir } = await import("node:os"); - const { join } = await import("node:path"); const dir = await mkdtemp(join(tmpdir(), "docs-index-")); - 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/); + 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/upload.mjs b/apps/docs/scripts/publish/upload.mjs index aedff1fc..6257b315 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { readFile, readdir } from "node:fs/promises"; import path from "node:path"; -import { DEV_KEY, lineKey, tagKey } from "@coder/docs-manifest"; +import { DEV_KEY, VERSION_REDIRECTS_KEY, lineKey, tagKey } from "@coder/docs-manifest"; import { copy, get, put } from "@vercel/blob"; import { contentTypeFor } from "../archive-layout-helpers.mjs"; import { logBlobRetry, withBlobRetry } from "./blob-retry.mjs"; @@ -110,7 +110,6 @@ export function liveArchivePrefix({ items, plan }) { // prefix. That is what makes it safe to copy from on the next publish: // `_publish.json` hashes are the untrusted build's claims. const OBJECTS_KEY = "_objects.json"; -const REDIRECTS_FILE = "_redirects.json"; async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) { try { @@ -186,8 +185,8 @@ export async function uploadDir({ `upload: the artifact has a file with an unsafe path: ${describeForLog(file)}`, ); } - // The publisher writes every other underscore-prefixed root file itself. - if (!file.includes("/") && file.startsWith("_") && file !== REDIRECTS_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)}`); } } diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index 2f3e0a2a..99952202 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -611,6 +611,15 @@ test("a file on disk with an unsafe name stops the upload, named without control ); }); +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"), From c86e24e0c0ee16149d2816affae1935b47f594ad Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 15:38:10 -0700 Subject: [PATCH 3/3] fix(docs): report an unparsable recorded _objects.json without quoting it The reuse step from main logs why it skipped reuse, and for a JSON parse failure that reason was Node's own message, which quotes a snippet of the blob. The text is the store's copy of a file whose keys came from an earlier artifact, so it now reports "not valid JSON" instead, the same way _publish.json parse failures are reported. Assisted-by: AI --- apps/docs/scripts/publish/upload.mjs | 7 +++++- apps/docs/scripts/publish/upload.test.mjs | 27 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs index a6924546..646639aa 100644 --- a/apps/docs/scripts/publish/upload.mjs +++ b/apps/docs/scripts/publish/upload.mjs @@ -136,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"); } diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs index aa2578b4..f5b9facb 100644 --- a/apps/docs/scripts/publish/upload.test.mjs +++ b/apps/docs/scripts/publish/upload.test.mjs @@ -725,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}`;