~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
ci: pin reviewed licenses, not tool versions, so Dependabot bumps pass (#7533)
LearningCircuitee5ab38c5e9d
diff --git a/.github/scripts/check_dependency_licenses.py b/.github/scripts/check_dependency_licenses.pyindex 1e38d2ff96..28e6c90f48 100644--- a/.github/scripts/check_dependency_licenses.py+++ b/.github/scripts/check_dependency_licenses.py@@ -5,25 +5,104 @@ The Dependency Review action ignores versions and manifests in its packageexceptions. Inspect repository requirements/PEP 621/PDM dependencies,including local requirements includes, before applying those exceptions.Other Python manifests and unreviewed project configuration fail closed.++Each exempted package is pinned to the license metadata that was reviewed,+not to a release number. Every exact version locked in a reviewed manifest+is looked up on PyPI (``/pypi/<name>/<version>/json``), and its+License-Expression, License, License-File and license classifiers must equal+the reviewed values. A release that keeps them passes without a code change;+a changed, missing or unreadable license, or a failed lookup, fails closed.+For packages in REVIEWED_WHEEL_CONTENTS (docutils), each hash-locked wheel+is also downloaded, hash-verified and listed, because that exception rests+on what the wheel leaves out rather than on its metadata."""from __future__ import annotationsimport argparse+import hashlib+import http.client+import io+import jsonimport reimport shleximport subprocessimport sys+import timeimport tomllib+import urllib.error+import urllib.parse+import urllib.request+import zipfile+from collections.abc import Callablefrom pathlib import Path+from typing import NamedTuplefrom packaging.requirements import Requirementfrom packaging.specifiers import InvalidSpecifier, SpecifierSet-from packaging.utils import canonicalize_name+from packaging.utils import (+ InvalidWheelFilename,+ canonicalize_name,+ parse_wheel_filename,+)+from packaging.version import InvalidVersion, Version+++class License(NamedTuple):+ """The license fields of one release's core metadata, normalized.++ ``expression`` is License-Expression (PEP 639), ``text`` the legacy+ License field, ``files`` the License-File entries and ``classifiers``+ the ``License ::`` trove classifiers. Every field takes part in the+ comparison, so a new license file or classifier also needs review,+ except that absent License-File entries are tolerated (see+ license_matches).+ """+ expression: str | None = None+ text: str | None = None+ files: tuple[str, ...] = ()+ classifiers: tuple[str, ...] = ()+ def describe(self) -> str:+ parts = [+ f"{label}={value!r}"+ for label, value in (+ ("License-Expression", self.expression),+ ("License", self.text),+ ("License-File", list(self.files)),+ ("classifiers", list(self.classifiers)),+ )+ if value+ ]+ return ", ".join(parts) or "no license metadata"+++# Package -> (reviewed license metadata, manifests the exception covers).+# Releases are not pinned here: any exactly pinned version whose PyPI+# metadata equals the reviewed license passes, so a Dependabot bump that+# keeps the license needs no edit. Changing a license or a location below+# is a license review; see requirements/README.md.REVIEWED = {- "docutils": ("0.23", {"requirements/twine.txt"}),+ # The metadata names every source license, GPL included. The exception+ # rests on the wheel omitting the GPL-covered Emacs source file, which+ # REVIEWED_WHEEL_CONTENTS checks in each locked wheel.+ "docutils": (+ License(+ files=(+ "COPYING.rst",+ "licenses/BSD-0-Clause.rst",+ "licenses/BSD-2-Clause.rst",+ "licenses/gpl-3-0.txt",+ ),+ classifiers=(+ "License :: OSI Approved :: BSD License",+ "License :: OSI Approved :: GNU General Public License (GPL)",+ "License :: Public Domain",+ ),+ ),+ {"requirements/twine.txt"},+ ),"semgrep": (# License review for 1.181.0 (2026-10-22, from 1.180.0): PyPI# metadata carries license_expression LGPL-2.1-or-later on both@@ -32,12 +111,15 @@ REVIEWED = {# exception's license scope is unchanged. Covers the CLI used in CI# only; see "Reviewed scanner license metadata" in# requirements/README.md.- "1.181.0",+ License(expression="LGPL-2.1-or-later", files=("LICENSE",)),{"requirements/semgrep.in", "requirements/semgrep.txt"},),- "protobuf": ("6.33.6", {"requirements/semgrep.txt"}),+ "protobuf": (+ License(text="3-Clause BSD License"),+ {"requirements/semgrep.txt"},+ ),"typing-extensions": (- "4.16.0",+ License(expression="PSF-2.0", files=("LICENSE",)),{"pyproject.toml","pdm.lock",@@ -49,6 +131,26 @@ REVIEWED = {),}+# Package -> top-level directories its wheel may contain besides its+# ``<name>-<version>.dist-info/``. Every hash-locked wheel of these packages+# is downloaded, hash-verified and listed; an entry elsewhere or a file with+# a FORBIDDEN_WHEEL_SUFFIXES suffix fails. For docutils this is the+# GPL-covered docutils/.../*.el Emacs mode that the sdist ships.+REVIEWED_WHEEL_CONTENTS = {"docutils": ("docutils",)}+FORBIDDEN_WHEEL_SUFFIXES = (".el",)++PYPI_JSON_URL = "https://pypi.org/pypi/{name}/{version}/json"+PYPI_HOST = "pypi.org"+WHEEL_HOSTS = frozenset({"files.pythonhosted.org", PYPI_HOST})+PYPI_TIMEOUT_SECONDS = 30+# The release JSON lists every file; semgrep's is well under 1 MB.+PYPI_MAX_BYTES = 16 * 1024 * 1024+# docutils' wheel is under 1 MB.+WHEEL_MAX_BYTES = 64 * 1024 * 1024+# Timeouts, connection failures and 5xx responses are retried once.+RETRY_DELAY_SECONDS = 2.0+_sleep = time.sleep+# These dependency formats/configurations are not parsed by this guard.# Refuse them even when they currently contain no exempted package: adding# parser support must precede any package-wide license exception there.@@ -114,7 +216,35 @@ class PolicyError(ValueError):"""A dependency cannot be covered by the reviewed exception."""-def check_requirement(text: str, manifest: str) -> None:+# (canonical name, version) -> the release's PyPI JSON document.+MetadataFetcher = Callable[[str, str], object]+# File URL from that document -> the file's bytes.+FileDownloader = Callable[[str], bytes]+++class Pin:+ """Where an exempted release is pinned, and the hashes locked for it."""++ def __init__(self) -> None:+ self.manifests: set[str] = set()+ self.hashes: set[str] = set()+++# (canonical name, version) -> pin whose license must be verified.+Pins = dict[tuple[str, str], Pin]+++def _is_version(text: str) -> bool:+ try:+ Version(text)+ except InvalidVersion:+ return False+ return True+++def check_requirement(+ text: str, manifest: str, pins: Pins, hashes: tuple[str, ...] = ()+) -> None:requirement = Requirement(text)name = canonicalize_name(requirement.name)if requirement.url:@@ -123,21 +253,274 @@ def check_requirement(text: str, manifest: str) -> None:raise PolicyError(f"{manifest}: {name}: direct source requires review")if name not in REVIEWED:return- version, locations = REVIEWED[name]+ _license, locations = REVIEWED[name]if manifest not in locations:raise PolicyError(f"{manifest}: {name} is outside its reviewed locations")- allowed = {f"=={version}"}+ specifier = str(requirement.specifier)if manifest == "pyproject.toml" and name == "typing-extensions":# Preserve the published application constraint. pdm.lock is checked# separately; this exception does not freeze consumer installations.- allowed.add("~=4.15")+ if specifier == "~=4.15":+ return# Never evaluate markers on the CI host: other platforms need review too.- if str(requirement.specifier) not in allowed:+ # Only one exact release can be looked up, so ranges, arbitrary+ # equality (===) and wildcards (==1.*, not a valid Version) are not+ # license-checkable.+ specs = list(requirement.specifier)+ if not (+ len(specs) == 1+ and specs[0].operator == "=="+ and _is_version(specs[0].version)+ ):raise PolicyError(- f"{manifest}: {name} requires review (reviewed version: {version})"+ f"{manifest}: {name}{specifier} requires review "+ "(only an exact == pin can be license-checked)")+ pin = pins.setdefault((name, specs[0].version), Pin())+ pin.manifests.add(manifest)+ pin.hashes.update(hashes)+++def _https_get(+ url: str, hosts: frozenset[str], max_bytes: int, timeout: float+) -> bytes:+ """GET an https URL on ``hosts``; retry transient failures once."""+ if urllib.parse.urlsplit(url).scheme != "https" or (+ urllib.parse.urlsplit(url).hostname not in hosts+ ):+ raise PolicyError(f"refusing to fetch {url}")+ # https on a reviewed host, checked above and after redirects (S310).+ request = urllib.request.Request(url) # noqa: S310+ for attempt in (1, 2):+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310+ final = urllib.parse.urlsplit(response.geturl())+ body = response.read(max_bytes + 1)+ break+ except urllib.error.HTTPError as exc:+ # 4xx answers are definitive; only server errors may pass.+ if exc.code < 500 or attempt == 2:+ raise PolicyError(f"download failed: {exc}") from exc+ except (+ urllib.error.URLError,+ TimeoutError,+ ConnectionError,+ http.client.HTTPException,+ ) as exc:+ if attempt == 2:+ raise PolicyError(f"download failed: {exc}") from exc+ except (OSError, ValueError) as exc:+ # Anything else (a malformed URL or response) is not transient.+ raise PolicyError(f"download failed: {exc}") from exc+ _sleep(RETRY_DELAY_SECONDS)+ if final.scheme != "https" or final.hostname not in hosts:+ raise PolicyError(f"download was redirected to {final.geturl()}")+ if len(body) > max_bytes:+ raise PolicyError(f"response from {url} is too large")+ return body+++def fetch_pypi_metadata(+ name: str, version: str, timeout: float = PYPI_TIMEOUT_SECONDS+) -> object:+ """Return PyPI's JSON document for one release; raise on any failure."""+ url = PYPI_JSON_URL.format(+ name=urllib.parse.quote(name, safe=""),+ version=urllib.parse.quote(version, safe=""),+ )+ body = _https_get(url, frozenset({PYPI_HOST}), PYPI_MAX_BYTES, timeout)+ try:+ document = json.loads(body)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise PolicyError(f"PyPI metadata is not JSON: {exc}") from exc+ if not isinstance(document, dict) or "info" not in document:+ raise PolicyError("PyPI metadata has no info object")+ return document+++def download_wheel(url: str, timeout: float = PYPI_TIMEOUT_SECONDS) -> bytes:+ """Download one release file from PyPI's file hosts."""+ return _https_get(url, WHEEL_HOSTS, WHEEL_MAX_BYTES, timeout)+++def _optional_text(info: dict, key: str) -> str | None:+ value = info.get(key)+ if value is None:+ return None+ if not isinstance(value, str):+ raise PolicyError(f"PyPI metadata field {key} is not a string")+ return value.strip() or None+++def _text_list(info: dict, key: str) -> list[str]:+ value = info.get(key)+ if value is None:+ return []+ if not isinstance(value, list) or not all(+ isinstance(item, str) for item in value+ ):+ raise PolicyError(f"PyPI metadata field {key} is not a list of strings")+ return value+++def license_from_metadata(info: object, name: str, version: str) -> License:+ """Normalize a release's license fields, failing closed on bad data."""+ if not isinstance(info, dict):+ raise PolicyError("PyPI metadata info is not an object")+ claimed_name = info.get("name")+ claimed_version = info.get("version")+ if not isinstance(claimed_name, str) or not isinstance(+ claimed_version, str+ ):+ raise PolicyError("PyPI metadata does not name its release")+ try:+ same_release = canonicalize_name(claimed_name) == name and Version(+ claimed_version+ ) == Version(version)+ except InvalidVersion:+ same_release = False+ if not same_release:+ raise PolicyError(+ f"PyPI returned metadata for {claimed_name} {claimed_version}"+ )+ found = License(+ expression=_optional_text(info, "license_expression"),+ text=_optional_text(info, "license"),+ files=tuple(sorted(set(_text_list(info, "license_files")))),+ classifiers=tuple(+ sorted(+ {+ item.strip()+ for item in _text_list(info, "classifiers")+ if item.strip().startswith("License ::")+ }+ )+ ),+ )+ if not (found.expression or found.text or found.classifiers):+ raise PolicyError("PyPI metadata declares no license")+ return found+++def license_matches(found: License, expected: License) -> bool:+ """Whether release metadata matches the reviewed license.++ PyPI's ``info`` comes from the release's first uploaded file, and+ builds of one release can differ in License-File only (semgrep's Linux+ wheels list none; its macOS/Windows wheels list LICENSE). An empty+ License-File list is therefore accepted when every other field matches.+ A non-empty list must equal the reviewed one: a new or renamed license+ file still needs review.+ """+ if found == expected:+ return True+ return not found.files and found._replace(files=expected.files) == expected+++def _locked_wheels(name: str, version: str, release: dict, hashes: set[str]):+ """Yield (filename, url, sha256) for every locked wheel of a release."""+ if not hashes:+ raise PolicyError("no --hash is locked, so the wheel cannot be checked")+ files = release.get("urls")+ if not isinstance(files, list):+ raise PolicyError("PyPI metadata has no file list")+ by_digest = {}+ for entry in files:+ digests = entry.get("digests") if isinstance(entry, dict) else None+ digest = digests.get("sha256") if isinstance(digests, dict) else None+ if isinstance(digest, str):+ by_digest[digest.lower()] = entry+ wheels = 0+ for locked in sorted(hashes):+ algorithm, _, digest = locked.partition(":")+ digest = digest.lower()+ if algorithm != "sha256" or not re.fullmatch(r"[0-9a-f]{64}", digest):+ raise PolicyError(f"locked hash {locked} is not a sha256 digest")+ entry = by_digest.get(digest)+ if entry is None:+ raise PolicyError(+ f"locked hash {digest} is not a file of the release"+ )+ filename, url = entry.get("filename"), entry.get("url")+ if not isinstance(filename, str) or not isinstance(url, str):+ raise PolicyError(f"PyPI file entry for {digest} is malformed")+ if not filename.endswith(".whl"):+ # The lock's sdist hash is never installed: the only consumer+ # installs with --only-binary=:all: (pinned by+ # tests/ci/test_semgrep_workflow.py's Twine install contract).+ continue+ try:+ wheel_name, wheel_version, _build, _tags = parse_wheel_filename(+ filename+ )+ except (InvalidWheelFilename, InvalidVersion) as exc:+ raise PolicyError(f"invalid wheel filename {filename}") from exc+ if wheel_name != name or wheel_version != Version(version):+ raise PolicyError(f"{filename} is not a wheel of this release")+ wheels += 1+ yield filename, url, digest+ if not wheels:+ raise PolicyError("no wheel is locked, so none can be checked")+++def check_wheel_contents(filename: str, body: bytes, digest: str, packages):+ """Fail unless the wheel matches its hash and holds only reviewed files."""+ if hashlib.sha256(body).hexdigest() != digest:+ raise PolicyError(f"{filename} does not match its locked sha256")+ # <escaped name>-<version>.dist-info, as named in the wheel filename.+ dist_info = "-".join(filename.split("-")[:2]) + ".dist-info/"+ allowed = (*(f"{package}/" for package in packages), dist_info)+ try:+ with zipfile.ZipFile(io.BytesIO(body)) as wheel:+ entries = wheel.namelist()+ except (zipfile.BadZipFile, ValueError, OSError) as exc:+ raise PolicyError(f"{filename} is not a readable wheel: {exc}") from exc+ for entry in entries:+ parts = entry.split("/")+ if "\\" in entry or ".." in parts or not entry.startswith(allowed):+ raise PolicyError(f"{filename} contains unreviewed path {entry}")+ if entry.casefold().endswith(FORBIDDEN_WHEEL_SUFFIXES):+ raise PolicyError(f"{filename} contains {entry}")+++def check_license(+ name: str,+ version: str,+ fetch: MetadataFetcher,+ download: FileDownloader = download_wheel,+ hashes: set[str] = frozenset(),+) -> None:+ expected, _locations = REVIEWED[name]+ try:+ release = fetch(name, version)+ info = release.get("info") if isinstance(release, dict) else None+ found = license_from_metadata(info, name, version)+ except Exception as exc:+ # Fail closed on anything, including an unexpected fetcher error:+ # an unverified release must not reach the package-wide exception.+ raise PolicyError(+ f"{name} {version}: cannot verify license, requires review: {exc}"+ ) from exc+ if not license_matches(found, expected):+ raise PolicyError(+ f"{name} {version}: license metadata changed, requires review "+ f"(reviewed: {expected.describe()}; found: {found.describe()})"+ )+ if name not in REVIEWED_WHEEL_CONTENTS:+ return+ try:+ for filename, url, digest in _locked_wheels(+ name, version, release, hashes+ ):+ check_wheel_contents(+ filename, download(url), digest, REVIEWED_WHEEL_CONTENTS[name]+ )+ except Exception as exc:+ raise PolicyError(+ f"{name} {version}: wheel contents need review: {exc}"+ ) from excdef logical_lines(path: Path):@@ -161,7 +544,11 @@ def logical_lines(path: Path):def check_requirements(- root: Path, path: Path, origin: str, parents: tuple[Path, ...] = ()+ root: Path,+ path: Path,+ origin: str,+ pins: Pins,+ parents: tuple[Path, ...] = (),) -> None:resolved = path.resolve()if not resolved.is_relative_to(root) or resolved in parents:@@ -185,14 +572,20 @@ def check_requirements(# Retain the importing environment. An application requirements# file must not import the otherwise-approved Semgrep/Twine lock.check_requirements(- root, path.parent / targets[0], origin, (*parents, resolved)+ root,+ path.parent / targets[0],+ origin,+ pins,+ (*parents, resolved),)continue# Only hashes are per-requirement options in our committed locks.# Other options, bare URLs, editables and environment substitutions# are rejected by Requirement instead of being silently skipped.- line = re.sub(r"\s+--hash(?:=|\s+)\S+", "", line)- check_requirement(line, origin)+ hash_option = r"\s+--hash(?:=|\s+)(\S+)"+ hashes = tuple(re.findall(hash_option, line))+ line = re.sub(hash_option, "", line)+ check_requirement(line, origin, pins, hashes)def check_project_configuration(project: dict) -> None:@@ -267,9 +660,14 @@ def repository_paths(root: Path) -> list[Path]:]-def validate(root: Path) -> list[str]:+def validate(+ root: Path,+ fetch: MetadataFetcher = fetch_pypi_metadata,+ download: FileDownloader = download_wheel,+) -> list[str]:root = root.resolve()errors = []+ pins: Pins = {}for relative in repository_paths(root):path = root / relativemanifest = relative.as_posix()@@ -295,12 +693,12 @@ def validate(root: Path) -> list[str]:if unsupported:raise PolicyError("unsupported Python manifest needs review")if requirements:- check_requirements(root, path, manifest)+ check_requirements(root, path, manifest, pins)elif name == "pyproject.toml":project = tomllib.loads(path.read_text(encoding="utf-8"))check_project_configuration(project)for requirement in project_requirements(project):- check_requirement(requirement, manifest)+ check_requirement(requirement, manifest, pins)else:lock = tomllib.loads(path.read_text(encoding="utf-8"))if "packages" in lock or "lock-version" in lock:@@ -342,13 +740,27 @@ def validate(root: Path) -> list[str]:raise PolicyError(f"{name}: lock file url entries need review")- check_requirement(f"{name}=={package['version']}", manifest)+ check_requirement(+ f"{name}=={package['version']}", manifest, pins+ )except (ValueError, OSError, KeyError) as exc:errors.append(f"{manifest}: {exc}")+ if errors:+ # The manifests already fail review; do not query PyPI as well.+ return errors+ for (name, version), pin in sorted(pins.items()):+ try:+ check_license(name, version, fetch, download, pin.hashes)+ except PolicyError as exc:+ errors.append(f"{', '.join(sorted(pin.manifests))}: {exc}")return errors-def main() -> int:+def main(+ argv: list[str] | None = None,+ fetch: MetadataFetcher = fetch_pypi_metadata,+ download: FileDownloader = download_wheel,+) -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("root",@@ -356,7 +768,7 @@ def main() -> int:type=Path,default=Path(__file__).resolve().parents[2],)- errors = validate(parser.parse_args().root)+ errors = validate(parser.parse_args(argv).root, fetch, download)if errors:print("Dependency license exception policy failed:", file=sys.stderr)for error in errors:diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.ymlindex 244739088f..54005344a6 100644--- a/.github/workflows/dependency-review.yml+++ b/.github/workflows/dependency-review.yml@@ -101,14 +101,17 @@ jobs:BlueOak-1.0.0# Allow specific packages with complex license expressions.# dompurify is dual-licensed (Apache-2.0 OR MPL-2.0) but npm reports complex SPDX- # docutils 0.23 is only in the isolated Twine validation environment.+ # docutils is only in the isolated Twine validation environment.# Its wheel omits the GPL-covered Emacs source file; metadata reports# all source licenses. The guard above rejects application use.# Semgrep is an isolated CI CLI, never an application dependency.# Protobuf's wheel carries BSD-3-Clause; typing-extensions declares# PSF-2.0. GitHub reports extra LicenseRef / historical GPL terms.- # The guard above checks reviewed versions and manifest locations,- # including requirements includes and normalized names. Exceptions+ # The guard above checks manifest locations (including requirements+ # includes and normalized names) and that every locked version's+ # PyPI license metadata equals the reviewed license, and that each+ # locked docutils wheel has no .el or other unreviewed file; it+ # needs egress to pypi.org and files.pythonhosted.org. Exceptions# do not bypass vulnerability review.allow-dependencies-licenses: >-pkg:npm/dompurify,diff --git a/requirements/README.md b/requirements/README.mdindex c2d5efadbb..581ce50420 100644--- a/requirements/README.md+++ b/requirements/README.md@@ -5,8 +5,12 @@ with SHA256 hashes. Regenerate `.in` files using the pip-tools command in theirheaders on Python 3.12, and review version and hash changes before committingthe input and export together. Installs use `--require-hashes`.-Semgrep is pinned to 1.181.0, whose default ignore rules are modeled by the report-integrity tests. Twine is pinned to the current 7.0.0 release and runs in its own+Semgrep is pinned with `==` in `semgrep.in`, and+`tests/ci/test_semgrep_workflow.py` checks that `semgrep.txt` locks the same+release (and a PyJWT release satisfying the floor below). The report integrity+tests model Semgrep's default ignore rules as of 1.181.0; no automated check+detects a release that changes them, so re-check that model when reviewing a+Semgrep bump. Twine is pinned to the current 7.0.0 release and runs in its ownvirtual environment so it cannot change application dependencies under test.Both tool installs require binary wheels. The application wheel and sdist checkscontinue to use fresh pip resolution of the shipped package metadata; these CI@@ -59,15 +63,52 @@ environment.### Reviewed scanner license metadataDependency review adds MIT-0 to its general license list alongside these-changes. The package-level exceptions for the isolated scanner were reviewed at-Semgrep 1.181.0 (LGPL-2.1-or-later; license metadata unchanged from 1.180.0),-protobuf 6.33.6 and typing-extensions 4.16.0. Docutils 0.23 is reviewed only in-the isolated Twine lock. The action ignores versions and manifest locations in-exception PURLs, so+changes. The package-level exceptions for the isolated scanner were first+reviewed at Semgrep 1.179.0, protobuf 6.33.6 and typing-extensions 4.16.0, and+docutils at 0.23, only in the isolated Twine lock. The Semgrep 1.181.0 review+confirmed its LGPL-2.1-or-later license metadata is unchanged from 1.180.0.+The action ignores versions and manifest locations in exception PURLs, so`.github/scripts/check_dependency_licenses.py` runs in the Dependency Reviewjob before the action can apply these exceptions. Its parser andcommand-line regression tests run in the same job, using only the-hash-locked `packaging` dependency in `dependency-review.txt`.+hash-locked `packaging` dependency in `dependency-review.txt`; the tests use a+fake index and never contact PyPI.++The guard pins each exempted package's reviewed license metadata (`REVIEWED`+in the script), not a release number. For every exact `==` version of an+exempted package in a reviewed manifest it fetches+`https://pypi.org/pypi/<name>/<version>/json` and requires+`License-Expression`, `License`, `License-File` and the `License ::`+classifiers to equal the reviewed values. A Dependabot bump that keeps the+license therefore passes with no edit. A release whose license metadata+differs fails with both licenses in the message; missing or malformed+metadata, a mismatched release in the response, a redirect away from+`https://pypi.org`, a timeout or any other lookup error also fail closed.+Timeouts, connection errors and 5xx responses are retried once after a short+pause; 4xx and malformed responses are not.++PyPI's release metadata comes from the first file uploaded for a release, and+builds can differ in `License-File` only (semgrep's Linux wheels list none,+its macOS and Windows wheels list `LICENSE`). An empty `License-File` list is+therefore accepted when every other field matches; a non-empty list that+differs from the reviewed one still fails. The metadata is declared by the+package authors: a release that changes a LICENSE file's text but keeps the+same metadata and file names passes. That is an accepted trade-off for+package-wide exceptions that stay limited to the manifests above.++Docutils is the exception, because its exception rests on the wheel's+contents rather than its metadata (which names the GPL too). For each+docutils wheel hash in `requirements/twine.txt` the guard finds that file in+the release JSON, downloads it from `files.pythonhosted.org`, verifies the+sha256, and fails if the wheel contains any `.el` file or any entry outside+`docutils/` and its `docutils-<version>.dist-info/`. The sdist hash that+pip-compile also locks is not downloaded: the Twine install uses+`--only-binary=:all:`, which `tests/ci/test_semgrep_workflow.py` pins.++When the guard fails on a bump, review the new release's license (and, for+docutils, its wheel contents). Update `REVIEWED` only if the license itself+changed and is still acceptable; a release that keeps the license needs no+change there.The guard checks every tracked or new, non-ignored requirements manifest(`requirements*.in`, `requirements*.txt`, and `.in`/`.txt` files under any@@ -112,13 +153,14 @@ requests/lxml resolution overrides remain supported.This source policy covers committed configuration, not ambient machineconfiguration or arbitrary commands outside the dependency manifests.-The explicit version and location policy keeps Semgrep in its scanner files,+The license and location policy keeps Semgrep in its scanner files,protobuf in the scanner lock, and docutils in the Twine lock. Typing-extensionsis already an application dependency: its existing `~=4.15` project constraint-remains, while the application and CI locks must resolve to reviewed 4.16.0.-The MCP extra lock is a reviewed location for that pin (it pulls-typing-extensions transitively). New versions, locations or requirement forms-need an explicit policy review.+remains, while the application and CI locks must pin exact releases whose+license metadata matches the reviewed license. The MCP extra lock is a reviewed+location for typing-extensions, which it pulls transitively; its locked release+must also satisfy the application's constraint. New licenses, locations or+requirement forms (ranges, wildcards, `===`) need an explicit policy review.This checks committed dependencies; it does not constrain versions installedby package consumers. Vulnerability checks still apply to every package, andLGPL/GPL are not added to the general license list.diff --git a/tests/ci/standalone/test_dependency_licenses.py b/tests/ci/standalone/test_dependency_licenses.pyindex 786a481828..9c1db1d56b 100644--- a/tests/ci/standalone/test_dependency_licenses.py+++ b/tests/ci/standalone/test_dependency_licenses.py@@ -1,14 +1,21 @@"""Exercise the real license guard against repository and requirements changes."""+import contextlib+import hashlibimport importlib.util+import ioimport jsonimport re+import socketimport subprocessimport sysimport tempfileimport tomllibimport unittest+import urllib.error+import zipfilefrom pathlib import Path+from unittest import mockROOT = Path(__file__).resolve().parents[3]@@ -17,6 +24,134 @@ SPEC = importlib.util.spec_from_file_location("dependency_licenses", SCRIPT)POLICY = importlib.util.module_from_spec(SPEC)SPEC.loader.exec_module(POLICY)+# Versions here are synthetic: the guard pins licenses, not releases, and+# the fake index below serves the reviewed license for every version except+# UNREVIEWED, whose license differs. Nothing in these tests is tied to the+# currently locked release numbers.+UNREVIEWED = "0.0.0"+BUMPED = "999.0.0"+CHANGED = POLICY.License(expression="GPL-3.0-only", files=("COPYING",))+++def pypi_info(name, version, license):+ """A PyPI JSON ``info`` object carrying ``license``'s fields."""+ return {+ "name": name,+ "version": version,+ "license_expression": license.expression,+ "license": license.text or "",+ "license_files": list(license.files) or None,+ "classifiers": [+ "Programming Language :: Python :: 3",+ *license.classifiers,+ ],+ }+++def make_wheel(version, extra=()):+ """A deterministic docutils-like wheel; ``extra`` adds entry names."""+ buffer = io.BytesIO()+ dist_info = f"docutils-{version}.dist-info"+ with zipfile.ZipFile(buffer, "w") as wheel:+ for name in (+ "docutils/__init__.py",+ "docutils/parsers/rst/__init__.py",+ f"{dist_info}/METADATA",+ f"{dist_info}/licenses/COPYING.rst",+ f"{dist_info}/licenses/licenses/gpl-3-0.txt",+ f"{dist_info}/RECORD",+ *extra,+ ):+ wheel.writestr(zipfile.ZipInfo(name, (2020, 1, 1, 0, 0, 0)), "")+ return buffer.getvalue()+++def sha256(body):+ return hashlib.sha256(body).hexdigest()+++SDIST_DIGEST = "a" * 64+++def wheel_url(version):+ return (+ "https://files.pythonhosted.org/packages/00/"+ f"docutils-{version}-py3-none-any.whl"+ )+++def docutils_lock(version):+ """A twine.txt pin locking the fake wheel and an sdist, as pip-compile does."""+ return (+ f"docutils=={version} \\\n"+ f" --hash=sha256:{sha256(make_wheel(version))} \\\n"+ f" --hash=sha256:{SDIST_DIGEST}\n"+ )+++def release_files(name, version):+ """PyPI's ``urls`` list: the fake wheel and an sdist for docutils."""+ if name != "docutils":+ return []+ return [+ {+ "filename": f"docutils-{version}-py3-none-any.whl",+ "url": wheel_url(version),+ "digests": {"sha256": sha256(make_wheel(version))},+ },+ {+ "filename": f"docutils-{version}.tar.gz",+ "url": f"https://files.pythonhosted.org/docutils-{version}.tar.gz",+ "digests": {"sha256": SDIST_DIGEST},+ },+ ]+++class FakePyPI:+ """Stand-in for fetch_pypi_metadata; never touches the network.++ ``responses`` overrides a release's ``info`` object (or raises an+ exception); ``documents`` overrides the whole JSON document.+ """++ def __init__(self):+ self.calls = []+ self.responses = {}+ self.documents = {}++ def __call__(self, name, version):+ self.calls.append((name, version))+ if (name, version) in self.documents:+ return self.documents[(name, version)]+ if (name, version) in self.responses:+ response = self.responses[(name, version)]+ if isinstance(response, BaseException):+ raise response+ info = response+ else:+ reviewed, _locations = POLICY.REVIEWED[name]+ license = CHANGED if version == UNREVIEWED else reviewed+ info = pypi_info(name, version, license)+ return {"info": info, "urls": release_files(name, version)}+++class FakeFiles:+ """Stand-in for download_wheel serving the fake wheels."""++ def __init__(self):+ self.calls = []+ self.responses = {}++ def __call__(self, url):+ self.calls.append(url)+ response = self.responses.get(url)+ if isinstance(response, BaseException):+ raise response+ if response is not None:+ return response+ version = url.rsplit("/", 1)[1].split("-")[1]+ return make_wheel(version)+def mcp_extra_mirror_errors(root: Path) -> list[str]:"""Return drift between requirements/mcp-extra.in and pyproject.toml.@@ -43,15 +178,16 @@ def mcp_extra_mirror_errors(root: Path) -> list[str]:shared = named(metadata.get("dependencies", []))extra = named(metadata["optional-dependencies"]["mcp"])- pinned = set()+ pinned: dict[str, list[str]] = {}for line in ((root / "requirements/mcp-extra.txt").read_text(encoding="utf-8").splitlines()):- match = re.match(r"([A-Za-z0-9][A-Za-z0-9._-]*)==", line)+ match = re.match(r"([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;\\]+)", line)if match:- pinned.add(POLICY.canonicalize_name(match.group(1)))+ name = POLICY.canonicalize_name(match.group(1))+ pinned.setdefault(name, []).append(match.group(2))repeats = {}mirrors = {}for line in POLICY.logical_lines(root / "requirements/mcp-extra.in"):@@ -96,12 +232,21 @@ def mcp_extra_mirror_errors(root: Path) -> list[str]:f" pyproject.toml specifier ({found.specifier} against"f" {bound.specifier})")- for name in sorted(set(shared) & pinned):- if name in mirrors:- continue+ for name in sorted(set(shared) & pinned.keys()):if name in POLICY.REVIEWED:- # The license policy holds this package at its exact reviewed- # lock version and rejects a mirror here, so it cannot drift.+ # The license policy checks exact releases instead of a range+ # mirror. Those releases must still satisfy application bounds.+ for version in pinned[name]:+ if not shared[name].specifier.contains(+ version, prereleases=True+ ):+ errors.append(+ f"requirements/mcp-extra.txt: {name}=={version}"+ " does not satisfy its pyproject.toml specifier"+ f" ({shared[name].specifier})"+ )+ continue+ if name in mirrors:continueerrors.append(f"requirements/mcp-extra.in: {name} is a pyproject.toml"@@ -112,7 +257,12 @@ def mcp_extra_mirror_errors(root: Path) -> list[str]:class LicensePolicyTests(unittest.TestCase):+ def validate(self, root=None):+ return POLICY.validate(root or self.root, self.pypi, self.files)+def setUp(self):+ self.pypi = FakePyPI()+ self.files = FakeFiles()directory = tempfile.TemporaryDirectory()self.addCleanup(directory.cleanup)self.root = Path(directory.name)@@ -123,16 +273,14 @@ class LicensePolicyTests(unittest.TestCase):)self.write("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n',+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n',)- # 1.181.0 reviewed on this bump: license identical to reviewed- # 1.180.0 (PyPI License-Expression: LGPL-2.1-or-later).- self.write("requirements/semgrep.in", "semgrep==1.181.0\n")+ self.write("requirements/semgrep.in", "semgrep==1.0.0\n")self.write("requirements/semgrep.txt",- "semgrep==1.181.0\nprotobuf==6.33.6\ntyping-extensions==4.16.0\n",+ "semgrep==1.0.0\nprotobuf==1.0.0\ntyping-extensions==1.0.0\n",)- self.write("requirements/twine.txt", "docutils==0.23\n")+ self.write("requirements/twine.txt", docutils_lock("1.0.0"))def write(self, relative, content):path = self.root / relative@@ -145,7 +293,7 @@ class LicensePolicyTests(unittest.TestCase):previous = path.read_text(encoding="utf-8") if path.exists() else Nonetry:self.write(relative, content)- errors = POLICY.validate(self.root)+ errors = self.validate()self.assertTrue(errors, (relative, content))self.assertIn(message, "\n".join(errors))finally:@@ -155,8 +303,12 @@ class LicensePolicyTests(unittest.TestCase):path.write_text(previous, encoding="utf-8")def test_repository_and_reviewed_fixture_pass(self):- self.assertEqual(POLICY.validate(ROOT), [])- self.assertEqual(POLICY.validate(self.root), [])+ # The real locks' wheel hashes name real PyPI files, which the fake+ # index does not serve; the wheel check is exercised on fixtures+ # below and against PyPI by the workflow's enforcement step.+ with mock.patch.object(POLICY, "REVIEWED_WHEEL_CONTENTS", {}):+ self.assertEqual(POLICY.validate(ROOT, self.pypi, self.files), [])+ self.assertEqual(self.validate(), [])def test_plain_requirements_in_new_locations_do_not_bypass_review(self):# Regression: the old regex only recognized pins ending in a backslash.@@ -173,17 +325,17 @@ class LicensePolicyTests(unittest.TestCase):"ci/Requirements/extra.IN",):with self.subTest(location=location):- self.reject(location, "protobuf==6.33.5\n", "protobuf")+ self.reject(location, "protobuf==0.0.0\n", "protobuf")def test_normalized_names_spaces_markers_extras_and_hashes_are_parsed(self):self.write("requirements/semgrep.txt",- "# protobuf==6.33.5 is only a comment\n"- ' PROTOBUF [extra] == 6.33.6 ; sys_platform == "win32"\n'- "TyPiNg_.Extensions == 4.16.0 \\\n"+ "# protobuf==0.0.0 is only a comment\n"+ ' PROTOBUF [extra] == 1.0.0 ; sys_platform == "win32"\n'+ "TyPiNg_.Extensions == 1.0.0 \\\n"" --hash=sha256:1234 # pip hash option\n",)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])for spelling in ("typing_extensions","Typing.Extensions",@@ -192,42 +344,44 @@ class LicensePolicyTests(unittest.TestCase):with self.subTest(spelling=spelling):self.reject("requirements/semgrep.txt",- f"{spelling}==4.15.0\n",+ f"{spelling}==0.0.0\n","typing-extensions",)def test_versions_ranges_direct_urls_and_false_markers_need_review(self):- for requirement in (- "protobuf==6.33.5",- "protobuf>=6.33.6",- "protobuf~=6.33.6",- "protobuf==6.33.*",- "protobuf===6.33.6",- "protobuf",- 'protobuf==6.33.5; python_version < "2"',- "protobuf @ https://example.test/protobuf-6.33.6.whl",- "semgrep==1.182.0",- "typing_extensions>=4.16.0",+ exact_only = "only an exact == pin can be license-checked"+ for requirement, message in (+ ("protobuf==0.0.0", "license metadata changed"),+ ("protobuf>=1.0.0", exact_only),+ ("protobuf~=1.0.0", exact_only),+ ("protobuf==1.0.*", exact_only),+ ("protobuf===1.0.0", exact_only),+ ("protobuf==1.0.0,!=2.0.0", exact_only),+ ("protobuf", exact_only),+ (+ 'protobuf==0.0.0; python_version < "2"',+ "license metadata changed",+ ),+ (+ "protobuf @ https://example.test/protobuf-1.0.0.whl",+ "direct source requires review",+ ),+ ("semgrep==0.0.0", "license metadata changed"),+ ("typing_extensions>=1.0.0", exact_only),):with self.subTest(requirement=requirement):- self.reject(- "requirements/semgrep.txt", requirement, "requires review"- )+ self.reject("requirements/semgrep.txt", requirement, message)self.reject(- "requirements/twine.txt", "docutils==0.24", "requires review"- )- self.reject(- "requirements/semgrep.in", "semgrep>=1.179.0", "requires review"+ "requirements/twine.txt", "docutils==0.0.0", "requires review")+ self.reject("requirements/semgrep.in", "semgrep>=1.0.0", exact_only)def test_reviewed_version_cannot_move_to_another_environment(self):for requirement in (- # Each entry is its package's reviewed version; the location- # alone must reject it. Keep semgrep at the reviewed version.- "semgrep==1.181.0",- "docutils==0.23",- "protobuf==6.33.6",- "typing_extensions==4.16.0",+ "semgrep==1.0.0",+ "docutils==1.0.0",+ "protobuf==1.0.0",+ "typing_extensions==1.0.0",):with self.subTest(requirement=requirement):self.reject("requirements/runtime.txt", requirement, "outside")@@ -235,20 +389,44 @@ class LicensePolicyTests(unittest.TestCase):def test_mcp_extra_lock_is_a_reviewed_typing_extensions_location(self):self.write("requirements/mcp-extra.txt",- "mcp==1.30.0\ntyping-extensions==4.16.0\n",+ "mcp==1.30.0\ntyping-extensions==1.0.0\n",)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])self.reject("requirements/mcp-extra.txt",- "mcp==1.30.0\ntyping-extensions==4.15.0\n",+ "mcp==1.30.0\ntyping-extensions==0.0.0\n","typing-extensions",)self.reject("requirements/mcp-extra.in",- "typing-extensions==4.16.0\n",+ "typing-extensions==1.0.0\n","outside",)+ def test_mcp_reviewed_lock_versions_follow_project_bounds(self):+ self.write(+ "pyproject.toml",+ '[project]\ndependencies = ["typing-extensions~=4.15"]\n'+ "[project.optional-dependencies]\nmcp = []\n",+ )+ for mirror in ("", "typing-extensions~=4.15\n"):+ self.write("requirements/mcp-extra.in", mirror)+ for version, accepted in (+ ("4.15.0", True),+ ("4.17.0", True),+ ("4.14.9", False),+ ("5.0.0", False),+ ):+ with self.subTest(version=version, mirrored=bool(mirror)):+ self.write(+ "requirements/mcp-extra.txt",+ f"typing-extensions=={version}\n",+ )+ errors = mcp_extra_mirror_errors(self.root)+ self.assertEqual(not errors, accepted, errors)+ if not accepted:+ self.assertIn("typing-extensions", "\n".join(errors))+def test_mcp_extra_mirrors_track_pyproject_bounds(self):# Regression: the README asked for the mirrored pins to stay in# sync with pyproject.toml but nothing enforced it, so a drifted@@ -281,10 +459,10 @@ class LicensePolicyTests(unittest.TestCase):}for relative, content in base.items():self.write(relative, content)- # typing-extensions is held at its exact reviewed lock pin by the- # license policy instead of a mirror. A mirror with no matching- # pyproject.toml dependency yet (certifi) may bound a package- # pinned in the lock, so it can land before that dependency.+ # typing-extensions uses an exact lock pin instead of a range mirror,+ # and that pin is checked against the application's bound. A mirror+ # with no matching pyproject.toml dependency yet (certifi) may bound+ # a package pinned in the lock, so it can land before that dependency.self.assertEqual(mcp_extra_mirror_errors(self.root), [])httpx_project = ("[project]\n"@@ -375,7 +553,7 @@ class LicensePolicyTests(unittest.TestCase):self.write(relative, base[relative])def test_local_includes_are_checked_in_the_importing_environment(self):- self.write("requirements/pins.data", "protobuf==6.33.6\n")+ self.write("requirements/pins.data", "protobuf==1.0.0\n")for directive in ("-r pins.data","-rpins.data",@@ -388,10 +566,10 @@ class LicensePolicyTests(unittest.TestCase):):with self.subTest(directive=directive):self.write("requirements/semgrep.txt", directive)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])self.reject("requirements/pins.data",- "protobuf==6.33.5",+ "protobuf==0.0.0","requires review",)self.write("requirements/middle.data", "-r semgrep.txt\n")@@ -417,10 +595,10 @@ class LicensePolicyTests(unittest.TestCase):def test_unsupported_requirements_syntax_fails_closed(self):for requirement in (- "https://example.test/protobuf-6.33.5.whl",+ "https://example.test/protobuf-0.0.0.whl","-e git+https://example.test/protobuf.git#egg=protobuf",- "${PACKAGE}==6.33.5",- "protobuf==6.33.5 \\\n",+ "${PACKAGE}==0.0.0",+ "protobuf==0.0.0 \\\n","--index-url https://example.test/simple",):with self.subTest(requirement=requirement):@@ -436,13 +614,13 @@ class LicensePolicyTests(unittest.TestCase):# parses on the line after it (pip's join_lines terminates the# logical line at a comment, so both requirements are installed).for third_line in (- "protobuf==6.33.5",+ "protobuf==0.0.0","protobuf @ https://example.test/protobuf-evil.whl",):with self.subTest(third_line=third_line):self.reject("requirements/semgrep.txt",- "typing-extensions==4.16.0 \\\n"+ "typing-extensions==1.0.0 \\\n""# via semgrep \\\n"f"{third_line}\n","protobuf",@@ -450,13 +628,13 @@ class LicensePolicyTests(unittest.TestCase):# A comment without its own continuation also terminates the join.self.reject("requirements/semgrep.txt",- "typing-extensions==4.16.0 \\\n# via semgrep\nprotobuf==6.33.5\n",+ "typing-extensions==1.0.0 \\\n# via semgrep\nprotobuf==0.0.0\n","protobuf",)# The requirement before the terminated comment stays checked too.self.reject("requirements/semgrep.txt",- "typing-extensions==4.15.0 \\\n# via semgrep\nprotobuf==6.33.6\n",+ "typing-extensions==0.0.0 \\\n# via semgrep\nprotobuf==1.0.0\n","typing-extensions",)@@ -467,8 +645,8 @@ class LicensePolicyTests(unittest.TestCase):# guard never inspected [metadata].self.reject("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'- 'files = [{url = "https://evil.test/typing_extensions-4.16.0'+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n'+ 'files = [{url = "https://evil.test/typing_extensions-1.0.0''-py3-none-any.whl", hash = "sha256:abc"}]\n',"url entries",)@@ -477,18 +655,18 @@ class LicensePolicyTests(unittest.TestCase):self.write("pdm.lock",'[[package]]\nname = "typing-extensions"\n'- 'version = "4.16.0"\n\n[metadata]\n'+ 'version = "1.0.0"\n\n[metadata]\n'f'strategy = ["inherit_metadata", "{strategy}"]\n',)- errors = POLICY.validate(self.root)+ errors = self.validate()self.assertTrue(errors)self.assertIn("static-urls lock strategy", "\n".join(errors))# The executed bypass shape: url entry plus the enabling strategy.self.reject("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n''groups = ["default"]\n'- 'files = [{url = "https://evil.test/typing_extensions-4.16.0'+ 'files = [{url = "https://evil.test/typing_extensions-1.0.0''-py3-none-any.whl", hash = "sha256:abc"}]\n''\n[metadata]\nstrategy = ["inherit_metadata", "static-urls"]\n',"pdm.lock",@@ -496,12 +674,12 @@ class LicensePolicyTests(unittest.TestCase):# Plain {file, hash} entries and non-static strategies stay allowed.self.write("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'- 'files = [{file = "typing_extensions-4.16.0-py3-none-any.whl", '+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n'+ 'files = [{file = "typing_extensions-1.0.0-py3-none-any.whl", ''hash = "sha256:abc"}]\n\n''[metadata]\nstrategy = ["inherit_metadata"]\n',)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])def test_lock_vcs_pin_and_inline_source_spellings_need_review(self):# Companion spellings of the direct-source keys pinned above:@@ -509,14 +687,14 @@ class LicensePolicyTests(unittest.TestCase):for source in ('commit = "8f14e45fceea167a5a36dedd4bea2543"','branch = "backdoor"',- 'tag = "v4.16.0-backdoor"',+ 'tag = "v1.0.0-backdoor"','source = {name = "private", url = "https://example.test/simple"}',):with self.subTest(source=source):self.reject("pdm.lock",'[[package]]\nname = "typing-extensions"\n'- 'version = "4.16.0"\n' + source + "\n",+ 'version = "1.0.0"\n' + source + "\n","direct sources",)@@ -529,7 +707,7 @@ class LicensePolicyTests(unittest.TestCase):for name in ("typing-extensions[probe]","typing-extensions[]",- "typing-extensions==4.16.0",+ "typing-extensions==1.0.0",'typing-extensions; python_version >= "0"',"typing-extensions @ https://example.test/te.whl","typing-extensions\n",@@ -550,7 +728,7 @@ class LicensePolicyTests(unittest.TestCase):self.reject("pdm.lock",f"[[package]]\nname = {json.dumps(name)}\n"- 'version = "4.16.0"\n' + source,+ 'version = "1.0.0"\n' + source,"name is invalid",)# Extras have a separate lock field. Legitimate case, underscore,@@ -564,9 +742,9 @@ class LicensePolicyTests(unittest.TestCase):self.write("pdm.lock",f"[[package]]\nname = {json.dumps(name)}\n"- 'version = "4.16.0"\nextras = ["probe"]\n',+ 'version = "1.0.0"\nextras = ["probe"]\n',)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])def test_all_project_dependency_sections_reject_isolated_tools(self):for section, key in (@@ -576,7 +754,7 @@ class LicensePolicyTests(unittest.TestCase):("dependency-groups", "tools"),("tool.pdm.dev-dependencies", "tools"),):- for requirement in ("Semgrep==1.181.0", "docutils==0.23"):+ for requirement in ("Semgrep==1.0.0", "docutils==1.0.0"):with self.subTest(section=section, requirement=requirement):self.reject("pyproject.toml",@@ -594,7 +772,7 @@ class LicensePolicyTests(unittest.TestCase):)self.reject("pdm.lock",- '[[package]]\nname = "Typing_Extensions"\nversion = "4.15.0"\n',+ '[[package]]\nname = "Typing_Extensions"\nversion = "0.0.0"\n',"requires review",)for source in (@@ -614,7 +792,7 @@ class LicensePolicyTests(unittest.TestCase):with self.subTest(source=source):self.reject("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n'+ source,"direct sources",)@@ -626,7 +804,7 @@ class LicensePolicyTests(unittest.TestCase):self.reject("pdm.lock",'lock-version = "1.0"\n\n[[packages]]\n'- 'name = "typing-extensions"\nversion = "4.16.0"\n\n'+ 'name = "typing-extensions"\nversion = "1.0.0"\n\n''[packages.vcs]\ntype = "hg"\n''url = "https://example.test/te.hg"\n''requested-revision = "backdoor"\n',@@ -635,14 +813,14 @@ class LicensePolicyTests(unittest.TestCase):# Even a source-free pylock lock must not slip past unexamined.self.reject("pdm.lock",- '[[packages]]\nname = "typing-extensions"\nversion = "4.15.0"\n',+ '[[packages]]\nname = "typing-extensions"\nversion = "0.0.0"\n',"pylock",)# Even another claimed name must not hide an exempted wheel behind# a direct source; PDM uses the installed artifact's actual name.self.reject("pdm.lock",- '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n\n'+ '[[package]]\nname = "typing-extensions"\nversion = "1.0.0"\n\n''[[package]]\nname = "other-package"\nversion = "1.0"\n''hg = "https://example.test/other.hg"\n',"direct sources",@@ -651,7 +829,7 @@ class LicensePolicyTests(unittest.TestCase):def test_valid_aliases_cannot_hide_direct_artifacts(self):for name in ("helper-package", "typing-extensions"):for source in (- 'url = "https://example.test/typing_extensions-4.16.0.whl"',+ 'url = "https://example.test/typing_extensions-1.0.0.whl"','path = "./vendor/helper"','git = "https://example.test/helper.git"','[package.source]\nurl = "https://example.test/simple"',@@ -660,14 +838,14 @@ class LicensePolicyTests(unittest.TestCase):with self.subTest(name=name, source=source):self.reject("pdm.lock",- f'[[package]]\nname = "{name}"\nversion = "4.16.0"\n'+ f'[[package]]\nname = "{name}"\nversion = "1.0.0"\n'+ source,"review",)self.reject("pdm.lock","[metadata]\nstatic_urls = true\n"- f'[[package]]\nname = "{name}"\nversion = "4.16.0"\n',+ f'[[package]]\nname = "{name}"\nversion = "1.0.0"\n',"static-urls",)for location, content in (@@ -703,12 +881,12 @@ class LicensePolicyTests(unittest.TestCase):def test_subproject_manifests_are_not_skipped(self):self.reject("tools/pyproject.toml",- '[project]\ndependencies = ["semgrep==1.181.0"]',+ '[project]\ndependencies = ["semgrep==1.0.0"]',"outside",)self.reject("tools/pdm.lock",- '[[package]]\nname = "docutils"\nversion = "0.23"',+ '[[package]]\nname = "docutils"\nversion = "1.0.0"',"outside",)@@ -717,11 +895,11 @@ class LicensePolicyTests(unittest.TestCase):# requirements/PEP 621/PDM parsers. Never execute setup.py to read it.manifests = {"setup.py": 'raise RuntimeError("must not execute setup.py")',- "setup.cfg": "[options]\ninstall_requires = semgrep==1.178.0\n",- "Pipfile": '[packages]\nsemgrep = "==1.178.0"\n',- "Pipfile.lock": '{"default":{"semgrep":{"version":"==1.178.0"}}}',- "poetry.lock": '[[package]]\nname="semgrep"\nversion="1.178.0"\n',- "uv.lock": '[[package]]\nname="semgrep"\nversion="1.178.0"\n',+ "setup.cfg": "[options]\ninstall_requires = semgrep==0.0.0\n",+ "Pipfile": '[packages]\nsemgrep = "==0.0.0"\n',+ "Pipfile.lock": '{"default":{"semgrep":{"version":"==0.0.0"}}}',+ "poetry.lock": '[[package]]\nname="semgrep"\nversion="0.0.0"\n',+ "uv.lock": '[[package]]\nname="semgrep"\nversion="0.0.0"\n',"uv.toml": 'index-url = "https://example.test/simple"\n',"pylock.toml": 'lock-version = "1.0"\n',"pylock.tools.toml": 'lock-version = "1.0"\n',@@ -737,15 +915,15 @@ class LicensePolicyTests(unittest.TestCase):def test_unparsed_project_dependency_schemas_fail_closed(self):for content in (- '[tool.poetry.dependencies]\nsemgrep = "1.178.0"\n',- '[tool.poetry.group.dev.dependencies]\nsemgrep = "1.178.0"\n',- '[tool.uv]\ndev-dependencies = ["semgrep==1.178.0"]\n',- '[tool.hatch.envs.default]\ndependencies = ["semgrep==1.178.0"]\n',- '[tool.pixi.pypi-dependencies]\nsemgrep = "==1.178.0"\n',+ '[tool.poetry.dependencies]\nsemgrep = "0.0.0"\n',+ '[tool.poetry.group.dev.dependencies]\nsemgrep = "0.0.0"\n',+ '[tool.uv]\ndev-dependencies = ["semgrep==0.0.0"]\n',+ '[tool.hatch.envs.default]\ndependencies = ["semgrep==0.0.0"]\n',+ '[tool.pixi.pypi-dependencies]\nsemgrep = "==0.0.0"\n','[project]\ndynamic = ["dependencies"]\n','[project]\ndynamic = ["optional-dependencies"]\n','[tool.setuptools.dynamic]\ndependencies = {file = "deps.data"}\n',- '[tool.pdm]\nplugins = ["semgrep==1.178.0"]\n',+ '[tool.pdm]\nplugins = ["semgrep==0.0.0"]\n','[tool.pdm.resolution.overrides]\nTyping_Extensions = ">=4"\n',"[tool.pdm.resolution.overrides]\n"'"typing-extensions[extra]" = "https://example.test/te.whl"\n',@@ -762,7 +940,7 @@ class LicensePolicyTests(unittest.TestCase):'include_packages = ["torch", "torch*"]\n')self.write("pyproject.toml", baseline + torch)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])for source in ('name = "pypi"\nurl = "https://example.test/simple"\n','name = "pypi"\ntype = "find_links"\nurl = "file:///tmp/wheels"\n'@@ -805,19 +983,408 @@ class LicensePolicyTests(unittest.TestCase):'[tool.pdm.resolution.overrides]\nrequests = ">=2.33"\n''lxml = ">=6.0"\n[tool.setuptools]\ninclude-package-data = true\n',)- self.assertEqual(POLICY.validate(self.root), [])+ self.assertEqual(self.validate(), [])def test_symlinked_manifests_and_includes_are_rejected(self):- target = self.write("pins.data", "protobuf==6.33.6\n")+ target = self.write("pins.data", "protobuf==1.0.0\n")path = self.root / "requirements/semgrep.txt"path.unlink()path.symlink_to(target)- self.assertIn("symlink", "\n".join(POLICY.validate(self.root)))+ self.assertIn("symlink", "\n".join(self.validate()))- def test_cli_returns_failure_for_the_original_bypass(self):+ def write_bumped_fixture(self, version):+ self.write("requirements/semgrep.in", f"semgrep=={version}\n")+ self.write(+ "requirements/semgrep.txt",+ f"semgrep=={version}\nprotobuf=={version}\n"+ f"typing-extensions=={version}\n",+ )+ self.write("requirements/twine.txt", docutils_lock(version))+ self.write(+ "pdm.lock",+ f'[[package]]\nname = "typing-extensions"\nversion = "{version}"\n',+ )++ def test_reviewed_licenses_are_concrete(self):+ # An empty License would never match real metadata (the guard+ # rejects a release declaring no license), so it would block every+ # version rather than review one.+ for name, (license, locations) in POLICY.REVIEWED.items():+ with self.subTest(name=name):+ self.assertTrue(+ license.expression or license.text or license.classifiers+ )+ self.assertTrue(locations)++ def test_same_license_version_bump_passes_without_code_change(self):+ self.write_bumped_fixture(BUMPED)+ self.assertEqual(self.validate(), [])+ self.assertEqual(+ sorted(self.pypi.calls),+ sorted((name, BUMPED) for name in POLICY.REVIEWED),+ )++ def test_every_locked_release_is_looked_up_once(self):+ self.assertEqual(self.validate(), [])+ # typing-extensions is pinned in two manifests at the same version.+ self.assertEqual(+ sorted(self.pypi.calls),+ sorted((name, "1.0.0") for name in POLICY.REVIEWED),+ )+ self.write(+ "pdm.lock",+ f'[[package]]\nname = "typing-extensions"\nversion = "{BUMPED}"\n',+ )+ self.pypi.calls.clear()+ self.assertEqual(self.validate(), [])+ self.assertIn(("typing-extensions", "1.0.0"), self.pypi.calls)+ self.assertIn(("typing-extensions", BUMPED), self.pypi.calls)++ def test_changed_license_fails_naming_package_and_both_licenses(self):+ for name, (reviewed, _locations) in POLICY.REVIEWED.items():+ with self.subTest(name=name):+ self.write_bumped_fixture(BUMPED)+ self.pypi.responses = {+ (name, BUMPED): pypi_info(name, BUMPED, CHANGED)+ }+ errors = "\n".join(self.validate())+ self.assertIn(+ f"{name} {BUMPED}: license metadata changed", errors+ )+ self.assertIn(f"reviewed: {reviewed.describe()}", errors)+ self.assertIn(f"found: {CHANGED.describe()}", errors)+ self.assertIn("GPL-3.0-only", errors)+ # Only the changed package fails.+ self.assertEqual(errors.count("license metadata changed"), 1)++ def test_any_license_field_change_fails(self):+ reviewed, _locations = POLICY.REVIEWED["semgrep"]+ for changed in (+ reviewed._replace(expression="LGPL-2.1-only"),+ reviewed._replace(text="LGPL"),+ reviewed._replace(files=(*reviewed.files, "NOTICE")),+ reviewed._replace(files=("COPYING",)),+ reviewed._replace(+ classifiers=("License :: OSI Approved :: MIT License",)+ ),+ ):+ with self.subTest(changed=changed):+ self.pypi.responses = {+ ("semgrep", "1.0.0"): pypi_info("semgrep", "1.0.0", changed)+ }+ errors = "\n".join(self.validate())+ self.assertIn("semgrep 1.0.0: license metadata changed", errors)++ def test_equivalent_metadata_spelling_still_matches(self):+ # Ordering, duplicates, surrounding whitespace and non-license+ # classifiers do not count as a license change.+ reviewed, _locations = POLICY.REVIEWED["docutils"]+ info = pypi_info("Docutils", "1.0", reviewed)+ info["classifiers"] = [+ f" {item} " for item in reversed(info["classifiers"])+ ] + [reviewed.classifiers[0], "Topic :: Documentation"]+ info["license_files"] = list(reversed(reviewed.files))+ self.pypi.responses = {("docutils", "1.0.0"): info}+ self.assertEqual(self.validate(), [])++ def test_missing_or_unparseable_metadata_fails_closed(self):+ reviewed = pypi_info("semgrep", "1.0.0", POLICY.REVIEWED["semgrep"][0])+ for label, info, message in (+ ("not an object", None, "info is not an object"),+ ("list", [reviewed], "info is not an object"),+ (+ "no license fields",+ {"name": "semgrep", "version": "1.0.0"},+ "declares no license",+ ),+ (+ "empty license fields",+ {+ **reviewed,+ "license_expression": "",+ "license": " ",+ "classifiers": [],+ },+ "declares no license",+ ),+ (+ "non-string expression",+ {**reviewed, "license_expression": ["LGPL-2.1-or-later"]},+ "license_expression is not a string",+ ),+ (+ "non-list classifiers",+ {**reviewed, "classifiers": "License :: OSI Approved"},+ "classifiers is not a list",+ ),+ (+ "non-string license file",+ {**reviewed, "license_files": [None]},+ "license_files is not a list",+ ),+ (+ "unnamed release",+ {**reviewed, "name": None},+ "does not name its release",+ ),+ (+ "another release",+ {**reviewed, "version": "2.0.0"},+ "metadata for semgrep 2.0.0",+ ),+ (+ "another package",+ {**reviewed, "name": "semgrep-fork"},+ "metadata for semgrep-fork",+ ),+ (+ "invalid version",+ {**reviewed, "version": "not a version"},+ "metadata for semgrep not a version",+ ),+ ):+ with self.subTest(label=label):+ self.pypi.responses = {("semgrep", "1.0.0"): info}+ errors = "\n".join(self.validate())+ self.assertIn(+ "semgrep 1.0.0: cannot verify license, requires review",+ errors,+ )+ self.assertIn(message, errors)++ def test_lookup_errors_fail_closed(self):+ for error in (+ POLICY.PolicyError("PyPI metadata lookup failed: offline"),+ OSError("network unreachable"),+ RuntimeError("unexpected fetcher failure"),+ ):+ with self.subTest(error=error):+ self.pypi.responses = {("protobuf", "1.0.0"): error}+ errors = "\n".join(self.validate())+ self.assertIn(+ "requirements/semgrep.txt: protobuf 1.0.0: cannot verify "+ "license, requires review",+ errors,+ )+ self.assertIn(str(error), errors)++ def test_manifest_errors_are_reported_without_querying_pypi(self):+ self.write("requirements/runtime.txt", "semgrep==1.0.0\n")+ self.assertIn("outside", "\n".join(self.validate()))+ self.assertEqual(self.pypi.calls, [])++ def test_main_reports_a_license_change(self):+ self.write_bumped_fixture(BUMPED)+ self.pypi.responses = {+ ("protobuf", BUMPED): pypi_info("protobuf", BUMPED, CHANGED)+ }+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ self.assertEqual(+ POLICY.main([str(self.root)], self.pypi, self.files), 1+ )+ self.assertIn(+ f"protobuf {BUMPED}: license metadata changed", stderr.getvalue()+ )+ self.pypi.responses = {}+ with contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(+ POLICY.main([str(self.root)], self.pypi, self.files), 0+ )++ def test_absent_license_files_are_tolerated_only_when_all_else_matches(+ self,+ ):+ # PyPI's info comes from the first uploaded file; semgrep's Linux+ # wheels list no License-File while its other wheels list LICENSE.+ reviewed, _locations = POLICY.REVIEWED["semgrep"]+ for files in ((), None):+ with self.subTest(files=files):+ info = pypi_info("semgrep", "1.0.0", reviewed)+ info["license_files"] = None if files is None else []+ self.pypi.responses = {("semgrep", "1.0.0"): info}+ self.assertEqual(self.validate(), [])+ # Without license files, the other fields must still match.+ info = pypi_info(+ "semgrep", "1.0.0", reviewed._replace(expression="MIT", files=())+ )+ self.pypi.responses = {("semgrep", "1.0.0"): info}+ self.assertIn("license metadata changed", "\n".join(self.validate()))++ def test_pyproject_typing_extensions_constraint_is_exactly_reviewed(self):+ exact_only = "only an exact == pin can be license-checked"+ self.assertEqual(self.validate(), [])+ self.assertNotIn(("typing-extensions", "4.15"), self.pypi.calls)+ for constraint in ("~=4.14", "~=4.16", "~=4.0", "~=4.15.0", ">=4.15"):+ with self.subTest(constraint=constraint):+ self.reject(+ "pyproject.toml",+ "[project]\ndependencies = "+ f'["typing-extensions{constraint}"]\n',+ exact_only,+ )+ # The range is accepted only in pyproject.toml.+ self.reject(+ "requirements/semgrep.txt", "typing-extensions~=4.15", exact_only+ )++ def test_clean_locked_wheel_is_downloaded_and_passes(self):+ self.write_bumped_fixture(BUMPED)+ self.assertEqual(self.validate(), [])+ # Only the wheel is downloaded; the sdist is never installed.+ self.assertEqual(self.files.calls, [wheel_url(BUMPED)])++ def wheel_errors(self, body=None, error=None):+ url = wheel_url("1.0.0")+ self.files.responses = {url: error if error else body}+ return "\n".join(self.validate())++ def test_wheel_with_unreviewed_contents_fails(self):+ for extra, message in (+ (("docutils/tools/editors/emacs/rst.el",), "rst.el"),+ (("docutils-1.0.0.dist-info/rst.EL",), "rst.EL"),+ (("tools/editors/emacs/rst.el",), "unreviewed path"),+ (("docutils_extra/__init__.py",), "unreviewed path"),+ (("docutils-2.0.0.dist-info/METADATA",), "unreviewed path"),+ (("docutils/../evil.py",), "unreviewed path"),+ (("docutils\\evil.py",), "unreviewed path"),+ (("docutils/x\\..\\..\\evil.py",), "unreviewed path"),+ (("setup.py",), "unreviewed path"),+ ):+ with self.subTest(extra=extra):+ body = make_wheel("1.0.0", extra)+ # Lock the modified wheel so only its contents differ.+ self.pypi.documents = {+ ("docutils", "1.0.0"): {+ "info": pypi_info(+ "docutils", "1.0.0", POLICY.REVIEWED["docutils"][0]+ ),+ "urls": [+ {+ "filename": "docutils-1.0.0-py3-none-any.whl",+ "url": wheel_url("1.0.0"),+ "digests": {"sha256": sha256(body)},+ }+ ],+ }+ }+ self.write(+ "requirements/twine.txt",+ f"docutils==1.0.0 --hash=sha256:{sha256(body)}\n",+ )+ errors = self.wheel_errors(body)+ self.assertIn(+ "docutils 1.0.0: wheel contents need review", errors+ )+ self.assertIn(message, errors)++ def test_wheel_that_does_not_match_its_lock_hash_fails(self):+ tampered = make_wheel("1.0.0", ("docutils/extra.py",))+ errors = self.wheel_errors(tampered)+ self.assertIn("does not match its locked sha256", errors)++ def test_wheel_download_errors_fail_closed(self):+ for error in (+ POLICY.PolicyError("download failed: offline"),+ OSError("network unreachable"),+ RuntimeError("unexpected downloader failure"),+ ):+ with self.subTest(error=error):+ errors = self.wheel_errors(error=error)+ self.assertIn(+ "docutils 1.0.0: wheel contents need review", errors+ )+ self.assertIn(str(error), errors)++ def test_unreadable_wheel_fails_closed(self):+ body = b"not a zip"+ self.pypi.documents = {+ ("docutils", "1.0.0"): {+ "info": pypi_info(+ "docutils", "1.0.0", POLICY.REVIEWED["docutils"][0]+ ),+ "urls": [+ {+ "filename": "docutils-1.0.0-py3-none-any.whl",+ "url": wheel_url("1.0.0"),+ "digests": {"sha256": sha256(body)},+ }+ ],+ }+ }self.write(- "requirements/license-review-probe.txt", "protobuf==6.33.5\n"+ "requirements/twine.txt",+ f"docutils==1.0.0 --hash=sha256:{sha256(body)}\n",)+ self.assertIn("not a readable wheel", self.wheel_errors(body))++ def test_wheel_lock_must_identify_a_reviewable_wheel(self):+ wheel = sha256(make_wheel("1.0.0"))+ info = pypi_info("docutils", "1.0.0", POLICY.REVIEWED["docutils"][0])+ files = release_files("docutils", "1.0.0")+ for label, lock, urls, message in (+ ("no hash", "docutils==1.0.0\n", files, "no --hash is locked"),+ (+ "sdist only",+ f"docutils==1.0.0 --hash=sha256:{SDIST_DIGEST}\n",+ files,+ "no wheel is locked",+ ),+ (+ "unknown hash",+ f"docutils==1.0.0 --hash=sha256:{'b' * 64}\n",+ files,+ "is not a file of the release",+ ),+ (+ "other algorithm",+ f"docutils==1.0.0 --hash=sha512:{wheel}\n",+ files,+ "not a sha256 digest",+ ),+ (+ "no file list",+ f"docutils==1.0.0 --hash=sha256:{wheel}\n",+ None,+ "no file list",+ ),+ (+ "another release's wheel",+ f"docutils==1.0.0 --hash=sha256:{wheel}\n",+ [+ {+ **files[0],+ "filename": "docutils-2.0.0-py3-none-any.whl",+ }+ ],+ "not a wheel of this release",+ ),+ (+ "invalid wheel name",+ f"docutils==1.0.0 --hash=sha256:{wheel}\n",+ [{**files[0], "filename": "docutils.whl"}],+ "invalid wheel filename",+ ),+ (+ "no url",+ f"docutils==1.0.0 --hash=sha256:{wheel}\n",+ [{**files[0], "url": None}],+ "malformed",+ ),+ ):+ with self.subTest(label=label):+ self.write("requirements/twine.txt", lock)+ self.pypi.documents = {+ ("docutils", "1.0.0"): {"info": info, "urls": urls}+ }+ errors = "\n".join(self.validate())+ self.assertIn(+ "docutils 1.0.0: wheel contents need review", errors+ )+ self.assertIn(message, errors)++ def test_cli_returns_failure_for_the_original_bypass(self):+ self.write("requirements/license-review-probe.txt", "protobuf==0.0.0\n")result = subprocess.run([sys.executable, str(SCRIPT), str(self.root)],capture_output=True,@@ -828,5 +1395,175 @@ class LicensePolicyTests(unittest.TestCase):self.assertIn("protobuf", result.stderr)+class FakeResponse(io.BytesIO):+ def __init__(self, body, url):+ super().__init__(body)+ self.url = url+ self.reads = []++ def read(self, size=-1):+ self.reads.append(size)+ return super().read(size)++ def geturl(self):+ return self.url+++def http_error(url, code):+ return urllib.error.HTTPError(url, code, "error", {}, None)+++class PyPIFetchTests(unittest.TestCase):+ """The real fetchers, with urlopen and sleep replaced (no network)."""++ URL = "https://pypi.org/pypi/semgrep/1.0.0/json"++ def setUp(self):+ self.sleeps = []+ patcher = mock.patch.object(POLICY, "_sleep", self.sleeps.append)+ patcher.start()+ self.addCleanup(patcher.stop)++ def run_fetch(self, outcomes, call):+ outcomes = list(outcomes)++ def urlopen(request, timeout):+ self.requests.append((request.full_url, timeout))+ outcome = outcomes.pop(0)+ if isinstance(outcome, BaseException):+ raise outcome+ return outcome++ self.requests = []+ with mock.patch.object(POLICY.urllib.request, "urlopen", urlopen):+ return call()++ def fetch(self, *outcomes, version="1.0.0"):+ return self.run_fetch(+ outcomes, lambda: POLICY.fetch_pypi_metadata("semgrep", version)+ )++ def test_returns_the_release_document_from_pypi(self):+ document = {"info": {"name": "semgrep", "version": "1.0.0"}, "urls": []}+ body = json.dumps(document).encode()+ self.assertEqual(self.fetch(FakeResponse(body, self.URL)), document)+ self.assertEqual(+ self.requests, [(self.URL, POLICY.PYPI_TIMEOUT_SECONDS)]+ )+ self.assertEqual(self.sleeps, [])++ def test_version_cannot_change_the_lookup_path(self):+ body = json.dumps({"info": {}}).encode()+ self.fetch(FakeResponse(body, self.URL), version="1.0/../../x")+ self.assertEqual(+ self.requests[0][0],+ "https://pypi.org/pypi/semgrep/1.0%2F..%2F..%2Fx/json",+ )++ def test_reads_are_bounded_by_the_cap(self):+ # An unbounded read() would also see too much data; the cap must be+ # enforced by the read size itself, not by buffering everything.+ with mock.patch.object(POLICY, "PYPI_MAX_BYTES", 10):+ response = FakeResponse(b'{"info": {}}' + b" " * 100, self.URL)+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.fetch(response)+ self.assertIn("too large", str(raised.exception))+ self.assertEqual(response.reads, [11])+ # Exactly at the cap is accepted.+ response = FakeResponse(b'{"info":1}', self.URL)+ self.assertEqual(self.fetch(response), {"info": 1})++ def test_transient_failures_are_retried_once(self):+ body = json.dumps({"info": {}}).encode()+ for transient in (+ http_error(self.URL, 503),+ http_error(self.URL, 500),+ urllib.error.URLError("temporary failure in name resolution"),+ socket.timeout("timed out"),+ TimeoutError("timed out"),+ ConnectionResetError("reset"),+ POLICY.http.client.IncompleteRead(b""),+ ):+ with self.subTest(transient=transient):+ self.sleeps.clear()+ self.assertEqual(+ self.fetch(transient, FakeResponse(body, self.URL)),+ {"info": {}},+ )+ self.assertEqual(len(self.requests), 2)+ self.assertEqual(self.sleeps, [POLICY.RETRY_DELAY_SECONDS])+ self.sleeps.clear()+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.fetch(transient, transient)+ self.assertIn("download failed", str(raised.exception))+ self.assertEqual(len(self.requests), 2)++ def test_definitive_failures_are_not_retried(self):+ body = json.dumps({"info": {}}).encode()+ for outcome, message in (+ (http_error(self.URL, 404), "download failed"),+ (http_error(self.URL, 403), "download failed"),+ (ValueError("unknown url type"), "download failed"),+ (FakeResponse(b"<html>", self.URL), "not JSON"),+ ):+ with self.subTest(outcome=outcome):+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.fetch(outcome, FakeResponse(body, self.URL))+ self.assertIn(message, str(raised.exception))+ self.assertEqual(len(self.requests), 1)+ self.assertEqual(self.sleeps, [])++ def test_failures_raise_policy_errors(self):+ for label, outcome, message in (+ ("not found", http_error(self.URL, 404), "download failed"),+ (+ "redirected",+ FakeResponse(b"{}", "https://example.test/pypi/semgrep/json"),+ "redirected",+ ),+ (+ "downgraded",+ FakeResponse(b"{}", "http://pypi.org/pypi/semgrep/1.0.0/json"),+ "redirected",+ ),+ ("not json", FakeResponse(b"<html>", self.URL), "not JSON"),+ ("not utf-8", FakeResponse(b"\xff\xfe{", self.URL), "not JSON"),+ ("no info", FakeResponse(b'{"urls": []}', self.URL), "no info"),+ ("array", FakeResponse(b"[]", self.URL), "no info"),+ ):+ with self.subTest(label=label):+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.fetch(outcome, outcome)+ self.assertIn(message, str(raised.exception))++ def test_wheel_downloads_stay_on_pypi_file_hosts(self):+ url = wheel_url("1.0.0")+ body = make_wheel("1.0.0")+ self.assertEqual(+ self.run_fetch(+ [FakeResponse(body, url)], lambda: POLICY.download_wheel(url)+ ),+ body,+ )+ for bad in (+ "http://files.pythonhosted.org/docutils.whl",+ "https://example.test/docutils.whl",+ "file:///tmp/docutils.whl",+ ):+ with self.subTest(url=bad):+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.run_fetch(+ [], lambda bad=bad: POLICY.download_wheel(bad)+ )+ self.assertIn("refusing to fetch", str(raised.exception))+ self.assertEqual(self.requests, [])+ with self.assertRaises(POLICY.PolicyError) as raised:+ self.run_fetch(+ [FakeResponse(body, "https://example.test/x.whl")],+ lambda: POLICY.download_wheel(url),+ )+ self.assertIn("redirected", str(raised.exception))++if __name__ == "__main__":unittest.main()diff --git a/tests/ci/test_dependency_review_workflow.py b/tests/ci/test_dependency_review_workflow.pyindex ba5be5a5a1..45b29ba508 100644--- a/tests/ci/test_dependency_review_workflow.py+++ b/tests/ci/test_dependency_review_workflow.py@@ -72,3 +72,21 @@ def test_package_exceptions_preserve_general_license_and_vulnerability_policy()assert "GPL-1.0-or-later" not in allowedassert policy["fail-on-severity"] == "high"assert policy.get("license-check", True) in (True, "true")+++def test_license_guard_can_reach_pypi() -> None:+ # The guard reads each locked release's license from pypi.org and+ # downloads locked docutils wheels from files.pythonhosted.org, failing+ # closed without them. A block egress policy must allow both.+ steps = _workflow()["jobs"]["dependency-review"]["steps"]+ harden = next(+ step+ for step in steps+ if step.get("uses", "").startswith("step-security/harden-runner@")+ )+ policy = harden.get("with", {})+ if policy.get("egress-policy") == "block":+ allowed = policy.get("allowed-endpoints", "").split()+ assert {"pypi.org:443", "files.pythonhosted.org:443"} <= set(allowed)+ else:+ assert policy.get("egress-policy") == "audit"diff --git a/tests/ci/test_semgrep_workflow.py b/tests/ci/test_semgrep_workflow.pyindex d34b1ca52c..56ebba5e0b 100644--- a/tests/ci/test_semgrep_workflow.py+++ b/tests/ci/test_semgrep_workflow.py@@ -36,6 +36,9 @@ from pathlib import Pathimport pytestimport yaml+from packaging.requirements import Requirement+from packaging.utils import canonicalize_name+from packaging.version import VersionREPO_ROOT = Path(__file__).resolve().parents[2]@@ -502,68 +505,184 @@ UPLOAD_CASES = []-def test_installed_scanner_matches_the_version_whose_ignores_we_model():- """A tool update needs a review of the scanner's default skip rules.-- Premise change 2026-10-22: the pin moved 1.180.0 -> 1.181.0, and the- default-skip model below was reviewed against that release and found- unchanged before this assertion moved with it. Upstream surfaces- checked across v1.179.0/v1.180.0/v1.181.0: ``default.semgrepignore``- byte-identical (so the modelled names, dirs and file globs still match- exactly, and a 16,060-case differential of the model against a- faithful port of upstream parse+match semantics found 0 differences),- ``Find_targets.ml``, ``Skip_target.ml``, ``Semgrepignore.ml``,- ``target_manager.py``, ``libs/paths/Project.ml`` and the- default-ignore e2e snapshot byte-identical, and- ``DEFAULT_MAX_TARGET_SIZE`` still 1,000,000 bytes with the same- ``size > max_bytes`` boundary. The window's ignore-machinery changes- are ``Parse_gitignore.ml``, ``libs/glob/Match.ml`` (the glob->PCRE2- compiler every ignore pattern matches through),- ``libs/commons/Pcre2_.ml`` and ``.mli`` (the regex-engine wrapper,- full API migration), ``src/targeting/Guess_lang.ml`` (shebang- guessing migration), ``libs/git_wrapper/Git_wrapper.ml``- (diff-hunk/object-table refactor) and comment-only churn in- ``libs/gitignore/Gitignore_cache.ml``; all are behaviour-preserving- for the modelled semantics: ``Match.ml``'s ``translate_*`` functions- are byte-identical (error path fail-closed in both), ``Pcre2_`` keeps- UTF and the same limits, ``Guess_lang``'s case migration is- equivalent, and ``Git_wrapper.ml``'s ``ls_files`` (the tracked-file- listing) is byte-identical, its remaining changes being object-store- traversal, diff-hunk parsing and remote-repo-name (SCA paths). The- window also refactors the ``# nosemgrep`` recogniser in- ``Nosemgrep.ml``, fuzz-equivalent over 400k cases. The changed- ``Parse_gitignore.ml`` is behaviour-equivalent on UTF-8 input and- unreachable for this scan: the parser sees only the fixed built-in- ASCII ``default.semgrepignore``, since no ``.semgrepignore`` exists- anywhere in the tree. The ignore filter loads only- ``.semgrepignore``, so ``.gitignore`` is not consulted there, though- git itself applies ``.gitignore`` when listing untracked files. A- future bump whose review finds a default-skip change must move the- model, not just this pin.+def _locked_versions(lock_text: str) -> dict[str, list[str]]:+ """Map each ``name==version`` line in a pip-compile lock to its versions."""+ locked: dict[str, list[str]] = {}+ for match in re.finditer(+ r"(?m)^([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;\\]+)", lock_text+ ):+ locked.setdefault(canonicalize_name(match[1]), []).append(match[2])+ return locked+++def test_scanner_lock_matches_its_input_roots():+ """``semgrep.txt`` locks exactly the Semgrep that ``semgrep.in`` pins.++ The input has exactly two roots: Semgrep pinned with ``==`` (so the job+ installs one known release) and PyJWT with a ``>=`` security floor. The+ hash lock must lock that same Semgrep release once and a PyJWT release+ that satisfies the floor, so a hand edit of one file, or a regeneration+ that went wrong, fails. Versions are read from the files rather than+ repeated here, so a Dependabot bump that updates both files passes.++ This does not prove a new release keeps the built-in ignores and+ ``--max-target-bytes`` default modelled in ``DEFAULT_IGNORED_*`` and+ ``MAX_TARGET_BYTES``. On a bump the scan job still runs the custom rule+ tests (``semgrep --test``), the installed-scanner integration tests in+ ``tests/ci/standalone/test_semgrep*.py``, and the report validator,+ which fails on scanner errors, skipped rules or an empty scanned-file+ list. None of those notices a newly default-ignored ``src/`` path, so+ re-checking that model remains part of reviewing a Semgrep update.++ The model was reviewed for the currently locked 1.181.0 release on+ 2026-10-22. Across v1.179.0/v1.180.0/v1.181.0,+ ``default.semgrepignore``, ``Find_targets.ml``, ``Skip_target.ml``,+ ``Semgrepignore.ml``, ``target_manager.py``, ``libs/paths/Project.ml``+ and the default-ignore snapshot were unchanged; the target cap remains+ 1,000,000 bytes with the same ``size > max_bytes`` boundary. That review+ also covered the changed gitignore/glob/PCRE2 wrappers, language+ guessing, Git wrapper and ``Nosemgrep.ml`` recognizer before accepting+ the unchanged model. Future release reviews must assess those paths as+ well as the default patterns; matching the two lock inputs alone does+ not establish that behavior."""- # 1.181.0 reviewed on this bump: license identical to reviewed- # 1.180.0 (PyPI License-Expression: LGPL-2.1-or-later). Default skip- # rules and max_target_bytes byte-identical per the upstream- # v1.180.0...v1.181.0 diff: default.semgrepignore, Semgrepignore.ml,- # Find_targets.ml, libs/paths/Project.ml, and the default-ignore e2e- # snapshot are unchanged.tools = REPO_ROOT / "requirements"+ _assert_scanner_lock_matches(+ (tools / "semgrep.in").read_text(), (tools / "semgrep.txt").read_text()+ )+++def _assert_scanner_lock_matches(inputs: str, lock: str) -> None:roots = [- line.strip()- for line in (tools / "semgrep.in").read_text().splitlines()+ Requirement(line.strip())+ for line in inputs.splitlines()if line.strip() and not line.lstrip().startswith("#")]- assert roots == ["semgrep==1.181.0", "pyjwt>=2.15.1"]- assert re.search(- r"(?m)^semgrep==1\.181\.0(?:\s|;)",- (tools / "semgrep.txt").read_text(),- )- assert re.search(- r"(?m)^pyjwt==2\.15\.1(?:\s|;)",- (tools / "semgrep.txt").read_text(),+ assert [canonicalize_name(root.name) for root in roots] == [+ "semgrep",+ "pyjwt",+ ]+ semgrep, pyjwt = roots+ for root in roots:+ assert not root.url and not root.extras and root.marker is None, root+ (pin,) = semgrep.specifier+ assert pin.operator == "==" and "*" not in pin.version, semgrep+ (floor,) = pyjwt.specifier+ assert floor.operator == ">=", pyjwt+ assert Version(floor.version) >= Version("2.15.1"), pyjwt++ locked = _locked_versions(lock)+ assert locked.get("semgrep") == [pin.version], locked.get("semgrep")+ assert len(locked.get("pyjwt", [])) == 1, locked.get("pyjwt")+ assert pyjwt.specifier.contains(locked["pyjwt"][0]), locked["pyjwt"]+++_GOOD_INPUTS = "# header\nsemgrep==9.0.0\n# note\npyjwt>=2.15.1\n"+_GOOD_LOCK = (+ "pyjwt==2.16.0 \\\n --hash=sha256:00\n"+ "semgrep==9.0.0 \\\n --hash=sha256:11\n"+)+++def test_scanner_lock_check_accepts_a_consistent_synthetic_pair():+ _assert_scanner_lock_matches(_GOOD_INPUTS, _GOOD_LOCK)+++def test_scanner_lock_check_accepts_a_raised_pyjwt_floor():+ _assert_scanner_lock_matches(+ _GOOD_INPUTS.replace("2.15.1", "2.17.0"),+ _GOOD_LOCK.replace("2.16.0", "2.17.1"),)+ ("inputs", "lock"),+ [+ pytest.param(+ _GOOD_INPUTS,+ _GOOD_LOCK.replace("9.0.0", "9.0.1"),+ id="lock-mismatch",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("9.0.0", "9.0.1"),+ _GOOD_LOCK,+ id="input-mismatch",+ ),+ pytest.param(+ _GOOD_INPUTS,+ _GOOD_LOCK + "semgrep==9.0.0\n",+ id="duplicate-semgrep",+ ),+ pytest.param(+ _GOOD_INPUTS, _GOOD_LOCK + "pyjwt==2.2.0\n", id="duplicate-pyjwt"+ ),+ pytest.param(+ _GOOD_INPUTS,+ _GOOD_LOCK.replace("semgrep==", "semgrep>="),+ id="semgrep-unlocked",+ ),+ pytest.param(+ _GOOD_INPUTS,+ _GOOD_LOCK.replace("2.16.0", "2.15.0"),+ id="pyjwt-below-floor",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("2.15.1", "2.15.0"),+ _GOOD_LOCK,+ id="pyjwt-lower-input-floor",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("2.15.1", "2.15.0"),+ _GOOD_LOCK.replace("2.16.0", "2.15.0"),+ id="pyjwt-lower-floor-and-lock",+ ),+ pytest.param(+ _GOOD_INPUTS,+ _GOOD_LOCK.replace("pyjwt==2.16.0 \\\n --hash=sha256:00\n", ""),+ id="pyjwt-missing",+ ),+ pytest.param(+ _GOOD_INPUTS.replace(+ "semgrep==9.0.0", 'semgrep==9.0.0; sys_platform == "linux"'+ ),+ _GOOD_LOCK,+ id="marker",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("semgrep==9.0.0", "semgrep[extra]==9.0.0"),+ _GOOD_LOCK,+ id="extras",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("semgrep==", "semgrep>="),+ _GOOD_LOCK,+ id="semgrep-range",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("9.0.0", "9.0.*"),+ _GOOD_LOCK,+ id="semgrep-wildcard",+ ),+ pytest.param(+ _GOOD_INPUTS.replace("pyjwt>=", "pyjwt=="),+ _GOOD_LOCK,+ id="pyjwt-pinned",+ ),+ pytest.param(+ _GOOD_INPUTS + "requests==2.0\n", _GOOD_LOCK, id="extra-root"+ ),+ pytest.param(+ _GOOD_INPUTS.replace("# note\npyjwt>=2.15.1\n", ""),+ _GOOD_LOCK,+ id="missing-root",+ ),+ ],+)+def test_scanner_lock_check_rejects_inconsistent_pairs(inputs, lock):+ with pytest.raises(AssertionError):+ _assert_scanner_lock_matches(inputs, lock)++def test_scan_has_no_severity_filter():"""``--severity`` selects exact levels; any use drops the other levels."""assert not [t for t in _scan_tokens(_steps()) if "--severity" in t]