diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 690e6c66..5f6ec7e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,9 +126,25 @@ jobs: - "@coder/docs-transforms" - "@coder/docs-ui" - "@coder/offlinedocs" + env: + GITLEAKS_VERSION: 8.30.1 + GITLEAKS_SHA256: 551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/setup + # Pinned like actionlint below; with CI set, the secret-scan tests fail without it. + - name: Install gitleaks + if: matrix.package == '@coder/dist-release' + run: | + set -euo pipefail + base="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}" + tarball="gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" + cd "$RUNNER_TEMP" + curl -fsSLO "$base/$tarball" + echo "$GITLEAKS_SHA256 $tarball" | sha256sum -c - + mkdir -p gitleaks-bin + tar -xzf "$tarball" -C gitleaks-bin gitleaks + echo "$RUNNER_TEMP/gitleaks-bin" >> "$GITHUB_PATH" - name: Test run: pnpm turbo run test --filter=${{ matrix.package }} diff --git a/apps/dist-release/README.md b/apps/dist-release/README.md index c0204deb..0feff451 100644 --- a/apps/dist-release/README.md +++ b/apps/dist-release/README.md @@ -19,6 +19,12 @@ Bytes such as gzip's OS field differ between toolchains, so the release workflow Each package tarball may hold only `package.json`, `README.md`, `LICENSE` and the paths that `PACKAGE_ALLOW` in `src/config.mjs` names for that package, whatever the package's own `files` field says. TypeScript source files other than declarations fail the pack wherever they are, as do `.map` files, `sourceMappingURL` comments, and entries that are not regular files or directories. Any comment left in a shipped `.js`, `.mjs`, `.cjs` or `.d.ts` file fails the pack too; the files are parsed, so `//` inside a string is not a comment. +Each finished tarball is unpacked and scanned with [gitleaks](https://github.com/gitleaks/gitleaks) 8.19 or later (CI pins 8.30.1), and any finding fails the pack; findings name the rule, file and line, never the matched text. +A missing `gitleaks` on `PATH` fails the pack too. +For a local dry run only, `--allow-missing-gitleaks` skips the scan instead and prints `secret scan skipped`; it is refused with `--release` or when `CI` is set. +The scan uses gitleaks' built-in rules through an explicit config and ignore path, so `GITLEAKS_CONFIG`, `GITLEAKS_CONFIG_TOML` and a `.gitleaksignore` in the working directory don't change it, and a `.gitleaksignore` in the scanned directory fails it. +Inline `gitleaks:allow` markers are ignored, and an exit status other than 0 or gitleaks' leak status fails the pack with gitleaks' own error. +The built-in config skips image, font and archive extensions, including `.svg`, so a secret in a shipped `.svg` (such as `docs-theme`'s `assets/favicons/*.svg`) is not found; dropping that path allowlist would mean vendoring the whole default config. The package READMEs ship as written, because they are written for consumers. The tarball's own `package.json` is read back and must be private, with this release's version and license, every `@coder` dependency a published package pinned to this release's URL, and every other dependency a plain registry range or tag. A `workspace:`, `catalog:`, `file:`, `link:` or `npm:` specifier, a git or GitHub spec, a URL, a path (including one that starts with `.`) or a `.tgz`, `.tar` or `.tar.gz` file fails the pack. diff --git a/apps/dist-release/src/cli.mjs b/apps/dist-release/src/cli.mjs index b9726aa1..e5338414 100644 --- a/apps/dist-release/src/cli.mjs +++ b/apps/dist-release/src/cli.mjs @@ -15,11 +15,19 @@ const { positionals, values } = parseArgs({ tag: { type: "string" }, out: { type: "string" }, release: { type: "boolean", default: false }, + "allow-missing-gitleaks": { type: "boolean", default: false }, }, }); if (positionals[0] !== "build" || !values.tag || !values.out) { - console.error("usage: cli.mjs build --tag vX.Y.Z --out [--release]"); + console.error( + "usage: cli.mjs build --tag vX.Y.Z --out [--release | --allow-missing-gitleaks]", + ); + process.exit(2); +} +const allowMissingGitleaks = values["allow-missing-gitleaks"]; +if (allowMissingGitleaks && (values.release || process.env.CI)) { + console.error("--allow-missing-gitleaks is for local dry runs, not releases or CI"); process.exit(2); } let license, version; @@ -36,10 +44,11 @@ if ((await readdir(outDir)).length) { console.error(`refusing to build: ${outDir} is not empty`); process.exit(1); } +const secretScan = { required: !allowMissingGitleaks }; await buildPackagesForRelease(repoRoot); for (const pkg of PUBLISHED_PACKAGES) { console.log( - `packed ${path.basename(await packPackage({ repoRoot, pkg, version, license, outDir }))}`, + `packed ${path.basename(await packPackage({ repoRoot, pkg, version, license, outDir, secretScan }))}`, ); } console.log(`wrote ${await writeSha256Sums(outDir, releaseTarballNames(version))}`); diff --git a/apps/dist-release/src/contents.mjs b/apps/dist-release/src/contents.mjs index bfa48706..03b62030 100644 --- a/apps/dist-release/src/contents.mjs +++ b/apps/dist-release/src/contents.mjs @@ -66,6 +66,12 @@ export async function checkEntryTypes(file) { .map((line) => `not a regular file or directory: ${line}`); } +export async function extractTarball(file, dest) { + const problems = await checkEntryTypes(file); + if (problems.length) throw new Error(`${file}:\n ${problems.join("\n ")}`); + await run("tar", ["-xzf", file, "-C", dest]); +} + export async function findSourceMapReferences(dir) { const problems = []; for (const entry of await readdir(dir, { recursive: true, withFileTypes: true })) { diff --git a/apps/dist-release/src/contents.test.mjs b/apps/dist-release/src/contents.test.mjs index c255d296..1736a934 100644 --- a/apps/dist-release/src/contents.test.mjs +++ b/apps/dist-release/src/contents.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { linkSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs"; +import { linkSync, mkdirSync, readdirSync, symlinkSync, writeFileSync } from "node:fs"; import path from "node:path"; import test from "node:test"; import { @@ -8,6 +8,7 @@ import { checkEntries, checkEntryTypes, checkPackageEntries, + extractTarball, findComments, findSourceMapReferences, listTarball, @@ -135,6 +136,24 @@ test("a symlink or hardlink entry fails, naming it", async () => { assert.deepEqual(await checkEntryTypes(tarballOf({ "package/dist/index.js": "" })), []); }); +test("a tarball with a symlink is refused before anything is extracted", async () => { + const dir = tempDir("contents-"); + mkdirSync(path.join(dir, "package", "dist"), { recursive: true }); + writeFileSync(path.join(dir, "package", "dist", "index.js"), "export {};\n"); + symlinkSync("/etc/hosts", path.join(dir, "package", "dist", "hosts.js")); + const file = path.join(dir, "p.tgz"); + execFileSync("tar", ["-czf", file, "-C", dir, "package"]); + const dest = tempDir("contents-out-"); + await assert.rejects(extractTarball(file, dest), /not a regular file or directory: .*hosts\.js/); + assert.deepEqual(readdirSync(dest), []); +}); + +test("a tarball of regular files is extracted", async () => { + const dest = tempDir("contents-out-"); + await extractTarball(tarballOf({ "package/dist/index.js": "" }), dest); + assert.deepEqual(readdirSync(path.join(dest, "package", "dist")), ["index.js"]); +}); + test("a sourceMappingURL comment fails even with no .map file beside it", async () => { const dir = tempDir("contents-"); mkdirSync(path.join(dir, "dist", "nested"), { recursive: true }); diff --git a/apps/dist-release/src/gitleaks-probe.mjs b/apps/dist-release/src/gitleaks-probe.mjs new file mode 100644 index 00000000..74060eb1 --- /dev/null +++ b/apps/dist-release/src/gitleaks-probe.mjs @@ -0,0 +1,8 @@ +import { spawnSync } from "node:child_process"; + +const hasGitleaks = spawnSync("gitleaks", ["version"]).status === 0; + +// In CI a missing gitleaks fails these tests rather than skipping them. +export const needsGitleaks = { + skip: hasGitleaks || process.env.CI ? false : "gitleaks is not on PATH", +}; diff --git a/apps/dist-release/src/pack.mjs b/apps/dist-release/src/pack.mjs index 6a4005a4..62aad417 100644 --- a/apps/dist-release/src/pack.mjs +++ b/apps/dist-release/src/pack.mjs @@ -7,12 +7,14 @@ import { PUBLISHED_PACKAGES, packageTarballName } from "./config.mjs"; import { checkEntryTypes, checkPackageEntries, + extractTarball, findComments, findSourceMapReferences, listTarball, readTarballEntry, } from "./contents.mjs"; import { assertReleaseDependencies, rewriteManifest } from "./manifest.mjs"; +import { findSecrets } from "./secrets.mjs"; const run = promisify(execFile); @@ -81,12 +83,12 @@ export async function checkTarball(pkg, file, { version, license }) { return problems; } -export async function packPackage({ repoRoot, pkg, version, license, outDir }) { +export async function packPackage({ repoRoot, pkg, version, license, outDir, secretScan = {} }) { if (!license.text?.trim()) throw new Error(`${pkg}: no license text to write as LICENSE`); const work = await mkdtemp(path.join(tmpdir(), `pack-${pkg}-`)); try { const first = await pnpmPack(path.join(repoRoot, "packages", pkg), path.join(work, "first")); - await run("tar", ["-xzf", first, "-C", work]); + await extractTarball(first, work); const packageDir = path.join(work, "package"); const manifestPath = path.join(packageDir, "package.json"); const manifest = rewriteManifest(JSON.parse(await readFile(manifestPath, "utf8")), { @@ -102,7 +104,14 @@ export async function packPackage({ repoRoot, pkg, version, license, outDir }) { ...(await findComments(packageDir)), ...(await checkTarball(pkg, file, { version, license })), ]; - if (problems.length) throw new Error(`${pkg}:\n ${problems.join("\n ")}`); + const fail = () => new Error(`${pkg}:\n ${problems.join("\n ")}`); + if (problems.length) throw fail(); + // Scan what the tarball holds, not the directory it was packed from. + const unpacked = path.join(work, "unpacked"); + await mkdir(unpacked); + await extractTarball(file, unpacked); + problems.push(...(await findSecrets(unpacked, secretScan))); + if (problems.length) throw fail(); const out = path.join(outDir, packageTarballName(pkg, version)); await copyFile(file, out); return out; diff --git a/apps/dist-release/src/pack.test.mjs b/apps/dist-release/src/pack.test.mjs index 21d5e65f..980a88f6 100644 --- a/apps/dist-release/src/pack.test.mjs +++ b/apps/dist-release/src/pack.test.mjs @@ -12,6 +12,7 @@ import { import path from "node:path"; import test from "node:test"; import { listTarball, readTarballEntry } from "./contents.mjs"; +import { needsGitleaks } from "./gitleaks-probe.mjs"; import { checkTarball, packPackage, removePublishedDist } from "./pack.mjs"; import { tempDir } from "./temp-dir.mjs"; @@ -66,7 +67,14 @@ function fakeRepo( } const packFake = (repo, outDir = newOutDir(), license = apache) => - packPackage({ repoRoot: repo, pkg: "docs-ui", version: "0.1.0", license, outDir }); + packPackage({ + repoRoot: repo, + pkg: "docs-ui", + version: "0.1.0", + license, + outDir, + secretScan: { required: false }, + }); test("packs a workspace package with release URLs, catalog versions and the version", async () => { const file = await packFake( @@ -121,6 +129,36 @@ test("adding src to a package's files fails the pack and leaves no tarball", asy assert.deepEqual(readdirSync(outDir), []); }); +test("a secret in dist fails the pack and leaves no tarball", needsGitleaks, async () => { + const outDir = newOutDir(); + // Built at run time so no secret-shaped string is committed. + const key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); + await assert.rejects( + packFake( + fakeRepo(["dist"], { extra: { "dist/leak.env": `AWS_ACCESS_KEY_ID=${key}\n` } }), + outDir, + ), + (error) => error.message.includes("secret (aws-access-token): package/dist/leak.env"), + ); + assert.deepEqual(readdirSync(outDir), []); +}); + +test("the secret scan is required by default, so a missing gitleaks fails the pack", async () => { + const outDir = newOutDir(); + await assert.rejects( + packPackage({ + repoRoot: fakeRepo(["dist"]), + pkg: "docs-ui", + version: "0.1.0", + license: apache, + outDir, + secretScan: { command: "gitleaks-is-not-installed" }, + }), + /gitleaks is required but was not found/, + ); + assert.deepEqual(readdirSync(outDir), []); +}); + test("a source map in dist fails the pack and leaves no tarball", async () => { const outDir = newOutDir(); await assert.rejects( diff --git a/apps/dist-release/src/secrets.mjs b/apps/dist-release/src/secrets.mjs new file mode 100644 index 00000000..14b96c6a --- /dev/null +++ b/apps/dist-release/src/secrets.mjs @@ -0,0 +1,66 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { promisify, stripVTControlCharacters } from "node:util"; + +const run = promisify(execFile); +// gitleaks exits 1 on fatal errors as well as on leaks, so leaks get a code of their own. +const LEAKS_FOUND = 3; +const CONFIG = "[extend]\nuseDefault = true\n"; + +/** + * Scan an unpacked package with gitleaks' built-in rules only. A finding names the rule, file and + * line, never the matched text. A missing gitleaks fails the scan unless `required` is false. + */ +export async function findSecrets(dir, { command = "gitleaks", required = true } = {}) { + const entries = await readdir(dir); + if (entries.includes(".gitleaksignore")) { + return [".gitleaksignore would suppress findings: .gitleaksignore"]; + } + const work = await mkdtemp(path.join(tmpdir(), "gitleaks-")); + const report = path.join(work, "report.json"); + const config = path.join(work, "gitleaks.toml"); + try { + await writeFile(config, CONFIG); + await run( + command, + [ + "dir", + "--no-banner", + "--redact", + "--ignore-gitleaks-allow", + "--config", + config, + "--gitleaks-ignore-path", + work, + "--exit-code", + String(LEAKS_FOUND), + "--report-format", + "json", + "--report-path", + report, + dir, + ], + { cwd: work, maxBuffer: 16 * 1024 * 1024 }, + ); + return []; + } catch (error) { + if (error.code === "ENOENT" && error.path === command) { + if (required) return [`gitleaks is required but was not found on PATH (${command})`]; + console.warn(`secret scan skipped: gitleaks was not found on PATH (${command})`); + return []; + } + if (error.code !== LEAKS_FOUND) { + const stderr = stripVTControlCharacters(String(error.stderr ?? "")).trim(); + throw new Error(`gitleaks exited ${error.code}: ${stderr}`, { cause: error }); + } + const findings = JSON.parse(await readFile(report, "utf8")); + if (!findings.length) throw new Error("gitleaks reported leaks but wrote no findings"); + return findings.map( + (f) => `secret (${f.RuleID}): ${path.relative(dir, f.File)}:${f.StartLine}`, + ); + } finally { + await rm(work, { recursive: true, force: true }); + } +} diff --git a/apps/dist-release/src/secrets.test.mjs b/apps/dist-release/src/secrets.test.mjs new file mode 100644 index 00000000..7beea617 --- /dev/null +++ b/apps/dist-release/src/secrets.test.mjs @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { needsGitleaks } from "./gitleaks-probe.mjs"; +import { findSecrets } from "./secrets.mjs"; +import { tempDir } from "./temp-dir.mjs"; + +// Built at run time so no secret-shaped string is committed. +const plantedKey = () => `AWS_ACCESS_KEY_ID=${["AKIA", "ABCDEFGHIJKLMNOP"].join("")}\n`; + +function packageWith(name, body) { + const dir = tempDir("secrets-"); + mkdirSync(path.join(dir, "dist"), { recursive: true }); + writeFileSync(path.join(dir, "dist", name), body); + return dir; +} + +// A stand-in for gitleaks that writes `report` to --report-path, prints `stderr` and exits `code`. +function fakeGitleaks({ code, report, stderr = "" }) { + const file = path.join(tempDir("fake-gitleaks-"), "gitleaks"); + writeFileSync( + file, + [ + "#!/bin/sh", + 'while [ $# -gt 0 ]; do [ "$1" = --report-path ] && printf %s ' + + `'${report}' > "$2"; shift; done`, + `printf %s '${stderr}' >&2`, + `exit ${code}`, + "", + ].join("\n"), + ); + chmodSync(file, 0o755); + return file; +} + +// Runs the real gitleaks with extra arguments after ours. +function gitleaksWith(...extra) { + const file = path.join(tempDir("gitleaks-wrapper-"), "gitleaks"); + writeFileSync(file, `#!/bin/sh\nexec gitleaks "$@" ${extra.join(" ")}\n`); + chmodSync(file, 0o755); + return file; +} + +test("a missing gitleaks fails closed by default", async () => { + const problems = await findSecrets(tempDir("secrets-"), { + command: "gitleaks-is-not-installed", + }); + assert.equal(problems.length, 1); + assert.match(problems[0], /gitleaks is required but was not found/); +}); + +test("a missing gitleaks is skipped, with a warning, only when the scan is optional", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + const problems = await findSecrets(tempDir("secrets-"), { + command: "gitleaks-is-not-installed", + required: false, + }); + assert.deepEqual(problems, []); + assert.equal(warn.mock.callCount(), 1); + assert.match(warn.mock.calls[0].arguments[0], /secret scan skipped/); +}); + +test("a gitleaks failure that writes an empty report is an error, with its stderr", async () => { + await assert.rejects( + findSecrets(tempDir("secrets-"), { + command: fakeGitleaks({ code: 1, report: "[]", stderr: "FTL timed out" }), + }), + /exited 1.*FTL timed out/s, + ); +}); + +test("the leaks exit code with no findings is an error, not a pass", async () => { + await assert.rejects( + findSecrets(tempDir("secrets-"), { command: fakeGitleaks({ code: 3, report: "[]" }) }), + /no findings/, + ); +}); + +test("a directory that does not exist is an error, not a clean scan", async () => { + await assert.rejects( + findSecrets(path.join(tempDir("secrets-"), "missing"), { + command: fakeGitleaks({ code: 0, report: "[]" }), + }), + /ENOENT/, + ); +}); + +test("a clean package has no findings", needsGitleaks, async () => { + assert.deepEqual(await findSecrets(packageWith("index.js", "export {};\n")), []); +}); + +test("a planted secret is reported by rule and file without its value", needsGitleaks, async () => { + const problems = await findSecrets(packageWith("config.env", plantedKey())); + assert.equal(problems.length, 1); + assert.match(problems[0], /aws-access-token/); + assert.match(problems[0], /config\.env/); + assert.doesNotMatch(problems[0], /ABCDEFGHIJKLMNOP/); +}); + +test("a fatal gitleaks error is thrown with gitleaks' own message", needsGitleaks, async () => { + await assert.rejects( + findSecrets(packageWith("index.js", "export {};\n"), { + command: gitleaksWith("--config", "/nonexistent/gitleaks.toml"), + }), + /unable to load gitleaks config/, + ); +}); + +test("an inline gitleaks:allow marker does not hide a secret", needsGitleaks, async () => { + const [first, ...rest] = plantedKey().split("\n"); + const body = [`${first} # gitleaks:allow`, ...rest].join("\n"); + assert.deepEqual(await findSecrets(packageWith("config.env", body)), [ + "secret (aws-access-token): dist/config.env:1", + ]); +}); + +test("a config named in the environment does not change the scan", needsGitleaks, async (t) => { + const config = path.join(tempDir("secrets-"), "allow-all.toml"); + writeFileSync(config, "[allowlist]\npaths = ['''.*''']\n"); + for (const name of ["GITLEAKS_CONFIG", "GITLEAKS_CONFIG_TOML"]) { + const saved = process.env[name]; + process.env[name] = name === "GITLEAKS_CONFIG" ? config : "[allowlist]\npaths = ['''.*''']\n"; + t.after(() => { + if (saved === undefined) delete process.env[name]; + else process.env[name] = saved; + }); + } + assert.deepEqual(await findSecrets(packageWith("config.env", plantedKey())), [ + "secret (aws-access-token): dist/config.env:1", + ]); +}); + +test("a .gitleaksignore in the scanned directory fails the scan", async () => { + const dir = packageWith("index.js", "export {};\n"); + writeFileSync(path.join(dir, ".gitleaksignore"), ""); + const problems = await findSecrets(dir, { command: fakeGitleaks({ code: 0, report: "[]" }) }); + assert.deepEqual(problems, [".gitleaksignore would suppress findings: .gitleaksignore"]); +}); diff --git a/apps/offlinedocs/scripts/csp-check-helpers.mjs b/apps/offlinedocs/scripts/csp-check-helpers.mjs index 91d2f4cc..08705fa3 100644 --- a/apps/offlinedocs/scripts/csp-check-helpers.mjs +++ b/apps/offlinedocs/scripts/csp-check-helpers.mjs @@ -1,6 +1,7 @@ // Pure helpers for scripts/csp-check.mjs, split out so the parsing and // per-script policy checks can be unit tested without a built export. import { createHash } from "node:crypto"; +import { JSDOM } from "jsdom"; /** * Parse a `Content-Security-Policy` header value into a directive -> token @@ -69,32 +70,37 @@ export function isJavaScriptScriptType(type) { * JavaScript MIME type (`application/json`, `importmap`, * `speculationrules`, ...) is a data block, not code — browsers never apply * script-src to it, so it is skipped. - * Matching is a plain regex over the serialized HTML, not a full parse: it - * is only asked to find `` tags, which Next always - * emits well-formed and un-nested. + * Parsed by jsdom, including `