Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ctrl-gaurav_effGen /effgen /security /supply_chain.py
| """ | |
| Runtime supply-chain integrity verification. | |
| When the environment variable ``EFFGEN_VERIFY_HASHES=1`` is set, effGen | |
| verifies that every installed dependency's version matches what is pinned in | |
| the lockfile (``requirements-lock.txt``). | |
| Design note on hash verification | |
| --------------------------------- | |
| A ``--generate-hashes`` lockfile records the SHA-256 of the **downloaded | |
| wheel archive** (.whl file). Once a package is installed those wheel files | |
| are gone — only the extracted dist-info directory and Python files remain. | |
| We cannot reconstruct the original wheel hash from an installed package. | |
| What we *can* do (and what this module does) is: | |
| 1. **Version pinning** — assert that the installed version exactly matches the | |
| pinned version in the lockfile. A version mismatch is a definitive sign of | |
| drift (someone installed a different version outside the locked set). | |
| 2. **Hash recording** — compute a reproducible SHA-256 fingerprint of each | |
| distribution's ``WHEEL`` metadata file, which contains the build tag and | |
| Python/ABI/platform tags. This fingerprint is stored in | |
| ``~/.effgen/supply_chain/installed_hashes.json`` the first time | |
| ``EFFGEN_VERIFY_HASHES=1`` is run. Subsequent runs compare against the | |
| stored snapshot, alerting the operator if any package was silently swapped | |
| for a different build. | |
| If drift is detected a :class:`HashDriftWarning` is emitted via | |
| :mod:`warnings`. The application is **not** terminated — the warning is a | |
| signal to the operator, not a hard failure. | |
| Usage:: | |
| EFFGEN_VERIFY_HASHES=1 python -c "import effgen" | |
| Lock file format | |
| ---------------- | |
| Generated by:: | |
| python scripts/gen_locks.py | |
| Each package line is:: | |
| package==version \\ | |
| --hash=sha256:<hex> \\ | |
| ... | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import warnings | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| # Plain stdlib logger so the startup hook stays import-safe (it runs before the | |
| # rest of effGen is imported, so we cannot depend on effgen.observability here). | |
| _log = logging.getLogger("effgen.security.supply_chain") | |
| __all__ = [ | |
| "HashDriftWarning", | |
| "VerificationResult", | |
| "verify_installed_hashes", | |
| "verify_on_startup", | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Public types | |
| # --------------------------------------------------------------------------- | |
| class HashDriftWarning(UserWarning): | |
| """Emitted when an installed package version or build does not match the lockfile.""" | |
| class VerificationResult: | |
| """Summary returned by :func:`verify_installed_hashes`.""" | |
| checked: int = 0 | |
| """Number of distributions checked against the lockfile.""" | |
| ok: int = 0 | |
| """Number of distributions whose versions matched (no drift).""" | |
| drifted: list[str] = field(default_factory=list) | |
| """Package names where the installed version differs from the lockfile pin.""" | |
| not_in_lockfile: list[str] = field(default_factory=list) | |
| """Packages installed but absent from the lockfile (dev tools, extras).""" | |
| skipped: int = 0 | |
| """Packages where metadata was unavailable.""" | |
| def clean(self) -> bool: | |
| """True when no version drift was detected in locked packages.""" | |
| return len(self.drifted) == 0 | |
| # --------------------------------------------------------------------------- | |
| # Lock file parsing | |
| # --------------------------------------------------------------------------- | |
| _PKG_VER_RE = re.compile(r"^([A-Za-z0-9_.\-]+)==([^\s\\]+)") | |
| _HASH_RE = re.compile(r"--hash=sha256:([0-9a-f]{64})") | |
| def _normalize(name: str) -> str: | |
| """Normalise a package name to lowercase-with-dashes (PEP 503).""" | |
| return re.sub(r"[-_.]+", "-", name).lower() | |
| def _parse_lockfile(lockfile: Path) -> dict[str, tuple[str, set[str]]]: | |
| """Parse a ``--generate-hashes`` lockfile. | |
| Returns a mapping of ``{normalized_name: (pinned_version, {sha256, ...})}``. | |
| """ | |
| index: dict[str, tuple[str, set[str]]] = {} | |
| if not lockfile.exists(): | |
| return index | |
| current_name: str | None = None | |
| current_ver: str | None = None | |
| current_hashes: set[str] = set() | |
| def _flush(): | |
| if current_name and current_ver: | |
| existing = index.get(current_name) | |
| if existing: | |
| index[current_name] = (current_ver, existing[1] | current_hashes) | |
| else: | |
| index[current_name] = (current_ver, set(current_hashes)) | |
| with lockfile.open() as fh: | |
| for raw_line in fh: | |
| line = raw_line.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| m = _PKG_VER_RE.match(line) | |
| if m: | |
| _flush() | |
| current_name = _normalize(m.group(1)) | |
| current_ver = m.group(2) | |
| current_hashes = set(_HASH_RE.findall(line)) | |
| index.setdefault(current_name, (current_ver, set())) | |
| continue | |
| if current_name and line.startswith("--"): | |
| for h in _HASH_RE.findall(line): | |
| current_hashes.add(h) | |
| _flush() | |
| return index | |
| # --------------------------------------------------------------------------- | |
| # Installed-build fingerprinting | |
| # --------------------------------------------------------------------------- | |
| def _wheel_fingerprint(dist: importlib.metadata.Distribution) -> str: | |
| """Compute a stable fingerprint for an installed distribution. | |
| Uses the ``WHEEL`` metadata file, which records build tag, Python tag, | |
| ABI tag, and platform tag — unique per build. Falls back to a hash of | |
| the distribution ``Name==Version`` string if WHEEL is not available | |
| (e.g. for sdist installs or editable installs). | |
| """ | |
| wheel_text = dist.read_text("WHEEL") | |
| if wheel_text: | |
| return hashlib.sha256(wheel_text.encode("utf-8")).hexdigest() | |
| # Fallback: hash Name+Version | |
| meta = dist.metadata | |
| label = f"{meta.get('Name', '?')}=={meta.get('Version', '?')}" | |
| return hashlib.sha256(label.encode()).hexdigest() | |
| def _default_snapshot_path() -> Path: | |
| """Return the path for the installed-hashes snapshot. | |
| Uses ``~/.effgen/supply_chain/installed_hashes.json`` so the snapshot is | |
| stored in the user directory (not inside the source tree or site-packages). | |
| Falls back to a temp-file path if the home directory is not writable. | |
| """ | |
| try: | |
| p = Path.home() / ".effgen" / "supply_chain" / "installed_hashes.json" | |
| p.parent.mkdir(parents=True, exist_ok=True) | |
| return p | |
| except Exception: | |
| import tempfile | |
| return Path(tempfile.gettempdir()) / "effgen_installed_hashes.json" | |
| _SNAPSHOT_PATH = _default_snapshot_path() | |
| def _load_snapshot() -> dict[str, str]: | |
| """Load the stored hash snapshot (empty dict if not yet created).""" | |
| if _SNAPSHOT_PATH.exists(): | |
| try: | |
| with _SNAPSHOT_PATH.open() as fh: | |
| return json.load(fh) | |
| except Exception: | |
| return {} | |
| return {} | |
| def _save_snapshot(snapshot: dict[str, str]) -> None: | |
| """Persist the hash snapshot to disk.""" | |
| try: | |
| _SNAPSHOT_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| with _SNAPSHOT_PATH.open("w") as fh: | |
| json.dump(snapshot, fh, indent=2, sort_keys=True) | |
| except Exception: | |
| pass # read-only FS or permissions issue — silently skip | |
| # --------------------------------------------------------------------------- | |
| # Main verification function | |
| # --------------------------------------------------------------------------- | |
| def verify_installed_hashes( | |
| lockfile: Path | None = None, | |
| *, | |
| warn: bool = True, | |
| ) -> VerificationResult: | |
| """Verify installed distributions against the lock file. | |
| Checks: | |
| 1. **Version pinning** — the installed version must match the pinned | |
| version in ``requirements-lock.txt``. | |
| 2. **Build fingerprint** — if a snapshot exists (from a previous run), | |
| the WHEEL-file fingerprint must match. On the first run a snapshot is | |
| created; on subsequent runs it is compared. | |
| Parameters | |
| ---------- | |
| lockfile: | |
| Path to ``requirements-lock.txt``. Defaults to the file in the | |
| project root (located by walking up from this source file). | |
| warn: | |
| If *True* (default), emit :class:`HashDriftWarning` for every | |
| drifted package. | |
| Returns | |
| ------- | |
| :class:`VerificationResult` | |
| """ | |
| if lockfile is None: | |
| here = Path(__file__).resolve().parent | |
| for ancestor in [here, here.parent, here.parent.parent]: | |
| candidate = ancestor / "requirements-lock.txt" | |
| if candidate.exists(): | |
| lockfile = candidate | |
| break | |
| else: | |
| # No lockfile found — silently succeed | |
| return VerificationResult() | |
| lock_index = _parse_lockfile(lockfile) | |
| if not lock_index: | |
| return VerificationResult() | |
| snapshot = _load_snapshot() | |
| new_snapshot: dict[str, str] = {} | |
| result = VerificationResult() | |
| # importlib.metadata can yield the same distribution more than once | |
| # (e.g. duplicate .dist-info dirs across path entries); dedupe by name so a | |
| # package is never double-counted or listed twice in `drifted`. | |
| seen: set[str] = set() | |
| for dist in importlib.metadata.distributions(): | |
| try: | |
| raw_name = dist.metadata.get("Name") or "" | |
| raw_ver = dist.metadata.get("Version") or "" | |
| if not raw_name: | |
| continue | |
| name = _normalize(raw_name) | |
| if name in seen: | |
| continue | |
| seen.add(name) | |
| result.checked += 1 | |
| if name not in lock_index: | |
| result.not_in_lockfile.append(name) | |
| continue | |
| locked_ver, _ = lock_index[name] | |
| # --- Version pinning check --- | |
| if raw_ver != locked_ver: | |
| result.drifted.append(name) | |
| if warn: | |
| warnings.warn( | |
| f"[effgen supply-chain] Version drift for '{name}': " | |
| f"installed={raw_ver!r} but lockfile pins {locked_ver!r}. " | |
| "Regenerate the lockfile with `python scripts/gen_locks.py` " | |
| "or `pip install -c requirements-lock.txt` to enforce it.", | |
| HashDriftWarning, | |
| stacklevel=4, | |
| ) | |
| continue | |
| # --- Build fingerprint check (snapshot-based) --- | |
| fp = _wheel_fingerprint(dist) | |
| new_snapshot[name] = fp | |
| if snapshot and name in snapshot and snapshot[name] != fp: | |
| # Build changed between runs — same version, different wheel | |
| result.drifted.append(name) | |
| if warn: | |
| warnings.warn( | |
| f"[effgen supply-chain] Build fingerprint changed for '{name}' " | |
| f"{raw_ver}: the installed wheel metadata has changed since the " | |
| "last verification snapshot. This may indicate a supply-chain " | |
| "substitution. Inspect the package and run " | |
| f"`pip install --force-reinstall {name}` from a trusted source.", | |
| HashDriftWarning, | |
| stacklevel=4, | |
| ) | |
| else: | |
| result.ok += 1 | |
| except Exception: # noqa: BLE001 | |
| result.skipped += 1 | |
| continue | |
| # Persist snapshot for subsequent runs (only update/create, never delete) | |
| if new_snapshot: | |
| merged = {**snapshot, **new_snapshot} | |
| _save_snapshot(merged) | |
| return result | |
| # --------------------------------------------------------------------------- | |
| # Startup hook | |
| # --------------------------------------------------------------------------- | |
| def verify_on_startup() -> None: | |
| """Check supply-chain integrity if ``EFFGEN_VERIFY_HASHES=1`` is set. | |
| Called automatically on ``import effgen``. On a clean environment it emits | |
| a single ``hash_verification: ok`` log line; when drift is detected it logs | |
| ``hash_verification: drift`` naming the affected packages and also raises a | |
| :class:`HashDriftWarning`. Never raises or blocks startup. | |
| """ | |
| if os.environ.get("EFFGEN_VERIFY_HASHES", "0") != "1": | |
| return | |
| try: | |
| result = verify_installed_hashes() | |
| n_drifted = len(result.drifted) | |
| if n_drifted: | |
| drifted_names = ", ".join(result.drifted) | |
| _log.warning( | |
| "hash_verification: drift — %d package(s) drifted: %s " | |
| "(checked=%d, ok=%d)", | |
| n_drifted, | |
| drifted_names, | |
| result.checked, | |
| result.ok, | |
| ) | |
| warnings.warn( | |
| f"[effgen startup] Supply-chain check: {n_drifted} package(s) have " | |
| f"version or build drift — {result.drifted[:5]}" | |
| f"{'...' if n_drifted > 5 else ''}. " | |
| "Set EFFGEN_VERIFY_HASHES=0 to suppress or update requirements-lock.txt.", | |
| HashDriftWarning, | |
| stacklevel=2, | |
| ) | |
| else: | |
| _log.info( | |
| "hash_verification: ok — %d package(s) verified against lockfile " | |
| "(%d not in lockfile, %d skipped)", | |
| result.ok, | |
| len(result.not_in_lockfile), | |
| result.skipped, | |
| ) | |
| except Exception as exc: # noqa: BLE001 | |
| _log.warning("hash_verification: error — %s", exc) | |
| warnings.warn( | |
| f"[effgen startup] Supply-chain hash verification failed: {exc}", | |
| HashDriftWarning, | |
| stacklevel=2, | |
| ) | |
Xet Storage Details
- Size:
- 14 kB
- Xet hash:
- 8098f80013e272b6208543cc31f7f6a5f8303f1a29ce6c2c7933a8292e580ff3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.