From dc662a87ea71b700baa5d4fc40d42e3c7d8996ed Mon Sep 17 00:00:00 2001 From: George Oastler Date: Fri, 6 Nov 2026 21:37:11 +0000 Subject: [PATCH] Shared pinned-versions check for npm, cargo and python --- .github/scripts/pinned_versions.py | 243 ++++++++++++++++++++++++ .github/scripts/test_pinned_versions.py | 123 ++++++++++++ .github/workflows/pinned-versions.yml | 60 ++++++ README.md | 1 + 4 files changed, 427 insertions(+) create mode 100644 .github/scripts/pinned_versions.py create mode 100644 .github/scripts/test_pinned_versions.py create mode 100644 .github/workflows/pinned-versions.yml diff --git a/.github/scripts/pinned_versions.py b/.github/scripts/pinned_versions.py new file mode 100644 index 0000000..ae49622 --- /dev/null +++ b/.github/scripts/pinned_versions.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Fail on any dependency that is not pinned to one exact version. + +Walks a repo (skipping build output, virtualenvs and git submodules, which +are checked in their own repo) and checks: + +- package.json dependencies/devDependencies/optionalDependencies: "1.2.3", + workspace:* or workspace:1.2.3, npm:alias@1.2.3, file:/link:, or a git/URL + spec ending in a 40-hex commit. peerDependencies are exempt: they state what + a consumer may install, so a range is the point. +- package-lock.json and pnpm-lock.yaml: every registry package carries an + integrity hash, so a re-publish under the same version cannot slip in. +- Cargo.toml [*dependencies] and [workspace.dependencies]: "=1.2.3". A bare + "1.2" is a caret range in cargo. path, `workspace = true` and git deps with + `rev` need no version; a version given alongside path must still be exact. +- pyproject.toml [project] dependencies and optional-dependencies, + [dependency-groups], and requirements*.txt: "name==1.2.3" (extras and + markers allowed) or "name @ @<40-hex>". [build-system] requires is + exempt: build backends are resolved per build, outside the lockfile. + +Run from the repo root: python3 pinned_versions.py --root . +""" + +from __future__ import annotations + +import argparse +import fnmatch +import json +import re +import sys +from collections.abc import Iterator +from pathlib import Path + +import tomllib + +IGNORE_DIRS = { + "node_modules", ".git", "dist", "build", ".next", ".astro", ".turbo", ".nx", + "coverage", ".cache", ".venv", "venv", "target", "__pycache__", +} +NPM_SECTIONS = ("dependencies", "devDependencies", "optionalDependencies") +SEMVER = r"\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?" +EXACT_SEMVER = re.compile(rf"^{SEMVER}$") +EXACT_CARGO = re.compile(rf"^={SEMVER}$") +GIT_COMMIT = re.compile(r"[#@][0-9a-f]{40}$") +PY_NAME = r"[A-Za-z0-9][A-Za-z0-9._-]*(?:\[[^\]]*\])?" +PY_EXACT = re.compile(rf"^{PY_NAME}\s*===?\s*[0-9][^\s,;]*\s*(?:;.*)?$") +PY_URL = re.compile(rf"^{PY_NAME}\s*@\s*\S+[#@][0-9a-f]{{40}}\s*(?:;.*)?$") + + +def npm_pinned(spec: object) -> bool: + v = str(spec).strip() + if EXACT_SEMVER.match(v) or v.startswith(("file:", "link:")): + return True + if v.startswith("workspace:"): + rest = v.removeprefix("workspace:") + return rest == "*" or bool(EXACT_SEMVER.match(rest)) + if v.startswith("npm:"): + at = v.rfind("@") + return at > len("npm:") and bool(EXACT_SEMVER.match(v[at + 1:])) + if re.match(r"^(git\+|git:|github:|https?:)", v): + return bool(GIT_COMMIT.search(v)) + return False + + +def cargo_pinned(spec: object) -> bool: + if isinstance(spec, str): + return bool(EXACT_CARGO.match(spec.strip())) + if not isinstance(spec, dict): + return False + if spec.get("workspace") is True: + return True + if "git" in spec: + return "rev" in spec and re.fullmatch(r"[0-9a-f]{40}", str(spec["rev"])) is not None + if "version" in spec: + return bool(EXACT_CARGO.match(str(spec["version"]).strip())) + return "path" in spec + + +def python_pinned(req: str) -> bool: + req = req.strip() + return bool(PY_EXACT.match(req) or PY_URL.match(req)) + + +def check_package_json(path: Path, rel: str) -> Iterator[str]: + try: + pkg = json.loads(path.read_text()) + except json.JSONDecodeError as exc: + yield f"{rel}: invalid JSON ({exc})" + return + for section in NPM_SECTIONS: + for name, spec in (pkg.get(section) or {}).items(): + if not npm_pinned(spec): + yield f'{rel} {section} > "{name}": "{spec}" is not an exact version' + + +def check_npm_lock(path: Path, rel: str) -> Iterator[str]: + lock = json.loads(path.read_text()) + if lock.get("lockfileVersion", 0) < 2: + yield f"{rel}: lockfileVersion {lock.get('lockfileVersion')} is too old; needs >= 2 for integrity hashes" + return + for key, entry in (lock.get("packages") or {}).items(): + if not key or "node_modules/" not in key or entry.get("link") is True: + continue + resolved = entry.get("resolved", "") + registry = resolved == "" or re.match(r"^https?://[^/]*registry\.", resolved) + if registry and not entry.get("integrity"): + yield f"{rel} {key}: missing integrity hash" + + +def pnpm_resolutions(text: str) -> Iterator[tuple[str, str]]: + """Yield (package key, resolution text) from a pnpm-lock.yaml. + + Line-based rather than a YAML parse (stdlib has none): under `packages:` + each key sits at two spaces and its `resolution:` is either an inline + `{integrity: ...}` map or a block whose keys sit at six spaces. + """ + section, key, block = "", "", None + for line in text.splitlines(): + if line and not line.startswith(" "): + section = line.rstrip(":") + continue + if section != "packages": + continue + if line.startswith(" ") and not line.startswith(" ") and line.rstrip().endswith(":"): + if block is not None: + yield key, block + key, block = line.strip().rstrip(":").strip("'\""), None + elif line.startswith(" resolution:"): + block = line.split(":", 1)[1].strip() + elif block is not None and line.startswith(" "): + block += " " + line.strip() + if block is not None: + yield key, block + + +def check_pnpm_lock(path: Path, rel: str) -> Iterator[str]: + for key, resolution in pnpm_resolutions(path.read_text()): + if not any(tag in resolution for tag in ("integrity:", "type:", "tarball:")): + yield f"{rel} {key}: missing integrity hash" + + +def _cargo_tables(doc: dict) -> Iterator[tuple[str, dict]]: + for name in ("dependencies", "dev-dependencies", "build-dependencies"): + if isinstance(doc.get(name), dict): + yield name, doc[name] + if isinstance(doc.get("workspace", {}).get("dependencies"), dict): + yield "workspace.dependencies", doc["workspace"]["dependencies"] + for target, body in (doc.get("target") or {}).items(): + for name, table in _cargo_tables(body): + if not name.startswith("workspace"): + yield f"target.{target}.{name}", table + + +def check_cargo(path: Path, rel: str) -> Iterator[str]: + doc = tomllib.loads(path.read_text()) + for section, table in _cargo_tables(doc): + for name, spec in table.items(): + if not cargo_pinned(spec): + yield f'{rel} [{section}] {name}: {json.dumps(spec)} is not an exact "=x.y.z" version' + + +def check_pyproject(path: Path, rel: str) -> Iterator[str]: + doc = tomllib.loads(path.read_text()) + project = doc.get("project") or {} + groups: list[tuple[str, list]] = [("project.dependencies", project.get("dependencies") or [])] + groups += [(f"project.optional-dependencies.{k}", v) for k, v in (project.get("optional-dependencies") or {}).items()] + groups += [(f"dependency-groups.{k}", v) for k, v in (doc.get("dependency-groups") or {}).items()] + for section, reqs in groups: + for req in reqs: + # {include-group = "..."} entries pull in another group, checked on its own. + if isinstance(req, str) and not python_pinned(req): + yield f'{rel} [{section}] "{req}" is not pinned with ==' + + +def check_requirements(path: Path, rel: str) -> Iterator[str]: + for number, raw in enumerate(path.read_text().splitlines(), 1): + line = raw.split(" #", 1)[0].strip() + if not line or line.startswith(("#", "-r", "-c", "--")): + continue + if not python_pinned(line.removeprefix("-e ").strip()): + yield f'{rel}:{number} "{line}" is not pinned with ==' + + +CHECKS = { + "package.json": check_package_json, + "package-lock.json": check_npm_lock, + "pnpm-lock.yaml": check_pnpm_lock, + "Cargo.toml": check_cargo, + "pyproject.toml": check_pyproject, +} + + +def submodules(root: Path) -> set[Path]: + gitmodules = root / ".gitmodules" + if not gitmodules.exists(): + return set() + found = re.findall(r"^\s*path\s*=\s*(.+?)\s*$", gitmodules.read_text(), re.M) + return {(root / p).resolve() for p in found} + + +def manifests(root: Path, exclude: list[str]) -> Iterator[Path]: + skip = submodules(root) + stack = [root] + while stack: + current = stack.pop() + for entry in sorted(current.iterdir()): + rel = entry.relative_to(root).as_posix() + if any(fnmatch.fnmatch(rel, pat) for pat in exclude): + continue + if entry.is_dir(): + if entry.name not in IGNORE_DIRS and entry.resolve() not in skip: + stack.append(entry) + elif entry.name in CHECKS or fnmatch.fnmatch(entry.name, "requirements*.txt"): + yield entry + + +def check(root: Path, exclude: list[str]) -> tuple[int, list[str]]: + count, errors = 0, [] + for path in manifests(root, exclude): + count += 1 + rel = path.relative_to(root).as_posix() + fn = CHECKS.get(path.name, check_requirements) + try: + errors.extend(fn(path, rel)) + except (ValueError, OSError) as exc: + errors.append(f"{rel}: cannot parse ({exc})") + return count, errors + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", type=Path, default=Path(".")) + parser.add_argument("--exclude", action="append", default=[], help="repo-relative glob to skip; repeatable") + args = parser.parse_args(argv) + count, errors = check(args.root.resolve(), args.exclude) + for err in errors: + print(f"::error::{err}") + print(json.dumps({"event": "pinned_versions", "manifests": count, "errors": len(errors)})) + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/.github/scripts/test_pinned_versions.py b/.github/scripts/test_pinned_versions.py new file mode 100644 index 0000000..c3c0b17 --- /dev/null +++ b/.github/scripts/test_pinned_versions.py @@ -0,0 +1,123 @@ +import json +import tempfile +import unittest +from pathlib import Path + +import pinned_versions as pv + +SHA = "a" * 40 + + +class NpmTest(unittest.TestCase): + def test_exact_and_local_specs_pass(self) -> None: + for spec in ["1.2.3", "1.2.3-beta.1", "workspace:*", "workspace:1.0.0", "npm:foo@2.0.0", + "file:../x", "link:../x", f"github:o/r#{SHA}"]: + self.assertTrue(pv.npm_pinned(spec), spec) + + def test_ranges_fail(self) -> None: + for spec in ["^1.2.3", "~1.2.3", "*", ">=1.0.0", "x", "1.x", "latest", "workspace:^", + "npm:foo@^2.0.0", "github:o/r#main"]: + self.assertFalse(pv.npm_pinned(spec), spec) + + +class CargoTest(unittest.TestCase): + def test_exact_and_local_specs_pass(self) -> None: + for spec in ["=1.2.3", {"version": "=1.2.3", "features": ["x"]}, {"workspace": True}, + {"path": "../x"}, {"path": "../x", "version": "=0.1.0"}, {"git": "u", "rev": SHA}]: + self.assertTrue(pv.cargo_pinned(spec), spec) + + def test_ranges_fail(self) -> None: + for spec in ["1.2", "1.2.3", "^1", "~1.2", "*", ">=1", {"version": "1"}, + {"path": "../x", "version": "0.1"}, {"git": "u"}, {"git": "u", "branch": "main"}]: + self.assertFalse(pv.cargo_pinned(spec), spec) + + +class PythonTest(unittest.TestCase): + def test_exact_specs_pass(self) -> None: + for req in ["pytest==8.0.0", "uvicorn[standard]==0.30.1", "a==1.0 ; python_version < '3.11'", + f"pkg @ git+https://x/y.git@{SHA}"]: + self.assertTrue(pv.python_pinned(req), req) + + def test_ranges_fail(self) -> None: + for req in ["pytest>=8.0.0", "a~=1.0", "a", "a<2", "a==1.0,<2", "pkg @ git+https://x/y.git@main"]: + self.assertFalse(pv.python_pinned(req), req) + + +class PnpmLockTest(unittest.TestCase): + def test_reads_inline_and_block_resolutions(self) -> None: + text = ( + "lockfileVersion: '9.0'\n\npackages:\n\n" + " a@1.0.0:\n resolution: {integrity: sha512-x}\n\n" + " b@1.0.0:\n resolution:\n integrity: sha512-y\n\n" + " '@c/d@1.0.0':\n resolution: {}\n\n" + "snapshots:\n\n a@1.0.0: {}\n" + ) + got = dict(pv.pnpm_resolutions(text)) + self.assertEqual(got, {"a@1.0.0": "{integrity: sha512-x}", "b@1.0.0": " integrity: sha512-y", "@c/d@1.0.0": "{}"}) + self.assertEqual(list(pv.check_pnpm_lock(_write(text, "pnpm-lock.yaml"), "l")), ["l @c/d@1.0.0: missing integrity hash"]) + + +def _write(text: str, name: str) -> Path: + path = Path(tempfile.mkdtemp()) / name + path.write_text(text) + return path + + +class RepoTest(unittest.TestCase): + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + + def tearDown(self) -> None: + self.tmp.cleanup() + + def put(self, rel: str, text: str) -> None: + path = self.root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + def test_reports_each_ecosystem_and_skips_ignored_dirs(self) -> None: + self.put("package.json", json.dumps({"dependencies": {"a": "^1.0.0"}, "peerDependencies": {"p": "^1"}})) + self.put("node_modules/x/package.json", json.dumps({"dependencies": {"a": "^1.0.0"}})) + self.put("sub/package.json", json.dumps({"dependencies": {"a": "^1.0.0"}})) + self.put(".gitmodules", '[submodule "sub"]\n\tpath = sub\n') + self.put("crate/Cargo.toml", '[dependencies]\nserde = "1"\n[target.\'cfg(unix)\'.dependencies]\nlibc = "=0.2.1"\n' + '[workspace.dependencies]\ntokio = { version = "1.0" }\n') + self.put("py/pyproject.toml", '[project]\nname="x"\ndependencies=["a>=1"]\n[project.optional-dependencies]\n' + 'e=["b==1"]\n[dependency-groups]\ndev=["c", {include-group = "e"}]\n[build-system]\nrequires=["hatchling"]\n') + self.put("py/requirements-dev.txt", "# c\n-r base.txt\nd==1.0 # ok\ne>=2\n") + count, errors = pv.check(self.root, []) + self.assertEqual(count, 4) + self.assertEqual(sorted(errors), sorted([ + 'package.json dependencies > "a": "^1.0.0" is not an exact version', + 'crate/Cargo.toml [dependencies] serde: "1" is not an exact "=x.y.z" version', + 'crate/Cargo.toml [workspace.dependencies] tokio: {"version": "1.0"} is not an exact "=x.y.z" version', + 'py/pyproject.toml [project.dependencies] "a>=1" is not pinned with ==', + 'py/pyproject.toml [dependency-groups.dev] "c" is not pinned with ==', + 'py/requirements-dev.txt:4 "e>=2" is not pinned with ==', + ])) + + def test_exclude_and_parse_errors(self) -> None: + self.put("vendor/package.json", json.dumps({"dependencies": {"a": "^1"}})) + self.put("bad/Cargo.toml", "[dependencies\n") + _, errors = pv.check(self.root, ["vendor"]) + self.assertEqual(len(errors), 1) + self.assertTrue(errors[0].startswith("bad/Cargo.toml: cannot parse")) + + def test_npm_lock_integrity(self) -> None: + self.put("package-lock.json", json.dumps({"lockfileVersion": 3, "packages": { + "": {}, "node_modules/a": {"resolved": "https://registry.npmjs.org/a.tgz"}, + "node_modules/b": {"resolved": "https://registry.npmjs.org/b.tgz", "integrity": "sha512-x"}, + "node_modules/c": {"link": True}}})) + _, errors = pv.check(self.root, []) + self.assertEqual(errors, ["package-lock.json node_modules/a: missing integrity hash"]) + + def test_main_exit_codes(self) -> None: + self.put("package.json", json.dumps({"dependencies": {"a": "1.0.0"}})) + self.assertEqual(pv.main(["--root", str(self.root)]), 0) + self.put("package.json", json.dumps({"dependencies": {"a": "latest"}})) + self.assertEqual(pv.main(["--root", str(self.root)]), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/pinned-versions.yml b/.github/workflows/pinned-versions.yml new file mode 100644 index 0000000..6a8de4a --- /dev/null +++ b/.github/workflows/pinned-versions.yml @@ -0,0 +1,60 @@ +# Fails when any npm, cargo or python dependency is not pinned to one exact +# version, or a lockfile entry lacks an integrity hash. The rules are in +# .github/scripts/pinned_versions.py. +# +# Callers: pull_request (drafts too: it takes seconds) and push to main. + +name: pinned-versions + +on: + workflow_call: + inputs: + actions-ref: + description: "Commit of prosopo/github_actions holding the script; pass the SHA this workflow is pinned at." + type: string + required: true + concurrency-key: + description: "Concurrency group prefix; defaults to pinned-versions." + type: string + default: "" + exclude: + description: "Repo-relative globs to skip, one per line (vendored or generated manifests)." + type: string + default: "" + runs-on: {description: "Runner label.", type: string, default: "ubuntu-latest"} + +permissions: + contents: read + +concurrency: + group: ${{ inputs.concurrency-key || 'pinned-versions' }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + check: + if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + runs-on: ${{ inputs.runs-on }} + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + timeout-minutes: 3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + timeout-minutes: 3 + with: + repository: prosopo/github_actions + ref: ${{ inputs.actions-ref }} + path: .shared-actions + - name: Check pinned versions + timeout-minutes: 2 + env: + EXCLUDE: ${{ inputs.exclude }} + run: | + args=(--root . --exclude .shared-actions) + while IFS= read -r glob; do + if [ -n "$glob" ]; then args+=(--exclude "$glob"); fi + done <<< "$EXCLUDE" + timeout 90 python3 .shared-actions/.github/scripts/pinned_versions.py "${args[@]}" diff --git a/README.md b/README.md index 6e0080c..9470117 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ Each takes `actions-ref`: pass the same SHA the `uses:` line pins, so the workfl Two calls in one run need distinct `workflow` or `concurrency-key` inputs, or they queue behind each other. `ci.yml`'s `selftest-pick-runner` jobs call it as above and check the output shape. - `ci-coverage-audit.yml`: weekly (and on dispatch), the CI coverage matrix for every repo in `.github/scripts/ciaudit/repos.txt`: per unit (package, crate, Python project, Dockerfile, ...) whether CI builds, lints, typechecks, tests and e2e-tests it, from a static walk of each triggered workflow (reusable workflows, composite actions, package scripts, turbo tasks) cross-checked against its latest green run. HTML and JSON in the `ci-coverage` artifact, a text matrix in the step summary. A gap that is deliberate goes in `.github/scripts/ciaudit/optouts.json` with its reason. Run locally: `fetch.py --repos-file repos.txt --dest-prefix snap/` then `audit.py --snap-prefix snap/ --repos-file repos.txt --out-json r.json --out-html r.html`; `why.py` prints the evidence behind one unit. - `auto-update-pr.yml`: updates one random behind, mergeable, auto-merge PR at a time (`.github/scripts/auto_update_pr.py`). +- `pinned-versions.yml`: fails on any npm, cargo or python dependency not pinned to one exact version, and on lockfile entries without an integrity hash (`.github/scripts/pinned_versions.py`). - `branch-cleanup.yml`: deletes branches whose PR merged and that nobody has pushed to since; dry run by default (`.github/scripts/branch_cleanup.py`). ## This repo's own CI