diff --git a/CHANGELOG.md b/CHANGELOG.md index d2f780d2..a2c829fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Fixed +- **`triage`'s pip score is no longer higher than npm's for running fewer probes.** The + score is a flat penalty count (`100 - 45*critical - 12*warning`), so it fell out of how + many probes an ecosystem HAS: `pip opensandbox-server` printed 100/100 next to + `npm deepsec`'s 88/100, and that 88 existed only because the npm path looked for + something the pip path never did (maintainer count, newness). A reader comparing the two + numbers in the same CLI concluded the Python package was the safer one. + + Absence is now printed rather than scored, the same `didNotRun` rule kit applies + everywhere else: the pip path declares `maintainer count` as unavailable (PyPI's JSON API + publishes no maintainer list), and the report carries `Probes declared unavailable: N` + plus a `Coverage: PARTIAL — …` line, so a 100 with a skipped probe can no longer read as + a 100 with everything clean. A declared gap does not withhold `TRIAGE PASSED` — it is an + unknown, not a finding. + + Two probes that were absent rather than impossible now run: **pip newness** (PyPI has no + `created` field, but the oldest release file's upload time is the first publish — warns + under 30 days, as npm does) and **npm license** (the pip path had warned on a missing + license since it was written; the npm path never looked). After this the two paths run the + same probe set except maintainer count. + +- **`author: unknown` for nearly every modern Python package.** `info.author` is `null` + under PEP 621 (`authors = [{name=…, email=…}]`); the value lands in `info.author_email`. + Attribution is what settles a look-alike-repo provenance question cheaply, so it now falls + back — measured: `author: unknown` → `author: OpenSandbox Team <…@alibaba-inc.com>`. + - **A third test that reported a verdict its environment could not support.** The `writeCheckDetail` failed-write test forced its precondition with `chmod 0o500` without checking whether the mode denied *this* process — root mkdirs straight through it, so the diff --git a/skills/triage/scripts/triage.py b/skills/triage/scripts/triage.py index ec993177..83c4d7e0 100644 --- a/skills/triage/scripts/triage.py +++ b/skills/triage/scripts/triage.py @@ -8,7 +8,13 @@ kit (src/triage.ts) shells to this script and reads its STDOUT: - the line "TRIAGE PASSED" must be present for kit to treat the target as safe; - "Health score: N/100", "Critical issues: N", "Warnings: N" are parsed for the - structured summary. + structured summary; + - "Probes declared unavailable: N" and, when N > 0, a "Coverage: PARTIAL -- ..." line + report probes this ecosystem's registry cannot answer. The score is a flat penalty + count, so it falls out of how many probes an ecosystem HAS: a pip 100/100 ran one + fewer probe than an npm 100/100 (PyPI publishes no maintainer list). Absence is + printed rather than scored, matching kit's `didNotRun` rule that coverage which + could not run is UNKNOWN, never clean. Design contract (matches kit's watertight gate): - Deterministic. No LLM, no randomness. Same input + same upstream state => same verdict. @@ -24,7 +30,8 @@ - PASS means the SPECIFIC target — including a pinned version or dist-tag (`name@1.2.3`, `name@next`, `name==1.2.3`) — EXISTS and clears the health checks: not-found, deprecated, or yanked is a CRITICAL; newness / abandonment / single-maintainer / no-license are - warnings. A pinned version is triaged directly, so a clean `latest` never vouches for a + warnings. npm and pip run the same probe set except maintainer count, which the pip + path declares as unavailable instead of leaving unmentioned. A pinned version is triaged directly, so a clean `latest` never vouches for a yanked or malicious pinned version. - PASS is NOT a malware verdict. This gate does no typosquat, install-script, or behavioral analysis. Deep malware detection is GuardDog (opt-in, separate + heavier: `KIT_GUARDDOG=1` @@ -92,6 +99,7 @@ def __init__(self, ttype, target): self.criticals = [] self.warnings = [] self.facts = [] + self.notrun = [] def critical(self, m): self.criticals.append(m) @@ -102,6 +110,19 @@ def warn(self, m): def fact(self, m): self.facts.append(m) + def notchecked(self, probe, why): + """Record a probe that this ecosystem's registry cannot answer. + + The score is a flat penalty count (100 - 45*crit - 12*warn), so it falls out of how + many probes an ecosystem HAS, not out of how safe the package is: before this, a pip + package scored 100/100 while the npm path scored 88 for the same package shape, purely + because npm exposes maintainer count and PyPI does not. Rather than let a number that + ran fewer checks read as the cleaner one, absence is printed -- the same `didNotRun` + semantics kit uses everywhere else, where coverage that could not run is UNKNOWN, not + clean. + """ + self.notrun.append((probe, why)) + def emit(self): score = max(0, 100 - 45 * len(self.criticals) - 12 * len(self.warnings)) # Sanitize the echoed target: it is attacker-influenceable, and a newline @@ -115,10 +136,23 @@ def emit(self): print(f" ! WARNING: {w}") for c in self.criticals: print(f" x CRITICAL: {c}") + for probe, why in self.notrun: + print(f" ~ NOT CHECKED: {probe} -- {why}") print() print(f"Health score: {score}/100") print(f"Critical issues: {len(self.criticals)}") print(f"Warnings: {len(self.warnings)}") + # Counts only what this path DECLARED it cannot answer -- never a completeness + # claim about the probe set itself, which is documented per type above. + print(f"Probes declared unavailable: {len(self.notrun)}") + if self.notrun: + # Without this line a 100/100 with a skipped probe is indistinguishable from a + # 100/100 with everything green -- which is the defect (#489). + probes = ", ".join(probe for probe, _ in self.notrun) + print( + f"Coverage: PARTIAL -- {len(self.notrun)} probe(s) cannot run for this " + f"ecosystem ({probes}); the score covers only what was checked" + ) if not self.criticals: print("TRIAGE PASSED") else: @@ -272,6 +306,11 @@ def triage_npm(rep): rep.warn(f"no publish in {last_days} days -- possibly abandoned") if len(maint) <= 1: rep.warn("single maintainer -- bus-factor / takeover risk") + # License parity with the pip path, which has warned on a missing license since it was + # written. Comparability breaks in both directions: an npm 100 must not be a 100 that + # never looked at the terms. + if not (meta.get("license") or data.get("license")): + rep.warn("no declared license -- review terms before use") def _split_pip_spec(target): @@ -394,7 +433,12 @@ def triage_pip(rep): if any(f.get("yanked") for f in files): rep.critical(f"version {ver} is YANKED") tag = f" (latest {latest})" if ver != latest else "" - rep.fact(f"triaged {ver}{tag}, {len(releases)} releases, author: {info.get('author') or 'unknown'}") + # `info.author` is null for every PEP 621 package: `authors = [{name=..., email=...}]` + # lands in `author_email` instead, so the old fallback printed "author: unknown" for + # essentially all modern Python packages -- and attribution is what settles a + # look-alike-repo provenance question cheaply. + author = info.get("author") or info.get("author_email") or "unknown" + rep.fact(f"triaged {ver}{tag}, {len(releases)} releases, author: {author}") last_iso = files[0].get("upload_time_iso_8601") if files else None last_days = _days_since(last_iso) if last_days is not None and last_days > ABANDONED_DAYS: @@ -402,6 +446,29 @@ def triage_pip(rep): if not info.get("license") and not (info.get("classifiers") or []): rep.warn("no declared license -- review terms before use") + # Newness parity with the npm path. PyPI has no "created" field, but every release file + # carries its upload time, so first-publish is the OLDEST one -- the probe was absent, + # not impossible. + first_days = None + for rel_files in releases.values(): + for f in rel_files or []: + d = _days_since(f.get("upload_time_iso_8601") or f.get("upload_time")) + if d is not None and (first_days is None or d > first_days): + first_days = d + if first_days is not None: + rep.fact(f"first published {first_days} days ago") + if first_days < NEW_DAYS: + rep.warn(f"package is very new ({first_days} days) -- limited track record") + + # The one npm probe PyPI cannot answer. `info.maintainer` / `maintainer_email` are + # free-text and usually empty, and the JSON API publishes no maintainer list at all, so + # a count here would be invented. Declared instead of silently skipped. + rep.notchecked( + "maintainer count", + "PyPI's JSON API publishes no maintainer list (info.maintainer is free-text and " + "usually empty), so bus-factor / account-takeover risk was NOT assessed", + ) + def _owner_repo(target): t = target.strip() diff --git a/src/triage-ecosystem-parity.test.ts b/src/triage-ecosystem-parity.test.ts new file mode 100644 index 00000000..2da446fd --- /dev/null +++ b/src/triage-ecosystem-parity.test.ts @@ -0,0 +1,301 @@ +/** + * The triage score is a flat penalty count (`100 - 45*crit - 12*warn`), so it falls out of + * how many probes an ecosystem HAS, not out of how safe the package is. + * + * Measured against 6.6.3 (#489): + * + * kit triage npm deepsec -> 88/100 ! single maintainer + * kit triage npm @deepseek-ai/dsh -> 88/100 ! package is very new (4 days) + * kit triage pip opensandbox-server -> 100/100 (no warnings) + * + * Both 88s existed only because the npm path looked for something the pip path never did. + * A reader comparing the two numbers in the same CLI concludes the Python package is the + * safer one — a verdict that reads stronger than its evidence, which is kit's own + * `didNotRun` rule inverted. + * + * These tests run the real `triage.py` against a LOCAL registry fixture (both hosts are + * env-overridable for air-gapped mirrors, which makes them injectable here), so the + * assertions are on the script's actual stdout — the text kit prints verbatim to the + * operator — not on a re-implementation of its logic. + */ + +import { describe, it, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, type Server } from "node:http"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const exec = promisify(execFile); +const TRIAGE_PY = resolve( + dirname(fileURLToPath(import.meta.url)), + "..", + "skills", + "triage", + "scripts", + "triage.py", +); + +const iso = (daysAgo: number): string => + new Date(Date.now() - daysAgo * 86_400_000).toISOString().replace(/\.\d{3}Z$/, ".000000Z"); + +/** PyPI `/pypi//json`, PEP 621 shape: `author` null, attribution in `author_email`. */ +function pypiPackage(opts: { + version: string; + firstReleaseDaysAgo: number; + lastReleaseDaysAgo: number; + authorEmail?: string | null; + author?: string | null; + license?: string; +}): unknown { + const older = `0.0.1`; + return { + info: { + version: opts.version, + author: opts.author ?? null, + author_email: opts.authorEmail ?? null, + license: opts.license ?? "Apache-2.0", + classifiers: ["License :: OSI Approved :: Apache Software License"], + }, + releases: { + [older]: [ + { + yanked: false, + upload_time_iso_8601: iso(opts.firstReleaseDaysAgo), + }, + ], + [opts.version]: [ + { + yanked: false, + upload_time_iso_8601: iso(opts.lastReleaseDaysAgo), + }, + ], + }, + }; +} + +/** npm packument, trimmed to the fields the npm path reads. */ +function npmPackument(opts: { + version: string; + createdDaysAgo: number; + publishedDaysAgo: number; + maintainers: number; + license?: string | null; +}): unknown { + return { + "dist-tags": { latest: opts.version }, + versions: { + [opts.version]: { + name: "fixture", + version: opts.version, + ...(opts.license === null ? {} : { license: opts.license ?? "Apache-2.0" }), + }, + }, + time: { + created: iso(opts.createdDaysAgo), + [opts.version]: iso(opts.publishedDaysAgo), + }, + maintainers: Array.from({ length: opts.maintainers }, (_, i) => ({ + name: `m${i}`, + email: `m${i}@example.test`, + })), + }; +} + +describe("triage ecosystem parity (real triage.py against a local registry)", () => { + let server: Server; + let base = ""; + const routes = new Map(); + + before(async () => { + server = createServer((req, res) => { + const body = routes.get(req.url ?? ""); + if (body === undefined) { + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ message: "Not Found" })); + return; + } + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const addr = server.address(); + if (addr === null || typeof addr === "string") throw new Error("no fixture port"); + base = `http://127.0.0.1:${addr.port}`; + }); + + after(async () => { + await new Promise((r) => server.close(() => r())); + }); + + /** + * Skips LOUDLY when python3 is absent: the script under test IS python, so a silent + * skip here would report a passing suite for a probe that never ran — the same defect + * class this file exists to close. + */ + const runTriage = async ( + type: "npm" | "pip", + target: string, + t: { skip: (m: string) => void }, + ): Promise => { + try { + const { stdout } = await exec("python3", [TRIAGE_PY, type, target], { + env: { + ...process.env, + KIT_PYPI_INDEX: base, + KIT_NPM_REGISTRY: base, + }, + timeout: 30_000, + }); + return stdout; + } catch (err) { + const e = err as { code?: string | number; stdout?: string }; + if (e.code === "ENOENT") { + t.skip("python3 not installed — triage.py's own behaviour is NOT verified in this run"); + return null; + } + // The script exits 0 on a completed evaluation, so a non-zero exit is a real failure. + throw err; + } + }; + + it("a clean pip package cannot print 100/100 without saying what it did not check", async (t) => { + routes.set( + "/pypi/opensandbox-server/json", + pypiPackage({ + version: "1.4.0", + firstReleaseDaysAgo: 400, + lastReleaseDaysAgo: 20, + authorEmail: "OpenSandbox Team ", + }), + ); + const out = await runTriage("pip", "opensandbox-server", t); + if (out === null) return; + + assert.match(out, /Health score: 100\/100/); + assert.match(out, /Probes declared unavailable: 1/); + assert.match(out, /Coverage: PARTIAL/); + assert.match(out, /NOT CHECKED: maintainer count/); + assert.match(out, /bus-factor \/ account-takeover risk was NOT assessed/); + assert.ok( + out.split("\n").includes("TRIAGE PASSED"), + "declared coverage gaps must not withhold PASS — they are unknowns, not findings", + ); + }); + + it("PEP 621 attribution comes from author_email, not 'unknown'", async (t) => { + routes.set( + "/pypi/pep621-pkg/json", + pypiPackage({ + version: "2.0.0", + firstReleaseDaysAgo: 900, + lastReleaseDaysAgo: 30, + author: null, + authorEmail: "OpenSandbox Team ", + }), + ); + const out = await runTriage("pip", "pep621-pkg", t); + if (out === null) return; + + assert.match(out, /author: OpenSandbox Team /); + assert.doesNotMatch(out, /author: unknown/); + }); + + it("the pip path now warns on a very new package, like npm always did", async (t) => { + routes.set( + "/pypi/fresh-pkg/json", + pypiPackage({ + version: "0.1.0", + firstReleaseDaysAgo: 4, + lastReleaseDaysAgo: 1, + authorEmail: "a@example.test", + }), + ); + const out = await runTriage("pip", "fresh-pkg", t); + if (out === null) return; + + assert.match(out, /first published 4 days ago/); + assert.match(out, /package is very new \(4 days\) -- limited track record/); + assert.match(out, /Health score: 88\/100/); + }); + + it("an npm package with the same shape scores the same as pip on the shared probes", async (t) => { + routes.set( + "/fresh-npm", + npmPackument({ + version: "0.1.0", + createdDaysAgo: 4, + publishedDaysAgo: 1, + // Two maintainers: isolates the newness probe, which is the one pip was missing. + maintainers: 2, + }), + ); + const npmOut = await runTriage("npm", "fresh-npm", t); + if (npmOut === null) return; + + assert.match(npmOut, /package is very new \(4 days\) -- limited track record/); + assert.match(npmOut, /Health score: 88\/100/); + // npm answers maintainer count, so it declares no gap — that asymmetry is the point: + // the reader can now see WHY two 88s are not the same 88. + assert.match(npmOut, /Probes declared unavailable: 0/); + assert.doesNotMatch(npmOut, /Coverage: PARTIAL/); + }); + + it("npm no longer prints a clean score for a package with no declared license", async (t) => { + routes.set( + "/no-license", + npmPackument({ + version: "3.2.1", + createdDaysAgo: 800, + publishedDaysAgo: 40, + maintainers: 3, + license: null, + }), + ); + const out = await runTriage("npm", "no-license", t); + if (out === null) return; + + assert.match(out, /no declared license -- review terms before use/); + assert.match(out, /Health score: 88\/100/); + }); + + it("a single-maintainer npm package still warns (bus factor), and pip says it cannot", async (t) => { + routes.set( + "/solo-pkg", + npmPackument({ + version: "1.0.0", + createdDaysAgo: 500, + publishedDaysAgo: 10, + maintainers: 1, + }), + ); + routes.set( + "/pypi/solo-pkg/json", + pypiPackage({ version: "1.0.0", firstReleaseDaysAgo: 500, lastReleaseDaysAgo: 10 }), + ); + + const npmOut = await runTriage("npm", "solo-pkg", t); + if (npmOut === null) return; + const pipOut = await runTriage("pip", "solo-pkg", t); + if (pipOut === null) return; + + assert.match(npmOut, /single maintainer -- bus-factor \/ takeover risk/); + assert.match(npmOut, /Health score: 88\/100/); + + // The pip score is still higher for the same package shape — that is inherent to a + // flat penalty count. What must never happen again is that being invisible. + assert.match(pipOut, /Health score: 100\/100/); + assert.match(pipOut, /Coverage: PARTIAL/); + assert.match(pipOut, /maintainer count/); + }); + + it("a missing package is still a fail-closed CRITICAL, coverage lines notwithstanding", async (t) => { + const out = await runTriage("pip", "no-such-package-xyz", t); + if (out === null) return; + + assert.match(out, /CRITICAL: package 'no-such-package-xyz' not found on PyPI/); + assert.ok(out.split("\n").includes("TRIAGE FAILED")); + assert.doesNotMatch(out, /TRIAGE PASSED/); + }); +});