From 1977180f6d50c9232d4e39d4f972b778733530bb Mon Sep 17 00:00:00 2001 From: Jon Thia Date: Tue, 1 Sep 2026 14:08:42 +1000 Subject: [PATCH] feat: absorb the dependency-gate action Moves velocity-exchange/dependency-gate in as dependency-gate/, so the org's shared CI lives in one protected repo instead of two. It is a composite action with a Python parser and no build artifact, so it relocates as plain files. Relocation fixes, since everything in it assumed the repo root: - `uses: ./` -> `uses: ./dependency-gate` (3 call sites) - `lockfiles:` fixture paths gain the dependency-gate/ prefix - `python3 tests/test_parser.py` and `open("action.yml")` gain the prefix; test_parser.py itself resolves fixtures from __file__, so it needed none - its `push:` trigger was `[main]`; this repo's default branch is `master` - both workflows renamed to dependency-gate-{test,selfgate}.yml and given distinct `name:`s, now that they share a repo The action itself is unchanged; it locates its parser via $GITHUB_ACTION_PATH, which already works from a subdirectory. Verified: the full parser suite passes when invoked the way CI invokes it, and action.yml still satisfies the contract its own CI asserts (composite, required lockfiles input, the three outputs, every step bash, no Actions expressions interpolated into run bodies). Note the test workflow now carries paths filters. YAML anchors were NOT used to share them - GitHub Actions does not support anchors, and a workflow using them fails to parse. Co-Authored-By: Claude Opus 5 (1M context) --- .github/CODEOWNERS | 4 + .../workflows/dependency-gate-selfgate.yml | 35 ++ .github/workflows/dependency-gate-test.yml | 150 +++++ .gitignore | 3 + README.md | 49 ++ dependency-gate/README.md | 294 ++++++++++ dependency-gate/action.yml | 421 ++++++++++++++ dependency-gate/lockfile_packages.py | 421 ++++++++++++++ dependency-gate/tests/fixtures/Cargo.lock | 11 + .../tests/fixtures/stable/Cargo.lock | 17 + dependency-gate/tests/fixtures/stable/uv.lock | 24 + dependency-gate/tests/test_parser.py | 528 ++++++++++++++++++ 12 files changed, 1957 insertions(+) create mode 100644 .github/workflows/dependency-gate-selfgate.yml create mode 100644 .github/workflows/dependency-gate-test.yml create mode 100644 .gitignore create mode 100644 dependency-gate/README.md create mode 100644 dependency-gate/action.yml create mode 100644 dependency-gate/lockfile_packages.py create mode 100644 dependency-gate/tests/fixtures/Cargo.lock create mode 100644 dependency-gate/tests/fixtures/stable/Cargo.lock create mode 100644 dependency-gate/tests/fixtures/stable/uv.lock create mode 100644 dependency-gate/tests/test_parser.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index d21d68e..3a42e3d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -11,3 +11,7 @@ * @0xahzam @ChewingGlass @jt-lumen @ChesterSim @csadminlc @noah-velocity-admin @jtadminlc /.github/workflows/publish-image.yml @0xahzam @ChewingGlass @jt-lumen @ChesterSim @csadminlc @noah-velocity-admin @jtadminlc + +# The dependency gate inspects the pull request that is changing it, so its +# parser deliberately lives outside the repos it gates. +/dependency-gate/ @0xahzam @ChewingGlass @jt-lumen @ChesterSim @csadminlc @noah-velocity-admin diff --git a/.github/workflows/dependency-gate-selfgate.yml b/.github/workflows/dependency-gate-selfgate.yml new file mode 100644 index 0000000..f01a941 --- /dev/null +++ b/.github/workflows/dependency-gate-selfgate.yml @@ -0,0 +1,35 @@ +name: Dependency gate (self) + +# This repository gates itself the way a consumer would, so the failure path is +# exercised for real rather than only in tests. tests/fixtures/Cargo.lock is the file +# under watch: adding a package to it must make this job fail until the deps-reviewed +# label is applied. +# +# pull_request_target runs this workflow from the base branch instead of from the pull +# request. Under pull_request it is the pull request's own copy that runs, so a pull +# request could empty the lockfiles input or make enforcement exit 0 in the same diff +# that adds a package. The usual pull_request_target hazard does not apply, because the +# pull request is never checked out: its lockfiles are read as bytes through the +# contents API at a pinned head SHA and parsed by the base branch's parser. +on: + pull_request_target: + types: [opened, synchronize, reopened, labeled, unlabeled] + +permissions: + contents: read + issues: write # label removal goes through the issues API + pull-requests: write + +jobs: + gate: + name: Dependency gate + runs-on: ubuntu-latest + steps: + # Checks out the base branch, which is what pull_request_target resolves to. + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + - uses: ./dependency-gate + with: + lockfiles: dependency-gate/tests/fixtures/Cargo.lock + require-pull-request-target: "true" diff --git a/.github/workflows/dependency-gate-test.yml b/.github/workflows/dependency-gate-test.yml new file mode 100644 index 0000000..e5c6f40 --- /dev/null +++ b/.github/workflows/dependency-gate-test.yml @@ -0,0 +1,150 @@ +name: Dependency gate tests + +on: + push: + branches: [master] + paths: + - "dependency-gate/**" + - ".github/workflows/dependency-gate-test.yml" + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + paths: + - "dependency-gate/**" + - ".github/workflows/dependency-gate-test.yml" + # Only the dogfood-prt job below uses this. Under pull_request_target the workflow, + # and `uses: ./`, both come from the base branch, so this exercises the base branch's + # action rather than the pull request's. That is the point of the mode. + pull_request_target: + types: [opened, synchronize, reopened, labeled, unlabeled] + paths: + - "dependency-gate/**" + - ".github/workflows/dependency-gate-test.yml" + +permissions: + contents: read + +jobs: + parser: + name: Parser tests + # Must run the pull request's own code, so not under pull_request_target. + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - run: python3 dependency-gate/tests/test_parser.py + + action-yml: + name: action.yml is valid + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Parse action.yml and check the declared contract + run: | + python3 - <<'PY' + import re + import yaml + d = yaml.safe_load(open("dependency-gate/action.yml")) + assert d["runs"]["using"] == "composite", d["runs"]["using"] + assert "lockfiles" in d["inputs"], "lockfiles input missing" + assert d["inputs"]["lockfiles"]["required"] is True + assert set(d["outputs"]) == {"count", "digest", "findings"}, set(d["outputs"]) + for step in d["runs"]["steps"]: + assert step.get("shell") == "bash", step.get("name") + # Every Actions expression must arrive through env:, never interpolated into + # a run: body, where a crafted value would be pasted straight into bash. + leaked = [ + (step["name"], m) + for step in d["runs"]["steps"] + for m in re.findall(r"\$\{\{[^}]*\}\}", step.get("run") or "") + ] + assert not leaked, f"expressions interpolated into run bodies: {leaked}" + print(f'ok: {len(d["runs"]["steps"])} composite steps, no leaked expressions') + PY + + shell: + name: Shellcheck the composite steps + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Extract each run block and shellcheck it + run: | + set -euo pipefail + python3 - <<'PY' + import pathlib, re, yaml + d = yaml.safe_load(open("dependency-gate/action.yml")) + out = pathlib.Path("shell-blocks"); out.mkdir(exist_ok=True) + for i, step in enumerate(d["runs"]["steps"]): + script = step.get("run") + if not script: + continue + # Actions expressions are substituted before bash sees them; replace + # them with a placeholder so shellcheck parses the real structure. + script = re.sub(r"\$\{\{[^}]*\}\}", "PLACEHOLDER", script) + (out / f"step{i}.sh").write_text("#!/usr/bin/env bash\n" + script) + PY + sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck + # SC2086 is noisy here: $LOCKFILES is intentionally word-split. + shellcheck --severity=warning --exclude=SC2086 shell-blocks/*.sh + + dogfood-pr: + name: Gate this repository with itself (pull_request mode) + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + pull-requests: write + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + - id: gate + uses: ./dependency-gate + with: + # The stable fixtures never change, so this job stays green. The gate's + # failure path is exercised by .github/workflows/dependency-gate.yml, which + # watches tests/fixtures/Cargo.lock. + lockfiles: dependency-gate/tests/fixtures/stable/Cargo.lock dependency-gate/tests/fixtures/stable/uv.lock + comment: "false" + - name: The stable fixtures are unchanged, so the count must be zero + env: + COUNT: ${{ steps.gate.outputs.count }} + DIGEST: ${{ steps.gate.outputs.digest }} + run: | + set -euo pipefail + test "$COUNT" = "0" || { echo "expected count=0, got '$COUNT'"; exit 1; } + test -n "$DIGEST" || { echo "expected a digest to be reported"; exit 1; } + echo "ok: count=$COUNT digest=$DIGEST" + + dogfood-prt: + name: Gate this repository with itself (pull_request_target mode) + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + pull-requests: write + steps: + # Checks out the base branch, which is what pull_request_target resolves to. The + # pull request's own files are never checked out; the gate reads its lockfiles + # through the contents API at a pinned head SHA. + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + - id: gate + uses: ./dependency-gate + with: + lockfiles: dependency-gate/tests/fixtures/stable/Cargo.lock dependency-gate/tests/fixtures/stable/uv.lock + comment: "false" + require-pull-request-target: "true" + - name: The stable fixtures are unchanged, so the count must be zero + env: + COUNT: ${{ steps.gate.outputs.count }} + DIGEST: ${{ steps.gate.outputs.digest }} + run: | + set -euo pipefail + test "$COUNT" = "0" || { echo "expected count=0, got '$COUNT'"; exit 1; } + test -n "$DIGEST" || { echo "expected a digest to be reported"; exit 1; } + echo "ok: count=$COUNT digest=$DIGEST" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..507767b --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +shell-blocks/ diff --git a/README.md b/README.md index 2bc0be0..33ca990 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,55 @@ jobs: Secrets: `build_secrets`, newline-separated `id=value` docker build secrets. +## `dependency-gate/` + +A composite action, not a reusable workflow — used as a step. It flags the +dependencies a pull request newly introduces, and existing ones it repoints at a +new source, then requires a `deps-reviewed` label before the PR can merge. The +sign-off is bound to the exact set of findings it was shown, so adding another +dependency afterwards re-opens the gate. + +Version bumps within the same source stay quiet; only new packages and changed +origins are reported. Supports `bun.lock`, `yarn.lock`, `pnpm-lock.yaml`, +`Cargo.lock` and `uv.lock`. + +The parser lives here rather than in the repo being gated, so a pull request +cannot weaken the check that is inspecting it. Callers run it under +`pull_request_target` and pass `require-pull-request-target: true`, which makes +the action fail loudly if that is ever downgraded. + +```yaml +on: + pull_request_target: + types: [opened, synchronize, reopened, labeled, unlabeled] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + new-dependency-gate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: velocity-exchange/shared-workflows/dependency-gate@ + with: + lockfiles: yarn.lock apps/foo/Cargo.lock + require-pull-request-target: true +``` + +| input | required | default | notes | +| --- | --- | --- | --- | +| `lockfiles` | yes | — | Space-separated, repo-relative lockfile paths | +| `label` | no | `deps-reviewed` | Label recording human sign-off | +| `comment` | no | `true` | Post/update a sticky comment listing findings | +| `require-pull-request-target` | no | `false` | Fail if not run under `pull_request_target` | + +Outputs: `count`, `digest`, `findings`. + ## `secret-scan-reusable.yml` Scans a pull request's own commits (`merge-base..head`) with TruffleHog. diff --git a/dependency-gate/README.md b/dependency-gate/README.md new file mode 100644 index 0000000..566b42a --- /dev/null +++ b/dependency-gate/README.md @@ -0,0 +1,294 @@ +# dependency-gate + +A composite GitHub Action that flags the dependencies a pull request newly introduces, +and the existing ones it repoints at a new source, then requires an explicit human +sign-off label before the pull request can merge. + +It answers one security question: *was the provenance of this package checked before it +became a dependency?* It does not judge whether a package is trustworthy. It makes a new +package, or a quietly redirected one, impossible to merge unnoticed, and records who +accepted it. + +## What v2 changes + +v1 compared package **names**. That left three holes, each now closed. + +1. **Source substitution.** Rewriting `"husky": ["husky@8.0.3"` to + `husky@https://attacker.invalid/evil.tgz` in a real `bun.lock` leaves the name list + byte-identical, 145 entries before and after, so v1 reported nothing. v2 compares + name **and source**. +2. **Stale sign-off.** v1 checked only that the label was currently present. Approving + package A therefore let package B merge unreviewed on a later push. v2 binds + sign-off to a digest of the exact finding set and drops the label when that digest + moves. +3. **Workflow tampering.** Under plain `pull_request` the pull request's own copy of the + workflow runs, so a pull request can empty the `lockfiles` input in the same diff + that adds a package. v2 supports `pull_request_target`, where the workflow comes from + the base branch. + +## Usage + +Two trigger modes are supported, and which one you can use depends on whether this +workflow already exists on your base branch. Start at step 1 and move to step 2. + +### Step 1: `pull_request`, to get the gate merged + +```yaml +name: Dependency gate + +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + gate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + - uses: velocity-exchange/dependency-gate@v2 + with: + lockfiles: bun.lock ui/bun.lock +``` + +`fetch-depth: 0` is required: the action compares against the base commit, which a +shallow clone does not contain. + +In this mode the action emits a `::warning::` on every run, because the workflow it is +running from is the pull request's own copy. That is not paranoia, it is the residual +hole from v1, and the warning is there to stop the mode becoming permanent. + +### Step 2: `pull_request_target`, once the workflow is on the base branch + +```yaml +on: + pull_request_target: + types: [opened, synchronize, reopened, labeled, unlabeled] + +# ... same permissions ... + +jobs: + gate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + - uses: velocity-exchange/dependency-gate@v2 + with: + lockfiles: bun.lock ui/bun.lock + require-pull-request-target: "true" +``` + +Set `require-pull-request-target: "true"` at the same time. It makes the action fail if +it is ever triggered by anything else, so the trigger cannot be quietly downgraded. + +**Why both modes exist.** Under `pull_request_target` the workflow is read from the base +branch, so a pull request that *introduces* the gate does not run it at all: there is no +gate on the base branch yet to run. Shipping `pull_request_target` alone would mean the +gate silently produces no check on exactly the pull request that adds it. So +`pull_request` is a first-class mode for bootstrapping, not a deprecated fallback. Merge +the workflow with `pull_request`, then switch the trigger. + +### Do not check out the pull request under `pull_request_target` + +Under `pull_request_target` the job runs with a writable token. The action is safe there +because the pull request's code is never checked out or executed: + +- `actions/checkout` with no `ref` gets the base branch. +- The action reads the pull request's lockfiles as **bytes** through the contents API at + the pinned `github.event.pull_request.head.sha`, and only ever parses them as text. +- The parser never installs, resolves, evaluates or reaches the network. + +If you add `ref: ${{ github.event.pull_request.head.sha }}` to that checkout, or run any +install step, you reintroduce the hazard this mode exists to avoid. + +### Inputs + +| Input | Default | Description | +| --- | --- | --- | +| `lockfiles` | required | Space-separated, repo-relative lockfile paths to watch. | +| `label` | `deps-reviewed` | Label recording sign-off on the reported findings. | +| `comment` | `true` | Post or update a sticky comment listing the findings. | +| `comment-author` | `github-actions[bot]` | Login that must have authored a comment for the sign-off marker inside it to be honoured. Change this only if `token` is not the default `GITHUB_TOKEN`, since the marker is then written under that token's identity. | +| `require-pull-request-target` | `false` | Fail unless the run was triggered by `pull_request_target`. | +| `token` | `github.token` | Token used to read the pull request and write the comment. | + +### Outputs + +| Output | Description | +| --- | --- | +| `count` | Number of findings. | +| `digest` | Digest of the finding set that sign-off is bound to. | +| `findings` | Tab-separated `lockfilechangenamesource` lines. | + +v1's `packages` output is gone; `findings` replaces it with a different shape. Anything +reading `packages` must be updated. + +### Required permissions + +```yaml +permissions: + contents: read # read the base branch and the head lockfiles + issues: write # delete a stale label, which goes through the issues API + pull-requests: write # post and update the sticky comment +``` + +`issues: write` is new in v2. Without it the action still enforces, but it cannot remove +a label that was applied for a different finding set, and it will say so as a warning +instead. Since a stale label does not grant sign-off either way, the gate stays correct +without the permission; it is just less tidy. + +## How sign-off works + +1. The action computes the findings and a digest over them. +2. If there are findings and the label is absent, the job fails. +3. Applying the label re-runs the workflow (hence the `labeled` trigger). The label was + applied for the set that run computes, so the run passes and records + `` in its own sticky comment. +4. On a later push the digest is recomputed. If it still matches the recorded one, the + sign-off stands. If it moved, the label is deleted and the job fails, so the new set + gets reviewed rather than inheriting the old approval. + +The digest is 24 hex characters, 96 bits, over the sorted finding set. Sorting makes it +independent of the order findings happen to be produced in. 96 bits is chosen so that +searching for a second finding set with an already-approved digest is not feasible, even +though package names can be picked freely. + +### What the marker does and does not protect + +The marker is only honoured on comments authored by `comment-author`, so nobody who can +merely comment on a pull request can forge a sign-off. In particular a pull request from +a fork cannot: its `GITHUB_TOKEN` is read-only, so it cannot post as the bot at all. + +Be clear about the limit, though. Anyone who can make *any* workflow in the repository +comment with `GITHUB_TOKEN` can write a comment carrying the marker, so a same-repository +pull request that adds a workflow of its own could record a digest the gate would later +honour. That grants no new capability: applying the label already requires write or +triage access, and anyone with that can simply apply it. The marker guards against +outside comments, not against people who could approve anyway. Closing it needs the same +repository configuration as the point below. + +## What cannot be closed from inside a workflow + +Two gaps remain, and both need repository configuration rather than code: + +- **Require the check.** Nothing here stops a pull request deleting its own workflow + file, or, under `pull_request`, editing it. Require this job through a branch ruleset, + so a missing check blocks the merge instead of reading as a pass. This also pins the + check to a head SHA, which is what stops a pull request being merged with a newer, + ungated head. +- **Own `.github/**`.** Add a CODEOWNERS entry for `.github/**` so workflow changes need + a review from someone who is not the author. This is also what closes the marker + caveat above, since it stops a pull request adding a workflow that comments as the bot. + +Neither can be asserted by the action. If your repository has not set both up, this gate +is a strong speed bump, not a wall. + +## What counts as a changed source + +A finding is `new` when the package name is absent from the base lockfile, and `source` +when the name is already there but is fetched from somewhere new. + +"Source" means the **origin of the bytes**, not their content: + +- A registry download collapses to the registry's base URL, so **an ordinary version + bump produces no finding**. +- Any change of **protocol, host or path** produces a finding: a tarball URL, a git + remote, a local `file:`/`link:` path, an `npm:` alias to a different package, or a + different registry. +- The **resolved** revision is dropped, and only the resolved one. A git dependency on + `?branch=main` stays quiet as the branch advances, because nothing the repository asked + for changed. Repointing it at `?rev=` is reported, because someone chose a + different commit deliberately. + +Registries are recognised **structurally**, by the `/-/` download path every +npm-compatible registry serves, not by a list of known hostnames. A hostname allowlist +would classify every entry in a repository installing from Artifactory, GitHub Packages +or Verdaccio as a non-registry source, so every routine bump would raise a finding. A +gate that cries wolf on every bump gets its label applied without being read, which is a +worse failure than the one it was protecting against. + +Known limits, stated rather than hidden: + +- A new release from the same registry, or a new commit on the same branch, is out of + scope by design. This gate reports a change of origin, not a change of content. +- `pnpm-lock.yaml` records no per-package registry in v9, so a registry swap made only in + `.npmrc` is invisible here. Tarball and git overrides in a `resolution:` block *are* + read. + +## Supported lockfiles + +`bun.lock`, `yarn.lock` (v1 classic and berry), `pnpm-lock.yaml`, `Cargo.lock`, `uv.lock`. + +Files are dispatched by filename, so the path may be nested but the basename must be one +of the above. `bun.lockb` is bun's binary format and is not supported; convert it to the +text `bun.lock` format to gate it. + +`bun.lock` is parsed as the JSONC document bun itself reads, rather than scanned line by +line, so reformatting the file cannot hide an entry from a line-anchored pattern. + +An unparseable lockfile is a hard error. This runs as a merge gate, and "unparseable" +must never be read as "nothing was added". + +The parser reads text only. It never installs, resolves, or reaches the network, so it is +safe to run against a lockfile from an untrusted pull request. + +## Why the parser lives here + +The obvious implementation puts the script in each repository, next to the workflow. That +has a hole: on a `pull_request` event the workflow runs against the merge commit, so the +script is the pull request's own copy. A pull request can add a dependency and edit the +script meant to report it, in one diff, and the check passes. + +Shipping the parser inside the action removes it from that editable surface. Callers +reference it by tag or commit SHA, and the code that runs is the code in this repository. + +## Behaviour outside a pull request + +On a `push` event, or any other event, the action reports to the job summary and never +fails, since there is nothing to label. This is useful where an automation commits +dependency bumps straight to a branch, so the change is at least recorded. A push with no +predecessor (a new branch, a first push, a force push) has nothing to compare against and +is skipped. + +## Fork pull requests + +A pull request from a fork gets a read-only token, so commenting fails. The action +downgrades that to a warning and still enforces the label, rather than aborting before +the check it exists to perform. + +## Requirements + +`bash`, `python3`, `jq` and `gh`, all present on GitHub-hosted Linux and macOS runners. +Windows runners are not supported. + +Under `pull_request_target` the action lists the head tree in one API call. If that +listing comes back truncated, which needs a very large repository, the job fails rather +than guess which lockfiles exist. + +## Development + +```bash +python3 tests/test_parser.py +``` + +No third-party packages. A dependency gate that needed its own dependency tree would be a +poor advertisement for itself. + +The tests are the specification for what "source" means. Two cases matter most and are +asserted directly: an ordinary registry version bump produces no finding, and a change of +protocol, host or path does. When changing the parser, add a case first. Every consumer +repository pins this action, so a defect here reaches all of them at once. + +This repository also gates itself. `.github/workflows/dependency-gate.yml` watches +`tests/fixtures/Cargo.lock` under `pull_request_target`, so the failure path runs for +real on any pull request that touches it. The dogfood jobs in `test.yml` watch the +never-changing fixtures under `tests/fixtures/stable/` and assert a zero count in both +trigger modes. diff --git a/dependency-gate/action.yml b/dependency-gate/action.yml new file mode 100644 index 0000000..479dd18 --- /dev/null +++ b/dependency-gate/action.yml @@ -0,0 +1,421 @@ +name: Dependency gate +description: > + Flag the dependencies a pull request newly introduces, and the existing ones it + repoints at a new source, then require an explicit human sign-off label before it + can merge. Sign-off is bound to the exact set of findings it was given for. +author: velocity-exchange + +branding: + icon: package + color: green + +inputs: + lockfiles: + description: > + Space-separated, repo-relative lockfile paths to watch. Supported names: + bun.lock, yarn.lock, pnpm-lock.yaml, Cargo.lock, uv.lock. + required: true + label: + description: Label that records human sign-off on the reported findings. + required: false + default: deps-reviewed + comment: + description: Post or update a sticky comment listing the findings. + required: false + default: "true" + comment-author: + description: > + Login that must have authored a comment for the sign-off marker inside it to be + honoured. Change this only if `token` is not the default GITHUB_TOKEN, because + the marker is then written under that token's own identity. + required: false + default: github-actions[bot] + require-pull-request-target: + description: > + Fail the run unless it was triggered by `pull_request_target`. Set this once the + workflow exists on the base branch, so nobody can quietly downgrade the trigger. + required: false + default: "false" + token: + description: Token used to read the pull request and write the sticky comment. + required: false + default: ${{ github.token }} + +outputs: + count: + description: Number of findings. + value: ${{ steps.collect.outputs.count }} + digest: + description: Digest of the finding set that sign-off is bound to. + value: ${{ steps.collect.outputs.digest }} + findings: + description: > + Tab-separated "lockfilechangenamesource" lines, where change is + `new` or `source`. + value: ${{ steps.collect.outputs.findings }} + +runs: + using: composite + steps: + # The parser lives inside this action rather than in the calling repository, so a + # pull request cannot weaken the check that is inspecting it. + - name: Work out the trigger mode and the base revision + id: resolve + shell: bash + env: + EVENT: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PUSH_BEFORE: ${{ github.event.before }} + REQUIRE_PRT: ${{ inputs.require-pull-request-target }} + run: | + set -euo pipefail + resolve() { git rev-parse --verify --quiet "$1^{commit}"; } + + # prt: the workflow comes from the base branch and the pull request's files are + # never checked out. This is the mode to run in. + # pr: the workflow is the pull request's own copy, so it can be edited in the + # same diff it is meant to gate. Supported because a pull request that + # *introduces* the gate cannot run under pull_request_target at all. + # other: a push or anything else. Reported, never enforced. + case "$EVENT" in + pull_request_target) mode="prt" ;; + pull_request) mode="pr" ;; + *) mode="other" ;; + esac + echo "mode=$mode" >> "$GITHUB_OUTPUT" + + if [ "$REQUIRE_PRT" = "true" ] && [ "$mode" != "prt" ]; then + echo "::error::require-pull-request-target is set, but this run was triggered by '$EVENT'." + exit 1 + fi + + if [ "$mode" = "pr" ]; then + echo "::warning::Triggered by 'pull_request', so this workflow file is the pull request's own copy and the pull request can edit or delete its own gate. Switch the trigger to 'pull_request_target' once this workflow exists on the base branch." + fi + + if [ "$mode" = "prt" ]; then + if ! [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Expected a 40-character head SHA in the event payload, got '$HEAD_SHA'." + exit 1 + fi + fi + + base="" + case "$mode" in + prt) + # Every candidate here is base-branch content. The last one is the tip of + # the base branch, which is what actions/checkout leaves in the tree under + # pull_request_target, so a default shallow checkout still works. + base=$(resolve "$BASE_SHA" || resolve "origin/$GITHUB_BASE_REF" || resolve HEAD || true) + ;; + pr) + # Not HEAD here: under pull_request that is the merge commit, which + # contains the pull request's own changes. + base=$(resolve "$BASE_SHA" || resolve "origin/$GITHUB_BASE_REF" || true) + ;; + *) + if [ -n "${PUSH_BEFORE:-}" ] && [ "$PUSH_BEFORE" != "0000000000000000000000000000000000000000" ]; then + base=$(resolve "$PUSH_BEFORE" || true) + fi + ;; + esac + + if [ -z "$base" ]; then + if [ "$mode" != "other" ]; then + # On a pull request the base is always knowable, so this is a + # misconfiguration and must not pass quietly. + echo "::error::Could not resolve the base revision. Check out the repository before this action, with 'fetch-depth: 0' so the base commit is present." + exit 1 + fi + # Elsewhere there may genuinely be no predecessor: a new branch, a first + # push, or a force push. Nothing to diff against, so skip. + echo "skip=true" >> "$GITHUB_OUTPUT" + echo "No base revision to compare against; skipping." + exit 0 + fi + echo "base=$base" >> "$GITHUB_OUTPUT" + echo "Mode $mode, comparing against $base" + + - name: Collect new packages and changed sources + id: collect + if: steps.resolve.outputs.skip != 'true' + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + REPO: ${{ github.repository }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + LOCKFILES: ${{ inputs.lockfiles }} + MODE: ${{ steps.resolve.outputs.mode }} + BASE: ${{ steps.resolve.outputs.base }} + run: | + set -euo pipefail + parser="$GITHUB_ACTION_PATH/lockfile_packages.py" + work=$(mktemp -d) + : > "$work/findings.tsv" + + if [ "$MODE" = "prt" ]; then + # One authoritative listing of the head tree. A "Not Found" on an individual + # file cannot be used to skip it: a wrong SHA, a revoked token and a genuinely + # absent path all look alike, and reading any of them as "nothing was added" + # would open the gate. So existence is decided here, once, and anything wrong + # with this listing fails the job. + if ! gh api "repos/$REPO/git/trees/$HEAD_SHA?recursive=1" > "$work/tree.json"; then + echo "::error::Could not list the head tree at $HEAD_SHA. The token needs 'contents: read', and the head commit must be reachable from this repository. Refusing to continue, because an unreadable listing must not be read as 'nothing was added'." + exit 1 + fi + if [ "$(jq -r '.truncated' "$work/tree.json")" != "false" ]; then + echo "::error::The head tree listing was truncated, so which lockfiles exist cannot be established." + exit 1 + fi + jq -r '.tree[] | select(.type == "blob") | .path' "$work/tree.json" > "$work/head-paths.txt" + fi + + seen=0 + for lock in $LOCKFILES; do + case "$lock" in + -*|/*|*..*) + echo "::error::Refusing the lockfile path '$lock': it must be repo-relative and must not escape the repository." + exit 1 ;; + esac + + head_copy="" + if [ "$MODE" = "prt" ]; then + if grep -qxF "$lock" "$work/head-paths.txt"; then + mkdir -p "$work/head/$(dirname "$lock")" + # Read as bytes at a pinned SHA. None of the pull request's commits enter + # the checkout, so there is nothing of the pull request's to execute. + # The tree listing above already said this path exists, so a failure here + # is a real problem and never an absent file. + if ! gh api "repos/$REPO/contents/$lock?ref=$HEAD_SHA" \ + -H "Accept: application/vnd.github.raw" > "$work/head/$lock"; then + echo "::error::Could not read '$lock' at $HEAD_SHA even though the head tree lists it. Refusing to treat that as 'nothing was added'." + exit 1 + fi + head_copy="$work/head/$lock" + fi + elif [ -f "$lock" ]; then + head_copy="$lock" + fi + + # The parser treats a path that does not exist as "added by this change, so + # everything in it is new". An empty file is not the same thing and would be a + # parse error, so remove the file git show may have half-written. + mkdir -p "$work/base/$(dirname "$lock")" + git show "$BASE:$lock" > "$work/base/$lock" 2>/dev/null || rm -f "$work/base/$lock" + + if [ -z "$head_copy" ] && [ ! -f "$work/base/$lock" ]; then + echo "::warning::Watched lockfile '$lock' exists at neither the base nor the head; skipping." + continue + fi + seen=$((seen + 1)) + if [ -z "$head_copy" ]; then + echo "::warning::Watched lockfile '$lock' is deleted by this change; nothing to compare." + continue + fi + + # Package names travel by file, never on a command line, so ENVIRON is used + # rather than an -v assignment, which would interpret backslash escapes. + python3 "$parser" "$work/base/$lock" "$head_copy" \ + | LOCK="$lock" awk '{ print ENVIRON["LOCK"] "\t" $0 }' >> "$work/findings.tsv" + done + + if [ "$seen" -eq 0 ]; then + echo "::error::None of the watched lockfiles exist at the base or the head. Check the 'lockfiles' input." + exit 1 + fi + + count=$(wc -l < "$work/findings.tsv" | tr -d ' ') + # Sign-off is bound to this digest, so adding to the finding set later + # invalidates it. Computed by the parser so ordering and locale cannot affect it. + digest=$(python3 "$parser" --digest "$work/findings.tsv") + + echo "count=$count" >> "$GITHUB_OUTPUT" + echo "digest=$digest" >> "$GITHUB_OUTPUT" + echo "tsv=$work/findings.tsv" >> "$GITHUB_OUTPUT" + # Every finding line contains three tab characters, so no finding can ever be + # mistaken for this delimiter. + { + echo "findings<<__FINDINGS_EOF__" + cat "$work/findings.tsv" + echo "__FINDINGS_EOF__" + } >> "$GITHUB_OUTPUT" + echo "Findings: $count (digest $digest)" + cat "$work/findings.tsv" + + - name: Read the sign-off recorded in the gate's own comment + id: signoff + if: steps.resolve.outputs.skip != 'true' && steps.resolve.outputs.mode != 'other' + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + AUTHOR: ${{ inputs.comment-author }} + MARKER: "" + run: | + set -euo pipefail + # Only comments the gate itself wrote can carry sign-off. Anyone able to comment + # on the pull request could otherwise paste the marker and forge one. + if ! [[ "$AUTHOR" =~ ^[A-Za-z0-9._-]+(\[bot\])?$ ]]; then + echo "::error::comment-author '$AUTHOR' is not a plausible login." + exit 1 + fi + + work=$(mktemp -d) + : > "$work/comments.ndjson" + # One object per line across every page, so the newest matching comment in the + # whole thread is found rather than the newest on some single page. + gh api --paginate "repos/$REPO/issues/$PR/comments" --jq '.[]' \ + > "$work/comments.ndjson" 2>/dev/null \ + || echo "::warning::Could not read the pull request comments; treating sign-off as unrecorded." + + # --arg, so neither the login nor the marker is ever interpolated into the filter. + row=$(jq -rs --arg author "$AUTHOR" --arg marker "$MARKER" ' + [ .[] + | select(.user.login == $author) + | select((.body // "") | contains($marker)) + ] | last + | if . == null then "\t" + else "\(.id)\t\((([ (.body // "") | scan("") ] + | flatten | first) // ""))" + end' "$work/comments.ndjson") + + id=${row%%$'\t'*} + approved=${row#*$'\t'} + [[ "$id" =~ ^[0-9]*$ ]] || id="" + [[ "$approved" =~ ^[0-9a-f]*$ ]] || approved="" + echo "id=$id" >> "$GITHUB_OUTPUT" + echo "approved=$approved" >> "$GITHUB_OUTPUT" + echo "Gate comment: ${id:-none}, recorded sign-off: ${approved:-none}" + + - name: Report and enforce + if: steps.resolve.outputs.skip != 'true' + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + MODE: ${{ steps.resolve.outputs.mode }} + COUNT: ${{ steps.collect.outputs.count }} + DIGEST: ${{ steps.collect.outputs.digest }} + TSV: ${{ steps.collect.outputs.tsv }} + COMMENT_ID: ${{ steps.signoff.outputs.id }} + APPROVED_DIGEST: ${{ steps.signoff.outputs.approved }} + LABEL: ${{ inputs.label }} + WANT_COMMENT: ${{ inputs.comment }} + EVENT_ACTION: ${{ github.event.action }} + LABEL_CHANGED: ${{ github.event.label.name }} + LABELS_JSON: ${{ toJson(github.event.pull_request.labels.*.name) }} + MARKER: "" + run: | + set -euo pipefail + + label_present=false + approved=false + + if [ "$MODE" != "other" ] && [ "$COUNT" -gt 0 ]; then + # The event payload's label list is a snapshot from when the run started, so + # ask the API. Falling back to the payload beats treating a failed read as + # "no label", which would make the gate unsatisfiable. + labels=$(gh api --paginate "repos/$REPO/issues/$PR/labels" --jq '.[].name' 2>/dev/null) || { + echo "::warning::Could not read labels from the API; falling back to the event payload." + labels=$(printf '%s' "$LABELS_JSON" | jq -r '.[]?') + } + if printf '%s\n' "$labels" | grep -Fxq "$LABEL"; then + label_present=true + fi + fi + + if [ "$label_present" = true ]; then + if [ "$EVENT_ACTION" = "labeled" ] && [ "$LABEL_CHANGED" = "$LABEL" ]; then + # Applied by the event that triggered this run, so it signs off the findings + # this run has just computed. + approved=true + elif [ -n "$APPROVED_DIGEST" ] && [ "$APPROVED_DIGEST" = "$DIGEST" ]; then + approved=true + else + # The label was applied for a different set of findings. Drop it, so the + # current set gets reviewed instead of inheriting the earlier sign-off. + echo "::warning::'$LABEL' was applied for a different set of findings; review the current set and apply it again." + label_path=$(jq -rn --arg name "$LABEL" '$name|@uri') + gh api --method DELETE "repos/$REPO/issues/$PR/labels/$label_path" --silent \ + || echo "::warning::Could not remove the stale '$LABEL' label. It does not grant sign-off either way." + fi + fi + + # Package names and sources reach markdown only through this file, and are HTML + # escaped on the way, so a crafted name cannot break out of its table cell or + # forge the approval marker above. + body=$(mktemp) + { + echo "$MARKER" + if [ "$approved" = true ]; then + echo "" + fi + if [ "$COUNT" -eq 0 ]; then + echo "### No new dependencies" + echo + echo "Every package in the watched lockfiles was already on the base branch, from the same source." + else + echo "### New dependencies in this pull request" + echo + echo "This pull request adds packages, or changes where existing packages are" + echo "fetched from. Confirm each one's **source, maintainer and integrity**, then" + echo "apply the \`$LABEL\` label to merge." + echo + echo '| Lockfile | Change | Package | Source |' + echo '| --- | --- | --- | --- |' + awk -F'\t' ' + function esc(s) { + gsub(/&/, "\\&", s); gsub(//, "\\>", s) + gsub(/\|/, "\\|", s); gsub(/`/, "\\`", s) + return s + } + { change = ($2 == "new") ? "new package" : "**source changed**" + print "| " esc($1) " | " change \ + " | " esc($3) " | " esc($4) " |" } + ' "$TSV" + echo + echo "Sign-off covers exactly this set (digest \`$DIGEST\`). Adding to it" + echo "afterwards drops the label and needs a fresh review." + if [ "$MODE" = "pr" ]; then + echo + echo "> Produced by a \`pull_request\` run, so this gate's own workflow came from" + echo "> the pull request. Prefer \`pull_request_target\`." + fi + fi + } > "$body" + + cat "$body" >> "$GITHUB_STEP_SUMMARY" + + # Outside a pull request there is nothing to label or comment on, so record the + # result and never fail the run. + if [ "$MODE" = "other" ]; then + echo "Not a pull request; reported to the job summary only." + exit 0 + fi + + if [ "$WANT_COMMENT" = "true" ] && { [ "$COUNT" -gt 0 ] || [ -n "$COMMENT_ID" ]; }; then + # A pull request from a fork gets a read-only token, so commenting can fail. + # That must not stop the enforcement below from running. + if [ -n "$COMMENT_ID" ]; then + gh api --method PATCH "repos/$REPO/issues/comments/$COMMENT_ID" -F body=@"$body" --silent \ + || echo "::warning::Could not update the gate comment; still enforcing." + else + gh api --method POST "repos/$REPO/issues/$PR/comments" -F body=@"$body" --silent \ + || echo "::warning::Could not post the gate comment; still enforcing." + fi + fi + + if [ "$COUNT" -eq 0 ]; then + echo "No new dependencies and no changed sources." + exit 0 + fi + + if [ "$approved" = true ]; then + echo "::notice::$COUNT finding(s), signed off via the '$LABEL' label (digest $DIGEST)." + else + echo "::error::$COUNT finding(s) need review. Check each package's source, then apply the '$LABEL' label." + exit 1 + fi diff --git a/dependency-gate/lockfile_packages.py b/dependency-gate/lockfile_packages.py new file mode 100644 index 0000000..c4b2a25 --- /dev/null +++ b/dependency-gate/lockfile_packages.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""Print the packages a lockfile records, together with where each is fetched from. + +Supports bun.lock, yarn.lock (v1 classic and berry), pnpm-lock.yaml, Cargo.lock and +uv.lock. Parses text only: never installs, never resolves, never reaches the network, +so it is safe to run against a lockfile taken from an untrusted pull request. + + lockfile_packages.py "\\t", one line per source + lockfile_packages.py what adds, one finding per line: + new the name is absent from the base lockfile + source the name is present, but fetched from somewhere new + lockfile_packages.py --digest sign-off digest of a findings file + +Why the source is compared and not just the name +------------------------------------------------ +Comparing names alone is not enough. Repointing an existing package at a tarball, a +git remote, a local path or a different registry leaves its name untouched, so a +name-only diff reports nothing while the bytes that get installed change completely. + +What "source" means here is deliberately narrow: it is the *origin* of the bytes, not +their content. A download from a registry collapses to that registry's base, with the +package version dropped, so an ordinary version bump is silent. Any change of +protocol, host or path is reported. + +The *resolved* revision is dropped too, and only the resolved one: a URL "#fragment", +which is where a lockfile records the commit it settled on. What a dependency declares +it wants is kept. For a git dependency that means "git+https://host/repo?branch=main" +stays silent as the branch advances, because nothing the repository asked for changed, +while repointing it at "?rev=" is reported, because someone deliberately +chose a different commit. That is the split worth having: the mechanical bump is quiet +and the deliberate change is surfaced. + +Registry downloads are recognised structurally, by the "/-/" path layout +that every npm-compatible registry serves, rather than by matching a list of known +hostnames. A hostname allowlist would classify every single entry in a repository that +installs from a private registry (Artifactory, GitHub Packages, Verdaccio) as a +non-registry source, so every routine version bump would raise a finding. A gate that +cries wolf on every bump gets its label applied without being read. + +The deliberate limit of all this: the gate reports a change of origin, not a change of +content within one origin. A new release from the same registry, or a new commit on +the same git remote, is out of scope by design, and the same boundary is applied on +every side so the behaviour is predictable. + +A lockfile that cannot be parsed is a hard error, never an empty result. This runs as +a merge gate, and "unparseable" must never be read as "nothing was added". +""" + +import hashlib +import json +import re +import sys +from pathlib import Path + +DEFAULT_REGISTRY = "registry:default" + +# How many hex characters of the sha256 the sign-off digest keeps. Sign-off is bound to +# this value, so it has to survive a second-preimage search by someone who can pick +# package names freely; 96 bits does, and stays short enough to read in a comment. +DIGEST_LENGTH = 24 + +_PROTOCOLS = ( + "npm", "patch", "workspace", "file", "link", "portal", "git", r"git\+[a-z]+", + "https?", "ssh", "exec", "virtual", "alias", "github", +) +# A locator's protocol, as in "pkg@npm:..." or "pkg@patch:...". +_PROTOCOL = re.compile(r"@(?:" + "|".join(_PROTOCOLS) + r"):") +# A reference starting with one of these is not a plain registry version. +_REF_PROTOCOL = re.compile(r"^(?:" + "|".join(_PROTOCOLS) + r"):") +# A semver, or a range that resolves to one. Anything else after "npm:" names a +# different package, which makes it an alias. +_VERSIONISH = re.compile(r"^[\^~><=v\s]*\d") +# The download path every npm-compatible registry serves: "//-/". +# The captured base is the registry, so the version in the filename drops out. +_REGISTRY_PATH = re.compile(r"^(.*?)/(?:@[^/]+/)?[^/]+/-/[^/]+$") +# Package names and sources are attacker-controlled text that ends up in a +# tab-separated record. A tab or a newline inside one would forge or split a finding. +_UNSAFE = re.compile(r"[\x00-\x1f\x7f]") + + +def _clean(value): + """Keep one finding on one line, whatever the lockfile put in the name.""" + return _UNSAFE.sub(lambda m: "\\x%02x" % ord(m.group()), value) + + +def split_name(spec): + """'@scope/pkg@1.2.3' -> '@scope/pkg'; 'pkg@npm:@other/pkg@^1' -> 'pkg'.""" + spec = spec.split("(", 1)[0] # drop a pnpm peer suffix + proto = _PROTOCOL.search(spec) + if proto and proto.start() > 0: + return spec[: proto.start()] + at = spec.rfind("@") + return spec[:at] if at > 0 else spec + + +def split_ref(locator): + """'@scope/pkg@1.2.3' -> ('@scope/pkg', '1.2.3').""" + name = split_name(locator) + rest = locator[len(name):] + return name, rest[1:] if rest.startswith("@") else "" + + +def _registry(base): + return f"registry:{base.rstrip('/')}" if base else DEFAULT_REGISTRY + + +def source_of(ref, registry=""): + """Classify where a package is fetched from, ignoring its version.""" + if ref.startswith("npm:"): + target = ref[4:] + # An ordinary registry dependency is written "pkg@npm:1.2.3"; an alias names a + # different package instead, as in "pkg@npm:other-pkg@1.2.3". + if _VERSIONISH.match(target): + return _registry(registry) + return f"npm-alias:{split_name(target)}" + if _REF_PROTOCOL.match(ref): + if ref.startswith(("http://", "https://")): + return source_of_url(ref) + return ref.split("#", 1)[0] + return _registry(registry) + + +def source_of_url(url): + """Classify a download URL: a registry download collapses to the registry base.""" + url = url.split("#", 1)[0] + match = _REGISTRY_PATH.match(url) + return _registry(match.group(1)) if match else url + + +def _put(out, name, source): + out.setdefault(_clean(name), set()).add(_clean(source)) + + +def _add(out, locator, registry="", source=None): + name, ref = split_ref(locator) + _put(out, name, source if source is not None else source_of(ref, registry)) + + +def _strip_jsonc(text): + """Drop comments and trailing commas so json can load a JSONC document.""" + out = [] + i, n = 0, len(text) + while i < n: + char = text[i] + if char == '"': + j = i + 1 + while j < n: + if text[j] == "\\": + j += 2 + continue + if text[j] == '"': + break + j += 1 + out.append(text[i:j + 1]) + i = j + 1 + elif char == "/" and i + 1 < n and text[i + 1] in "/*": + if text[i + 1] == "/": + end = text.find("\n", i) + else: + end = text.find("*/", i + 2) + end = -1 if end == -1 else end + 2 + i = n if end == -1 else end + elif char == ",": + j = i + 1 + while j < n and text[j].isspace(): + j += 1 + if not (j < n and text[j] in "]}"): + out.append(char) + i += 1 + else: + out.append(char) + i += 1 + return "".join(out) + + +def bun(text, path=""): + """bun.lock: "packages": { "": ["@", "", {...}, ""] } + + Parsed as the JSONC document bun itself reads, not scanned line by line, so what + the gate sees is what bun installs: reformatting the file to hide an entry from a + line-anchored pattern cannot work. The key is not always the package name (a + hoisted duplicate gets a compound key such as "anchor-bankrun/@coral-xyz/anchor"), + so the name comes from the array's own first element. The registry slot is empty + for the default registry, and absent for non-registry sources where the protocol + in the locator already identifies the origin. + """ + data = json.loads(_strip_jsonc(text)) + if not isinstance(data, dict): + sys.exit(f"{path}: top level is not an object") + packages = data.get("packages", {}) + if not isinstance(packages, dict): + sys.exit(f"{path}: 'packages' is not an object") + out = {} + for key, entry in packages.items(): + if not isinstance(entry, list) or not entry or not isinstance(entry[0], str): + sys.exit(f"{path}: unexpected entry for {key!r}: {entry!r}") + registry = entry[1] if len(entry) > 1 and isinstance(entry[1], str) else "" + _add(out, entry[0], registry) + # A lockfile recording no packages while its workspaces still declare some is not + # an empty project, it is a lockfile that has been emptied. + declared = _bun_declared(data) + if declared and not out: + sys.exit(f"{path}: workspaces declare {declared} dependencies " + f"but no packages are recorded") + return out + + +def _bun_declared(data): + total = 0 + workspaces = data.get("workspaces") + if isinstance(workspaces, dict): + for workspace in workspaces.values(): + if not isinstance(workspace, dict): + continue + for field in ("dependencies", "devDependencies", + "optionalDependencies", "peerDependencies"): + block = workspace.get(field) + if isinstance(block, dict): + total += len(block) + return total + + +def yarn(text, path=""): + out = {} + if "__metadata:" in text: # berry, v2 and later + for match in re.finditer(r'^\s+resolution:\s*"([^"]+)"', text, re.M): + _add(out, match.group(1)) + if not out: + sys.exit(f"{path}: berry lockfile with no resolution entries") + return out + + # v1 classic: comma-separated descriptor headers, then a "resolved" download URL. + # A header carries a range rather than a version, so where a registry entry really + # comes from is only visible in the URL. The range-derived value is a placeholder + # that keeps the name recorded even if the URL is missing, and is replaced once the + # URL is read so a single entry does not report two sources. + descriptors = [] + placeholders = set() + for line in text.splitlines(): + stripped = line.strip() + if line and not line[0].isspace() and not stripped.startswith("#") \ + and stripped.endswith(":"): + descriptors = [s.strip().strip('"') for s in stripped[:-1].split(", ") if s.strip()] + for spec in descriptors: + name, ref = split_ref(spec) + if _REF_PROTOCOL.match(ref): + _put(out, name, source_of(ref)) + else: + _put(out, name, DEFAULT_REGISTRY) + placeholders.add(_clean(name)) + elif stripped.startswith("resolved "): + url = stripped.split(" ", 1)[1].strip().strip('"') + for spec in descriptors: + name, ref = split_ref(spec) + if _REF_PROTOCOL.match(ref): + continue # a protocol descriptor is already its own source + name = _clean(name) + if name in placeholders: + out[name].discard(DEFAULT_REGISTRY) + placeholders.discard(name) + _put(out, name, source_of_url(url)) + if not out and text.strip() and "yarn lockfile" not in text: + sys.exit(f"{path}: no entries and no yarn lockfile header") + return out + + +def pnpm(text, path=""): + """pnpm v9 "packages:"/"snapshots:" keys, plus the legacy v5/v6 slash form. + + The key carries a non-registry spec verbatim ("pkg@https://host/x.tgz"), and the + resolution block beneath it records a tarball or git override that the key does + not always show, so both are read. + """ + if "lockfileVersion" not in text: + sys.exit(f"{path}: no 'lockfileVersion' key; not a pnpm-lock.yaml") + out = {} + lines = text.splitlines() + for index, line in enumerate(lines): + # The legacy v5/v6 form is checked first: "/@scope/pkg/1.2.3" also matches the + # v9 pattern below, where it would parse as a locator whose name is "/". + legacy = re.match(r"^ /((?:@[^/\s]+/)?[^/\s]+)/\d", line) + if legacy: + _put(out, legacy.group(1), _pnpm_resolution(lines, index) or DEFAULT_REGISTRY) + continue + entry = re.match(r"^ '?([^'\s:][^'\s]*?)'?:\s*$", line) + if entry: + spec = entry.group(1) + if spec.startswith("/") or "@" not in spec.lstrip("@"): + continue + name, ref = split_ref(spec) + _put(out, name, _pnpm_resolution(lines, index) or source_of(ref)) + return out + + +def _pnpm_resolution(lines, start): + """Read the resolution block belonging to the entry starting at `start`.""" + for line in lines[start + 1:start + 8]: + if line.strip() and not line.startswith(" "): + break # left this entry's block + block = re.match(r"^\s+resolution:\s*\{(.*)\}\s*$", line) + if not block: + continue + fields = {k: v.strip().strip("'\"") + for k, v in re.findall(r"([\w-]+):\s*([^,}]+)", block.group(1))} + if "tarball" in fields: + return source_of_url(fields["tarball"]) + if fields.get("type") == "git": + return "git:" + fields.get("repo", "unknown").split("#", 1)[0] + if "directory" in fields: + return "directory:" + fields["directory"] + if "integrity" in fields: + return DEFAULT_REGISTRY + return None + + +def _toml_blocks(text, path, kind): + """Yield (name, block) for each [[package]] in a Cargo.lock or uv.lock.""" + if "[[package]]" not in text: + if re.search(r"^version = \d+\s*$", text, re.M): + return # a well-formed lockfile that records no packages + sys.exit(f"{path}: no [[package]] block and no version header; not a {kind}") + for block in text.split("[[package]]")[1:]: + # Stop at the next table header so a [package.metadata] section, whose + # requires-dist entries also mention names, cannot be read as this package. + block = re.split(r"\n(?=\[)", block, maxsplit=1)[0] + name = re.search(r'^name = "([^"]+)"$', block, re.M) + if name is None: + sys.exit(f"{path}: a [[package]] block records no name") + yield name.group(1), block + + +def cargo(text, path=""): + out = {} + for name, block in _toml_blocks(text, path, "Cargo.lock"): + source = re.search(r'^source = "([^"]+)"$', block, re.M) + # No source line means a path dependency inside this workspace. + _put(out, name, source.group(1).split("#", 1)[0] if source else "path") + return out + + +# uv records the source as an inline table: { registry = "..." }, { git = "..." }, +# { url = "..." }, { path = "..." }, { editable = "..." } or { virtual = "..." }. +_UV_SOURCE = re.compile(r'^source = \{\s*([\w-]+)\s*=\s*"([^"]*)"', re.M) + + +def uv(text, path=""): + out = {} + for name, block in _toml_blocks(text, path, "uv.lock"): + source = _UV_SOURCE.search(block) + if source is None: + # uv always writes a source. Naming the gap is better than assuming one, + # because a source that later appears will then read as a change. + _put(out, name, "unspecified") + continue + kind, value = source.group(1), source.group(2).split("#", 1)[0] + _put(out, name, _registry(value) if kind == "registry" else f"{kind}:{value}") + return out + + +PARSERS = { + "bun.lock": bun, + "yarn.lock": yarn, + "pnpm-lock.yaml": pnpm, + "Cargo.lock": cargo, + "uv.lock": uv, +} + +SUPPORTED = ", ".join(sorted(PARSERS)) + + +def extract(path): + """Map every package name in `path` to the set of sources it is fetched from.""" + lockfile = Path(path) + parser = PARSERS.get(lockfile.name) + if parser is None: + sys.exit(f"unsupported lockfile: {lockfile.name} (supported: {SUPPORTED})") + if not lockfile.exists(): # added by this change, so everything in it is new + return {} + text = lockfile.read_text(encoding="utf-8", errors="replace") + try: + return parser(text, str(lockfile)) + except SystemExit: + raise + except Exception as exc: # a crash must never read as "nothing was added" + sys.exit(f"{path}: could not parse as {lockfile.name}: " + f"{exc.__class__.__name__}: {exc}") + + +def diff(base, head): + """Yield (change, name, source) for everything `head` adds over `base`.""" + for name in sorted(head): + if name not in base: + for source in sorted(head[name]): + yield "new", name, source + else: + for source in sorted(head[name] - base[name]): + yield "source", name, source + + +def digest(lines): + """Order-independent digest of a finding set, used to bind sign-off to it.""" + body = "\n".join(sorted(line.strip("\n") for line in lines if line.strip())) + return hashlib.sha256(body.encode()).hexdigest()[:DIGEST_LENGTH] + + +def main(argv): + if len(argv) == 3 and argv[1] == "--digest": + print(digest(Path(argv[2]).read_text(encoding="utf-8").splitlines())) + elif len(argv) == 2: + for name, sources in sorted(extract(argv[1]).items()): + for source in sorted(sources): + print(f"{name}\t{source}") + elif len(argv) == 3: + for row in diff(extract(argv[1]), extract(argv[2])): + print("\t".join(row)) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/dependency-gate/tests/fixtures/Cargo.lock b/dependency-gate/tests/fixtures/Cargo.lock new file mode 100644 index 0000000..23f1ec9 --- /dev/null +++ b/dependency-gate/tests/fixtures/Cargo.lock @@ -0,0 +1,11 @@ +# Fixture for the dogfood job in .github/workflows/test.yml. +# Not a real dependency set. Changing it changes that job's expected count. +version = 3 + +[[package]] +name = "example-crate" +version = "1.0.0" + +[[package]] +name = "another-crate" +version = "2.3.4" diff --git a/dependency-gate/tests/fixtures/stable/Cargo.lock b/dependency-gate/tests/fixtures/stable/Cargo.lock new file mode 100644 index 0000000..50734a0 --- /dev/null +++ b/dependency-gate/tests/fixtures/stable/Cargo.lock @@ -0,0 +1,17 @@ +# Fixture for the dogfood jobs in .github/workflows/test.yml. +# +# This file must never change. Those jobs assert that the gate reports zero +# findings for it, which is what proves the action runs clean in both trigger +# modes. To exercise a non-zero finding, change tests/fixtures/Cargo.lock +# instead: that is the one .github/workflows/dependency-gate.yml watches. +version = 3 + +[[package]] +name = "stable-crate" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0000000000000000000000000000000000000000000000000000000000000000" + +[[package]] +name = "stable-path-crate" +version = "0.1.0" diff --git a/dependency-gate/tests/fixtures/stable/uv.lock b/dependency-gate/tests/fixtures/stable/uv.lock new file mode 100644 index 0000000..dd6ba07 --- /dev/null +++ b/dependency-gate/tests/fixtures/stable/uv.lock @@ -0,0 +1,24 @@ +# Fixture for the dogfood jobs in .github/workflows/test.yml. Must never change. +# Present so those jobs exercise the multi-lockfile loop and the uv.lock parser, +# whose source lives in an inline table rather than a plain string. +version = 1 +revision = 2 +requires-python = ">=3.10" + +[[package]] +name = "stable-project" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "stable-dep" }, +] + +[package.metadata] +requires-dist = [ + { name = "stable-dep", specifier = ">=1.0" }, +] + +[[package]] +name = "stable-dep" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } diff --git a/dependency-gate/tests/test_parser.py b/dependency-gate/tests/test_parser.py new file mode 100644 index 0000000..5d31e3b --- /dev/null +++ b/dependency-gate/tests/test_parser.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Tests for lockfile_packages.py. Run with: python3 tests/test_parser.py + +Plain asserts and no third-party imports, so the suite has no dependencies of +its own. A dependency gate that needed its own dependency tree would be a poor +advertisement for itself. + +The tests are the specification for what "source" means. Two properties matter +most, and both are asserted directly below: + + * an ordinary registry version bump produces NO finding, and + * a change of protocol, host or path DOES produce a `source` finding. + +Get the first wrong and every dependency bump raises a finding, reviewers learn +to apply the label without reading, and the gate is worse than nothing. +""" + +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +import lockfile_packages as lp # noqa: E402 + +PARSER = str(ROOT / "lockfile_packages.py") + +failures = [] + + +def show(value): + if isinstance(value, set): + return sorted(value) + if isinstance(value, dict): + return {k: sorted(v) for k, v in sorted(value.items())} + return value + + +def check(label, got, want): + if got != want: + failures.append(f"{label}\n got: {show(got)}\n want: {show(want)}") + print(f" FAIL {label}") + else: + print(f" ok {label}") + + +def write(name, text): + path = Path(tempfile.mkdtemp()) / name + path.write_text(text) + return path + + +def run(*args, expect=0): + done = subprocess.run([sys.executable, PARSER, *[str(a) for a in args]], + capture_output=True, text=True) + if done.returncode != expect: + failures.append(f"{PARSER} {args} exited {done.returncode}, wanted {expect}\n" + f" stderr: {done.stderr.strip()}") + return done + + +def names(mapping): + return set(mapping) + + +def findings(base_text, head_text, name="bun.lock"): + """The findings a change to one lockfile produces, as a sorted list of tuples.""" + base = write(name, base_text) + head = write(name, head_text) + return sorted(lp.diff(lp.extract(base), lp.extract(head))) + + +# -------------------------------------------------------------------------- +print("split_name") +check("plain", lp.split_name("pkg@1.2.3"), "pkg") +check("scoped", lp.split_name("@scope/pkg@1.2.3"), "@scope/pkg") +check("yarn alias", lp.split_name("@coral-xyz/anchor-29@npm:@coral-xyz/anchor@0.29.0"), + "@coral-xyz/anchor-29") +check("yarn patch", lp.split_name("fsevents@patch:fsevents@npm%3A2.3.2"), "fsevents") +check("pnpm peer suffix", lp.split_name("@scope/pkg@1.1.2(react@19.0.0)"), "@scope/pkg") +check("workspace proto", lp.split_name("mypkg@workspace:."), "mypkg") +check("no version at all", lp.split_name("pkg"), "pkg") +check("scoped, no version", lp.split_name("@scope/pkg"), "@scope/pkg") + +# -------------------------------------------------------------------------- +print("\nsource classification") +check("plain semver is the default registry", lp.source_of("1.2.3"), "registry:default") +check("a range is the default registry", lp.source_of("^1.2.3"), "registry:default") +check("yarn npm: with a version is the registry", lp.source_of("npm:1.2.3"), "registry:default") +check("yarn npm: with a name is an alias", + lp.source_of("npm:@coral-xyz/anchor@0.29.0"), "npm-alias:@coral-xyz/anchor") +check("a declared registry is recorded", + lp.source_of("1.2.3", "https://npm.pkg.github.com/"), "registry:https://npm.pkg.github.com") +check("a tarball keeps its whole URL", + lp.source_of("https://attacker.invalid/evil.tgz"), "https://attacker.invalid/evil.tgz") +check("a git ref drops only the pinned revision", + lp.source_of("git+https://github.com/o/r.git#deadbeef"), "git+https://github.com/o/r.git") +check("file: is its own source", lp.source_of("file:../local"), "file:../local") +check("workspace: is its own source", lp.source_of("workspace:packages/sdk"), "workspace:packages/sdk") + +# Registry downloads are recognised by the npm "/-/" path layout, not by +# a list of known hosts. A host allowlist would report every version bump in any +# repository that installs from a private registry. +check("public npm URL collapses to its base", + lp.source_of_url("https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz#abc"), + "registry:https://registry.npmjs.org") +check("scoped npm URL collapses to its base", + lp.source_of_url("https://registry.yarnpkg.com/@scope/pkg/-/pkg-1.0.0.tgz"), + "registry:https://registry.yarnpkg.com") +check("a private registry collapses to its own base, so bumps stay quiet", + lp.source_of_url("https://artifactory.corp/api/npm/npm-remote/lodash/-/lodash-4.17.21.tgz"), + "registry:https://artifactory.corp/api/npm/npm-remote") +check("a URL with no registry layout keeps its full identity", + lp.source_of_url("https://attacker.invalid/evil.tgz"), "https://attacker.invalid/evil.tgz") +check("a host swap that mimics the registry layout still changes the source", + lp.source_of_url("https://evil.example/lodash/-/lodash-4.17.21.tgz"), + "registry:https://evil.example") + +# -------------------------------------------------------------------------- +print("\nbun.lock") +BUN = """{ + "lockfileVersion": 1, + "workspaces": { + "": { "name": "root", "dependencies": { "two": "^2.0.0" } }, + }, + "packages": { + "@scope/one": ["@scope/one@1.0.0", "", { "dependencies": {} }, "sha512-a"], + + "two": ["two@2.0.0", "", {}, "sha512-b"], + + "anchor-bankrun/@coral-xyz/anchor": ["@coral-xyz/anchor@0.29.0", "", {}, "sha512-c"], + + "native": ["native@1.0.0", "", { "os": [ "linux" ], "cpu": [ "x64" ] }, "sha512-d"], + } +} +""" +check("basic + compound key + os/cpu arrays are not packages", names(lp.bun(BUN)), + {"@scope/one", "two", "@coral-xyz/anchor", "native"}) +check("every entry resolves to the default registry", + lp.bun(BUN)["two"], {"registry:default"}) + +# bun.lock is JSONC, so whitespace is not significant to bun. An entry appended to an +# existing line installs identically, but a line-anchored regex would never see it. +# Parsing the document the way bun does makes the class of trick impossible. +MERGED = BUN.replace( + '"two": ["two@2.0.0", "", {}, "sha512-b"],', + '"two": ["two@2.0.0", "", {}, "sha512-b"], "evil": ["evil@9.9.9", "", {}, "sha512-e"],', +) +check("same-line entry is not missed", names(lp.bun(MERGED)), + {"@scope/one", "two", "@coral-xyz/anchor", "native", "evil"}) +check("comments do not hide an entry", + names(lp.bun(BUN.replace('"two":', '/* sneaky */ "two":'))), + {"@scope/one", "two", "@coral-xyz/anchor", "native"}) + +# -------------------------------------------------------------------------- +print("\nthe source-substitution bypass (v1 reported nothing here)") +# Reproduced from velocity-common/bun.lock: rewriting the locator's version to a URL +# keeps the package name, and therefore the name count, completely unchanged. +SUB_BASE = """{ + "lockfileVersion": 1, + "packages": { + "husky": ["husky@8.0.3", "", {}, "sha512-a"], + } +} +""" +SUB_HEAD = SUB_BASE.replace('"husky@8.0.3"', '"husky@https://attacker.invalid/evil.tgz"') +check("the name set is identical, which is why a name-only diff sees nothing", + names(lp.bun(SUB_BASE)), names(lp.bun(SUB_HEAD))) +check("substituting the source is reported", + findings(SUB_BASE, SUB_HEAD), + [("source", "husky", "https://attacker.invalid/evil.tgz")]) + +print("\nversion bumps stay quiet, origin changes do not") +check("a plain registry version bump produces no finding", + findings(SUB_BASE, SUB_BASE.replace("husky@8.0.3", "husky@8.0.4")), []) +check("a caret range bump produces no finding", + findings(SUB_BASE, SUB_BASE.replace('"husky@8.0.3"', '"husky@^9.1.0"')), []) +check("switching to git is reported", + findings(SUB_BASE, SUB_BASE.replace('"husky@8.0.3"', + '"husky@git+https://github.com/evil/husky.git#abc"')), + [("source", "husky", "git+https://github.com/evil/husky.git")]) +check("switching to a local path is reported", + findings(SUB_BASE, SUB_BASE.replace('"husky@8.0.3"', '"husky@file:../evil"')), + [("source", "husky", "file:../evil")]) +check("an npm alias to another package is reported", + findings(SUB_BASE, SUB_BASE.replace('"husky@8.0.3"', '"husky@npm:evil-husky@1.0.0"')), + [("source", "husky", "npm-alias:evil-husky")]) +check("a registry host swap is reported", + findings(SUB_BASE, SUB_BASE.replace('"husky@8.0.3", ""', + '"husky@8.0.3", "https://evil.example/"')), + [("source", "husky", "registry:https://evil.example")]) +check("a git revision bump inside the same origin is not reported", + findings(SUB_BASE.replace('"husky@8.0.3"', '"husky@git+https://github.com/o/r.git#aaa"'), + SUB_BASE.replace('"husky@8.0.3"', '"husky@git+https://github.com/o/r.git#bbb"')), + []) +check("a brand new package is reported as new, not as a source change", + findings(SUB_BASE, SUB_BASE.replace( + '"husky": ["husky@8.0.3", "", {}, "sha512-a"],', + '"husky": ["husky@8.0.3", "", {}, "sha512-a"],\n "evil": ["evil@1.0.0", "", {}, "sha512-e"],')), + [("new", "evil", "registry:default")]) + +# -------------------------------------------------------------------------- +print("\nyarn.lock") +YARN_V1 = """# THIS IS AN AUTOGENERATED FILE. +# yarn lockfile v1 + + +"@scope/one@^1.0.0": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@scope/one/-/one-1.0.1.tgz#aaa" + +two@^2.0.0, two@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/two/-/two-2.1.0.tgz#bbb" + +"@coral-xyz/anchor-29@npm:@coral-xyz/anchor@0.29.0": + version "0.29.0" + resolved "https://registry.yarnpkg.com/@coral-xyz/anchor/-/anchor-0.29.0.tgz#ccc" + +local@file:../local: + version "0.0.0" +""" +check("v1 classic, incl. multi-descriptor and alias", names(lp.yarn(YARN_V1)), + {"@scope/one", "two", "@coral-xyz/anchor-29", "local"}) +check("v1 takes a registry entry's source from its resolved URL, not its range", + lp.yarn(YARN_V1)["two"], {"registry:https://registry.yarnpkg.com"}) +check("v1 keeps a protocol descriptor as its own source", + lp.yarn(YARN_V1)["local"], {"file:../local"}) +check("v1 registry version bump produces no finding", + findings(YARN_V1, YARN_V1.replace("two-2.1.0.tgz", "two-2.2.0.tgz") + .replace('version "2.1.0"', 'version "2.2.0"'), "yarn.lock"), []) +check("v1 resolved-URL host swap is reported", + findings(YARN_V1, YARN_V1.replace("https://registry.yarnpkg.com/two/-/two-2.1.0.tgz", + "https://evil.example/two.tgz"), "yarn.lock"), + [("source", "two", "https://evil.example/two.tgz")]) + +YARN_BERRY = """__metadata: + version: 8 + cacheKey: 10c0 + +"@scope/one@npm:^1.0.0": + version: 1.0.1 + resolution: "@scope/one@npm:1.0.1" + +"fsevents@patch:fsevents@npm%3A2.3.2#optional!builtin": + version: 2.3.2 + resolution: "fsevents@patch:fsevents@npm%3A2.3.2#optional!builtin" + +"root@workspace:.": + version: 0.0.0-use.local + resolution: "root@workspace:." +""" +check("berry via resolution lines", names(lp.yarn(YARN_BERRY)), + {"@scope/one", "fsevents", "root"}) +check("berry npm: resolution is the registry", + lp.yarn(YARN_BERRY)["@scope/one"], {"registry:default"}) +check("berry version bump produces no finding", + findings(YARN_BERRY, YARN_BERRY.replace("npm:1.0.1", "npm:1.0.2"), "yarn.lock"), []) +check("berry switch to a tarball is reported", + findings(YARN_BERRY, + YARN_BERRY.replace('"@scope/one@npm:1.0.1"', '"@scope/one@https://evil.example/x.tgz"'), + "yarn.lock"), + [("source", "@scope/one", "https://evil.example/x.tgz")]) + +# -------------------------------------------------------------------------- +print("\npnpm-lock.yaml") +PNPM = """lockfileVersion: '9.0' + +packages: + + '@scope/one@1.0.0': + resolution: {integrity: sha512-a} + + two@2.0.0: + resolution: {integrity: sha512-b} + + three@1.0.0: + resolution: {tarball: https://evil.example/three.tgz} + +snapshots: + + '@scope/one@1.0.0(react@19.0.0)': + dependencies: {} +""" +check("v9 packages + peer-suffixed snapshots collapse", names(lp.pnpm(PNPM)), + {"@scope/one", "two", "three"}) +check("v9 integrity means the registry", lp.pnpm(PNPM)["two"], {"registry:default"}) +check("v9 tarball resolution is read, not ignored", + lp.pnpm(PNPM)["three"], {"https://evil.example/three.tgz"}) +check("v9 version bump produces no finding", + findings(PNPM, PNPM.replace("two@2.0.0", "two@2.1.0"), "pnpm-lock.yaml"), []) +check("v9 swapping a registry entry for a tarball is reported", + findings(PNPM, PNPM.replace(" resolution: {integrity: sha512-b}", + " resolution: {tarball: https://evil.example/two.tgz}"), + "pnpm-lock.yaml"), + [("source", "two", "https://evil.example/two.tgz")]) + +PNPM_LEGACY = """lockfileVersion: 5.4 + +packages: + + /@scope/one/1.0.0: + resolution: {integrity: sha512-a} + + /two/2.0.0: + resolution: {integrity: sha512-b} +""" +check("legacy v5 slash style", names(lp.pnpm(PNPM_LEGACY)), {"@scope/one", "two"}) +# A legacy scoped key must not also register a bogus package literally named "/". +check("legacy keys do not leak a '/' package", "/" in lp.pnpm(PNPM_LEGACY), False) + +# -------------------------------------------------------------------------- +print("\nCargo.lock") +CARGO = """version = 3 + +[[package]] +name = "serde" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaa" + +[[package]] +name = "velocity-rs" +version = "0.1.0" +source = "git+https://github.com/velocity-exchange/velocity-v1?branch=master#deadbeef" + +[[package]] +name = "local-crate" +version = "0.1.0" + +[metadata] +"checksum serde 1.0.0" = "aaa" +""" +check("cargo names", names(lp.cargo(CARGO)), {"serde", "velocity-rs", "local-crate"}) +check("cargo registry source", lp.cargo(CARGO)["serde"], + {"registry+https://github.com/rust-lang/crates.io-index"}) +check("cargo git source drops the pinned revision", lp.cargo(CARGO)["velocity-rs"], + {"git+https://github.com/velocity-exchange/velocity-v1?branch=master"}) +check("cargo path dependency", lp.cargo(CARGO)["local-crate"], {"path"}) +check("cargo version bump produces no finding", + findings(CARGO, CARGO.replace('name = "serde"\nversion = "1.0.0"', + 'name = "serde"\nversion = "1.0.1"'), "Cargo.lock"), []) +check("cargo branch-tracking commit bump produces no finding", + findings(CARGO, CARGO.replace("#deadbeef", "#cafebabe"), "Cargo.lock"), []) +# The resolved commit is dropped, but an explicitly declared rev is part of the source: +# repointing a git dependency at a chosen commit is a deliberate act, not a bump. +CARGO_REV = CARGO.replace("?branch=master#deadbeef", "?rev=aaaaaaa#deadbeef") +check("cargo declared rev is kept in the source", + lp.cargo(CARGO_REV)["velocity-rs"], + {"git+https://github.com/velocity-exchange/velocity-v1?rev=aaaaaaa"}) +check("cargo repin to a different declared rev is reported", + findings(CARGO_REV, CARGO_REV.replace("?rev=aaaaaaa", "?rev=bbbbbbb"), "Cargo.lock"), + [("source", "velocity-rs", + "git+https://github.com/velocity-exchange/velocity-v1?rev=bbbbbbb")]) +check("cargo swapping a git remote for another host is reported", + findings(CARGO, CARGO.replace("github.com/velocity-exchange/velocity-v1", + "evil.example/velocity-v1"), "Cargo.lock"), + [("source", "velocity-rs", "git+https://evil.example/velocity-v1?branch=master")]) +check("cargo registry swap is reported", + findings(CARGO, CARGO.replace("registry+https://github.com/rust-lang/crates.io-index", + "registry+https://evil.example/index"), "Cargo.lock"), + [("source", "serde", "registry+https://evil.example/index")]) +check("cargo new crate is reported", + findings(CARGO, CARGO + '\n[[package]]\nname = "evil"\nversion = "1.0.0"\n', "Cargo.lock"), + [("new", "evil", "path")]) + +# -------------------------------------------------------------------------- +print("\nuv.lock") +UV = """version = 1 +revision = 2 +requires-python = ">=3.10" + +[[package]] +name = "accumulation-tree" +version = "0.6.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/dc/accumulation_tree-0.6.4.tar.gz", hash = "sha256:aaa", size = 12635 } + +[[package]] +name = "calibration" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "numpy" }, +] + +[package.metadata] +requires-dist = [ + { name = "numpy", specifier = ">=1.0" }, +] + +[[package]] +name = "numpy" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } + +[[package]] +name = "numpy" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +""" +check("uv names, with a duplicated name counted once", names(lp.uv(UV)), + {"accumulation-tree", "calibration", "numpy"}) +check("uv registry source", lp.uv(UV)["numpy"], {"registry:https://pypi.org/simple"}) +check("uv virtual root", lp.uv(UV)["calibration"], {"virtual:."}) +check("uv sdist/wheel URLs are not mistaken for the source", + lp.uv(UV)["accumulation-tree"], {"registry:https://pypi.org/simple"}) +check("uv requires-dist entries are not packages", "specifier" in lp.uv(UV), False) +check("uv version bump produces no finding", + findings(UV, UV.replace('version = "2.2.0"', 'version = "2.3.0"'), "uv.lock"), []) +check("uv index swap is reported", + findings(UV, UV.replace('name = "numpy"\nversion = "2.2.0"\nsource = { registry = "https://pypi.org/simple" }', + 'name = "numpy"\nversion = "2.2.0"\nsource = { registry = "https://evil.example/simple" }'), + "uv.lock"), + [("source", "numpy", "registry:https://evil.example/simple")]) +check("uv switch to a git source is reported", + findings(UV, UV.replace('name = "accumulation-tree"\nversion = "0.6.4"\nsource = { registry = "https://pypi.org/simple" }', + 'name = "accumulation-tree"\nversion = "0.6.4"\nsource = { git = "https://evil.example/x?rev=a#deadbeef" }'), + "uv.lock"), + [("source", "accumulation-tree", "git:https://evil.example/x?rev=a")]) +check("uv has its own parser, not Cargo's", lp.PARSERS["uv.lock"] is lp.uv, True) + +# -------------------------------------------------------------------------- +print("\nunparseable input is a hard error, never an empty result") + + +def exits(label, name, text): + path = write(name, text) + try: + result = lp.extract(path) + except SystemExit: + print(f" ok {label}") + return + failures.append(f"{label}\n got: returned {show(result)}\n want: SystemExit") + print(f" FAIL {label}") + + +exits("bun.lock that is not JSON at all", "bun.lock", "this is not a lockfile\n") +exits("bun.lock whose packages value is not an object", "bun.lock", + '{"lockfileVersion": 1, "packages": []}') +exits("bun.lock emptied while workspaces still declare dependencies", "bun.lock", + '{"lockfileVersion": 1, "workspaces": {"": {"dependencies": {"lodash": "^4"}}},' + ' "packages": {}}') +exits("bun.lock entry that is not an array", "bun.lock", + '{"lockfileVersion": 1, "packages": {"a": "not-an-array"}}') +exits("yarn.lock with no entries and no header", "yarn.lock", "garbage\nmore garbage\n") +exits("berry yarn.lock with no resolutions", "yarn.lock", "__metadata:\n version: 8\n") +exits("pnpm-lock.yaml with no lockfileVersion", "pnpm-lock.yaml", "packages:\n nonsense\n") +exits("Cargo.lock with neither packages nor a version header", "Cargo.lock", "garbage\n") +exits("Cargo.lock block with no name", "Cargo.lock", 'version = 3\n\n[[package]]\nversion = "1.0"\n') +exits("uv.lock with neither packages nor a version header", "uv.lock", "garbage\n") + +# A lockfile that legitimately records nothing is still allowed to be empty. +check("an empty but well-formed Cargo.lock is not an error", + lp.extract(write("Cargo.lock", "version = 4\n")), {}) +check("an empty but well-formed yarn.lock is not an error", + lp.extract(write("yarn.lock", "# yarn lockfile v1\n")), {}) +check("an empty but well-formed pnpm-lock.yaml is not an error", + lp.extract(write("pnpm-lock.yaml", "lockfileVersion: '9.0'\n")), {}) +check("an empty but well-formed bun.lock is not an error", + lp.extract(write("bun.lock", '{"lockfileVersion": 1, "packages": {}}')), {}) + +# -------------------------------------------------------------------------- +print("\nfindings stay one per line") +# A package name is attacker-controlled text that ends up in a tab-separated record. +# A newline or tab inside it would forge an extra finding, or split one in two. +NASTY = ('{"lockfileVersion": 1, "packages": {' + '"a": ["ev\\til@1.0.0", "", {}, "h"],' + '"b": ["ev\\nil2@1.0.0", "", {}, "h"]}}') +nasty = lp.bun(NASTY) +check("tabs and newlines are escaped out of names", + names(nasty), {"ev\\x09il", "ev\\x0ail2"}) +rows = list(lp.diff({}, nasty)) +check("every finding is a single line", all("\n" not in "\t".join(r) for r in rows), True) +check("every finding has exactly three fields", + all(len("\t".join(r).split("\t")) == 3 for r in rows), True) + +# -------------------------------------------------------------------------- +print("\nsign-off digest") +SET_A = ["Cargo.lock\tnew\tserde\tpath", "bun.lock\tnew\tevil\tregistry:default"] +check("the digest does not depend on ordering", + lp.digest(SET_A), lp.digest(list(reversed(SET_A)))) +check("the digest ignores blank lines and trailing newlines", + lp.digest(SET_A), lp.digest([SET_A[0] + "\n", "", SET_A[1], "\n"])) +check("adding a finding changes the digest", + lp.digest(SET_A) != lp.digest(SET_A + ["bun.lock\tnew\tmore\tregistry:default"]), True) +check("removing a finding changes the digest", + lp.digest(SET_A) != lp.digest(SET_A[:1]), True) +check("the digest is hex and long enough to resist a second preimage", + len(lp.digest(SET_A)) >= 24 and all(c in "0123456789abcdef" for c in lp.digest(SET_A)), True) + +# -------------------------------------------------------------------------- +print("\ndispatch and CLI") +check("an unsupported filename exits non-zero", run("package-lock.json", expect=1).returncode, 1) +check("no arguments exits non-zero", run(expect=1).returncode, 1) + +missing = Path(tempfile.mkdtemp()) / "bun.lock" +check("an absent base means everything is new", lp.extract(missing), {}) +check("an absent base yields 'new' findings, not 'source' ones", + sorted(lp.diff(lp.extract(missing), lp.bun(SUB_BASE))), + [("new", "husky", "registry:default")]) + +base = write("bun.lock", BUN) +head = write("bun.lock", MERGED) +added = run(base, head) +check("diff mode reports only additions", added.stdout.strip(), "new\tevil\tregistry:default") +check("single-file mode prints name and source", + sorted(run(base).stdout.strip().splitlines())[0], "@coral-xyz/anchor\tregistry:default") +check("identical files report nothing", run(base, base).stdout.strip(), "") +check("a pure removal is not an addition", run(head, base).stdout.strip(), "") + +tsv = write("findings.tsv", "\n".join(SET_A) + "\n") +check("--digest matches the library digest", + run("--digest", tsv).stdout.strip(), lp.digest(SET_A)) +tsv_reordered = write("findings.tsv", "\n".join(reversed(SET_A)) + "\n") +check("--digest is order independent on the command line too", + run("--digest", tsv_reordered).stdout.strip(), run("--digest", tsv).stdout.strip()) + +# -------------------------------------------------------------------------- +print() +if failures: + print(f"{len(failures)} failure(s):") + for f in failures: + print(f" - {f}") + sys.exit(1) +print("all tests passed")