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
16 changes: 16 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

Expand Down
6 changes: 6 additions & 0 deletions apps/dist-release/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
13 changes: 11 additions & 2 deletions apps/dist-release/src/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir> [--release]");
console.error(
"usage: cli.mjs build --tag vX.Y.Z --out <dir> [--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;
Expand All @@ -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))}`);
6 changes: 6 additions & 0 deletions apps/dist-release/src/contents.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 })) {
Expand Down
21 changes: 20 additions & 1 deletion apps/dist-release/src/contents.test.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
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 {
allowedEntriesFor,
checkEntries,
checkEntryTypes,
checkPackageEntries,
extractTarball,
findComments,
findSourceMapReferences,
listTarball,
Expand Down Expand Up @@ -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 });
Expand Down
8 changes: 8 additions & 0 deletions apps/dist-release/src/gitleaks-probe.mjs
Original file line number Diff line number Diff line change
@@ -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",
};
15 changes: 12 additions & 3 deletions apps/dist-release/src/pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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")), {
Expand All @@ -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");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: the tarball is extracted even when checkEntryTypes has already flagged symlinks or hardlinks. The risk is low, since we produce the tarball ourselves and tar has its own protections, but throwing before extraction is cheap.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d60ab8f. A new extractTarball in contents.mjs runs checkEntryTypes and throws before calling tar, and packPackage uses it for both extractions. Before the final unpack it also throws on any problem found so far. A test checks that a tarball with a symlink is refused and the destination stays empty.

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;
Expand Down
40 changes: 39 additions & 1 deletion apps/dist-release/src/pack.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
66 changes: 66 additions & 0 deletions apps/dist-release/src/secrets.mjs
Original file line number Diff line number Diff line change
@@ -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 });
}
}
Loading
Loading