From b25f5871aa815a85dbe9adbc6e61cbe41fe0cded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Di=20Remigio=20Eik=C3=A5s?= Date: Sat, 21 Nov 2026 19:48:41 +0100 Subject: [PATCH] feat: scan the Rust crates of Cargo.lock The dependency scan only read uv.lock, so the crates that a Rust extension compiles into a wheel were never checked. It now reads every tracked Cargo.lock too, from the same script. The crates go to OSV, like the Python packages, rather than to cargo-audit: OSV imports the RustSec database and GitHub's advisories for crates.io, so the severity (GitHub's), the exceptions, the job summary and the annotations are shared, and the job needs no Rust toolchain. Only crates from crates.io are queried, so the names of crates from git, a path or another registry never leave the runner. Cargo.lock doesn't record dependency kinds, so every crate counts as a runtime dependency. RustSec's informational advisories (unmaintained, unsound, notice) have no GHSA record: they are reported with their kind as the severity and don't block. A RustSec vulnerability without a GHSA record still has an unknown severity and blocks. Crate names are compared exactly, as cargo does. The summary and the annotations name the lock they come from, a repository with only one kind of lock scans that kind, and one with neither still passes with a notice. Assisted-by: Pi:claude-sonnet-5-5 --- .github/workflows/dependency-scan.yml | 11 +- README.md | 79 ++++-- scripts/dependency_scan.py | 167 ++++++++++-- tests/test_dependency_scan.py | 371 +++++++++++++++++++++++++- 4 files changed, 573 insertions(+), 55 deletions(-) diff --git a/.github/workflows/dependency-scan.yml b/.github/workflows/dependency-scan.yml index 3b45f59..85c6862 100644 --- a/.github/workflows/dependency-scan.yml +++ b/.github/workflows/dependency-scan.yml @@ -1,9 +1,10 @@ name: Dependency scan -# Checks the Python packages locked in uv.lock against the OSV database of known -# vulnerabilities, on every pull request and in the merge queue. An organization ruleset requires it ("Require workflows to -# pass before merging"), so it runs in the repository of the pull request, with that -# repository's files and token: see README.md. +# Checks the Python packages locked in uv.lock and the Rust crates locked in Cargo.lock +# against the OSV database of known vulnerabilities, on every pull request and in the merge +# queue. An organization ruleset requires it ("Require workflows to pass before merging"), so +# it runs in the repository of the pull request, with that repository's files and token: see +# README.md. # # A ruleset ignores the filters of the triggers (branches, paths, types), so the job checks # by itself whether there is anything to scan. The scan is scripts/dependency_scan.py of this @@ -44,7 +45,7 @@ jobs: with: enable-cache: false - - name: Check uv.lock against OSV + - name: Check uv.lock and Cargo.lock against OSV env: EXCEPTIONS_FILE: .github/vulnerability-exceptions.toml # --no-config: the uv settings of the repository (uv.toml, [tool.uv]) are not for the diff --git a/README.md b/README.md index 4375faf..17833a2 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ repository the workflow runs in. ## Dependency scan [`dependency-scan.yml`](.github/workflows/dependency-scan.yml) checks the Python packages -locked in `uv.lock` against the [OSV](https://osv.dev) database of known vulnerabilities, on -every pull request and in the merge queue. +locked in `uv.lock`, and the Rust crates locked in `Cargo.lock`, against the +[OSV](https://osv.dev) database of known vulnerabilities, on every pull request and in the +merge queue. ### How it works @@ -24,14 +25,19 @@ it out from the commit of the workflow file (`job.workflow_repository`, `job.wor which the ruleset pins, and runs it with `uv run` (Python 3.13, standard library only, as its inline metadata says). The script: -1. finds the `uv.lock` files that git tracks. With none, it passes with a notice; -2. reads the packages of each one that come from a package index, with their versions: +1. finds the `uv.lock` and `Cargo.lock` files that git tracks, in the root and in any + directory below it. With neither, it passes with a notice; with one kind, it scans that + kind; +2. reads the packages of each `uv.lock` that come from a package index, with their versions: every extra and dependency group, whatever the index. The project itself and packages from git, a URL or a local path are left out: they have no version on PyPI to look up; -3. asks OSV which vulnerabilities affect each name and version, and reads their records. OSV - lists a vulnerability once per database (GHSA, PYSEC, …): the GHSA record is kept, as it - carries GitHub's severity; -4. writes a table of the findings to the job summary, and an error annotation for each one +3. reads the crates of each `Cargo.lock` that come from crates.io, with their versions. The + packages of the workspace and the crates from git, a path or another registry are left + out. Versions 3 and 4 of the lock have the same `[[package]]` tables, and both are read; +4. asks OSV which vulnerabilities affect each name and version in its ecosystem (`PyPI` or + `crates.io`), and reads their records. OSV lists a vulnerability once per database (GHSA, + PYSEC, RUSTSEC, …): the GHSA record is kept, as it carries GitHub's severity; +5. writes a table of the findings to the job summary, and an error annotation for each one that blocks. A finding **blocks the merge** when it is in a **runtime dependency** and its severity is @@ -41,20 +47,46 @@ are findings in packages that only the dependency groups need (`dev`, `test`, `d which don't ship with the project. A withdrawn advisory never blocks. If OSV can't be read, the job fails. -The runtime dependencies are those of the projects of the lock (its editable or virtual -packages) and of their extras, followed through the lock, with the extras each dependency -asks for. Whatever a project lists in `[project] dependencies` counts, even tools that only -its developers use: move those to a dependency group. A lock without a project counts every -package as a runtime dependency. +The runtime dependencies of a `uv.lock` are those of the projects of the lock (its editable +or virtual packages) and of their extras, followed through the lock, with the extras each +dependency asks for. Whatever a project lists in `[project] dependencies` counts, even tools +that only its developers use: move those to a dependency group. A lock without a project +counts every package as a runtime dependency. + +### Rust crates + +OSV imports the [RustSec advisory database](https://rustsec.org/) and GitHub's advisories for +crates.io, so a crate is checked with the same database, severity and rules as a Python +package. The differences: + +- **Every crate counts as a runtime dependency.** `Cargo.lock` doesn't record which crates + are dev-dependencies or build-dependencies, nor which features are on: only cargo knows + that, when it resolves the manifest. A finding in a crate that only the tests or the build + script use blocks like any other, so use an exception for it, with the reason. +- **Informational advisories don't block.** RustSec also publishes notices that aren't + vulnerabilities: an `unmaintained` or `unsound` crate, or a `notice`. They have no GHSA + record, hence no severity. The scan lists them with the kind as the severity + (`informational: unmaintained`) and never blocks on them. If GitHub has an advisory for the + same issue, GitHub's severity applies instead. +- **A RustSec vulnerability that GitHub doesn't know blocks**, as its severity is unknown: + the severity is GitHub's, not the CVSS score of RustSec. +- **Yanked crates aren't reported.** A yanked version isn't an advisory, and OSV doesn't list + it. +- Crate names are compared exactly: cargo treats `foo-bar` and `foo_bar` as different crates, + where Python names ignore the case and the separators. ### What leaves the repository -Only the name, the ecosystem (`PyPI`) and the version of each locked package, sent to -[OSV's API](https://google.github.io/osv.dev/post-v1-querybatch/) with Python's default -User-Agent; then the identifiers of the vulnerabilities found, to read their records. That -includes packages from private indexes: OSV matches by name, whatever the index. If a private -package shares its name with a public one that has advisories, the findings of the public one -are reported: record them as exceptions. +Only the name, the ecosystem (`PyPI` or `crates.io`) and the version of each locked package, +sent to [OSV's API](https://google.github.io/osv.dev/post-v1-querybatch/) with Python's +default User-Agent; then the identifiers of the vulnerabilities found, to read their records. +For Python, that includes packages from private indexes: OSV matches by name, whatever the +index. If a private package shares its name with a public one that has advisories, the +findings of the public one are reported: record them as exceptions. For Rust, only the crates +of crates.io are sent (`registry+https://github.com/rust-lang/crates.io-index` or +`sparse+https://index.crates.io/` as the source in `Cargo.lock`): those names are public. +Crates from git, a path or another registry are never sent, and neither are the names of the +packages of the workspace. ### Exceptions @@ -64,7 +96,7 @@ vulnerability: ```toml [[exception]] -id = "GHSA-xxxx-xxxx-xxxx" # the GHSA identifier, or any alias that the job summary shows +id = "GHSA-xxxx-xxxx-xxxx" # the GHSA identifier, or any alias (CVE-…, RUSTSEC-…, PYSEC-…) issue = "https://github.com///issues/" # the issue that approves it reason = "The vulnerable function is only used by the test suite." ``` @@ -96,6 +128,7 @@ The tests run `scripts/dependency_scan.py` as the workflow does: uv run --no-project --with pytest --with pyyaml pytest ``` -The end-to-end tests lock small projects with known vulnerable packages and need the network -(PyPI and OSV); set `OFFLINE=1` to skip them. CI also runs ruff, actionlint and zizmor. Changes need a pull request and a review: -every targeted repository runs this code. +The end-to-end tests lock small Python projects with known vulnerable packages, and use +hand-written `Cargo.lock` files with known vulnerable crates (no cargo needed). They need the +network (PyPI and OSV); set `OFFLINE=1` to skip them. CI also runs ruff, actionlint and +zizmor. Changes need a pull request and a review: every targeted repository runs this code. diff --git a/scripts/dependency_scan.py b/scripts/dependency_scan.py index 040e226..f869231 100644 --- a/scripts/dependency_scan.py +++ b/scripts/dependency_scan.py @@ -2,14 +2,15 @@ # requires-python = ">=3.13" # dependencies = [] # /// -"""Check the packages locked in the uv.lock files of the repository against OSV. - -Each package from a package index is looked up by name and version in the OSV database -(https://osv.dev), which is all that leaves the runner. A finding blocks the merge when it is -in a runtime dependency and its severity is high or critical, or unknown, unless -.github/vulnerability-exceptions.toml lists it. The severity is GitHub's, from the GHSA -records that OSV mirrors. Findings in packages that only dependency groups (dev, test, docs, -…) need are reported without blocking. +"""Check the packages locked in the uv.lock and Cargo.lock files of the repository against OSV. + +Each Python package from a package index, and each Rust crate from crates.io, is looked up by +name and version in the OSV database (https://osv.dev), which is all that leaves the runner. +A finding blocks the merge when it is in a runtime dependency and its severity is high or +critical, or unknown, unless .github/vulnerability-exceptions.toml lists it. The severity is +GitHub's, from the GHSA records that OSV mirrors. Findings in packages that only dependency +groups (dev, test, docs, …) need, and informational RustSec notices (unmaintained, unsound, +notice) that have no GitHub severity, are reported without blocking. """ from __future__ import annotations @@ -28,6 +29,11 @@ from pathlib import Path OSV = "https://api.osv.dev/v1" +# the `source` of the crates of crates.io in Cargo.lock: the git index, and the sparse one +CRATES_IO_SOURCES = { + "registry+https://github.com/rust-lang/crates.io-index", + "sparse+https://index.crates.io/", +} # OSV answers at most this many queries per batch BATCH = 1000 @@ -44,6 +50,10 @@ class Approval: used: bool = False +# the start of the severity of an informational notice, for example "informational: unmaintained" +INFORMATIONAL = "informational" + + @dataclass class Finding: lock: str @@ -55,6 +65,8 @@ class Finding: fix_versions: list[str] runtime: bool = True severity: str = "unknown" + # RustSec's kind of a notice that isn't a vulnerability: unmaintained, unsound or notice + informational: str | None = None withdrawn: bool = False exception: Approval | None = None @@ -70,6 +82,8 @@ def ghsa(self) -> str | None: def blocking(self) -> bool: if not self.runtime or self.withdrawn or self.exception is not None: return False + if self.severity.startswith(INFORMATIONAL): + return False return self.severity not in {"low", "moderate", "medium"} @@ -79,6 +93,8 @@ class Package: name: str version: str runtime: bool = True + # OSV's name of the ecosystem: PyPI for uv.lock, crates.io for Cargo.lock + ecosystem: str = "PyPI" @dataclass @@ -97,7 +113,7 @@ def vulnerabilities(self, packages: list[Package]) -> list[list[str]]: batch, pending = pending[:BATCH], pending[BATCH:] queries = [ { - "package": {"name": packages[i].name, "ecosystem": "PyPI"}, + "package": {"name": packages[i].name, "ecosystem": packages[i].ecosystem}, "version": packages[i].version, **({"page_token": token} if token else {}), } @@ -165,9 +181,9 @@ def load_exceptions(path: Path) -> list[Approval]: def lock_files(root: Path) -> list[Path]: - """The uv.lock files tracked by git, so generated or ignored ones don't count.""" + """The uv.lock and Cargo.lock files tracked by git, so generated or ignored ones don't count.""" output = subprocess.run( - ["git", "ls-files", "-z", "--", "uv.lock", "*/uv.lock"], + ["git", "ls-files", "-z", "--", "uv.lock", "*/uv.lock", "Cargo.lock", "*/Cargo.lock"], cwd=root, check=True, capture_output=True, @@ -210,16 +226,49 @@ def runtime_packages(packages: list[dict]) -> set[tuple[str, str | None]] | None return {(name, version) for name, version, _ in seen} +def read_lock(lock: Path, root: Path) -> dict: + try: + return tomllib.loads(lock.read_text(encoding="utf-8")) + except tomllib.TOMLDecodeError as error: + raise ScanError(f"{lock.relative_to(root)} is not valid TOML: {error}") from error + + def locked_packages(lock: Path, root: Path) -> list[Package]: - """The packages of LOCK that come from a package index, with their versions. + """The packages of LOCK, a uv.lock or a Cargo.lock, that OSV can look up.""" + if lock.name == "Cargo.lock": + return locked_crates(lock, root) + return locked_python_packages(lock, root) + + +def locked_crates(lock: Path, root: Path) -> list[Package]: + """The crates of the Cargo.lock LOCK that come from crates.io, with their versions. + + The packages of the workspace have no source, and the crates from git, a path or another + registry may not be on crates.io: they're left out, and their names aren't sent. Version 3 + and 4 of the lock have the same `[[package]]` tables with name, version and source. + + Cargo.lock doesn't say which crates only the development or the build need (that depends + on the dependency kinds and features, which only cargo resolves), so every crate counts as + a runtime dependency. + """ + name = str(lock.relative_to(root)) + return sorted( + { + Package(name, package["name"], package["version"], ecosystem="crates.io") + for package in read_lock(lock, root).get("package", []) + if package.get("source") in CRATES_IO_SOURCES and "version" in package + }, + key=lambda p: (p.name, p.version), + ) + + +def locked_python_packages(lock: Path, root: Path) -> list[Package]: + """The packages of the uv.lock LOCK that come from a package index, with their versions. The project itself and the packages from git, a URL or a local path have no version on PyPI to look up, so they're left out. """ - try: - data = tomllib.loads(lock.read_text(encoding="utf-8")) - except tomllib.TOMLDecodeError as error: - raise ScanError(f"{lock.relative_to(root)} is not valid TOML: {error}") from error + data = read_lock(lock, root) name = str(lock.relative_to(root)) runtime = runtime_packages(data.get("package", [])) return sorted( @@ -241,13 +290,32 @@ def normalize(name: str) -> str: return name.lower().replace("_", "-").replace(".", "-") -def fix_versions(record: dict, package: str) -> list[str]: +def affected_entries(record: dict, package: Package) -> list[dict]: + """The `affected` entries of RECORD that are about PACKAGE. + + Python names are compared as PEP 503 does, with the case and the separators ignored. Crate + names are exact: cargo tells `foo-bar` and `foo_bar` apart, and so does OSV. + """ + + def same(name: str) -> bool: + if package.ecosystem == "crates.io": + return name == package.name + return normalize(name) == normalize(package.name) + + return [ + affected + for affected in record.get("affected", []) + if affected.get("package", {}).get("ecosystem") == package.ecosystem + and same(affected.get("package", {}).get("name", "")) + ] + + +def fix_versions(record: dict, package: Package) -> list[str]: """The versions that fix RECORD for PACKAGE, from its affected ranges.""" return sorted( { event["fixed"] - for affected in record.get("affected", []) - if normalize(affected.get("package", {}).get("name", "")) == normalize(package) + for affected in affected_entries(record, package) for range_ in affected.get("ranges", []) for event in range_.get("events", []) if "fixed" in event @@ -255,6 +323,22 @@ def fix_versions(record: dict, package: str) -> list[str]: ) +def informational_kind(record: dict, package: Package) -> str | None: + """RustSec's kind of RECORD for PACKAGE (unmaintained, unsound, notice), if it has one. + + RustSec marks the advisories that aren't about a vulnerability in + `affected[].database_specific.informational`, which is null for the others. + """ + return next( + ( + kind + for affected in affected_entries(record, package) + if (kind := (affected.get("database_specific") or {}).get("informational")) + ), + None, + ) + + def find(packages: list[Package], osv: Osv) -> list[Finding]: """The vulnerabilities of PACKAGES, one finding per vulnerability and package. @@ -281,7 +365,8 @@ def find(packages: list[Package], osv: Osv) -> list[Finding]: id=id, aliases=aliases, summary=record.get("summary") or record.get("details", "").split("\n")[0], - fix_versions=fix_versions(record, package.name), + fix_versions=fix_versions(record, package), + informational=informational_kind(record, package), withdrawn=record.get("withdrawn") is not None, ) ) @@ -289,9 +374,17 @@ def find(packages: list[Package], osv: Osv) -> list[Finding]: def classify(findings: list[Finding], exceptions: list[Approval], osv: Osv) -> None: - """Fill in the severity and the exception of each finding.""" + """Fill in the severity and the exception of each finding. + + The severity is GitHub's, from the GHSA record. A RustSec advisory that isn't about a + vulnerability has no GHSA record: its severity is its informational kind, and it doesn't + block. A RustSec vulnerability without a GHSA record has an unknown severity, which blocks. + """ for finding in findings: - if finding.ghsa is not None: + if finding.ghsa is None: + if finding.informational: + finding.severity = f"{INFORMATIONAL}: {finding.informational}" + else: try: record = osv.record(finding.ghsa) except (urllib.error.URLError, TimeoutError, ValueError) as error: @@ -318,9 +411,23 @@ def cell(text: str) -> str: def report(findings: list[Finding], exceptions: list[Approval], locks: list[str]) -> str: """The job summary, in Markdown.""" blocking = [f for f in findings if f.blocking] + python = [lock for lock in locks if Path(lock).name != "Cargo.lock"] + rust = [lock for lock in locks if Path(lock).name == "Cargo.lock"] + checked = [ + f"the Python packages of {', '.join(f'`{lock}`' for lock in python)}" if python else "", + f"the Rust crates of {', '.join(f'`{lock}`' for lock in rust)}" if rust else "", + ] lines = ["## Dependency scan", ""] - lines.append(f"Checked {', '.join(f'`{lock}`' for lock in locks)} against OSV.") + lines.append(f"Checked {' and '.join(c for c in checked if c)} against OSV.") lines.append("") + if rust: + lines += [ + ( + "`Cargo.lock` doesn't say which crates only the development or the build need, " + "so every crate counts as a runtime dependency." + ), + "", + ] if not findings: lines.append("No known vulnerabilities.") else: @@ -328,7 +435,8 @@ def report(findings: list[Finding], exceptions: list[Approval], locks: list[str] f"{len(findings)} finding(s), {len(blocking)} blocking: in a runtime dependency, " "high, critical or of unknown severity, and not in " "`.github/vulnerability-exceptions.toml`. Findings in packages that only the " - "dependency groups need (dev, test, docs, …) don't block." + "dependency groups need (dev, test, docs, …) don't block, and neither do the " + "informational notices of RustSec (unmaintained, unsound, notice)." ) lines += [ "", @@ -338,6 +446,8 @@ def report(findings: list[Finding], exceptions: list[Approval], locks: list[str] order = {"critical": 0, "high": 1, "unknown": 2, "moderate": 3, "medium": 3, "low": 4} def key(f: Finding) -> tuple: + if f.severity.startswith(INFORMATIONAL): + return (not f.blocking, 5, f.package) return (not f.blocking, order.get(f.severity, 2), f.package) for f in sorted(findings, key=key): @@ -368,9 +478,14 @@ def main(osv: Osv | None = None) -> int: summary = os.environ.get("GITHUB_STEP_SUMMARY") locks = lock_files(root) if not locks: - print("::notice title=Dependency scan::No uv.lock in this repository: nothing to scan.") + print( + "::notice title=Dependency scan::No uv.lock or Cargo.lock in this repository: " + "nothing to scan." + ) if summary: - Path(summary).write_text("## Dependency scan\n\nNo `uv.lock`: nothing to scan.\n") + Path(summary).write_text( + "## Dependency scan\n\nNo `uv.lock` or `Cargo.lock`: nothing to scan.\n" + ) return 0 osv = osv or Osv(post=http_post, get=http_get) exceptions_file = os.environ.get("EXCEPTIONS_FILE", ".github/vulnerability-exceptions.toml") diff --git a/tests/test_dependency_scan.py b/tests/test_dependency_scan.py index be120c8..4c79325 100644 --- a/tests/test_dependency_scan.py +++ b/tests/test_dependency_scan.py @@ -350,6 +350,312 @@ def test_development_findings_never_block(scan) -> None: assert "| development |" in scan.report([f], [], ["uv.lock"]) +# --- Rust crates: Cargo.lock -------------------------------------------------------------- + + +def crate_record( + id: str, + aliases: list[str], + severity: str | None = None, + informational: str | None = None, + name: str = "krate", +) -> dict: + """A record as OSV serves RustSec's and GitHub's advisories of a crate.""" + record = { + "id": id, + "aliases": aliases, + "summary": f"Summary of {id}", + "affected": [ + { + "package": {"name": name, "ecosystem": "crates.io"}, + "ranges": [ + {"type": "SEMVER", "events": [{"introduced": "0.0.0-0"}, {"fixed": "0.2.0"}]} + ], + "database_specific": {"informational": informational}, + } + ], + } + if severity: + record["database_specific"] = {"severity": severity} + return record + + +RECORDS.update( + { + r["id"]: r + for r in [ + crate_record("GHSA-cccc-cccc-cccc", ["RUSTSEC-2024-0001"], "HIGH"), + crate_record("RUSTSEC-2024-0001", ["GHSA-cccc-cccc-cccc"]), + # a RustSec vulnerability that GitHub doesn't know: the severity is unknown + crate_record("RUSTSEC-2024-0002", []), + # notices that aren't vulnerabilities, without a GHSA record + crate_record("RUSTSEC-2024-0003", [], informational="unmaintained"), + crate_record("RUSTSEC-2024-0004", [], informational="unsound"), + crate_record("RUSTSEC-2024-0005", [], informational="notice"), + # a notice that GitHub has an advisory for: GitHub's severity counts + crate_record("RUSTSEC-2024-0006", ["GHSA-nnnn-nnnn-nnnn"], informational="unsound"), + crate_record("GHSA-nnnn-nnnn-nnnn", ["RUSTSEC-2024-0006"], "CRITICAL"), + ] + } +) + +CARGO_PACKAGES = """ +[[package]] +name = "demo" +version = "0.1.0" +dependencies = ["krate", "foo_bar"] + +[[package]] +name = "krate" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0000000000000000000000000000000000000000000000000000000000000000" + +[[package]] +name = "foo_bar" +version = "1.2.3" +source = "sparse+https://index.crates.io/" + +[[package]] +name = "fromgit" +version = "0.3.0" +source = "git+https://github.com/example/fromgit?rev=abc#abc" + +[[package]] +name = "private" +version = "2.0.0" +source = "registry+https://packages.example.com/index" + +[[package]] +name = "local" +version = "0.5.0" +""" + + +@pytest.mark.parametrize("version", [3, 4]) +def test_only_crates_from_crates_io_are_looked_up(scan, tmp_path: Path, version: int) -> None: + """Lock versions 3 and 4 have the same tables; only crates.io crates are sent.""" + lock = write(tmp_path / "Cargo.lock", f"version = {version}\n{CARGO_PACKAGES}") + packages = scan.locked_packages(lock, tmp_path) + assert [(p.name, p.version, p.ecosystem) for p in packages] == [ + ("foo_bar", "1.2.3", "crates.io"), + ("krate", "0.1.0", "crates.io"), + ] + # Cargo.lock doesn't tell the dependency kinds: every crate counts as a runtime one + assert all(p.runtime for p in packages) + osv = fake_osv(scan, {}) + scan.find(packages, osv) + assert osv.queries == [ + {"package": {"name": "foo_bar", "ecosystem": "crates.io"}, "version": "1.2.3"}, + {"package": {"name": "krate", "ecosystem": "crates.io"}, "version": "0.1.0"}, + ] + + +def test_a_crate_locked_twice_is_looked_up_once(scan, tmp_path: Path) -> None: + crate = ( + '[[package]]\nname = "krate"\nversion = "{}"\n' + 'source = "registry+https://github.com/rust-lang/crates.io-index"\n' + ) + lock = write( + tmp_path / "Cargo.lock", "version = 4\n" + crate.format("0.1.0") * 2 + crate.format("0.2.0") + ) + assert [p.version for p in scan.locked_packages(lock, tmp_path)] == ["0.1.0", "0.2.0"] + + +def test_an_invalid_cargo_lock_stops_the_scan(scan, tmp_path: Path) -> None: + with pytest.raises(scan.ScanError, match="Cargo.lock is not valid TOML"): + scan.locked_packages(write(tmp_path / "Cargo.lock", "[[package]\n"), tmp_path) + + +def test_crate_names_are_compared_exactly(scan) -> None: + """Cargo tells foo-bar and foo_bar apart; Python names ignore the separators and case.""" + record = crate_record("RUSTSEC-2024-0007", [], name="foo-bar") + assert scan.fix_versions( + record, scan.Package("Cargo.lock", "foo-bar", "0.1.0", True, "crates.io") + ) == ["0.2.0"] + assert ( + scan.fix_versions(record, scan.Package("Cargo.lock", "foo_bar", "0.1.0", True, "crates.io")) + == [] + ) + assert ( + scan.fix_versions(record, scan.Package("Cargo.lock", "Foo-Bar", "0.1.0", True, "crates.io")) + == [] + ) + python = osv_record("PYSEC-2020-9", []) + assert scan.fix_versions(python, scan.Package("uv.lock", "pkg", "1.0")) == ["1.1"] + # a record of another ecosystem isn't about a package of this one, even with the same name + assert ( + scan.fix_versions(python, scan.Package("Cargo.lock", "Pkg", "1.0", True, "crates.io")) == [] + ) + + +def scan_crate(scan, ids: list[str], exceptions=()) -> list: + package = scan.Package("rust/Cargo.lock", "krate", "0.1.0", ecosystem="crates.io") + osv = fake_osv(scan, {("krate", "0.1.0"): ids}) + findings = scan.find([package], osv) + scan.classify(findings, list(exceptions), osv) + return findings + + +@pytest.mark.parametrize( + ("ids", "severity", "blocking"), + [ + # RustSec and GitHub list one vulnerability twice: GitHub's severity counts + (["RUSTSEC-2024-0001", "GHSA-cccc-cccc-cccc"], "high", True), + (["RUSTSEC-2024-0001"], "high", True), + # a vulnerability without a GHSA record has an unknown severity, which blocks + (["RUSTSEC-2024-0002"], "unknown", True), + # notices are reported with their kind, and never block + (["RUSTSEC-2024-0003"], "informational: unmaintained", False), + (["RUSTSEC-2024-0004"], "informational: unsound", False), + (["RUSTSEC-2024-0005"], "informational: notice", False), + # unless GitHub has a severity for them + (["RUSTSEC-2024-0006"], "critical", True), + ], +) +def test_blocking_crates(scan, ids: list[str], severity: str, blocking: bool) -> None: + [f] = scan_crate(scan, ids) + assert (f.severity, f.blocking) == (severity, blocking) + + +def test_the_ghsa_record_of_a_crate_is_kept(scan) -> None: + [f] = scan_crate(scan, ["RUSTSEC-2024-0001", "GHSA-cccc-cccc-cccc"]) + assert f.id == "GHSA-cccc-cccc-cccc" + assert f.aliases == ["RUSTSEC-2024-0001"] + assert f.fix_versions == ["0.2.0"] + + +@pytest.mark.parametrize("id", ["RUSTSEC-2024-0001", "GHSA-cccc-cccc-cccc"]) +def test_an_exception_by_either_id_covers_a_crate(scan, id: str) -> None: + approval = scan.Approval(id, "https://e/1", "reason") + [f] = scan_crate(scan, ["RUSTSEC-2024-0001", "GHSA-cccc-cccc-cccc"], [approval]) + assert f.exception is approval + assert approval.used + assert not f.blocking + + +def test_a_blocking_unknown_crate_vulnerability_can_be_excepted(scan) -> None: + approval = scan.Approval("RUSTSEC-2024-0002", "https://e/1", "reason") + [f] = scan_crate(scan, ["RUSTSEC-2024-0002"], [approval]) + assert f.severity == "unknown" + assert not f.blocking + + +def test_the_report_of_a_lock_of_each_kind(scan) -> None: + package = scan.Package("rust/Cargo.lock", "krate", "0.1.0", ecosystem="crates.io") + osv = fake_osv(scan, {("krate", "0.1.0"): ["RUSTSEC-2024-0003", "RUSTSEC-2024-0002"]}) + findings = scan.find([package], osv) + scan.classify(findings, [], osv) + text = scan.report(findings, [], ["uv.lock", "rust/Cargo.lock"]) + assert "Python packages of `uv.lock` and the Rust crates of `rust/Cargo.lock`" in text + assert "every crate counts as a runtime dependency" in text + assert "| informational: unmaintained |" in text + assert "krate 0.1.0 (`rust/Cargo.lock`) | run time |" in text + # the blocking finding comes first, the notice last + assert text.index("RUSTSEC-2024-0002") < text.index("RUSTSEC-2024-0003") + only_python = scan.report([], [], ["uv.lock"]) + assert "Checked the Python packages of `uv.lock` against OSV." in only_python + assert "Cargo.lock" not in only_python + + +# --- the whole script on a repository, with a fake OSV ------------------------------------ + +UV_LOCK = ( + 'version = 1\n[[package]]\nname = "pkg"\nversion = "1.0"\n' + 'source = { registry = "https://pypi.org/simple" }\n' +) +CRATE_LOCK = ( + 'version = 4\n[[package]]\nname = "krate"\nversion = "0.1.0"\n' + 'source = "registry+https://github.com/rust-lang/crates.io-index"\n' +) + + +def tracked_repository(path: Path, files: dict[str, str]) -> Path: + path.mkdir() + git(path, "init", "--quiet") + for name, text in files.items(): + (path / name).parent.mkdir(parents=True, exist_ok=True) + (path / name).write_text(text, encoding="utf-8") + git(path, "add", "--all") + return path + + +def run_main(scan, repository: Path, osv, monkeypatch, capsys) -> tuple[int, str, str]: + summary = repository.parent / f"{repository.name}-summary.md" + monkeypatch.chdir(repository) + monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(summary)) + monkeypatch.setenv("EXCEPTIONS_FILE", ".github/vulnerability-exceptions.toml") + code = scan.main(osv) + return code, capsys.readouterr().out, summary.read_text(encoding="utf-8") + + +def test_the_locks_of_both_kinds_are_found(scan, tmp_path: Path) -> None: + repository = tracked_repository( + tmp_path / "repo", + { + "uv.lock": UV_LOCK, + "rust/Cargo.lock": CRATE_LOCK, + "Cargo.lock": CRATE_LOCK, + "docs/uv.lock": UV_LOCK, + }, + ) + # an untracked lock doesn't count + (repository / "other").mkdir() + (repository / "other" / "Cargo.lock").write_text(CRATE_LOCK, encoding="utf-8") + found = [str(p.relative_to(repository)) for p in scan.lock_files(repository)] + assert found == ["Cargo.lock", "docs/uv.lock", "rust/Cargo.lock", "uv.lock"] + + +def test_a_repository_with_both_locks(scan, tmp_path: Path, monkeypatch, capsys) -> None: + repository = tracked_repository( + tmp_path / "mixed", {"uv.lock": UV_LOCK, "rust/Cargo.lock": CRATE_LOCK} + ) + osv = fake_osv( + scan, + {("pkg", "1.0"): ["GHSA-medi-medi-medi"], ("krate", "0.1.0"): ["RUSTSEC-2024-0002"]}, + ) + code, out, summary = run_main(scan, repository, osv, monkeypatch, capsys) + assert code == 1 + assert "::error file=rust/Cargo.lock,title=unknown vulnerability in krate::" in out + assert "krate 0.1.0: RUSTSEC-2024-0002 (fixed in 0.2.0)" in out + assert "Python packages of `uv.lock` and the Rust crates of `rust/Cargo.lock`" in summary + assert "| ❌ blocking | krate 0.1.0 (`rust/Cargo.lock`) | run time |" in summary + assert "| reported | pkg 1.0 (`uv.lock`) |" in summary + # each ecosystem is queried for its own packages + assert {(q["package"]["name"], q["package"]["ecosystem"]) for q in osv.queries} == { + ("pkg", "PyPI"), + ("krate", "crates.io"), + } + + +def test_a_repository_with_only_a_cargo_lock(scan, tmp_path: Path, monkeypatch, capsys) -> None: + repository = tracked_repository(tmp_path / "rustonly", {"Cargo.lock": CRATE_LOCK}) + osv = fake_osv(scan, {("krate", "0.1.0"): ["RUSTSEC-2024-0003"]}) + code, out, summary = run_main(scan, repository, osv, monkeypatch, capsys) + assert code == 0 + assert "::error" not in out + assert "Checked the Rust crates of `Cargo.lock` against OSV." in summary + assert "informational: unmaintained" in summary + assert "| reported |" in summary + + +def test_a_crates_exception_passes_the_scan(scan, tmp_path: Path, monkeypatch, capsys) -> None: + repository = tracked_repository( + tmp_path / "excepted", + { + "rust/Cargo.lock": CRATE_LOCK, + ".github/vulnerability-exceptions.toml": ( + '[[exception]]\nid = "RUSTSEC-2024-0002"\n' + 'issue = "https://github.com/example/demo/issues/1"\nreason = "Test."\n' + ), + }, + ) + osv = fake_osv(scan, {("krate", "0.1.0"): ["RUSTSEC-2024-0002"]}) + code, out, summary = run_main(scan, repository, osv, monkeypatch, capsys) + assert code == 0, out + assert "[excepted](https://github.com/example/demo/issues/1)" in summary + + # --- end to end: real lock files and OSV -------------------------------------------------- needs_network = pytest.mark.skipif( @@ -402,7 +708,8 @@ def test_nothing_to_scan(script: Path, tmp_path: Path) -> None: git(repository, "init", "--quiet") result = run(script, repository) assert result.returncode == 0, result.stdout + result.stderr - assert "nothing to scan" in result.stdout + assert "No uv.lock or Cargo.lock" in result.stdout + assert "nothing to scan" in result.summary @needs_network @@ -466,3 +773,65 @@ def test_every_tracked_lock_is_scanned(script: Path, tmp_path: Path) -> None: result = run(script, repository) assert result.returncode == 1, result.stdout + result.stderr assert "tools/uv.lock" in result.summary + + +def crate(name: str, version: str) -> str: + return ( + f'\n[[package]]\nname = "{name}"\nversion = "{version}"\n' + 'source = "registry+https://github.com/rust-lang/crates.io-index"\n' + ) + + +@needs_network +def test_an_unmaintained_crate_is_reported_without_blocking(script: Path, tmp_path: Path) -> None: + """instant 0.1.12 is unmaintained (RUSTSEC-2024-0384): a notice, with no GHSA record.""" + lock = f"version = 4\n{crate('instant', '0.1.12')}" + result = run(script, tracked_repository(tmp_path / "instant", {"rust/Cargo.lock": lock})) + assert result.returncode == 0, result.stdout + result.stderr + assert "Checked the Rust crates of `rust/Cargo.lock` against OSV." in result.summary + assert "| reported | instant 0.1.12 (`rust/Cargo.lock`) | run time |" in result.summary + assert "RUSTSEC-2024-0384" in result.summary + assert "informational: unmaintained" in result.summary + + +@needs_network +def test_a_crate_advisory_is_one_finding_with_github_severity(script: Path, tmp_path: Path) -> None: + """RUSTSEC-2023-0071 and its two GHSA records are one finding, with the GHSA severity.""" + lock = f"version = 4\n{crate('rsa', '0.9.6')}" + result = run(script, tracked_repository(tmp_path / "rsa", {"rust/Cargo.lock": lock})) + assert "rsa 0.9.6 (`rust/Cargo.lock`)" in result.summary + assert "[GHSA-" in result.summary + assert "RUSTSEC-2023-0071" not in result.summary + assert "| unknown |" not in result.summary + + +@needs_network +def test_a_vulnerable_crate_fails_until_excepted(script: Path, tmp_path: Path) -> None: + # pyo3 0.19.0 has a high-severity advisory (out-of-bounds read), among others + lock = f"version = 4\n{crate('pyo3', '0.19.0')}" + repository = tracked_repository(tmp_path / "pyo3", {"rust/Cargo.lock": lock}) + result = run(script, repository) + assert result.returncode == 1, result.stdout + result.stderr + assert "::error file=rust/Cargo.lock,title=high vulnerability in pyo3::" in result.stdout + assert "❌ blocking" in result.summary + + ids = sorted( + { + line.split(": ", 1)[1].split(" ", 1)[0] + for line in result.stdout.splitlines() + if line.startswith("::error file=") + } + ) + assert ids + exceptions = repository / ".github" / "vulnerability-exceptions.toml" + exceptions.parent.mkdir() + exceptions.write_text( + "".join( + f'[[exception]]\nid = "{i}"\nissue = "https://github.com/example/demo/issues/1"\nreason = "Test."\n\n' + for i in ids + ), + encoding="utf-8", + ) + result = run(script, repository) + assert result.returncode == 0, result.stdout + result.stderr + assert "excepted" in result.summary