diff --git a/packages/tooling/vis/__tests__/native/attest-parity.test.ts b/packages/tooling/vis/__tests__/native/attest-parity.test.ts new file mode 100644 index 00000000..87cee2ce --- /dev/null +++ b/packages/tooling/vis/__tests__/native/attest-parity.test.ts @@ -0,0 +1,344 @@ +import type { ChildProcess } from "node:child_process"; +import { spawn } from "node:child_process"; +import { createHash, createSign, generateKeyPairSync } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative } from "node:path"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { binary, Harness, nodeEntry, workspaceFiles } from "./workspace-parity-harness"; + +/** + * `vis attest` exists twice: the Node handler (`src/commands/attest/handler.ts`) and the native path + * (`native/cli/src/attest/`). For every input the native path accepts it must print the same bytes on the same stream, end with the + * same exit status and leave the same cache files as Node; every input it declines must be handed to Node before anything is + * printed (see `workspace-parity-harness.ts` for how both are proved). + * + * The native path answers two leaves. `vis attest <subject>` answers the run with no ambient OIDC token, where Node hashes the artifact and + * skips signing. `vis attest verify` checks the locked packages against the registry: the registry is a stub in a separate process + * that the `.npmrc` of the workspace points both sides at, and the signing keys sit in the key cache of each side's `HOME` + * (fresh, so neither side asks the network), signed here with real ECDSA P-256 keys. Each side has its own `HOME`, because the + * caches live in `~/.vis/cache`; the `createdAt` of a fresh cache entry is masked. + */ + +const harness = new Harness(["attest"]); + +interface Answer { + body: string; + status?: number; +} + +interface Key { + id: string; + privateKey: ReturnType["privateKey"]; + spki: string; +} + +const newKey = (id: string): Key => { + const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" }); + + return { id, privateKey, spki: publicKey.export({ format: "der", type: "spki" }).toString("base64") }; +}; + +const GOOD = newKey("sha256-good"); +const OTHER = newKey("sha256-other"); +const OLD = newKey("sha256-old"); +const NOBODY = newKey("sha256-nobody"); +const KEYS = [ + { key: GOOD.spki, keyid: GOOD.id, keytype: "ecdsa-sha2-nistp256", scheme: "ecdsa-sha2-nistp256" }, + { expires: "2020-01-01T00:00:00.000Z", key: OLD.spki, keyid: OLD.id }, +]; + +const INTEGRITY = "sha512-AAAA"; + +const sign = (key: Key, name: string, version: string): { keyid: string; sig: string } => { + return { keyid: key.id, sig: createSign("SHA256").update(`${name}@${version}:${INTEGRITY}`).sign(key.privateKey, "base64") }; +}; + +const PROVENANCE = { provenance: { predicateType: "https://slsa.dev/provenance/v1" } }; + +const entry = (name: string, version: string, key?: Key, extra: Record = {}): Record => { + return { dist: { integrity: INTEGRITY, ...(key === undefined ? {} : { signatures: [sign(key, name, version)] }), ...extra }, version }; +}; + +const packument = (name: string, versions: Record>): Answer => { + return { body: JSON.stringify({ "dist-tags": { latest: Object.keys(versions).at(-1) }, name, versions }) }; +}; + +const ANSWERS: Record = { + "/@scope%2fscoped": packument("@scope/scoped", { "1.0.0": entry("@scope/scoped", "1.0.0", GOOD, { attestations: PROVENANCE }) }), + // Signed with another key's private half, under the id of the registry's key. + "/bad-sig": packument("bad-sig", { "1.0.0": entry("bad-sig", "1.0.0", { ...OTHER, id: GOOD.id }) }), + "/broken": { body: "broken", status: 500 }, + "/expired": packument("expired", { "1.0.0": entry("expired", "1.0.0", OLD) }), + "/no-integrity": packument("no-integrity", { "1.0.0": { dist: { signatures: [sign(GOOD, "no-integrity", "1.0.0")] }, version: "1.0.0" } }), + "/no-sig": packument("no-sig", { "1.0.0": entry("no-sig", "1.0.0") }), + "/regressed": packument("regressed", { + "1.0.0": entry("regressed", "1.0.0", GOOD, { attestations: PROVENANCE }), + "1.1.0-beta.1": entry("regressed", "1.1.0-beta.1", GOOD, { attestations: PROVENANCE }), + "2.0.0": entry("regressed", "2.0.0", GOOD), + }), + "/signed": packument("signed", { "1.0.0": entry("signed", "1.0.0", GOOD) }), + "/signed-too": packument("signed-too", { "2.3.4": entry("signed-too", "2.3.4", GOOD, { attestations: PROVENANCE }) }), + "/unknown-key": packument("unknown-key", { "1.0.0": entry("unknown-key", "1.0.0", NOBODY) }), +}; + +const STUB = String.raw` +const http = require("node:http"); +const answers = JSON.parse(process.env.ANSWERS); +const server = http.createServer((req, res) => { + const answer = answers[req.url.split("?")[0]]; + if (answer === undefined) { res.statusCode = 404; res.end("{}"); return; } + res.statusCode = answer.status ?? 200; + res.setHeader("content-type", "application/json"); + res.end(answer.body); +}); +server.listen(0, "127.0.0.1", () => process.stdout.write(String(server.address().port) + "\n")); +`; + +const lockfile = (packages: [string, string][]): string => { + const section = packages.map(([name, version]) => ` ${name}@${version}:\n resolution: {integrity: ${INTEGRITY}}\n`).join("\n"); + const snapshots = packages.map(([name, version]) => ` ${name}@${version}: {}\n`).join("\n"); + + return `lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n\nimporters:\n\n .: {}\n\npackages:\n\n${section}\nsnapshots:\n\n${snapshots}`; +}; + +let scratch: string; +let stub: ChildProcess; +let base: string; + +const makeHome = (): string => { + const directory = realpathSync(mkdtempSync(join(scratch, "home-"))); + const file = join(directory, ".vis/cache/registry-keys/npmjs.json"); + + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify({ createdAt: Date.now(), keys: KEYS, ttlMs: 86_400_000 })); + + return directory; +}; + +/** Every file under a home, with the `createdAt` of a cache entry written during this run masked. */ +const homeState = (home: string): Record => { + const files: Record = {}; + + for (const item of readdirSync(home, { recursive: true, withFileTypes: true })) { + if (item.isFile()) { + const path = join(item.parentPath, item.name); + + files[relative(home, path)] = readFileSync(path, "utf8").replace(/"createdAt":(\d+)/, (whole, stamp: string) => (Math.abs(Date.now() - Number(stamp)) < 120_000 ? '"createdAt":"NOW"' : whole)); + } + } + + return files; +}; + +interface Case { + args: string[]; + /** Extra files of the workspace. */ + files?: Record; + /** True when the native side must answer; false when it must hand the run to Node. */ + native: boolean; + packages?: [string, string][]; + /** True when a declined run has filled the caches Node then finds warm. */ + warm?: boolean; +} + +const run = ({ args, files: extra = {}, native, packages = [], warm = false }: Case): { status: number | null; stderr: string; stdout: string } => { + const files = workspaceFiles({ ".npmrc": `registry=${base}/\n`, ...(packages.length > 0 ? { "pnpm-lock.yaml": lockfile(packages) } : {}), ...extra }); + const [nodeRoot, nativeRoot] = harness.pair(files); + const nodeHome = makeHome(); + const nativeHome = makeHome(); + const node = harness.runNode(args, nodeRoot, { HOME: nodeHome }); + + if (native) { + const answered = harness.runNative(args, nativeRoot, { HOME: nativeHome, VIS_DEBUG_DECLINE: "1" }); + + expect(answered.status, `native stderr: ${answered.stderr}`).not.toBe(70); + expect(Harness.outcome(answered, nativeRoot)).toStrictEqual(Harness.outcome(node, nodeRoot)); + expect(homeState(nativeHome)).toStrictEqual(homeState(nodeHome)); + + return answered; + } + + const probeRoot = harness.materialize("native", files); + const probeHome = makeHome(); + const before = { files: Harness.snapshot(probeRoot), home: homeState(probeHome) }; + const declined = harness.runNative(args, probeRoot, { HOME: probeHome }); + + expect(declined.status, `stdout: ${declined.stdout}`).toBe(70); + expect(declined.stdout, "a declined run prints nothing").toBe(""); + + // A table of findings is drawn by Node, which finds the packuments this run fetched in the cache; the other declines write nothing. + if (!warm) { + expect({ files: Harness.snapshot(probeRoot), home: homeState(probeHome) }, "a declined run must not touch anything").toStrictEqual(before); + } + + const delegated = harness.runNative(args, nativeRoot, { HOME: nativeHome, VIS_FALLBACK_ENTRY: nodeEntry, VIS_NODE: process.execPath }); + + expect(Harness.outcome(delegated, nativeRoot)).toStrictEqual(Harness.outcome(node, nodeRoot)); + expect(homeState(nativeHome)).toStrictEqual(homeState(nodeHome)); + + return delegated; +}; + +const CLEAN: [string, string][] = [["signed", "1.0.0"], ["@scope/scoped", "1.0.0"], ["signed-too", "2.3.4"]]; +const FINDINGS: [string, string][] = [ + ...CLEAN, + ["regressed", "2.0.0"], + ["no-sig", "1.0.0"], + ["no-integrity", "1.0.0"], + ["unknown-key", "1.0.0"], + ["expired", "1.0.0"], + ["bad-sig", "1.0.0"], +]; + +describe.skipIf(!binary || process.platform === "win32" || !existsSync(nodeEntry))("vis attest: native vs Node", () => { + beforeAll(async () => { + harness.setup("vis-attest-parity-"); + scratch = mkdtempSync(join(tmpdir(), "vis-attest-homes-")); + // CI runs the suite with `FORCE_COLOR=3`: the stub gets it here on purpose, so its port reaches `base` as plain digits. + stub = spawn(process.execPath, ["-e", STUB], { env: Harness.environment({ ANSWERS: JSON.stringify(ANSWERS), FORCE_COLOR: "3" }), stdio: ["ignore", "pipe", "inherit"] }); + base = await new Promise((resolve) => { + stub.stdout?.once("data", (chunk: Buffer) => { + resolve(`http://127.0.0.1:${chunk.toString().trim()}`); + }); + }); + }); + + afterAll(() => { + stub.kill(); + harness.teardown(); + rmSync(scratch, { force: true, recursive: true }); + }); + + describe("attest verify", () => { + it("prints the JSON report of a clean tree", () => { + expect.hasAssertions(); + + const result = run({ args: ["verify", "--format", "json"], native: true, packages: CLEAN }); + + expect(result.stdout).toBe('{\n "findings": [],\n "ok": true\n}\n'); + expect(result.status).toBe(0); + }); + + it("prints the line of a clean tree in the table format", () => { + expect.hasAssertions(); + + expect(run({ args: ["verify"], native: true, packages: CLEAN }).stdout).toContain("No provenance regressions or signature problems across 3 locked packages."); + }); + + it("reports every kind of finding and fails", () => { + expect.hasAssertions(); + + const result = run({ args: ["verify", "--format", "json"], native: true, packages: FINDINGS }); + const codes = (JSON.parse(result.stdout) as { findings: { code: string }[] }).findings.map((finding) => finding.code); + + expect(codes).toStrictEqual(["provenance-regression", "missing-signature", "missing-signature", "unknown-keyid", "expired-key", "invalid-signature"]); + expect(result.status).toBe(1); + }); + + it("prints a line per finding in NDJSON", () => { + expect.hasAssertions(); + + const result = run({ args: ["verify", "--format=ndjson"], native: true, packages: FINDINGS }); + + expect(result.stdout.trim().split("\n")).toHaveLength(6); + expect(result.status).toBe(1); + }); + + it("fails only on errors with --fail-on error", () => { + expect.hasAssertions(); + + const warnings: [string, string][] = [["signed", "1.0.0"], ["regressed", "2.0.0"], ["no-sig", "1.0.0"]]; + const result = run({ args: ["verify", "--format", "json", "--fail-on", "error"], native: true, packages: warnings }); + + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: true }); + expect(run({ args: ["verify", "--format", "json", "--fail-on=error"], native: true, packages: FINDINGS }).status).toBe(1); + }); + + it("skips the allowlisted packages without asking the registry for them", () => { + expect.hasAssertions(); + + const result = run({ args: ["verify", "--format", "json", "--allowlist", " no-sig, regressed,,bad-sig,expired,no-integrity,unknown-key "], native: true, packages: FINDINGS }); + + expect(JSON.parse(result.stdout)).toStrictEqual({ findings: [], ok: true }); + }); + + it("counts a package the registry does not know as clean", () => { + expect.hasAssertions(); + + run({ args: ["verify", "--format", "json"], native: true, packages: [...CLEAN, ["ghost", "1.0.0"]] }); + }); + + it("hands the table of findings to Node, which finds the cache warm", () => { + expect.hasAssertions(); + + run({ args: ["verify"], native: false, packages: FINDINGS, warm: true }); + }); + + it.each([ + [["verify", "--prod-only"]], + [["verify", "--format", "xml"]], + [["verify", "--fail-on", "info"]], + [["verify", "extra"]], + ])("hands `attest %j` to Node", (args: string[]) => { + expect.hasAssertions(); + + run({ args, native: false, packages: CLEAN }); + }); + + it("hands a failing registry to Node, with the cache of the packages that were read", () => { + expect.hasAssertions(); + + run({ args: ["verify", "--format", "json"], native: false, packages: [...CLEAN, ["broken", "1.0.0"]], warm: true }); + }); + }); + + describe("attest ", () => { + const artifact = { "dist/app.tgz": "artifact bytes", "dist/café.tgz": "x" }; + + it("warns that signing is skipped", () => { + expect.hasAssertions(); + + const result = run({ args: ["dist/app.tgz"], files: artifact, native: true }); + + expect(result.stderr).toContain("No ambient OIDC token"); + expect(result.status).toBe(0); + }); + + it("prints the skip document with --format json", () => { + expect.hasAssertions(); + + const result = run({ args: ["dist/app.tgz", "--format", "json"], files: artifact, native: true }); + + expect(JSON.parse(result.stdout)).toStrictEqual({ ok: false, reason: "no-ambient-oidc", sha256: createHash("sha256").update("artifact bytes").digest("hex"), skipped: true, subject: "app.tgz" }); + }); + + it.each([ + [["--format=ndjson", "dist/app.tgz"]], + [["dist/app.tgz", "--output", "out.sigstore", "--predicate", "slsaProvenance", "--format", "table"]], + [["--format", "json", "dist/app.tgz", "--output=out.sigstore"]], + ])("answers `attest %j`", (args: string[]) => { + expect.hasAssertions(); + + run({ args, files: artifact, native: true }); + }); + + it.each([ + [["dist/missing.tgz"]], + [["dist"]], + [["./dist/app.tgz"]], + [["dist/../dist/app.tgz"]], + [["dist/café.tgz"]], + [["dist/app.tgz", "--format", "xml"]], + [["dist/app.tgz", "--predicate", "other"]], + [["dist/app.tgz", "--require-signing"]], + ])("hands `attest %j` to Node", (args: string[]) => { + expect.hasAssertions(); + + run({ args, files: artifact, native: false }); + }); + }); +}); diff --git a/packages/tooling/vis/__tests__/native/info-dlx-parity.test.ts b/packages/tooling/vis/__tests__/native/info-dlx-parity.test.ts index c81f47ff..ed094515 100644 --- a/packages/tooling/vis/__tests__/native/info-dlx-parity.test.ts +++ b/packages/tooling/vis/__tests__/native/info-dlx-parity.test.ts @@ -26,8 +26,11 @@ import { resolveNativeBinary } from "../../bin/resolve-binary.mjs"; * side. The environment the manager sees is compared in full, except for the variables the native launcher * contract adds on its own (`LAUNCHER_VARIABLES`): they are named, not hidden. * - * The first-run gate of `dlx` (package metadata over the network, a prompt) is never exercised: every native - * case switches it off, and every case that would run it only has to be handed to Node. + * The first-run gate of `dlx` skips itself, with no network work, in CI, off a terminal and with `--yes`, and + * these runs have neither a terminal nor a registry: the cases cover that fast path, with and without `--no-info`. + * The gate's panel and prompt (a terminal, an unapproved version) are Node's, and the lookup that tells an approved + * version from a new one runs only on a terminal; it is covered by the unit tests in `dlx.rs`, against a registry stub. + * `--info` and a value of `VIS_DLX_YES` or `VIS_DLX_NO_INFO` that is not ASCII are handed to Node. * * Needs the native `vis` binary, the built CLI (`dist/bin.js`) and the NAPI addon; skipped otherwise. */ @@ -449,6 +452,15 @@ describe.skipIf(!ready)("vis info and vis dlx: native vs Node", () => { } const DLX_SHAPES: DlxShape[] = [ + // The gate skips itself: no terminal, and `--yes`. + { args: ["dlx", "cowsay"] }, + { args: ["dlx", "cowsay", "hi"] }, + { args: ["dlx", "@scope/pkg@1", "a"] }, + { args: ["dlx", "--yes", "cowsay"] }, + { args: ["dlx", "-y", "cowsay"] }, + { args: ["dlx", "--silent", "cowsay"] }, + { args: ["dlx", "-p", "lolcatjs", "-s", "cowsay"] }, + { args: ["dlx", "./local.js", "-p", "cowsay", "-s"] }, { args: ["dlx", "--no-info", "cowsay"] }, { args: ["dlx", "cowsay", "--no-info"] }, { args: ["dlx", "--no-info", "cowsay", "hi", "there"] }, @@ -473,6 +485,10 @@ describe.skipIf(!ready)("vis info and vis dlx: native vs Node", () => { // Shell mode vets only the `-p` packages, so with none the gate is out without `--no-info`. { args: ["dlx", "-c", "echo hi"], needs: "shell" }, { args: ["dlx", "--shell-mode", "echo hi && echo there", "--silent"], needs: "shell" }, + { args: ["dlx", "-p", "lolcatjs", "-c", "echo hi"], needs: "shell" }, + { args: ["dlx", "-c", "echo hi", "-p", "lolcatjs", "-s"], needs: "shell" }, + { args: ["dlx", "-p", "lolcatjs", "-c", "./local.js"], needs: "shell" }, + { args: ["dlx", "--offline", "cowsay"], needs: "offline" }, // Paths, URLs and aliases are no registry specs. { args: ["dlx", "./local.js"] }, { args: ["dlx", "../tools/run.js", "a", "b"] }, @@ -498,6 +514,10 @@ describe.skipIf(!ready)("vis info and vis dlx: native vs Node", () => { ...["1", "true", "TRUE", "yes", "on", "anything", " 1 ", "2"].map((value) => { return { args: ["dlx", "cowsay", "hi"], env: { VIS_DLX_NO_INFO: value }, fixture: "pnpm-single", label: `VIS_DLX_NO_INFO=${JSON.stringify(value)}` }; }), // With the gate out the other variable changes nothing. { args: ["dlx", "--no-info", "cowsay"], env: { VIS_DLX_YES: "1" }, fixture: "pnpm-single", label: "VIS_DLX_YES beside --no-info" }, + // The gate skips itself whatever these say, because no stream is a terminal. + ...["0", "false", "", "no", " NO "].map((value) => { return { args: ["dlx", "cowsay"], env: { VIS_DLX_NO_INFO: value }, fixture: "pnpm-single", label: `VIS_DLX_NO_INFO=${JSON.stringify(value)} with a registry spec` }; }), + ...["1", "true", "yes", "on", " 1 ", "0", ""].map((value) => { return { args: ["dlx", "cowsay"], env: { VIS_DLX_YES: value }, fixture: "pnpm-single", label: `VIS_DLX_YES=${JSON.stringify(value)}` }; }), + { args: ["dlx", "cowsay"], ci: false, env: { VIS_NO_UPDATE_CHECK: UNSET }, fixture: "pnpm-single", label: "a registry spec outside CI, with the update check on" }, // A falsy value leaves the gate on, which only a non-registry spec makes irrelevant. ...["", "0", "false", "no", " NO "].map((value) => { return { args: ["dlx", "./local.js"], env: { VIS_DLX_NO_INFO: value }, fixture: "pnpm-single", label: `a path with VIS_DLX_NO_INFO=${JSON.stringify(value)}` }; }), // The lean entry runs the manager in the working directory, with no workspace root and no config. @@ -529,25 +549,14 @@ describe.skipIf(!ready)("vis info and vis dlx: native vs Node", () => { ]; const DLX_DELEGATED_CASES: DelegatedCase[] = [ - // The first-run gate may run (it skips itself in CI, without a terminal and with `--yes`, which the binary does not decide): Node's before any output. + // `--info` shows the panel on every run, and a value JavaScript and Rust could trim differently is Node's. ...[ - ["dlx", "cowsay"], - ["dlx", "cowsay", "hi"], - ["dlx", "--yes", "cowsay"], - ["dlx", "-y", "cowsay"], ["dlx", "--info", "cowsay"], - ["dlx", "--offline", "cowsay"], - ["dlx", "--silent", "cowsay"], - ["dlx", "@scope/pkg@1", "a"], - ["dlx", "-p", "lolcatjs", "-c", "echo hi"], - ["dlx", "-c", "echo hi", "-p", "lolcatjs", "-s"], - ["dlx", "-p", "lolcatjs", "-c", "./local.js"], - ["dlx", "./local.js", "-p", "cowsay", "-s"], + ["dlx", "cowsay", "--info"], ].map((args) => { return { args, fixture: "pnpm-single", label: `vis ${args.join(" ")}` }; }), - ...[{ VIS_DLX_YES: "1" }, { VIS_DLX_NO_INFO: "0" }, { VIS_DLX_NO_INFO: "false" }, { VIS_DLX_NO_INFO: "" }, { VIS_DLX_NO_INFO: "no" }, { VIS_DLX_NO_INFO: " 1" }, { VIS_DLX_NO_INFO: " " }].map((env) => { + ...[{ VIS_DLX_YES: "\u00A01" }, { VIS_DLX_YES: " " }, { VIS_DLX_NO_INFO: "\u00A01" }, { VIS_DLX_NO_INFO: " " }].map((env) => { return { args: ["dlx", "cowsay"], env, fixture: "pnpm-single", label: `environment ${JSON.stringify(env)}` }; }), - { args: ["dlx", "cowsay"], ci: false, fixture: "pnpm-single", label: "outside CI" }, // Shapes of the command line. ...[ ["dlx"], diff --git a/packages/tooling/vis/__tests__/native/route.test.ts b/packages/tooling/vis/__tests__/native/route.test.ts index 3b18c372..31030e24 100644 --- a/packages/tooling/vis/__tests__/native/route.test.ts +++ b/packages/tooling/vis/__tests__/native/route.test.ts @@ -192,6 +192,13 @@ describe("launcher routing (bin/route.mjs)", () => { [["dlx", "git+https://example.test/a.git"]], [["dlx", "npm:cowsay@1"]], [["dlx", "-p", "./local.tgz", "-c", "echo hi"]], + // The first-run gate is the binary's to decide: it does nothing with `--yes`, in CI and off a terminal, and on a + // terminal it answers only for a version that was approved. + [["dlx", "cowsay"]], + [["dlx", "--yes", "cowsay"]], + [["dlx", "cowsay", "-y"]], + [["dlx", "-p", "lolcatjs", "-c", "echo hi"]], + [["dlx", "-p", "lolcatjs", "-c", "./local.js"]], ])("routes `vis %j`, whatever the terminal and CI", (args: string[]) => { expect.assertions(3); @@ -201,12 +208,8 @@ describe("launcher routing (bin/route.mjs)", () => { }); it.each([ - // The first-run gate runs, which Node answers before any output. - [["dlx", "cowsay"]], - [["dlx", "--yes", "cowsay"]], + // `--info` shows the panel on every run, which Node renders. [["dlx", "--info", "cowsay"]], - [["dlx", "-p", "lolcatjs", "-c", "echo hi"]], - [["dlx", "-p", "lolcatjs", "-c", "./local.js"]], // Shapes of the command line. [["dlx"]], [["dlx", "--no-info"]], @@ -226,22 +229,6 @@ describe("launcher routing (bin/route.mjs)", () => { expect(routesToNative(args, "linux", {}, "/work/app", false)).toBe(false); }); - it("follows VIS_DLX_NO_INFO the way isTruthyEnv does, and leaves a non-ASCII value to Node", () => { - expect.assertions(11); - - const dlx = ["dlx", "cowsay"]; - - for (const value of ["1", "true", "YES", " on ", "anything"]) { - expect(routesToNative(dlx, "linux", { VIS_DLX_NO_INFO: value }, "/work/app", false)).toBe(true); - } - - for (const value of ["", "0", "false", "no", " No "]) { - expect(routesToNative(dlx, "linux", { VIS_DLX_NO_INFO: value }, "/work/app", false)).toBe(false); - } - - expect(routesToNative(dlx, "linux", { VIS_DLX_NO_INFO: "\u00A01" }, "/work/app", false)).toBe(false); - }); - it("keeps the dlx in Node on Windows and where the environment changes the installer or Node's output", () => { expect.assertions(8); diff --git a/packages/tooling/vis/bin/route.mjs b/packages/tooling/vis/bin/route.mjs index 5db17b5f..85f9195b 100644 --- a/packages/tooling/vis/bin/route.mjs +++ b/packages/tooling/vis/bin/route.mjs @@ -727,35 +727,12 @@ const dlxShape = (rest) => { return shape.words.length > 0 ? shape : undefined; }; -// `isRegistrySpec` of the first-run gate (`src/dlx/first-run.ts`): not a path, URL or protocol alias. -const PATH_SPEC = /^[./~]/; - -const isRegistrySpec = (spec) => { - const bare = spec.startsWith("@") ? spec.slice(1) : spec; - - return spec !== "" && !PATH_SPEC.test(spec) && !bare.includes(":"); -}; - -// `isTruthyEnv` for an ASCII value; the binary leaves any other to Node, where `trim` and Rust's differ. -const isAscii = (text) => [...text].every((character) => character.codePointAt(0) <= 0x7F); - -const dlxGateIsSwitchedOff = (environment, shape) => { - const value = environment.VIS_DLX_NO_INFO; - - if (value !== undefined && !isAscii(value)) { - return false; - } - - const noInfoFromEnvironment = value !== undefined && !["", "0", "false", "no"].includes(value.trim().toLowerCase()); - const vetted = [...shape.flags.has("-c") ? [] : shape.words.slice(0, 1), ...shape.packages]; - - return shape.flags.has("--no-info") || noInfoFromEnvironment || !vetted.some((spec) => isRegistrySpec(spec)); -}; - -// Whether `vis dlx` can pass the binary's native gate (`plan` in `dlx.rs`): only the runs where the first-run gate does -// nothing, the shapes above, and an environment that leaves the installer and Node's output alone. The lean entry reads -// no config and no workspace root, and prints nothing of its own, so a terminal and a missing `CI` make no difference. -// The binary re-checks everything, including the lockfiles, `packageManager` pins and `aube` on `PATH`. +// Whether `vis dlx` can pass the binary's native gate (`plan` in `dlx.rs`): the shapes above, and an environment that +// leaves the installer and Node's output alone. The first-run gate is the binary's to decide (it does nothing with +// `--no-info`, `--yes`, CI or a stream that is not a terminal, and on a terminal it looks the package up and answers only +// for a version already approved), and so are the lockfiles, `packageManager` pins and `aube` on `PATH`; this only skips +// the extra process for a shape the binary would delegate anyway. The lean entry reads no config and no workspace root, +// and prints nothing of its own. const dlxMayRunNatively = (platform, environment, args) => { if ( platform === "win32" @@ -766,9 +743,7 @@ const dlxMayRunNatively = (platform, environment, args) => { return false; } - const shape = dlxShape(args.slice(1)); - - return shape !== undefined && dlxGateIsSwitchedOff(environment, shape); + return dlxShape(args.slice(1)) !== undefined; }; // Whether `vis sync ci-workflow` can pass the binary's native gate (`native_root` and `parse` in @@ -1107,6 +1082,102 @@ const keysRefreshArgsAreNative = (args) => { return (flags.length === 1 && flags[0] === "--json") || (flags.length === 2 && flags.includes("--json") && flags.includes("--clear")); }; +// The flags of `vis attest` (`parse` in `attest/mod.rs`): `--name value` or `--name=value` for the values, `--name` for the +// switches, each at most once, and plain words. A value that is empty or starts with a dash, any other flag and `--` are not. +const attestFlag = (shape, rest, index, values, switches) => { + const [name, ...inline] = rest[index].slice(2).split("="); + + if (switches.includes(name)) { + if (inline.length > 0 || shape.switches.has(name)) { + return undefined; + } + + shape.switches.add(name); + + return index + 1; + } + + const value = inline.length > 0 ? inline.join("=") : rest[index + 1]; + + if (!values.includes(name) || shape.values.has(name) || value === undefined || value === "" || value.startsWith("-")) { + return undefined; + } + + shape.values.set(name, value); + + return inline.length > 0 ? index + 1 : index + 2; +}; + +const attestShape = (rest, values, switches) => { + const shape = { switches: new Set(), values: new Map(), words: [] }; + let index = 0; + + while (index < rest.length) { + const token = rest[index]; + + if (!token.startsWith("-")) { + shape.words.push(token); + index += 1; + + continue; + } + + index = token.startsWith("--") ? attestFlag(shape, rest, index, values, switches) : undefined; + + if (index === undefined) { + return undefined; + } + } + + return shape; +}; + +const ATTEST_FORMATS = ["json", "ndjson", "table"]; + +// Whether `vis attest ` can pass the binary's native gate (`answer` in `attest/emit.rs`): the run that has no ambient OIDC +// token, so Node hashes the artifact and skips signing. A run that signs, `--require-signing` and the failures stay in Node. The +// binary re-checks everything, including the subject and the workspace. +const attestEmitShapeIsNative = (environment, rest) => { + const shape = attestShape(rest, ["format", "output", "predicate"], ["require-signing"]); + + return shape !== undefined + && shape.words.length === 1 + && shape.words[0] !== "verify" + && !shape.switches.has("require-signing") + && ["slsaProvenance", undefined].includes(shape.values.get("predicate")) + && [undefined, ...ATTEST_FORMATS].includes(shape.values.get("format")) + && environment.CI !== "true" + && environment.ACTIONS_ID_TOKEN_REQUEST_URL === undefined + && environment.SIGSTORE_ID_TOKEN === undefined; +}; + +// Whether `vis attest verify` can pass the binary's native gate (`answer` in `attest/verify.rs`): no `--prod-only`, no word, no +// `MARSHALL_*` or `VIS_NPM_KEYS_URL`. The binary re-checks everything, including the lockfile, the registry and the keys. +const attestVerifyShapeIsNative = (environment, rest) => { + const shape = attestShape(rest, ["format", "fail-on", "allowlist"], []); + + return shape !== undefined + && shape.words.length === 0 + && [undefined, ...ATTEST_FORMATS].includes(shape.values.get("format")) + && ["error", undefined, "warning"].includes(shape.values.get("fail-on")) + && environment.VIS_NPM_KEYS_URL === undefined + && !Object.keys(environment).some((key) => key.startsWith("MARSHALL_")); +}; + +// `vis attest ` and `vis attest verify`, in a CI context off a terminal at the root of a pnpm workspace, with no proxy, +// CA or Node option in the environment. +const attestMayRunNatively = (platform, environment, args, cwd, interactive, holdsMarker) => { + if (platform === "win32" || interactive || !inCi(environment) || !cwdIsRoot(environment, cwd, holdsMarker) || !pailOutputIsDecidable(environment, args)) { + return false; + } + + if (!outputSettingsAreDefault(environment) || !networkEnvironmentIsPlain(environment)) { + return false; + } + + return args[1] === "verify" ? attestVerifyShapeIsNative(environment, args.slice(2)) : attestEmitShapeIsNative(environment, args.slice(1)); +}; + const keysRefreshMayRunNatively = (platform, environment, args, cwd, interactive, holdsMarker) => { if (platform === "win32" || interactive || !inCi(environment) || !cwdIsRoot(environment, cwd, holdsMarker) || nodeWarnsAboutColour(environment)) { return false; @@ -1425,6 +1496,8 @@ const NATIVE_SHAPE_GATES = new Map([ ["add", ({ args, environment, interactive, platform }) => helpOrNative(args, () => addMayRunNatively(platform, environment, args, interactive))], // `affected --sparse-checkout`. ["affected", ({ args, environment, interactive, platform }) => helpOrNative(args, () => affectedMayRunNatively(platform, environment, args, interactive))], + // `attest ` for a run with no OIDC token (Node skips signing) and `attest verify` (JSON, NDJSON, and a table of no findings). + ["attest", ({ args, cwd, environment, holdsMarker, interactive, platform }) => helpOrNative(args, () => attestMayRunNatively(platform, environment, args, cwd, interactive, holdsMarker))], // `audit --format json`, answered only when the scan finds nothing. ["audit", ({ args, cwd, environment, holdsMarker, interactive, platform }) => helpOrNative(args, () => auditMayRunNatively(platform, environment, args, cwd, interactive, holdsMarker))], // `cache list`, `cache size` (`cache.rs`), `cache clean` (`cache_clean.rs`), `cache prune` (`cache_prune.rs`), `cache hash` (`cache_hash.rs`) and `cache why` (`cache_why.rs`); the binary hands every other shape to Node itself. diff --git a/packages/tooling/vis/native/Cargo.lock b/packages/tooling/vis/native/Cargo.lock index 0ad9e8c1..db77da3e 100644 --- a/packages/tooling/vis/native/Cargo.lock +++ b/packages/tooling/vis/native/Cargo.lock @@ -2560,6 +2560,7 @@ dependencies = [ "rayon", "rcgen", "regex", + "ring", "rustls", "rustls-native-certs", "secret-scanner-core", diff --git a/packages/tooling/vis/native/cli/Cargo.toml b/packages/tooling/vis/native/cli/Cargo.toml index c7486da3..491a4e12 100644 --- a/packages/tooling/vis/native/cli/Cargo.toml +++ b/packages/tooling/vis/native/cli/Cargo.toml @@ -76,6 +76,9 @@ ureq = { version = "3.5", default-features = false, features = [ "rustls", "gzip" ] } +# `vis attest verify`: the ECDSA P-256 check of the registry's signatures (src/attest/signature.rs). The crate `rustls` +# already links as its crypto provider. +ring = "0.17" # Already in the tree through `ureq`; named here to read its errors apart (src/http/error.rs) and, in the tests, to # serve TLS. Same features as `ureq` turns on. rustls = { version = "0.23", default-features = false, features = [ diff --git a/packages/tooling/vis/native/cli/src/attest/emit.rs b/packages/tooling/vis/native/cli/src/attest/emit.rs new file mode 100644 index 00000000..6c5d0359 --- /dev/null +++ b/packages/tooling/vis/native/cli/src/attest/emit.rs @@ -0,0 +1,169 @@ +//! `vis attest ` (`attestEmitExecute`) for a run with no ambient OIDC token. +//! +//! Node hashes the artifact and, finding no token to sign with, skips signing: a JSON document with +//! `--format json`, a warning otherwise. That is all this module answers. The run that signs needs Sigstore, and the +//! failures (a missing subject or workspace root, an unreadable artifact, `--require-signing`, a predicate other than +//! `slsaProvenance`) are thrown by Node with a stack trace, so they stay Node's. +//! +//! The subject must be a path that needs no normalising (no `.` or `..` segment, no trailing slash) of printable ASCII, +//! so the name Node prints is the last segment as it is. + +use std::env; +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::exit; + +use sha2::{Digest, Sha256}; + +use super::{format_of, parse}; +use crate::js::{json_string, pretty_document}; +use crate::node_context::context_decline; +use crate::output::write_streams; +use crate::text::is_ascii_graphic; + +/// `detectAmbientOidc`: `CI` equal to `true`, or either token variable set to anything. +fn has_ambient_oidc() -> bool { + env::var_os("CI").is_some_and(|value| value == "true") + || env::var_os("ACTIONS_ID_TOKEN_REQUEST_URL").is_some() + || env::var_os("SIGSTORE_ID_TOKEN").is_some() +} + +/// What a run prints. +struct Outcome { + stdout: String, + stderr: String, +} + +/// Answers `vis attest ` natively or hands the whole invocation to Node. +pub fn run(args: &[String], raw_args: &[OsString]) -> ! { + match answer(args) { + Ok(outcome) => { + write_streams("attest", &outcome.stdout, &outcome.stderr); + + exit(0) + } + Err(reason) => crate::process::delegate_because(&reason, raw_args), + } +} + +fn answer(args: &[String]) -> Result { + let parsed = parse(args.get(1..).unwrap_or_default(), &["format", "output", "predicate"], &["require-signing"]) + .ok_or("not the plain flags of `attest `")?; + let [subject] = parsed.words.as_slice() else { return Err("not exactly one subject".to_owned()) }; + + // Node reads this word as the `verify` leaf wherever it stands. + if subject == "verify" { + return Err("the subject is named like the `verify` leaf".to_owned()); + } + + if parsed.switch("require-signing") { + return Err("`--require-signing` fails without a token, with a stack trace".to_owned()); + } + + if parsed.value("predicate").is_some_and(|predicate| predicate != "slsaProvenance") { + return Err("a predicate other than slsaProvenance is an error".to_owned()); + } + + let format = format_of(&parsed).ok_or("a format other than json, ndjson and table")?; + + if let Some(reason) = context_decline() { + return Err(reason.to_owned()); + } + + if has_ambient_oidc() { + return Err("an ambient OIDC token is present: Node signs".to_owned()); + } + + let root = env::current_dir().map_err(|error| format!("the working directory cannot be read: {error}"))?; + let path = subject_path(&root, subject)?; + let name = path.file_name().and_then(|name| name.to_str()).ok_or("the subject has no file name")?; + let sha256 = sha256_of(&path)?; + + if format == "json" { + let stdout = pretty_document(&[ + ("ok", "false".to_owned()), + ("reason", json_string("no-ambient-oidc")), + ("sha256", json_string(&sha256)), + ("skipped", "true".to_owned()), + ("subject", json_string(name)), + ]); + + return Ok(Outcome { stdout, stderr: String::new() }); + } + + // `logger.warn` of the toolbox writes the message and a line break to stderr. Whether it colours the line is + // only known where the run has no colour at all, which is all this answers. + if crate::term::piped_colour_level(args) != Some(0) { + return Err("the colour level cannot be told to be none without Node".to_owned()); + } + + let message = format!( + "No ambient OIDC token (not running in CI). Keyless signing needs a Fulcio identity from CI OIDC. Skipping signing (subject sha256: {sha256}). Pass --require-signing to make this fatal." + ); + + Ok(Outcome { stdout: String::new(), stderr: format!("{message}\n") }) +} + +/// The path of the subject: absolute as given, else below the workspace root; `Err` for a text that would need +/// normalising or that is not printable ASCII. +fn subject_path(root: &Path, subject: &str) -> Result { + let plain = !subject.is_empty() + && is_ascii_graphic(subject) + && !subject.ends_with('/') + && !subject.contains("//") + && subject.split('/').all(|segment| segment != "." && segment != ".."); + + if !plain { + return Err("the subject is a path that needs normalising, or is not printable ASCII".to_owned()); + } + + Ok(if subject.starts_with('/') { PathBuf::from(subject) } else { root.join(subject) }) +} + +/// The SHA-256 of the file, in lower-case hex; `Err` when it cannot be read (Node throws). +fn sha256_of(path: &Path) -> Result { + let metadata = fs::metadata(path).map_err(|error| format!("the subject cannot be read: {error}"))?; + + if !metadata.is_file() { + return Err("the subject is not a regular file".to_owned()); + } + + let bytes = fs::read(path).map_err(|error| format!("the subject cannot be read: {error}"))?; + + Ok(Sha256::digest(&bytes).iter().map(|byte| format!("{byte:02x}")).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_subject_path_needs_no_normalising() { + let root = Path::new("/work"); + + assert_eq!(subject_path(root, "dist/app.tgz").unwrap(), Path::new("/work/dist/app.tgz")); + assert_eq!(subject_path(root, "/abs/app.tgz").unwrap(), Path::new("/abs/app.tgz")); + + for odd in ["./app.tgz", "dist/../app.tgz", "dist/", "a//b", "caf\u{e9}.tgz", "a b", "", ".."] { + assert!(subject_path(root, odd).is_err(), "{odd:?}"); + } + } + + #[test] + fn the_digest_is_the_sha256_of_the_bytes() { + let directory = std::env::temp_dir().join(format!("vis-attest-emit-{}", std::process::id())); + + fs::create_dir_all(&directory).unwrap(); + + let file = directory.join("a.bin"); + + fs::write(&file, b"abc").unwrap(); + + assert_eq!(sha256_of(&file).unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + assert!(sha256_of(&directory).is_err()); + assert!(sha256_of(&directory.join("missing")).is_err()); + + fs::remove_dir_all(&directory).unwrap(); + } +} diff --git a/packages/tooling/vis/native/cli/src/attest/mod.rs b/packages/tooling/vis/native/cli/src/attest/mod.rs new file mode 100644 index 00000000..f1db394a --- /dev/null +++ b/packages/tooling/vis/native/cli/src/attest/mod.rs @@ -0,0 +1,144 @@ +//! `vis attest` — the offline and verification paths of `src/commands/attest/`, natively. +//! +//! The command has two leaves, and each answers the shapes it reproduces byte for byte and hands the rest to Node +//! before any output (a hand-off names its reason on stderr when `VIS_DEBUG_DECLINE` is set): +//! +//! - [`emit`] (`vis attest `) answers the run that has no ambient OIDC token: Node hashes the artifact and +//! skips signing, with a JSON document or a warning. A run that signs (`CI` equal to `true`, a GitHub Actions +//! token, a Sigstore token), `--require-signing` and every failure (they are thrown, with a stack) are Node's. +//! - [`verify`] (`vis attest verify`) checks the locked packages of a pnpm workspace against the registry's +//! provenance and signatures. The JSON and NDJSON reports are native, and so is the table report for a run that +//! finds nothing; a table of findings is drawn by the terminal UI and stays in Node. +//! +//! Both read the same flags; the parser below takes exact tokens, each at most once. + +pub(crate) mod emit; +mod signature; +pub(crate) mod verify; + +/// What the flags of a leaf were: the values and switches it takes and the words that are neither. +#[derive(Debug, Default, PartialEq, Eq)] +struct Parsed { + values: Vec<(&'static str, String)>, + switches: Vec<&'static str>, + words: Vec, +} + +impl Parsed { + fn value(&self, name: &str) -> Option<&str> { + self.values.iter().find(|(key, _)| *key == name).map(|(_, value)| value.as_str()) + } + + fn switch(&self, name: &str) -> bool { + self.switches.contains(&name) + } +} + +/// The arguments after the command words: `--name value` or `--name=value` for each of `values`, `--name` for each of +/// `switches`, every one at most once, and plain words. A value that is empty or starts with a dash, any other flag, a +/// switch with a value and `--` are `None`: cerebro reads them in ways this does not. +fn parse(rest: &[String], values: &[&'static str], switches: &[&'static str]) -> Option { + let mut parsed = Parsed::default(); + let mut tokens = rest.iter(); + + while let Some(token) = tokens.next() { + let Some(flag) = token.strip_prefix("--") else { + if token.starts_with('-') { + return None; + } + + parsed.words.push(token.clone()); + + continue; + }; + let (name, inline) = match flag.split_once('=') { + Some((name, value)) => (name, Some(value)), + None => (flag, None), + }; + + if let Some(known) = switches.iter().find(|known| **known == name) { + if inline.is_some() || parsed.switches.contains(known) { + return None; + } + + parsed.switches.push(known); + + continue; + } + + let known = values.iter().find(|known| **known == name)?; + let value = inline.or_else(|| tokens.next().map(String::as_str))?; + + if value.is_empty() || value.starts_with('-') || parsed.value(known).is_some() { + return None; + } + + parsed.values.push((known, value.to_owned())); + } + + Some(parsed) +} + +/// The `--format` values both leaves read: `json` and `ndjson` are machine formats, `table` is the default, and +/// Node reads any other text as `table`, which this does not rely on. +fn format_of(parsed: &Parsed) -> Option<&str> { + match parsed.value("format") { + None => Some("table"), + Some(format @ ("json" | "ndjson" | "table")) => Some(format), + Some(_) => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tokens(list: &[&str]) -> Vec { + list.iter().map(|item| (*item).to_owned()).collect() + } + + #[test] + fn values_switches_and_words_parse_and_everything_else_does_not() { + let parsed = parse( + &tokens(&["dist/app.tgz", "--format", "json", "--require-signing", "--output=out.sigstore"]), + &["format", "output"], + &["require-signing"], + ) + .unwrap(); + + assert_eq!(parsed.words, ["dist/app.tgz"]); + assert_eq!(parsed.value("format"), Some("json")); + assert_eq!(parsed.value("output"), Some("out.sigstore")); + assert!(parsed.switch("require-signing") && !parsed.switch("other")); + + for odd in [ + &["--format"][..], + &["--format", "--json"], + &["--format="], + &["--format", "a", "--format", "b"], + &["--format=a", "--format=b"], + &["--require-signing", "--require-signing"], + &["--require-signing=true"], + &["--unknown", "x"], + &["-f", "json"], + &["--"], + &["--no-format"], + ] { + assert!(parse(&tokens(odd), &["format"], &["require-signing"]).is_none(), "{odd:?}"); + } + } + + #[test] + fn the_format_is_one_of_three() { + let format = |list: &[&str]| { + let parsed = parse(&tokens(list), &["format"], &[]).unwrap(); + + format_of(&parsed).map(str::to_owned) + }; + + assert_eq!(format(&[]).as_deref(), Some("table")); + assert_eq!(format(&["--format", "json"]).as_deref(), Some("json")); + assert_eq!(format(&["--format=ndjson"]).as_deref(), Some("ndjson")); + assert_eq!(format(&["--format", "xml"]), None); + } +} diff --git a/packages/tooling/vis/native/cli/src/attest/signature.rs b/packages/tooling/vis/native/cli/src/attest/signature.rs new file mode 100644 index 00000000..26e293b8 --- /dev/null +++ b/packages/tooling/vis/native/cli/src/attest/signature.rs @@ -0,0 +1,191 @@ +//! `verifyEcdsaSignature` of `src/security/marshalls/verify-ecdsa.ts`: an ECDSA P-256 / SHA-256 signature, in the DER +//! form npm sends it, over `name@version:integrity`, against the registry's SPKI key. +//! +//! Node wraps the key in PEM, lets OpenSSL read it and answers `false` for anything that does not verify, including a +//! key or signature that cannot be read. This module answers the same for the shapes it reads the way OpenSSL does and +//! gives the reason for a hand-off for the rest: a base64 text that is not canonical (Node's decoder skips what it +//! does not know), a key that is not the 91 bytes of a P-256 SPKI, which OpenSSL may still use for another curve. + +use ring::signature::{UnparsedPublicKey, ECDSA_P256_SHA256_ASN1}; + +/// The DER prefix of an SPKI holding a prime256v1 key: `SEQUENCE { SEQUENCE { id-ecPublicKey, prime256v1 }, +/// BIT STRING (66 bytes, no unused bits) }`, up to the 65 bytes of the uncompressed point. +const SPKI_P256_PREFIX: [u8; 26] = [ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, +]; + +/// Standard base64 with padding and no other character: the only text Node's decoder and this one read alike. +fn decode(text: &str) -> Option> { + let bytes = text.as_bytes(); + + if bytes.is_empty() || !bytes.len().is_multiple_of(4) { + return None; + } + + let padding = bytes.iter().rev().take_while(|byte| **byte == b'=').count(); + + if padding > 2 { + return None; + } + + let mut out = Vec::with_capacity(bytes.len() / 4 * 3); + + for (index, chunk) in bytes.chunks(4).enumerate() { + let last = index == bytes.len() / 4 - 1; + let mut value = 0_u32; + let mut missing = 0; + + for (position, byte) in chunk.iter().enumerate() { + let sextet = match byte { + b'A'..=b'Z' => byte - b'A', + b'a'..=b'z' => byte - b'a' + 26, + b'0'..=b'9' => byte - b'0' + 52, + b'+' => 62, + b'/' => 63, + b'=' if last && position >= 4 - padding => { + missing += 1; + 0 + } + _ => return None, + }; + + value = value << 6 | u32::from(sextet); + } + + let triple = value.to_be_bytes(); + + out.extend_from_slice(&triple[1..4 - missing]); + + // The bits a padded group does not use must be zero, or Node's decoder and the canonical form differ. + if missing > 0 && triple[4 - missing..].iter().any(|byte| *byte != 0) { + return None; + } + } + + Some(out) +} + +/// Whether `signature_base64` verifies over `message` against `key_base64`, or the reason this module leaves the +/// decision to Node. +pub(super) fn verifies(key_base64: &str, message: &str, signature_base64: &str) -> Result { + // `wrapSpkiPem` drops every whitespace character before it cuts the text into lines. + let key_text: String = key_base64.chars().filter(|character| !character.is_whitespace()).collect(); + let key = decode(&key_text).ok_or("a registry key that is not canonical base64")?; + let point = key + .strip_prefix(&SPKI_P256_PREFIX[..]) + .filter(|point| point.len() == 65 && point[0] == 4) + .ok_or("a registry key that is not a P-256 SPKI")?; + let signature = decode(signature_base64).ok_or("a signature that is not canonical base64")?; + + Ok(UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, point).verify(message.as_bytes(), &signature).is_ok()) +} + +/// Signing keys and signatures for the tests of this module and of [`super::verify`]. +#[cfg(test)] +pub(super) mod support { + use ring::rand::SystemRandom; + use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING}; + + use super::SPKI_P256_PREFIX; + + pub(in crate::attest) fn encode(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + + for chunk in bytes.chunks(3) { + let value = chunk + .iter() + .enumerate() + .fold(0_u32, |value, (index, byte)| value | u32::from(*byte) << (16 - 8 * index)); + + for position in 0..4 { + if position <= chunk.len() { + out.push(char::from(ALPHABET[(value >> (18 - 6 * position) & 63) as usize])); + } else { + out.push('='); + } + } + } + + out + } + + /// A fresh key pair: the SPKI of the public key, and a signer of messages. + pub(in crate::attest) struct Signer { + pub(in crate::attest) key_base64: String, + pair: EcdsaKeyPair, + random: SystemRandom, + } + + impl Signer { + pub(in crate::attest) fn new() -> Self { + let random = SystemRandom::new(); + let document = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &random).unwrap(); + let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, document.as_ref(), &random).unwrap(); + let spki = [SPKI_P256_PREFIX.as_slice(), pair.public_key().as_ref()].concat(); + + Self { key_base64: encode(&spki), pair, random } + } + + pub(in crate::attest) fn sign(&self, message: &str) -> String { + encode(self.pair.sign(&self.random, message.as_bytes()).unwrap().as_ref()) + } + } +} + +#[cfg(test)] +mod tests { + use super::support::{encode, Signer}; + use super::*; + + fn signed(message: &str) -> (String, String) { + let signer = Signer::new(); + + (signer.key_base64.clone(), signer.sign(message)) + } + + #[test] + fn base64_is_read_in_the_canonical_form_only() { + assert_eq!(decode("TWFu").unwrap(), b"Man"); + assert_eq!(decode("TWE=").unwrap(), b"Ma"); + assert_eq!(decode("TQ==").unwrap(), b"M"); + + for odd in ["", "TWF", "TWFu\n", "TW=u", "TWE", "T===", "TWF-", "TQ=A", "TR==", "TWH="] { + assert!(decode(odd).is_none(), "{odd:?}"); + } + + for bytes in [&b""[..], b"a", b"ab", b"abc", b"abcd", &[0xff, 0x00, 0xfe, 0x01, 0xfd]] { + if !bytes.is_empty() { + assert_eq!(decode(&encode(bytes)).unwrap(), bytes); + } + } + } + + #[test] + fn a_signature_verifies_over_its_message_only() { + let message = "pkg@1.0.0:sha512-abc"; + let (key, signature) = signed(message); + + assert_eq!(verifies(&key, message, &signature), Ok(true)); + assert_eq!(verifies(&key, "pkg@1.0.1:sha512-abc", &signature), Ok(false)); + + // A signature that is not DER fails the way it does in OpenSSL. + assert_eq!(verifies(&key, message, &encode(&[1, 2, 3])), Ok(false)); + + // Whitespace in the key is dropped, as `wrapSpkiPem` drops it. + let wrapped = format!("{}\n{}", &key[..40], &key[40..]); + + assert_eq!(verifies(&wrapped, message, &signature), Ok(true)); + } + + #[test] + fn what_openssl_may_read_differently_is_handed_over() { + let (key, signature) = signed("m"); + + assert!(verifies("not base64!", "m", &signature).is_err()); + assert!(verifies(&encode(&[0x30, 0x03, 0x02, 0x01, 0x00]), "m", &signature).is_err()); + assert!(verifies(&key, "m", "not base64!").is_err()); + assert!(verifies(&key, "m", "").is_err()); + } +} diff --git a/packages/tooling/vis/native/cli/src/attest/verify.rs b/packages/tooling/vis/native/cli/src/attest/verify.rs new file mode 100644 index 00000000..641a927e --- /dev/null +++ b/packages/tooling/vis/native/cli/src/attest/verify.rs @@ -0,0 +1,785 @@ +//! `vis attest verify` (`attestVerifyExecute`): the provenance and signature marshalls over the locked packages of a +//! pnpm workspace, reported as JSON, NDJSON or a table. +//! +//! Node reads the lockfile, asks the registry for each package's packument (through the cache in +//! `~/.vis/cache/packuments`, which [`Packuments`] shares with `vis inspect`) and the registry's signing keys (cache +//! `~/.vis/cache/registry-keys`), runs both marshalls and prints the findings. This module does the same, with up to eight +//! packuments in flight as Node's `mapWithConcurrency` does, from a CI run off a terminal at the root of a pnpm +//! workspace (see [`context_decline`]). +//! +//! What it leaves to Node, before any output: +//! +//! - `--prod-only` (it walks the workspace's `package.json` files), any other flag, and every word after `verify`; +//! - a `MARSHALL_*` variable, a `VIS_NPM_KEYS_URL`, a proxy, CA or Node option, a `packageManager` pin, and a registry, +//! packument, key or signature this binary does not read the way Node does (see [`crate::inspect`] and +//! [`super::signature`]); +//! - a lockfile this crate does not read exactly, or none, and a name or version outside printable ASCII; +//! - the table report when there is a finding: the terminal UI draws it. The cache the run filled is written first, +//! so Node finds it warm; it is the bytes Node writes. + +use std::collections::{HashMap, HashSet}; +use std::env; +use std::ffi::OsString; +use std::fs; +use std::process::exit; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use super::signature::verifies; +use super::{format_of, parse}; +use crate::inspect::{commit, has_provenance, parse_date, prior_with_provenance, CacheAction, Packuments, View}; +use crate::js::json_string; +use crate::keys_refresh::{registry_keys, Js, RegistryKey}; +use crate::node_context::context_decline; +use crate::output::{node_may_cut_short, write_streams}; +use crate::pm_detect::ancestor_pins_package_manager; +use crate::pnpm_lock; +use crate::text::is_ascii_graphic; + +/// `DEFAULT_MARSHALL_CONCURRENCY`. +const CONCURRENCY: usize = 8; +/// `DEFAULT_FETCH_TIMEOUT_MS` of the packument module. +const PACKUMENT_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Severity { + Error, + Warning, +} + +impl Severity { + fn name(self) -> &'static str { + match self { + Self::Error => "error", + Self::Warning => "warning", + } + } +} + +/// An `AttestFinding`. +#[derive(Debug, PartialEq, Eq)] +struct Finding { + code: &'static str, + message: String, + package: String, + severity: Severity, + version: String, +} + +impl Finding { + /// `JSON.stringify(finding)` with the given line break and indent before each member. + fn json(&self, break_and_indent: &str, close: &str) -> String { + let members = [ + ("code", json_string(self.code)), + ("message", json_string(&self.message)), + ("packageName", json_string(&self.package)), + ("severity", json_string(self.severity.name())), + ("version", json_string(&self.version)), + ]; + let body: Vec = members + .iter() + .map(|(name, value)| { + format!("{break_and_indent}\"{name}\":{}{value}", if break_and_indent.is_empty() { "" } else { " " }) + }) + .collect(); + + format!("{{{}{close}}}", body.join(",")) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Flags<'a> { + format: &'a str, + fail_on_error: bool, +} + +/// What a run prints and the status it ends with. +struct Outcome { + stdout: String, + stderr: String, + status: i32, +} + +/// Answers `vis attest verify` natively or hands the whole invocation to Node. +pub fn run(args: &[String], raw_args: &[OsString]) -> ! { + match answer(args) { + Ok(outcome) => { + write_streams("attest", &outcome.stdout, &outcome.stderr); + + exit(outcome.status) + } + Err(reason) => crate::process::delegate_because(&reason, raw_args), + } +} + +fn now_ms() -> Result { + let elapsed = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970".to_owned())?; + + u64::try_from(elapsed.as_millis()).map_err(|_| "the clock is out of range".to_owned()) +} + +fn answer(args: &[String]) -> Result { + let parsed = parse(args.get(2..).unwrap_or_default(), &["format", "fail-on", "allowlist"], &[]) + .ok_or("not the plain flags of `attest verify`")?; + + if !parsed.words.is_empty() { + return Err("a word after `verify`".to_owned()); + } + + let fail_on_error = match parsed.value("fail-on") { + None | Some("warning") => false, + Some("error") => true, + Some(_) => return Err("a `--fail-on` value other than warning and error".to_owned()), + }; + let format = format_of(&parsed).ok_or("a format other than json, ndjson and table")?; + let allowlist: HashSet = parsed + .value("allowlist") + .unwrap_or_default() + .split(',') + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()) + .collect(); + + if !allowlist.iter().all(|name| is_ascii_graphic(name)) { + return Err("an allowlist entry that is not printable ASCII".to_owned()); + } + + if let Some(reason) = context_decline() { + return Err(reason.to_owned()); + } + + if env::vars_os().any(|(name, _)| name.to_string_lossy().starts_with("MARSHALL_")) { + return Err("a MARSHALL_* variable is set".to_owned()); + } + + let root = env::current_dir().map_err(|error| format!("the working directory cannot be read: {error}"))?; + + if ancestor_pins_package_manager(&root) { + return Err("a package.json pins the package manager".to_owned()); + } + + let packages = locked_packages(&root)?; + let packuments = Packuments::new(root, PACKUMENT_TIMEOUT)?; + let keys = registry_keys(now_ms()?)?; + // The table line is written by the toolbox's logger, which is only known to leave a run without colour plain. + if format == "table" && crate::term::piped_colour_level(args) != Some(0) { + return Err("the colour level cannot be told to be none without Node".to_owned()); + } + + let flags = Flags { format, fail_on_error }; + let (scanned, cache) = scan(&packuments, keys.keys.as_deref(), &packages, &allowlist, now_ms()?); + let outcome = scanned.and_then(|findings| report(flags, packages.len(), &findings)); + + // A run that ends here for Node (the table of findings, or a package this binary cannot read) leaves it the cache + // this run filled, which is the bytes Node writes, so Node does not fetch it all again. + let outcome = match outcome { + Ok(outcome) => outcome, + Err(reason) => { + commit(&cache)?; + keys.commit()?; + + return Err(reason); + } + }; + + if node_may_cut_short(outcome.stdout.len()) { + return Err("the report is larger than Node reliably writes to a pipe".to_owned()); + } + + commit(&cache)?; + keys.commit()?; + + Ok(outcome) +} + +/// A locked package. +struct Package { + name: String, + version: String, +} + +/// `lockedPackages` for a pnpm workspace with dev dependencies: the lockfile's packages, a name and version listed twice +/// counting once. +fn locked_packages(root: &std::path::Path) -> Result, String> { + let bytes = + fs::read(root.join("pnpm-lock.yaml")).map_err(|error| format!("pnpm-lock.yaml cannot be read: {error}"))?; + let entries = pnpm_lock::parse(&bytes).ok_or("pnpm-lock.yaml is not text this crate reads exactly")?; + + if entries.is_empty() { + return Err("the lockfile lists no package".to_owned()); + } + + let mut seen = HashSet::new(); + let mut packages = Vec::new(); + + for entry in entries { + if !is_ascii_graphic(&entry.name) || !is_ascii_graphic(&entry.version) { + return Err("a package name or version is not printable ASCII".to_owned()); + } + + if seen.insert(format!("{}@{}", entry.name, entry.version)) { + packages.push(Package { name: entry.name, version: entry.version }); + } + } + + Ok(packages) +} + +/// What the two marshalls find for one package, and the cache change of reading its packument. +struct Checked { + provenance: Option, + signatures: Vec, + cache: Vec, +} + +/// Both marshalls over every package, with [`CONCURRENCY`] packages in flight: the provenance findings, then the +/// signature findings, each in the order of the packages, and the cache changes of the packages that were read, whether or +/// not another one failed. The first failure is the run's. +fn scan( + packuments: &Packuments, + keys: Option<&[RegistryKey]>, + packages: &[Package], + allowlist: &HashSet, + now_ms: u64, +) -> (Result, String>, Vec) { + let by_id: HashMap<&str, &RegistryKey> = + keys.unwrap_or_default().iter().map(|key| (key.keyid.as_str(), key)).collect(); + let next = AtomicUsize::new(0); + let results: Mutex>>> = Mutex::new((0..packages.len()).map(|_| None).collect()); + + std::thread::scope(|scope| { + for _ in 0..CONCURRENCY.min(packages.len()) { + scope.spawn(|| loop { + let index = next.fetch_add(1, Ordering::SeqCst); + + let Some(package) = packages.get(index) else { return }; + let checked = if allowlist.contains(&package.name) { + Ok(Checked { provenance: None, signatures: Vec::new(), cache: Vec::new() }) + } else { + check(packuments, keys.is_some().then_some(&by_id), package, now_ms) + }; + + results.lock().expect("a worker panicked")[index] = Some(checked); + }); + } + }); + + let mut provenance = Vec::new(); + let mut signatures = Vec::new(); + let mut cache = Vec::new(); + let mut failure: Option = None; + + for (package, checked) in packages.iter().zip(results.into_inner().expect("a worker panicked")) { + let checked = match checked { + Some(Ok(checked)) => checked, + Some(Err(reason)) => { + failure.get_or_insert(reason); + + continue; + } + None => { + failure.get_or_insert_with(|| "a package was not checked".to_owned()); + + continue; + } + }; + + if let Some(prior) = checked.provenance { + provenance.push(Finding { + code: "provenance-regression", + message: format!( + "Resolved {0}@{1} has no published provenance attestation, but {0}@{prior} did \u{2014} a provenance regression.", + package.name, package.version + ), + package: package.name.clone(), + severity: Severity::Warning, + version: package.version.clone(), + }); + } + + signatures.extend(checked.signatures); + cache.extend(checked.cache); + } + + provenance.extend(signatures); + + (failure.map_or(Ok(provenance), Err), cache) +} + +/// Both marshalls for one package that is not on the allowlist. `keys` is `None` when the registry's keys could not be +/// had at all: every package then gets a `fetch-failed` warning, before its packument is read. +fn check( + packuments: &Packuments, + keys: Option<&HashMap<&str, &RegistryKey>>, + package: &Package, + now_ms: u64, +) -> Result { + let (checked, cache) = packuments.read(&package.name, |view| { + let provenance = match view { + Some(view) if !has_provenance(view.entry(&package.version))? => { + prior_with_provenance(view, &package.version)?.map(str::to_owned) + } + _ => None, + }; + let signatures = match (keys, view) { + (None, _) => vec![finding( + package, + "fetch-failed", + Severity::Warning, + "Could not fetch registry signing keys.".to_owned(), + )], + (Some(_), None) => Vec::new(), + (Some(keys), Some(view)) => signature_findings(view, keys, package, now_ms)?, + }; + + Ok((provenance, signatures)) + })?; + + Ok(Checked { provenance: checked.0, signatures: checked.1, cache }) +} + +fn finding(package: &Package, code: &'static str, severity: Severity, message: String) -> Finding { + Finding { code, message, package: package.name.clone(), severity, version: package.version.clone() } +} + +/// `dist.signatures` as (keyid, signature) pairs when there are some, and `dist.integrity`. +type DistSignatures<'a> = (Option>, Option<&'a str>); + +/// `entry.dist?.signatures` and `entry.dist?.integrity` of the version's entry. +fn signatures_of(entry: &Js) -> Result, String> { + let dist = match entry.member("dist") { + None => return Ok((None, None)), + Some(dist @ Js::Object(_)) => dist, + Some(_) => return Err("a `dist` that is not an object".to_owned()), + }; + let integrity = dist.member("integrity").and_then(Js::text); + let signatures = match dist.member("signatures") { + None => None, + Some(Js::Array(items)) => Some( + items + .iter() + .map(|item| match (item.member("keyid").and_then(Js::text), item.member("sig").and_then(Js::text)) { + (Some(keyid), Some(sig)) => Ok((keyid, sig)), + _ => Err("a signature without a text keyid and sig".to_owned()), + }) + .collect::, _>>()?, + ), + Some(_) => return Err("`dist.signatures` is not an array".to_owned()), + }; + + Ok((signatures, integrity)) +} + +/// The signature marshall for a package whose packument exists. +fn signature_findings( + view: &View<'_>, + keys: &HashMap<&str, &RegistryKey>, + package: &Package, + now_ms: u64, +) -> Result, String> { + let (name, version) = (package.name.as_str(), package.version.as_str()); + // `versions[version] ?? versions[latest]`, where latest is the `latest` tag when it names a version, else the last one. + let latest = view.tag("latest")?.filter(|tag| view.entry(tag).is_some()).or_else(|| view.last_version()); + let Some(entry) = view.entry(version).or_else(|| latest.and_then(|tag| view.entry(tag))) else { + return Ok(Vec::new()); + }; + let (signatures, integrity) = signatures_of(entry)?; + let missing = |message: String| vec![finding(package, "missing-signature", Severity::Warning, message)]; + + let Some(signatures) = signatures.filter(|signatures| !signatures.is_empty()) else { + return Ok(missing(format!("Package {name}@{version} has no dist.signatures from the registry."))); + }; + + let Some(integrity) = integrity.filter(|integrity| !integrity.is_empty()) else { + return Ok(missing(format!( + "Package {name}@{version} has signatures but no dist.integrity to verify against." + ))); + }; + + let message = format!("{name}@{version}:{integrity}"); + let mut findings = Vec::new(); + + for (keyid, sig) in signatures { + let Some(key) = keys.get(keyid) else { + findings.push(finding( + package, + "unknown-keyid", + Severity::Error, + format!("Package {name}@{version} was signed with an unrecognized keyid ({keyid})."), + )); + + continue; + }; + + if is_expired(key, now_ms)? { + findings.push(finding( + package, + "expired-key", + Severity::Warning, + format!( + "Package {name}@{version} was signed with an expired key ({keyid}, expired {}).", + key.expires.as_deref().unwrap_or("unknown") + ), + )); + + continue; + } + + if !verifies(&key.key, &message, sig)? { + findings.push(finding( + package, + "invalid-signature", + Severity::Error, + format!("Package {name}@{version} signature did not verify against {keyid}."), + )); + } + } + + Ok(findings) +} + +/// `isKeyExpired`: `Date.parse(expires) <= now`, for the one form registries write; another form is Node's. +fn is_expired(key: &RegistryKey, now_ms: u64) -> Result { + match key.expires.as_deref() { + None | Some("") => Ok(false), + Some(expires) => { + let at = + parse_date(expires).ok_or_else(|| format!("a key expiry {expires:?} this binary does not parse"))?; + + Ok(at <= now_ms as f64) + } + } +} + +/// The report of a run, or the reason Node prints it. +fn report(flags: Flags<'_>, count: usize, findings: &[Finding]) -> Result { + let gating = findings.iter().filter(|finding| !flags.fail_on_error || finding.severity == Severity::Error).count(); + let status = i32::from(gating > 0); + let none = String::new; + + match flags.format { + "json" => { + let list = if findings.is_empty() { + "[]".to_owned() + } else { + let items: Vec = + findings.iter().map(|finding| format!(" {}", finding.json("\n ", "\n "))).collect(); + + format!("[\n{}\n ]", items.join(",\n")) + }; + + Ok(Outcome { + stdout: format!("{{\n \"findings\": {list},\n \"ok\": {}\n}}\n", gating == 0), + stderr: none(), + status, + }) + } + "ndjson" => Ok(Outcome { + stdout: findings.iter().map(|finding| format!("{}\n", finding.json("", ""))).collect(), + stderr: none(), + status, + }), + _ if findings.is_empty() => { + // `logger.info` of the toolbox is the console: the message and a line break, on stdout. + let stdout = format!("No provenance regressions or signature problems across {count} locked packages.\n"); + + Ok(Outcome { stdout, stderr: none(), status }) + } + _ => Err("the table of findings is drawn by the terminal UI".to_owned()), + } +} + +#[cfg(test)] +mod tests { + use std::collections::{HashMap, HashSet}; + use std::sync::atomic::Ordering; + + use serde_json::{json, Value}; + + use super::super::signature::support::Signer; + use super::*; + use crate::inspect::tests::{ok, packuments_for, Registry}; + + const NOW: u64 = 1_718_452_800_000; + + fn package(name: &str, version: &str) -> Package { + Package { name: name.to_owned(), version: version.to_owned() } + } + + fn key(signer: &Signer, keyid: &str, expires: Option<&str>) -> RegistryKey { + RegistryKey { keyid: keyid.to_owned(), key: signer.key_base64.clone(), expires: expires.map(str::to_owned) } + } + + /// A packument whose versions hold the given `dist` objects. + fn packument(name: &str, versions: &[(&str, Value)]) -> Value { + let entries: serde_json::Map = + versions.iter().map(|(version, dist)| ((*version).to_owned(), json!({ "dist": dist }))).collect(); + + json!({ "name": name, "dist-tags": { "latest": versions.last().unwrap().0 }, "versions": entries }) + } + + fn signed_dist(signer: &Signer, keyid: &str, name: &str, version: &str) -> Value { + let integrity = "sha512-abc"; + + json!({ "integrity": integrity, "signatures": [{ "keyid": keyid, "sig": signer.sign(&format!("{name}@{version}:{integrity}")) }] }) + } + + type Scanned = Result<(Vec, Vec), String>; + + fn run_scan( + packuments: &HashMap, + keys: Option<&[RegistryKey]>, + packages: &[Package], + allowlist: &[&str], + ) -> (Scanned, usize) { + let registry = Registry::start(packuments.iter().map(|(name, body)| (format!("/{name}"), ok(body))).collect()); + let (source, _) = packuments_for(®istry); + let allowlist: HashSet = allowlist.iter().map(|name| (*name).to_owned()).collect(); + let (found, cache) = scan(&source, keys, packages, &allowlist, NOW); + + (found.map(|findings| (findings, cache)), registry.requests.load(Ordering::SeqCst)) + } + + fn codes(findings: &[Finding]) -> Vec<(String, &'static str, String)> { + findings.iter().map(|finding| (finding.package.clone(), finding.code, finding.message.clone())).collect() + } + + #[test] + fn provenance_and_signatures_are_checked_for_every_package_and_the_allowlist_is_not_asked() { + let signer = Signer::new(); + let other = Signer::new(); + let keys = [key(&signer, "sha256-known", None), key(&signer, "sha256-old", Some("2024-01-01T00:00:00.000Z"))]; + let attested = json!({ "attestations": { "provenance": { "predicateType": "x" } } }); + let packuments = HashMap::from([ + // Signed and valid, and its provenance was dropped after a release that had it. + ( + "a".to_owned(), + packument( + "a", + &[ + ("1.0.0", { + let mut dist = signed_dist(&signer, "sha256-known", "a", "1.0.0"); + dist["attestations"] = attested["attestations"].clone(); + dist + }), + ("2.0.0", signed_dist(&signer, "sha256-known", "a", "2.0.0")), + ], + ), + ), + // No signatures at all, then a signature without an integrity. + ("b".to_owned(), packument("b", &[("1.0.0", json!({}))])), + ( + "c".to_owned(), + packument("c", &[("1.0.0", json!({ "signatures": [{ "keyid": "sha256-known", "sig": "AAAA" }] }))]), + ), + // An unknown key, an expired key, and a signature by another key. + ("d".to_owned(), packument("d", &[("1.0.0", signed_dist(&signer, "sha256-nobody", "d", "1.0.0"))])), + ("e".to_owned(), packument("e", &[("1.0.0", signed_dist(&signer, "sha256-old", "e", "1.0.0"))])), + ("f".to_owned(), packument("f", &[("1.0.0", signed_dist(&other, "sha256-known", "f", "1.0.0"))])), + // A version the packument lacks (the latest entry is read instead), and `ghost`, which is not in the registry. + ("h".to_owned(), packument("h", &[("1.0.0", signed_dist(&signer, "sha256-known", "h", "1.0.0"))])), + ]); + let packages = [ + package("a", "2.0.0"), + package("b", "1.0.0"), + package("c", "1.0.0"), + package("d", "1.0.0"), + package("e", "1.0.0"), + package("f", "1.0.0"), + package("ghost", "1.0.0"), + package("h", "9.9.9"), + package("skipped", "1.0.0"), + ]; + let (result, requests) = run_scan(&packuments, Some(&keys), &packages, &["skipped"]); + let (findings, cache) = result.unwrap(); + + // `skipped` is never asked for; `ghost` is a 404 that leaves no cache entry. + assert_eq!(requests, 8); + assert_eq!(cache.len(), 7); + assert_eq!( + codes(&findings), + [ + ( + "a".to_owned(), + "provenance-regression", + "Resolved a@2.0.0 has no published provenance attestation, but a@1.0.0 did \u{2014} a provenance regression.".to_owned() + ), + ("b".to_owned(), "missing-signature", "Package b@1.0.0 has no dist.signatures from the registry.".to_owned()), + ( + "c".to_owned(), + "missing-signature", + "Package c@1.0.0 has signatures but no dist.integrity to verify against.".to_owned() + ), + ( + "d".to_owned(), + "unknown-keyid", + "Package d@1.0.0 was signed with an unrecognized keyid (sha256-nobody).".to_owned() + ), + ( + "e".to_owned(), + "expired-key", + "Package e@1.0.0 was signed with an expired key (sha256-old, expired 2024-01-01T00:00:00.000Z).".to_owned() + ), + ( + "f".to_owned(), + "invalid-signature", + "Package f@1.0.0 signature did not verify against sha256-known.".to_owned() + ), + // The entry of the latest version is read for a version the packument lacks, and the message it was + // signed over names the other version. + ( + "h".to_owned(), + "invalid-signature", + "Package h@9.9.9 signature did not verify against sha256-known.".to_owned() + ), + ] + ); + assert_eq!( + findings.iter().map(|finding| (finding.code, finding.severity)).collect::>(), + [ + ("provenance-regression", Severity::Warning), + ("missing-signature", Severity::Warning), + ("missing-signature", Severity::Warning), + ("unknown-keyid", Severity::Error), + ("expired-key", Severity::Warning), + ("invalid-signature", Severity::Error), + ("invalid-signature", Severity::Error), + ] + ); + } + + #[test] + fn without_keys_every_package_that_is_not_allowlisted_gets_a_warning_after_the_provenance_findings() { + let packuments = HashMap::from([("a".to_owned(), packument("a", &[("1.0.0", json!({}))]))]); + let (result, _) = run_scan( + &packuments, + None, + &[package("a", "1.0.0"), package("ghost", "1.0.0"), package("s", "1.0.0")], + &["s"], + ); + let (findings, _) = result.unwrap(); + + assert_eq!( + codes(&findings), + [ + ("a".to_owned(), "fetch-failed", "Could not fetch registry signing keys.".to_owned()), + ("ghost".to_owned(), "fetch-failed", "Could not fetch registry signing keys.".to_owned()), + ] + ); + } + + #[test] + fn a_packument_or_signature_this_binary_does_not_read_as_node_does_is_handed_over() { + let signer = Signer::new(); + let keys = [ + key(&signer, "k", None), + RegistryKey { keyid: "x".to_owned(), key: "!!".to_owned(), expires: Some("soon".to_owned()) }, + ]; + let bad = |body: Value, version: &str| { + let packuments = HashMap::from([("a".to_owned(), body)]); + + run_scan(&packuments, Some(&keys), &[package("a", version)], &[]).0.is_err() + }; + + // `dist.signatures` that is not a list, an element without a keyid, a key that is not a P-256 SPKI, a key expiry in + // another form, a version that is not strict semver. + assert!(bad(packument("a", &[("1.0.0", json!({ "integrity": "i", "signatures": "x" }))]), "1.0.0")); + assert!(bad( + packument("a", &[("1.0.0", json!({ "integrity": "i", "signatures": [{ "sig": "x" }] }))]), + "1.0.0" + )); + assert!(bad( + packument("a", &[("1.0.0", json!({ "integrity": "i", "signatures": [{ "keyid": "x", "sig": "AAAA" }] }))]), + "1.0.0" + )); + assert!(bad(packument("a", &[("1.0.0", json!({}))]), "1.0")); + } + + #[test] + fn a_failed_request_ends_the_scan() { + let signer = Signer::new(); + let registry = Registry::start(HashMap::from([("/a".to_owned(), (500, "{}".to_owned(), Vec::new()))])); + let (source, _) = packuments_for(®istry); + let (found, cache) = + scan(&source, Some(&[key(&signer, "k", None)]), &[package("a", "1.0.0")], &HashSet::new(), NOW); + + assert!(found.is_err() && cache.is_empty()); + } + + #[test] + fn a_failing_package_leaves_the_cache_of_the_others_to_node() { + let signer = Signer::new(); + let registry = Registry::start(HashMap::from([ + ("/a".to_owned(), ok(&packument("a", &[("1.0.0", signed_dist(&signer, "k", "a", "1.0.0"))]))), + ("/b".to_owned(), (500, "{}".to_owned(), Vec::new())), + ("/c".to_owned(), ok(&packument("c", &[("1.0.0", signed_dist(&signer, "k", "c", "1.0.0"))]))), + ])); + let (source, _) = packuments_for(®istry); + let packages = [package("a", "1.0.0"), package("b", "1.0.0"), package("c", "1.0.0")]; + let (found, cache) = scan(&source, Some(&[key(&signer, "k", None)]), &packages, &HashSet::new(), NOW); + + assert!(found.is_err()); + assert_eq!(cache.len(), 2); + } + + fn finding_of(code: &'static str, severity: Severity) -> Finding { + Finding { + code, + message: "m \u{2014} \"q\"".to_owned(), + package: "p".to_owned(), + severity, + version: "1.0.0".to_owned(), + } + } + + #[test] + fn the_json_report_is_what_json_stringify_writes() { + let flags = |format, fail_on_error| Flags { format, fail_on_error }; + let empty = report(flags("json", false), 3, &[]).unwrap(); + + assert_eq!((empty.stdout.as_str(), empty.status), ("{\n \"findings\": [],\n \"ok\": true\n}\n", 0)); + + let findings = + [finding_of("missing-signature", Severity::Warning), finding_of("invalid-signature", Severity::Error)]; + let full = report(flags("json", false), 3, &findings).unwrap(); + + assert_eq!(full.status, 1); + assert_eq!( + full.stdout, + concat!( + "{\n \"findings\": [\n {\n \"code\": \"missing-signature\",\n \"message\": \"m \u{2014} \\\"q\\\"\",\n", + " \"packageName\": \"p\",\n \"severity\": \"warning\",\n \"version\": \"1.0.0\"\n },\n", + " {\n \"code\": \"invalid-signature\",\n \"message\": \"m \u{2014} \\\"q\\\"\",\n", + " \"packageName\": \"p\",\n \"severity\": \"error\",\n \"version\": \"1.0.0\"\n }\n ],\n \"ok\": false\n}\n" + ) + ); + // The document is what a JSON reader gets from the objects. + assert_eq!(serde_json::from_str::(&full.stdout).unwrap()["findings"][1]["code"], "invalid-signature"); + + // Only error findings gate with `--fail-on error`. + assert_eq!(report(flags("json", true), 3, &findings[..1]).unwrap().status, 0); + assert!(report(flags("json", true), 3, &findings[..1]).unwrap().stdout.ends_with("\"ok\": true\n}\n")); + assert_eq!(report(flags("json", true), 3, &findings).unwrap().status, 1); + } + + #[test] + fn the_ndjson_report_has_a_line_per_finding_and_the_table_a_line_only_when_clean() { + let flags = |format| Flags { format, fail_on_error: false }; + let findings = [finding_of("missing-signature", Severity::Warning)]; + let lines = report(flags("ndjson"), 1, &findings).unwrap(); + + assert_eq!( + lines.stdout, + "{\"code\":\"missing-signature\",\"message\":\"m \u{2014} \\\"q\\\"\",\"packageName\":\"p\",\"severity\":\"warning\",\"version\":\"1.0.0\"}\n" + ); + assert_eq!(lines.status, 1); + assert_eq!(report(flags("ndjson"), 1, &[]).unwrap().stdout, ""); + + let clean = report(flags("table"), 12, &[]).unwrap(); + + assert_eq!(clean.stdout, "No provenance regressions or signature problems across 12 locked packages.\n"); + assert_eq!(clean.status, 0); + assert!(report(flags("table"), 1, &findings).is_err()); + } +} diff --git a/packages/tooling/vis/native/cli/src/dlx.rs b/packages/tooling/vis/native/cli/src/dlx.rs index 062e73bc..194d899b 100644 --- a/packages/tooling/vis/native/cli/src/dlx.rs +++ b/packages/tooling/vis/native/cli/src/dlx.rs @@ -2,14 +2,20 @@ //! //! The Node handler (`src/commands/dlx/handler.ts`, run by the lean entry `cli-exec.ts`: no config, no //! workspace root, no plugins) shows a first-run info panel for a registry package before it runs the -//! package manager's `dlx`. The gate skips itself in CI, without a terminal and with `--yes`, and for a -//! package it has seen; otherwise it fetches package metadata and may prompt. It decides that at run time -//! from the terminal, the CI variables and a state file in the home directory, none of which this module -//! reads. So it answers only the runs where the gate does nothing whatever those are, and hands everything -//! else to Node before any output: +//! package manager's `dlx`. The gate (`src/dlx/first-run.ts`) skips itself, with no network work, in CI, when +//! stdin or stdout is not a terminal and with `--yes` (or a truthy `VIS_DLX_YES`); on a terminal it fetches the +//! package's packument and shows the panel and a prompt for a version it has not seen. So this module answers +//! the runs where the gate does nothing and hands everything else to Node before any output: //! //! - the gate is off: `--no-info` or a truthy `VIS_DLX_NO_INFO`, or none of the packages it would vet is a //! registry spec (shell mode vets only the `-p` packages; paths, URLs and aliases are skipped); +//! - the gate skips itself: `--yes`, a truthy `VIS_DLX_YES`, CI, or a stream that is not a terminal; +//! - on a terminal, outside CI and without `--yes`, the gate resolves each vetted package against the registry +//! (the packument, through [`Packuments`], with Node's cache) and finds the version in `~/.vis/state/dlx-seen.json`: +//! an approved version with no Socket token makes the gate silent, so the run is native. A version it has not +//! seen (the panel and the prompt), a Socket token, `--offline` and every packument or spec this binary does +//! not read as Node does stay in Node. The panel itself is not ported: it renders a changelog fetched from +//! other services and colours of its own; //! - flags: `--no-info`, `-y`/`--yes`, `--offline`, `-s`/`--silent`, `-c`/`--shell-mode`, each at most once, and //! `-p`/`--package ` directly followed by another flag (the option takes every word up to the next //! flag, so a package or argument after it would be swallowed). The other words are the package and its @@ -22,19 +28,26 @@ use std::env; use std::ffi::OsString; -use std::path::Path; +use std::io::{stdin, stdout, IsTerminal}; +use std::path::{Path, PathBuf}; +use std::time::Duration; use vis_core::detect::{detect_package_manager, DetectPackageManagerOptions}; use vis_core::lockfiles::LOCKFILES; use vis_core::resolve::{resolve_dlx, DlxOptions, ResolvedCommand}; +use crate::inspect::{commit, parse_package, CacheAction, Packuments}; use crate::pm_run::{on_path, ManagerRun}; +/// `GATHER_BUDGET_MS`: the time the gate gives the registry before it proceeds without a panel. +const GATHER_BUDGET: Duration = Duration::from_secs(6); + /// What the command line asked for. #[derive(Debug, Default, PartialEq, Eq)] struct Flags { no_info: bool, offline: bool, + yes: bool, /// The `-p` packages, in order. packages: Vec, shell_mode: bool, @@ -51,21 +64,43 @@ pub fn run(args: &[String], raw: &[OsString]) -> ! { crate::process::delegate(raw); }; - plan.run_inherited(raw, |code| code) + // The registry is asked last, after every reason to delegate that needs no request, and its cache is written + // only once every package is known to be approved: a hand-off writes nothing. + if !plan.vetted.is_empty() { + match approved(&plan.vetted, &plan.run.cwd) { + Ok(cache) => { + if let Err(reason) = commit(&cache) { + crate::process::delegate_because(&reason, raw); + } + } + Err(reason) => crate::process::delegate_because(&reason, raw), + } + } + + plan.run.run_inherited(raw, |code| code) +} + +/// What the command line and the environment decided: the manager to run, and the packages the gate would vet on a +/// terminal that this run must find approved first. +struct Plan { + run: ManagerRun, + vetted: Vec, } /// The command to run and where, or `None` to delegate. -fn plan(args: &[String], raw: &[OsString]) -> Option { +fn plan(args: &[String], raw: &[OsString]) -> Option { // Windows keeps the Node path: it runs the package manager through a shell there. if !cfg!(unix) || raw.iter().any(|argument| argument.to_str().is_none()) { return None; } let flags = parse(args)?; - - if !gate_is_off(&flags)? { - return None; - } + let vetted = match gate(&flags, &|name| env::var_os(name), interactive())? { + Gate::Out => Vec::new(), + // `--offline` reads the packument cache only, which this module does not. + Gate::Panel if flags.offline || env::var_os("VIS_SOCKET_TOKEN").is_some() => return None, + Gate::Panel => vetted_packages(&flags), + }; // The Node runtime warns on stderr about conflicting colour variables, with its process id in the text, and // `DEBUG` and `CEREBRO_*` change cerebro's output (a debug trace on stdout) and the environment the manager gets. @@ -109,12 +144,9 @@ fn plan(args: &[String], raw: &[OsString]) -> Option { } // A manager that is not on `PATH` fails in Node with its own report. - on_path(&resolved.bin).then(|| ManagerRun { - bin: resolved.bin, - args: resolved.args, - cwd, - root: None, - notices: Vec::new(), + on_path(&resolved.bin).then(|| Plan { + run: ManagerRun { bin: resolved.bin, args: resolved.args, cwd, root: None, notices: Vec::new() }, + vetted, }) } @@ -153,20 +185,97 @@ fn apply_offline(resolved: &mut ResolvedCommand, manager: &str) { } } -/// Whether Node's first-run gate does nothing for these flags: it is switched off, or no package it would -/// vet is a registry spec. `None` when the environment variable is not plain ASCII. -fn gate_is_off(flags: &Flags) -> Option { - let no_info = flags.no_info - || match env::var_os("VIS_DLX_NO_INFO") { - None => false, - // JavaScript's `trim` and Rust's differ on some Unicode space, so only ASCII is decided here. - Some(value) => is_truthy(value.to_str().filter(|text| text.is_ascii())?), - }; +/// What Node's first-run gate does for a run. +#[derive(Debug, PartialEq, Eq)] +enum Gate { + /// Nothing: it is switched off, no package is a registry spec, or it skips itself (`--yes`, CI, no terminal). + Out, + /// It resolves the packages and shows a panel for a version it has not seen. + Panel, +} - // Shell mode vets the `-p` packages only; otherwise the positional comes first. - let mut targets = flags.words.first().filter(|_| !flags.shell_mode).into_iter().chain(&flags.packages); +/// `isInteractive`: stdin and stdout are terminals and the run is not in CI. +fn interactive() -> bool { + stdin().is_terminal() && stdout().is_terminal() && !crate::node_context::in_ci() +} - Some(no_info || !targets.any(|target| is_registry_spec(target))) +/// The gate for these flags, `lookup` as the environment and `interactive` as the terminal. `None` when an +/// environment variable is not plain ASCII, where JavaScript's `trim` and Rust's differ. +fn gate(flags: &Flags, lookup: &dyn Fn(&str) -> Option, interactive: bool) -> Option { + let truthy = |name: &str| -> Option { + match lookup(name) { + None => Some(false), + Some(value) => Some(is_truthy(value.to_str().filter(|text| text.is_ascii())?)), + } + }; + let no_info = flags.no_info || truthy("VIS_DLX_NO_INFO")?; + let yes = flags.yes || truthy("VIS_DLX_YES")?; + + Some(if no_info || yes || !interactive || vetted_packages(flags).is_empty() { Gate::Out } else { Gate::Panel }) +} + +/// The packages the gate would vet: shell mode vets the `-p` packages only, otherwise the positional comes first; +/// of those, the registry specs. +fn vetted_packages(flags: &Flags) -> Vec { + flags + .words + .first() + .filter(|_| !flags.shell_mode) + .into_iter() + .chain(&flags.packages) + .filter(|target| is_registry_spec(target)) + .cloned() + .collect() +} + +/// The cache changes of resolving every package of a gate that would show its panel, or the reason the run is +/// Node's: a package that is not approved (a version it has not seen is a panel and a prompt), or any answer +/// from the registry this module does not read the way the gate does. +fn approved(targets: &[String], cwd: &Path) -> Result, String> { + let home = env::var("HOME").map_err(|_| "HOME is not text".to_owned())?; + + approved_in(targets, &Packuments::new(cwd.to_path_buf(), GATHER_BUDGET)?, &state_file(&home)) +} + +/// [`approved`] with the packuments and the state file given. +fn approved_in(targets: &[String], registry: &Packuments, state: &Path) -> Result, String> { + let mut cache = Vec::new(); + + for target in targets { + let (name, spec) = parse_package(target).ok_or_else(|| format!("{target:?} is not a plain package spec"))?; + let (version, changes) = registry + .resolve_version(&name, spec.as_deref())? + .ok_or_else(|| format!("the registry names no version for {target:?}"))?; + + if !is_approved(state, &name, &version) { + return Err(format!("{name}@{version} has not been approved: the gate shows its panel")); + } + + cache.extend(changes); + } + + Ok(cache) +} + +fn state_file(home: &str) -> PathBuf { + Path::new(home).join(".vis").join("state").join("dlx-seen.json") +} + +/// `getSeenEntry` and `shouldReprompt` with no Socket alerts: whether `name@version` has an approval on file. The +/// file counts only in the shape `readDlxSeen` accepts (`version` 1, `packages` an object, the entry with a list of +/// text `alertKeys` and a numeric `seenAt`); anything else is an empty store, so a panel. +fn is_approved(file: &Path, name: &str, version: &str) -> bool { + let Ok(text) = std::fs::read_to_string(file) else { return false }; + let Ok(state) = serde_json::from_str::(&text) else { return false }; + + state.get("version").and_then(serde_json::Value::as_u64) == Some(1) + && state.get("packages").and_then(|packages| packages.get(format!("{name}@{version}"))).is_some_and(|entry| { + entry + .get("alertKeys") + .and_then(serde_json::Value::as_array) + .is_some_and(|keys| keys.iter().all(serde_json::Value::is_string)) + && entry.get("seenAt").is_some_and(serde_json::Value::is_number) + }) } /// `isTruthyEnv`: on unless empty, `0`, `false` or `no`, ignoring case and surrounding space. @@ -200,8 +309,10 @@ fn parse(args: &[String]) -> Option { flags.no_info = true; "no-info" } - // Accepted and ignored: with the gate out there is nothing to approve. - "-y" | "--yes" => "yes", + "-y" | "--yes" => { + flags.yes = true; + "yes" + } "--offline" => { flags.offline = true; "offline" @@ -259,7 +370,12 @@ fn is_known_flag(token: &str) -> bool { #[cfg(test)] mod tests { - use super::{apply_offline, is_registry_spec, is_truthy, nearest_lockfile_is_bun, parse, Flags}; + use std::ffi::OsString; + + use super::{ + apply_offline, gate, is_approved, is_registry_spec, is_truthy, nearest_lockfile_is_bun, parse, vetted_packages, + Flags, Gate, + }; use vis_core::resolve::ResolvedCommand; fn lockfiles_at(label: &str, files: &[(&str, &str)]) -> std::path::PathBuf { @@ -370,4 +486,136 @@ mod tests { assert_eq!(bun.args, ["dlx", "cowsay"]); assert_eq!(bun.warnings.len(), 1); } + + fn environment(pairs: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + let pairs = pairs.to_vec(); + + move |name| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| OsString::from(*value)) + } + + #[test] + fn the_gate_does_nothing_unless_a_terminal_is_asked_to_approve() { + let flags = |words: &[&str]| parse(&tokens(words)).unwrap(); + let none = environment(&[]); + + // Not a terminal, or CI (which `interactive` folds in): the gate skips itself. + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &none, false), Some(Gate::Out)); + // A terminal: the panel, for a registry spec. + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &none, true), Some(Gate::Panel)); + assert_eq!(gate(&flags(&["dlx", "cowsay@1.5.0", "hi"]), &none, true), Some(Gate::Panel)); + assert_eq!(gate(&flags(&["dlx", "-p", "a", "-s", "cowsay"]), &none, true), Some(Gate::Panel)); + // Switched off, or approved in advance. + assert_eq!(gate(&flags(&["dlx", "--no-info", "cowsay"]), &none, true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "--yes", "cowsay"]), &none, true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "cowsay", "-y"]), &none, true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &environment(&[("VIS_DLX_YES", "1")]), true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &environment(&[("VIS_DLX_YES", "no")]), true), Some(Gate::Panel)); + assert_eq!( + gate(&flags(&["dlx", "cowsay"]), &environment(&[("VIS_DLX_NO_INFO", "yes")]), true), + Some(Gate::Out) + ); + // Nothing to vet: a path, or shell mode with no `-p` package. + assert_eq!(gate(&flags(&["dlx", "./local.js"]), &none, true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "-c", "echo hi"]), &none, true), Some(Gate::Out)); + assert_eq!(gate(&flags(&["dlx", "-p", "a", "-c", "echo hi"]), &none, true), Some(Gate::Panel)); + // A value Rust and JavaScript could trim differently. + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &environment(&[("VIS_DLX_YES", "\u{a0}1")]), false), None); + assert_eq!(gate(&flags(&["dlx", "cowsay"]), &environment(&[("VIS_DLX_NO_INFO", "\u{2003}")]), true), None); + } + + #[test] + fn the_vetted_packages_are_the_registry_specs_the_gate_looks_at() { + let vetted = |words: &[&str]| vetted_packages(&parse(&tokens(words)).unwrap()); + + assert_eq!(vetted(&["dlx", "cowsay", "hi"]), ["cowsay"]); + assert_eq!(vetted(&["dlx", "cowsay", "-p", "a", "-p", "./b", "-s"]), ["cowsay", "a"]); + assert_eq!(vetted(&["dlx", "-p", "a", "-c", "echo hi"]), ["a"]); + assert!(vetted(&["dlx", "https://x.test/a.tgz"]).is_empty()); + } + + #[test] + fn a_version_is_approved_only_by_an_entry_in_the_shape_the_gate_reads() { + let directory = std::env::temp_dir().join(format!("vis-dlx-seen-{}", std::process::id())); + + std::fs::create_dir_all(&directory).unwrap(); + + let file = directory.join("dlx-seen.json"); + let with = |text: &str| { + std::fs::write(&file, text).unwrap(); + + is_approved(&file, "cowsay", "1.6.0") + }; + let entry = r#"{"alertKeys":["k"],"seenAt":1}"#; + + assert!(!is_approved(&directory.join("missing.json"), "cowsay", "1.6.0")); + assert!(with(&format!(r#"{{"packages":{{"cowsay@1.6.0":{entry}}},"version":1}}"#))); + assert!(with(r#"{"packages":{"cowsay@1.6.0":{"alertKeys":[],"seenAt":1700000000000}},"version":1}"#)); + assert!(!with(&format!(r#"{{"packages":{{"cowsay@1.5.0":{entry}}},"version":1}}"#))); + assert!(!with(&format!(r#"{{"packages":{{"cowsay@1.6.0":{entry}}},"version":2}}"#))); + assert!(!with(&format!(r#"{{"packages":{{"cowsay@1.6.0":{entry}}}}}"#))); + assert!(!with(r#"{"packages":{"cowsay@1.6.0":{"alertKeys":[1],"seenAt":1}},"version":1}"#)); + assert!(!with(r#"{"packages":{"cowsay@1.6.0":{"alertKeys":[]}},"version":1}"#)); + assert!(!with(r#"{"packages":{"cowsay@1.6.0":{"alertKeys":"k","seenAt":1}},"version":1}"#)); + assert!(!with(r#"{"packages":[],"version":1}"#)); + assert!(!with("not json")); + + std::fs::remove_dir_all(&directory).unwrap(); + } + + #[test] + fn a_terminal_run_is_native_only_for_an_approved_version_of_every_package() { + use std::collections::HashMap; + + use serde_json::json; + + use crate::inspect::tests::{ok, packuments_for, Registry}; + + let packument = |name: &str| { + ok(&json!({ + "name": name, + "dist-tags": { "latest": "2.0.0", "next": "3.0.0-beta.1" }, + "versions": { "1.0.0": {}, "2.0.0": {}, "3.0.0-beta.1": {} }, + })) + }; + let registry = Registry::start(HashMap::from([ + ("/cowsay".to_owned(), packument("cowsay")), + ("/lolcatjs".to_owned(), packument("lolcatjs")), + ])); + let (packuments, home) = packuments_for(®istry); + let state = super::state_file(&home.to_string_lossy()); + let targets = |list: &[&str]| list.iter().map(|item| (*item).to_owned()).collect::>(); + let seen = |entries: &[&str]| { + let packages: Vec = + entries.iter().map(|entry| format!(r#""{entry}":{{"alertKeys":[],"seenAt":1}}"#)).collect(); + + std::fs::create_dir_all(state.parent().unwrap()).unwrap(); + std::fs::write(&state, format!(r#"{{"packages":{{{}}},"version":1}}"#, packages.join(","))).unwrap(); + }; + + // No state file: the panel. + assert!(super::approved_in(&targets(&["cowsay"]), &packuments, &state) + .unwrap_err() + .contains("not been approved")); + + // `latest` is 2.0.0, a tag is its version, an exact version is itself. + seen(&["cowsay@2.0.0", "lolcatjs@2.0.0", "cowsay@3.0.0-beta.1", "cowsay@1.0.0"]); + + for list in [&["cowsay"][..], &["cowsay@latest"], &["cowsay@next"], &["cowsay@1.0.0"], &["cowsay", "lolcatjs"]] + { + let cache = super::approved_in(&targets(list), &packuments, &state).unwrap(); + + assert_eq!(cache.len(), list.len(), "{list:?}"); + } + + // One package without an approval is enough for the panel. + seen(&["cowsay@2.0.0"]); + assert!(super::approved_in(&targets(&["cowsay", "lolcatjs"]), &packuments, &state).is_err()); + assert!(super::approved_in(&targets(&["cowsay@1.0.0"]), &packuments, &state).is_err()); + + // A range needs node-semver, a package the registry does not know has no version to approve, and a name + // outside the plain shape is not asked for. + for odd in ["cowsay@^1", "ghost", "Cow.Say", "cowsay@x y"] { + assert!(super::approved_in(&targets(&[odd]), &packuments, &state).is_err(), "{odd}"); + } + } } diff --git a/packages/tooling/vis/native/cli/src/inspect/args.rs b/packages/tooling/vis/native/cli/src/inspect/args.rs index 6727f163..22674846 100644 --- a/packages/tooling/vis/native/cli/src/inspect/args.rs +++ b/packages/tooling/vis/native/cli/src/inspect/args.rs @@ -91,7 +91,7 @@ fn is_name(name: &str) -> bool { /// `parsePackageArg` for a name and spec in the plain shapes: the name splits at the `@` after its first character, /// and an empty spec is no spec. -fn parse_package(raw: &str) -> Option<(String, Option)> { +pub(crate) fn parse_package(raw: &str) -> Option<(String, Option)> { let separator = raw.get(1..)?.find('@').map(|at| at + 1); let (name, spec) = match separator { Some(at) => (&raw[..at], Some(&raw[at + 1..]).filter(|spec| !spec.is_empty())), diff --git a/packages/tooling/vis/native/cli/src/inspect/js_format.rs b/packages/tooling/vis/native/cli/src/inspect/js_format.rs index 3a58b066..594e7eff 100644 --- a/packages/tooling/vis/native/cli/src/inspect/js_format.rs +++ b/packages/tooling/vis/native/cli/src/inspect/js_format.rs @@ -3,7 +3,7 @@ /// `Date.parse` of `YYYY-MM-DDTHH:MM:SS.sssZ` in milliseconds since the epoch. Any other text, and a field out of range, /// is `None`: `Date` reads many other forms (and the legacy parser reads more still), which this does not reproduce. -pub(super) fn parse_date(text: &str) -> Option { +pub(crate) fn parse_date(text: &str) -> Option { let bytes = text.as_bytes(); if bytes.len() != 24 diff --git a/packages/tooling/vis/native/cli/src/inspect/js_value.rs b/packages/tooling/vis/native/cli/src/inspect/js_value.rs index 06cd4c40..f4be6921 100644 --- a/packages/tooling/vis/native/cli/src/inspect/js_value.rs +++ b/packages/tooling/vis/native/cli/src/inspect/js_value.rs @@ -5,14 +5,14 @@ use crate::keys_refresh::{array_index, Js}; impl Js { /// The own member `key` of an object; `None` for another kind of value and for a missing member. - pub(super) fn member(&self, key: &str) -> Option<&Self> { + pub(crate) fn member(&self, key: &str) -> Option<&Self> { match self { Self::Object(entries) => entries.iter().find(|(name, _)| name == key).map(|(_, value)| value), _ => None, } } - pub(super) fn text(&self) -> Option<&str> { + pub(crate) fn text(&self) -> Option<&str> { match self { Self::String(text) => Some(text), _ => None, diff --git a/packages/tooling/vis/native/cli/src/inspect/marshalls.rs b/packages/tooling/vis/native/cli/src/inspect/marshalls.rs index 5f0aaff0..52e8f57c 100644 --- a/packages/tooling/vis/native/cli/src/inspect/marshalls.rs +++ b/packages/tooling/vis/native/cli/src/inspect/marshalls.rs @@ -185,7 +185,7 @@ pub(super) fn author(view: &View, target: &Target, now_ms: f64) -> Result) -> Result { +pub(crate) fn has_provenance(entry: Option<&Js>) -> Result { let Some(entry) = entry else { return Ok(false) }; match entry.member("dist") { @@ -216,17 +216,21 @@ fn newest_before<'a>( Ok(candidates.first().map(|(name, _)| *name)) } +/// `findNewestPriorWithAttestations` for a version that has no provenance itself: the newest earlier release (no +/// prerelease) that has some. +pub(crate) fn prior_with_provenance<'a>(view: &View<'a>, version: &str) -> Result, String> { + let parsed = Version::parse(version).ok_or_else(|| format!("the version {version} is not strict semver"))?; + + newest_before(view, &parsed, &|name, other| Ok(!other.is_prerelease() && has_provenance(view.entry(name))?)) +} + /// The provenance marshall: the version has none, and an earlier release had. pub(super) fn provenance(view: &View, target: &Target) -> Result, String> { if has_provenance(view.entry(target.version))? { return Ok(Vec::new()); } - let version = parsed(target)?; - let prior = - newest_before(view, &version, &|name, other| Ok(!other.is_prerelease() && has_provenance(view.entry(name))?))?; - - Ok(prior + Ok(prior_with_provenance(view, target.version)? .map(|prior| { target.finding( "provenance", diff --git a/packages/tooling/vis/native/cli/src/inspect/mod.rs b/packages/tooling/vis/native/cli/src/inspect/mod.rs index c21b1c3a..7611dbf9 100644 --- a/packages/tooling/vis/native/cli/src/inspect/mod.rs +++ b/packages/tooling/vis/native/cli/src/inspect/mod.rs @@ -37,11 +37,15 @@ use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; use std::process::exit; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +pub(crate) use args::parse_package; use args::{Flags, Marshall}; +pub(crate) use js_format::parse_date; +pub(crate) use marshalls::{has_provenance, prior_with_provenance}; use marshalls::{Finding, Target}; -use packument::{Answer, Cached, View}; +pub(crate) use packument::View; +use packument::{Answer, Cached}; use crate::cache::dirs::vis_cache_dir; use crate::http::node_fetch::{fetch_config, network_environment_is_plain, url_is_plain}; @@ -53,7 +57,7 @@ use crate::pail::{Layout, Level}; /// A change to the cache a run makes once it is sure to answer. #[derive(Debug, PartialEq, Eq)] -enum CacheAction { +pub(crate) enum CacheAction { Write { file: PathBuf, text: String }, Remove(PathBuf), } @@ -144,20 +148,86 @@ fn answer(args: &[String]) -> Result { Ok(plan) } +/// The packuments as `getPackument` reaches them from a working directory, for the commands outside `inspect` that read +/// a packument: the places, the clock and the client, built once. +pub(crate) struct Packuments { + context: Context, + client: HttpClient, +} + +impl Packuments { + /// The registry for a run from `root`, with `limit` as the time one request may take (a command picks the limit + /// the Node code it replaces gives its own request), or the reason the run is Node's: a proxy, CA or Node option + /// in the environment, or no usable `HOME`. + pub(crate) fn new(root: PathBuf, limit: Duration) -> Result { + if !network_environment_is_plain() { + return Err("a proxy, CA or Node option is set in the environment".to_owned()); + } + + let cache_dir = vis_cache_dir().ok_or("no cache directory (HOME is not a plain absolute path)")?; + let home = std::env::var("HOME").map_err(|_| "HOME is not text".to_owned())?; + + Ok(Self::at( + root, + PathBuf::from(home), + cache_dir, + now_ms()?, + HttpClient::new(fetch_config(HttpConfig::from_env(limit, limit), limit)), + )) + } + + /// The packuments of a run from `root`, with the places, the clock and the client given. + pub(crate) fn at(root: PathBuf, home: PathBuf, cache_dir: String, now_ms: u64, client: HttpClient) -> Self { + Self { context: Context { root, home, cache_dir, now_ms, layout: None }, client } + } + + /// What `getPackument` finds for a package, read through `read` with the view of it (`None` for a package the + /// registry does not know), and the cache change that goes with the lookup. The reason for a hand-off for a + /// request that fails and for a packument this module does not read as Node does. + pub(crate) fn read( + &self, + name: &str, + read: impl FnOnce(Option<&View<'_>>) -> Result, + ) -> Result<(T, Vec), String> { + let (found, cache) = packument_of(name, &self.context, &self.client)?; + + match found { + None => Ok((read(None)?, cache)), + Some(found) => Ok((read(Some(&View::new(&found)?))?, cache)), + } + } + + /// `resolveVersionRange` for a package: its version and the cache change that goes with the lookup. `None` for a + /// package the registry does not know, or a spec that names no version; the reason for a spec that is a range + /// (it needs node-semver), a packument this module does not read as Node does, and every failed request. + pub(crate) fn resolve_version( + &self, + name: &str, + spec: Option<&str>, + ) -> Result)>, String> { + let (found, cache) = packument_of(name, &self.context, &self.client)?; + let Some(found) = found else { return Ok(None) }; + let view = View::new(&found)?; + let Some(version) = resolve(&view, spec)? else { return Ok(None) }; + + if args::is_prototype_name(version) || semver_js::Version::parse(version).is_none() { + return Err(format!("the resolved version {version:?} is not strict semver")); + } + + Ok(Some((version.to_owned(), cache))) + } +} + /// What `getPackument` returns for the package: the cut-down document, and the cache change that goes with it. -fn packument_of( - flags: &Flags, - context: &Context, - client: &HttpClient, -) -> Result<(Option, Vec), String> { - let file = packument::cache_file(&context.cache_dir, &flags.name); +fn packument_of(name: &str, context: &Context, client: &HttpClient) -> Result<(Option, Vec), String> { + let file = packument::cache_file(&context.cache_dir, name); let stale_file = match packument::read_cache(&file, context.now_ms as f64)? { Cached::Fresh(found) => return Ok((Some(found), Vec::new())), Cached::Fetch { stale_file } => stale_file, }; - let registry = npmrc::registry_for(&flags.name, &context.home, &context.root)?; + let registry = npmrc::registry_for(name, &context.home, &context.root)?; let base = registry.strip_suffix('/').unwrap_or(®istry); - let url = format!("{base}/{}", flags.name.replacen('/', "%2f", 1)); + let url = format!("{base}/{}", name.replacen('/', "%2f", 1)); if !url_is_plain(&url) { return Err(format!("the registry URL {url:?} is not a URL `fetch` and the client read alike")); @@ -200,7 +270,7 @@ fn resolve<'a>(view: &View<'a>, spec: Option<&str>) -> Result, S /// The whole run, up to what it prints: pure but for the cache read, the registry request and the clock in `context`. fn plan(flags: &Flags, run: &[Marshall], context: &Context, client: &HttpClient) -> Result { - let (found, cache) = packument_of(flags, context, client)?; + let (found, cache) = packument_of(&flags.name, context, client)?; let missing = |message: String| -> Result { let layout = context .layout @@ -256,7 +326,7 @@ fn plan(flags: &Flags, run: &[Marshall], context: &Context, client: &HttpClient) } /// Makes the cache changes of a plan. A change that fails is Node's to report. -fn commit(actions: &[CacheAction]) -> Result<(), String> { +pub(crate) fn commit(actions: &[CacheAction]) -> Result<(), String> { for action in actions { match action { CacheAction::Write { file, text } => { @@ -282,4 +352,4 @@ fn remove(file: &Path) -> Result<(), String> { } #[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/packages/tooling/vis/native/cli/src/inspect/packument.rs b/packages/tooling/vis/native/cli/src/inspect/packument.rs index aa1d56c8..3e5844b0 100644 --- a/packages/tooling/vis/native/cli/src/inspect/packument.rs +++ b/packages/tooling/vis/native/cli/src/inspect/packument.rs @@ -221,18 +221,18 @@ fn strip(raw: Js) -> Result { } /// A cut-down packument as the marshalls read it: its versions in JavaScript's order and by name, its tags and times. -pub(super) struct View<'a> { +pub(crate) struct View<'a> { versions: Vec<(&'a str, &'a Js)>, by_name: HashMap<&'a str, &'a Js>, dist_tags: Option<&'a Js>, time: HashMap<&'a str, &'a Js>, - pub readme: Option<&'a str>, + pub(crate) readme: Option<&'a str>, parsed: OnceCell, String>>, } impl<'a> View<'a> { /// The view of a cut-down packument, or the reason it is Node's. - pub(super) fn new(packument: &'a Js) -> Result { + pub(crate) fn new(packument: &'a Js) -> Result { let Js::Object(_) = packument else { return Err("the packument is not an object".to_owned()) }; let versions_value = packument.member("versions").ok_or("the packument has no versions member")?; @@ -269,25 +269,25 @@ impl<'a> View<'a> { }) } - pub(super) fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { self.versions.is_empty() } /// `Object.keys(versions).at(-1)`. - pub(super) fn last_version(&self) -> Option<&'a str> { + pub(crate) fn last_version(&self) -> Option<&'a str> { self.versions.last().map(|(name, _)| *name) } - pub(super) fn entry(&self, version: &str) -> Option<&'a Js> { + pub(crate) fn entry(&self, version: &str) -> Option<&'a Js> { self.by_name.get(version).copied() } - pub(super) fn versions(&self) -> &[(&'a str, &'a Js)] { + pub(crate) fn versions(&self) -> &[(&'a str, &'a Js)] { &self.versions } /// `dist-tags[tag]`: `Ok(None)` when it is missing, and the reason for a hand-off when it is not text. - pub(super) fn tag(&self, tag: &str) -> Result, String> { + pub(crate) fn tag(&self, tag: &str) -> Result, String> { match self.dist_tags.and_then(|tags| tags.member(tag)) { None => Ok(None), Some(Js::String(version)) => Ok(Some(version)), @@ -296,7 +296,7 @@ impl<'a> View<'a> { } /// `time[version]`: `Ok(None)` when it is missing, and the reason for a hand-off when it is not text. - pub(super) fn time(&self, version: &str) -> Result, String> { + pub(crate) fn time(&self, version: &str) -> Result, String> { match self.time.get(version) { None => Ok(None), Some(Js::String(stamp)) => Ok(Some(stamp)), diff --git a/packages/tooling/vis/native/cli/src/inspect/tests.rs b/packages/tooling/vis/native/cli/src/inspect/tests.rs index 4c921df7..9c87dc72 100644 --- a/packages/tooling/vis/native/cli/src/inspect/tests.rs +++ b/packages/tooling/vis/native/cli/src/inspect/tests.rs @@ -46,16 +46,16 @@ fn ago(days: f64) -> String { iso(NOW - (days * DAY as f64) as u64) } -type Answers = HashMap)>; +pub(crate) type Answers = HashMap)>; -struct Registry { +pub(crate) struct Registry { port: u16, - requests: Arc, + pub(crate) requests: Arc, paths: Arc>>, } impl Registry { - fn start(answers: Answers) -> Self { + pub(crate) fn start(answers: Answers) -> Self { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let (requests, paths) = (Arc::new(AtomicUsize::new(0)), Arc::new(Mutex::new(Vec::new()))); @@ -72,7 +72,7 @@ impl Registry { Self { port, requests, paths } } - fn url(&self) -> String { + pub(crate) fn url(&self) -> String { format!("http://127.0.0.1:{}", self.port) } } @@ -101,11 +101,11 @@ fn serve(mut stream: TcpStream, answers: &Answers, count: &AtomicUsize, seen: &M drop(stream.write_all(reply.as_bytes())); } -fn ok(body: &Value) -> (u16, String, Vec<(String, String)>) { +pub(crate) fn ok(body: &Value) -> (u16, String, Vec<(String, String)>) { (200, body.to_string(), Vec::new()) } -struct Setup { +pub(crate) struct Setup { context: Context, home: PathBuf, } @@ -141,6 +141,13 @@ fn setup(registry: Option<&Registry>) -> Setup { } } +/// The packuments of a run against `registry`, with the home directory they cache under. +pub(crate) fn packuments_for(registry: &Registry) -> (Packuments, PathBuf) { + let Setup { context, home } = setup(Some(registry)); + + (Packuments::at(context.root, home.clone(), context.cache_dir, NOW, client()), home) +} + fn client() -> HttpClient { HttpClient::new(fetch_config(HttpConfig::default(), FETCH_TIMEOUT)) } diff --git a/packages/tooling/vis/native/cli/src/keys_refresh.rs b/packages/tooling/vis/native/cli/src/keys_refresh.rs index a638a246..0afd0a45 100644 --- a/packages/tooling/vis/native/cli/src/keys_refresh.rs +++ b/packages/tooling/vis/native/cli/src/keys_refresh.rs @@ -408,12 +408,132 @@ fn fetched_keys(text: &str) -> Option { Some(Fetched { count: items.len(), raw: compact }) } +/// One signing key of the registry's list, with the members the signature check reads. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RegistryKey { + pub(crate) keyid: String, + /// Base64 of the SPKI public key. + pub(crate) key: String, + pub(crate) expires: Option, +} + +/// The keys of a list, or the reason this module does not read it as `verifySignatures` does: a list that is not an +/// array, an entry that is not an object with a text `keyid` and `key`, or an `expires` that is not text. +fn registry_keys_of(list: &Value) -> Result, String> { + let entries = list.as_array().ok_or("the key list is not an array")?; + let text = |entry: &Value, name: &str| entry.get(name).and_then(Value::as_str).map(str::to_owned); + + entries + .iter() + .map(|entry| { + let expires = match entry.get("expires") { + // `Date.parse(null)` is `NaN`, which is no expiry. + None | Some(Value::Null) => None, + Some(Value::String(text)) => Some(text.clone()), + Some(_) => return Err("a key whose `expires` is not text".to_owned()), + }; + + Ok(RegistryKey { + keyid: text(entry, "keyid").ok_or("a key without a text `keyid`")?, + key: text(entry, "key").ok_or("a key without a text `key`")?, + expires, + }) + }) + .collect() +} + +/// What `fetchRegistryKeys` reads from disk: the keys, and whether the entry is past its time to live. +struct CachedKeys { + keys: Vec, + expired: bool, +} + +fn read_keys(file: &Path, now_ms: u64) -> Result, String> { + let Some(_) = read_cache(file)? else { return Ok(None) }; + let text = fs::read_to_string(file).map_err(|error| format!("the cache file cannot be read: {error}"))?; + let entry: Value = serde_json::from_str(&text).map_err(|_| "the cache file is not JSON".to_owned())?; + let number = + |name: &str| entry.get(name).and_then(Value::as_f64).ok_or(format!("the cache file has no numeric {name}")); + let expired = now_ms as f64 - number("createdAt")? > number("ttlMs")?; + + Ok(Some(CachedKeys { keys: registry_keys_of(entry.get("keys").ok_or("the cache file has no keys")?)?, expired })) +} + +/// A key set `fetchRegistryKeys` returns, and the cache entry to write for a fetched one. +pub(crate) struct KeyLookup { + /// `None` when the network and the cache both failed. + pub(crate) keys: Option>, + pending: Option<(PathBuf, String)>, +} + +impl KeyLookup { + /// Writes the cache entry of a fetched list; the reason for a hand-off when it cannot be written (Node then + /// falls back to the old keys, which this lookup no longer knows). + pub(crate) fn commit(&self) -> Result<(), String> { + match &self.pending { + Some((file, entry)) if !write_entry(file, entry) => Err("the registry keys cannot be cached".to_owned()), + _ => Ok(()), + } + } +} + +/// `fetchRegistryKeys` for the default keys URL (`VIS_NPM_KEYS_URL` is Node's to read): the cache when it is fresh, +/// else the registry, else the old cache. Nothing is written until [`KeyLookup::commit`]. +pub(crate) fn registry_keys(now_ms: u64) -> Result { + if env::var_os("VIS_NPM_KEYS_URL").is_some() { + return Err("VIS_NPM_KEYS_URL is set".to_owned()); + } + + let file = PathBuf::from(vis_cache_dir().ok_or("no cache directory (HOME is not a plain absolute path)")?) + .join("registry-keys") + .join("npmjs.json"); + let client = + HttpClient::new(node_fetch::fetch_config(HttpConfig::from_env(FETCH_TIMEOUT, FETCH_TIMEOUT), FETCH_TIMEOUT)); + + registry_keys_at(&file, DEFAULT_KEYS_URL, now_ms, &client) +} + +fn registry_keys_at(file: &Path, url: &str, now_ms: u64, client: &HttpClient) -> Result { + let cached = read_keys(file, now_ms)?; + + if let Some(CachedKeys { keys, expired: false }) = cached { + return Ok(KeyLookup { keys: Some(keys), pending: None }); + } + + if !node_fetch::url_is_plain(url) { + return Err(format!("the keys URL {url:?} is not a URL `fetch` and the client read alike")); + } + + let stale = cached.map(|cached| cached.keys); + + match client.get(url, &[("accept", "application/json")]) { + Ok(response) => { + let text = response.text().map_err(|error| format!("the answer is not UTF-8 text: {error}"))?; + let fetched = fetched_keys(text).ok_or("a 2xx answer that is not a JSON object Node reads the same way")?; + let list: Value = serde_json::from_str(&fetched.raw).map_err(|_| "the keys do not parse".to_owned())?; + let entry = entry_text(now_ms, &fetched); + + Ok(KeyLookup { keys: Some(registry_keys_of(&list)?), pending: Some((file.to_owned(), entry)) }) + } + Err(error @ (HttpError::TooLarge { .. } | HttpError::Redirect(_))) => Err(error.to_string()), + Err(_) => Ok(KeyLookup { keys: stale, pending: None }), + } +} + +/// `JSON.stringify({createdAt, keys, ttlMs})` for a fetched list. +fn entry_text(now_ms: u64, keys: &Fetched) -> String { + format!("{{\"createdAt\":{now_ms},\"keys\":{},\"ttlMs\":{TTL_MS}}}", keys.raw) +} + +fn write_entry(file: &Path, entry: &str) -> bool { + file.parent().is_some_and(|directory| fs::create_dir_all(directory).is_ok()) && fs::write(file, entry).is_ok() +} + /// `writeCachedKeys`: `JSON.stringify({createdAt, keys, ttlMs})`. fn store(file: &Path, keys: &Fetched) -> bool { let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else { return false }; - let entry = format!("{{\"createdAt\":{},\"keys\":{},\"ttlMs\":{TTL_MS}}}", now.as_millis(), keys.raw); - file.parent().is_some_and(|directory| fs::create_dir_all(directory).is_ok()) && fs::write(file, entry).is_ok() + write_entry(file, &entry_text(u64::try_from(now.as_millis()).unwrap_or(u64::MAX), keys)) } #[cfg(test)] @@ -540,4 +660,91 @@ mod tests { fs::remove_dir_all(&directory).unwrap(); } + + fn key_directory(label: &str) -> PathBuf { + let directory = std::env::temp_dir().join(format!("vis-keys-lookup-{label}-{}", std::process::id())); + + let _ = fs::remove_dir_all(&directory); + fs::create_dir_all(&directory).unwrap(); + + directory + } + + fn key(id: &str) -> RegistryKey { + RegistryKey { keyid: id.to_owned(), key: format!("key-{id}"), expires: None } + } + + #[test] + fn the_keys_come_from_a_fresh_cache_else_the_registry_else_the_old_cache() { + use std::collections::HashMap; + use std::sync::atomic::Ordering; + + use crate::inspect::tests::Registry; + + let directory = key_directory("lookup"); + let file = directory.join("registry-keys").join("npmjs.json"); + let body = r#"{"keys":[{"keyid":"new","key":"key-new","expires":null}]}"#; + let registry = Registry::start(HashMap::from([("/keys".to_owned(), (200, body.to_owned(), Vec::new()))])); + let url = format!("{}/keys", registry.url()); + let client = HttpClient::new(node_fetch::fetch_config(HttpConfig::default(), FETCH_TIMEOUT)); + let write = |text: &str| { + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(&file, text).unwrap(); + }; + + // A fresh entry answers without a request. + write( + r#"{"createdAt":1000,"keys":[{"keyid":"old","key":"key-old","expires":"2030-01-01T00:00:00.000Z"}],"ttlMs":500}"#, + ); + + let fresh = registry_keys_at(&file, &url, 1500, &client).unwrap(); + + assert_eq!( + fresh.keys, + Some(vec![RegistryKey { expires: Some("2030-01-01T00:00:00.000Z".to_owned()), ..key("old") }]) + ); + assert!(fresh.pending.is_none()); + assert_eq!(registry.requests.load(Ordering::SeqCst), 0); + + // A stale one is replaced by what the registry says, written only on `commit`. + let fetched = registry_keys_at(&file, &url, 1501, &client).unwrap(); + + assert_eq!(fetched.keys, Some(vec![key("new")])); + assert_eq!(registry.requests.load(Ordering::SeqCst), 1); + assert!(fs::read_to_string(&file).unwrap().contains("\"old\"")); + + fetched.commit().unwrap(); + + assert_eq!( + fs::read_to_string(&file).unwrap(), + r#"{"createdAt":1501,"keys":[{"keyid":"new","key":"key-new","expires":null}],"ttlMs":86400000}"# + ); + + // The registry failing leaves the old keys, and no keys at all where there are none. + let down = Registry::start(HashMap::from([("/keys".to_owned(), (500, "{}".to_owned(), Vec::new()))])); + let down_url = format!("{}/keys", down.url()); + let stale = registry_keys_at(&file, &down_url, u64::MAX / 2, &client).unwrap(); + + assert_eq!(stale.keys, Some(vec![key("new")])); + assert!(stale.pending.is_none()); + + fs::remove_file(&file).unwrap(); + + assert_eq!(registry_keys_at(&file, &down_url, 0, &client).unwrap().keys, None); + + // A cache or a key list this module does not read as Node does is handed over. + for odd in [ + "not json", + r#"{"createdAt":1,"keys":[{"keyid":"a"}],"ttlMs":5}"#, + r#"{"createdAt":1,"keys":[{"keyid":"a","key":"b","expires":5}],"ttlMs":5}"#, + r#"{"createdAt":"1","keys":[],"ttlMs":5}"#, + r#"{"keys":[],"ttlMs":5}"#, + ] { + write(odd); + + assert!(registry_keys_at(&file, &url, 0, &client).is_err(), "{odd}"); + } + + fs::remove_dir_all(&directory).unwrap(); + } } diff --git a/packages/tooling/vis/native/cli/src/main.rs b/packages/tooling/vis/native/cli/src/main.rs index c373a153..f3c85dbd 100644 --- a/packages/tooling/vis/native/cli/src/main.rs +++ b/packages/tooling/vis/native/cli/src/main.rs @@ -28,6 +28,7 @@ use std::process::exit; mod add; mod advisories; mod affected; +mod attest; mod audit; mod cache; #[cfg(unix)] diff --git a/packages/tooling/vis/native/cli/src/route.rs b/packages/tooling/vis/native/cli/src/route.rs index e859b046..db364d59 100644 --- a/packages/tooling/vis/native/cli/src/route.rs +++ b/packages/tooling/vis/native/cli/src/route.rs @@ -85,6 +85,8 @@ static ROUTES: &[Route] = &[ answers(&["shim", "status"], crate::shim_status::run), answers(&["deps"], crate::deps::run), answers(&["self-update"], crate::self_update::run), + answers(&["attest", "verify"], crate::attest::verify::run), + answers(&["attest"], crate::attest::emit::run), answers(&["add"], crate::add::run), answers(&["install"], crate::install::run), answers(&["i"], crate::install::run), @@ -183,6 +185,8 @@ mod tests { &["shim", "status"], &["deps"], &["self-update"], + &["attest", "verify"], + &["attest"], &["add"], &["install"], &["i"], diff --git a/packages/tooling/vis/native/cli/tests/fixtures/native-routes.snap b/packages/tooling/vis/native/cli/tests/fixtures/native-routes.snap index 83703bde..a5d97c29 100644 --- a/packages/tooling/vis/native/cli/tests/fixtures/native-routes.snap +++ b/packages/tooling/vis/native/cli/tests/fixtures/native-routes.snap @@ -22,6 +22,7 @@ ["--color","analyze"] => surface ["--color","approve-builds"] => surface ["--color","attest"] => surface +["--color","attest","verify"] => surface ["--color","audit"] => surface ["--color","c"] => surface ["--color","cache"] => surface @@ -182,6 +183,7 @@ ["--no-color","analyze"] => surface ["--no-color","approve-builds"] => surface ["--no-color","attest"] => surface +["--no-color","attest","verify"] => surface ["--no-color","audit"] => surface ["--no-color","bloom","status"] => surface ["--no-color","bloom","status","--help"] => surface @@ -338,6 +340,7 @@ ["--quiet","analyze"] => surface ["--quiet","approve-builds"] => surface ["--quiet","attest"] => surface +["--quiet","attest","verify"] => surface ["--quiet","audit"] => surface ["--quiet","c"] => surface ["--quiet","cache"] => surface @@ -779,22 +782,52 @@ ["approve-builds","target"] => surface ["approve-builds","target","--help"] => surface ["approve-builds","target","other"] => surface -["attest"] => surface -["attest","--"] => surface -["attest","--","--help"] => surface -["attest","--format","json"] => surface +["attest"] => attest +["attest","--"] => attest +["attest","--","--help"] => attest +["attest","--format","json"] => attest +["attest","--format","json","verify"] => attest +["attest","--format=ndjson","dist/app.tgz"] => attest ["attest","--help"] => surface ["attest","--no-color","-h"] => surface -["attest","--version"] => surface +["attest","--version"] => attest ["attest","--version","--help"] => surface ["attest","-h"] => surface -["attest","bloom","status"] => surface +["attest","./dist/app.tgz"] => attest +["attest","bloom","status"] => attest ["attest","bloom","status","--help"] => surface -["attest","list"] => surface +["attest","dist/app.tgz"] => attest +["attest","dist/app.tgz","--format","json","--predicate","slsaProvenance","--output=out.sigstore"] => attest +["attest","dist/app.tgz","--format","xml"] => attest +["attest","dist/app.tgz","--predicate","other"] => attest +["attest","dist/app.tgz","--require-signing"] => attest +["attest","dist/app.tgz","other.tgz"] => attest +["attest","list"] => attest ["attest","status","--help"] => surface -["attest","target"] => surface +["attest","target"] => attest ["attest","target","--help"] => surface -["attest","target","other"] => surface +["attest","target","other"] => attest +["attest","verify"] => attest verify +["attest","verify","--"] => attest verify +["attest","verify","--","--help"] => attest verify +["attest","verify","--fail-on","info"] => attest verify +["attest","verify","--format","json"] => attest verify +["attest","verify","--format","json","--fail-on","error","--allowlist","a,b"] => attest verify +["attest","verify","--format","xml"] => attest verify +["attest","verify","--help"] => surface +["attest","verify","--no-color","-h"] => surface +["attest","verify","--prod-only"] => attest verify +["attest","verify","--version"] => attest verify +["attest","verify","--version","--help"] => surface +["attest","verify","-h"] => surface +["attest","verify","bloom","status"] => attest verify +["attest","verify","bloom","status","--help"] => surface +["attest","verify","extra"] => attest verify +["attest","verify","list"] => attest verify +["attest","verify","status","--help"] => surface +["attest","verify","target"] => attest verify +["attest","verify","target","--help"] => surface +["attest","verify","target","other"] => attest verify ["audit"] => audit ["audit","--"] => audit ["audit","--","--help"] => audit @@ -1277,6 +1310,7 @@ ["dlx","bloom","status"] => dlx ["dlx","bloom","status","--help"] => surface ["dlx","cowsay"] => dlx +["dlx","cowsay","-y"] => dlx ["dlx","git+https://example.test/a.git"] => dlx ["dlx","list"] => dlx ["dlx","status","--help"] => surface diff --git a/packages/tooling/vis/native/cli/tests/fixtures/routing.json b/packages/tooling/vis/native/cli/tests/fixtures/routing.json index 80f3397d..3407d7dd 100644 --- a/packages/tooling/vis/native/cli/tests/fixtures/routing.json +++ b/packages/tooling/vis/native/cli/tests/fixtures/routing.json @@ -731,11 +731,14 @@ { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "native", "env": { "VIS_DLX_NO_INFO": "1" }, "stubPackageManagers": true }, { "args": ["dlx", "--no-info", "cowsay"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80", "FORCE_COLOR": "1" }, "stubPackageManagers": true }, { "args": ["dlx", "--no-info", "cowsay"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80" }, "interactive": true, "stubPackageManagers": true }, - { "args": ["dlx", "cowsay"], "launcher": "node", "binary": "node", "env": {}, "stubPackageManagers": true, "note": "the first-run gate may fetch package metadata and prompt (it skips itself in CI, without a terminal and with --yes, which the binary does not decide), before any output" }, - { "args": ["dlx", "--yes", "cowsay"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "stubPackageManagers": true, "note": "--yes makes the first-run gate skip itself, but the binary does not decide that, so Node answers" }, - { "args": ["dlx", "cowsay"], "launcher": "node", "binary": "node", "env": { "VIS_DLX_YES": "1" }, "stubPackageManagers": true, "note": "VIS_DLX_YES makes the first-run gate skip itself, but the binary does not decide that, so Node answers" }, - { "args": ["dlx", "cowsay"], "launcher": "node", "binary": "node", "env": { "VIS_DLX_NO_INFO": "0" }, "stubPackageManagers": true }, - { "args": ["dlx", "-p", "lolcatjs", "-c", "echo hi"], "launcher": "node", "binary": "node", "env": {}, "stubPackageManagers": true }, + { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "native", "env": {}, "stubPackageManagers": true, "note": "no terminal on stdin and stdout, so the first-run gate skips itself" }, + { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "native", "env": {}, "interactive": true, "stubPackageManagers": true, "note": "the launcher sees a terminal on stdout, but the binary reads stdin too: with none, the gate skips itself (on a terminal it looks the package up, and answers only for an approved version)" }, + { "args": ["dlx", "--yes", "cowsay"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80" }, "stubPackageManagers": true }, + { "args": ["dlx", "cowsay", "-y"], "launcher": "native", "binary": "native", "env": {}, "stubPackageManagers": true }, + { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "native", "env": { "VIS_DLX_YES": "1" }, "stubPackageManagers": true }, + { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "native", "env": { "VIS_DLX_NO_INFO": "0" }, "stubPackageManagers": true }, + { "args": ["dlx", "cowsay"], "launcher": "native", "binary": "node", "env": { "VIS_DLX_YES": "\u00a01" }, "stubPackageManagers": true, "note": "JavaScript's trim and Rust's differ on a no-break space, so the binary leaves a value that is not ASCII to Node" }, + { "args": ["dlx", "-p", "lolcatjs", "-c", "echo hi"], "launcher": "native", "binary": "native", "env": {}, "stubPackageManagers": true }, { "args": ["dlx", "--no-info", "cowsay", "--"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "stubPackageManagers": true }, { "args": ["dlx", "--no-info", "cowsay", "-x"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "stubPackageManagers": true }, { "args": ["dlx", "--no-info", "cowsay", "--version"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "stubPackageManagers": true }, @@ -992,6 +995,32 @@ { "args": ["audit", "--format=json", "--policies=none"], "launcher": "native", "binary": "node", "env": { "CI": "1" } }, { "args": ["audit", "--format", "json", "--policies", "none", "--severity", "high"], "launcher": "native", "binary": "node", "env": { "CI": "1" } }, { "args": ["audit", "--fail-on=critical", "--policies", "none", "--format", "json", "--exit-code"], "launcher": "native", "binary": "node", "env": { "CI": "1" } }, + { "args": ["attest", "dist/app.tgz"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" }, "note": "no ambient OIDC token: Node hashes the artifact and skips signing" }, + { "args": ["attest", "dist/app.tgz", "--format", "json", "--predicate", "slsaProvenance", "--output=out.sigstore"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "--format=ndjson", "dist/app.tgz"], "launcher": "native", "binary": "native", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz"], "launcher": "native", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "note": "the artifact does not exist, which Node throws" }, + { "args": ["attest", "./dist/app.tgz"], "launcher": "native", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" }, "note": "a path that needs normalising" }, + { "args": ["attest", "dist/app.tgz"], "launcher": "node", "binary": "node", "env": { "CI": "true", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" }, "note": "CI equal to true is an ambient OIDC token: Node signs" }, + { "args": ["attest", "dist/app.tgz"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80", "ACTIONS_ID_TOKEN_REQUEST_URL": "https://token.test" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80", "SIGSTORE_ID_TOKEN": "t" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz", "--require-signing"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz", "--predicate", "other"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz", "--format", "xml"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "dist/app.tgz", "other.tgz"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" } }, + { "args": ["attest", "--format", "json", "verify"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "note": "cerebro reads this word as the verify leaf" }, + { "args": ["attest", "dist/app.tgz"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "files": { "dist/app.tgz": "artifact" }, "interactive": true }, + { "args": ["attest", "verify"], "launcher": "native", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "note": "the fixture project's lockfile lists no package, so the binary hands the run to Node before it asks the registry; the answered cases are the whole-run tests in `native/cli/src/attest/verify.rs`" }, + { "args": ["attest", "verify", "--format", "json", "--fail-on", "error", "--allowlist", "a,b"], "launcher": "native", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" } }, + { "args": ["attest", "verify", "--prod-only"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" } }, + { "args": ["attest", "verify", "--format", "xml"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" } }, + { "args": ["attest", "verify", "--fail-on", "info"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" } }, + { "args": ["attest", "verify", "extra"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" } }, + { "args": ["attest", "verify"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80", "MARSHALL_DISABLE_ALL": "1" } }, + { "args": ["attest", "verify"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80", "VIS_NPM_KEYS_URL": "https://keys.test/keys" } }, + { "args": ["attest", "verify"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80", "HTTPS_PROXY": "http://proxy.test:3128" } }, + { "args": ["attest", "verify"], "launcher": "node", "binary": "node", "env": { "CI": "1", "COLUMNS": "80" }, "interactive": true }, + { "args": ["attest", "--help"], "launcher": "native", "binary": "native" }, + { "args": ["attest", "verify", "--help"], "launcher": "native", "binary": "native" }, { "args": ["audit", "--help"], "launcher": "native", "binary": "native" }, { "args": ["audit", "--format", "json", "--policies", "none"], "launcher": "native", "binary": "node", "env": { "CI": "1", "NO_PROXY": "localhost" } }, { "args": ["audit", "--format", "json", "--policies", "none"], "launcher": "native", "binary": "node", "env": { "CI": "1", "NODE_ENV": "production" } },