diff --git a/.github/scripts/gate_drill.lock.json b/.github/scripts/gate_drill.lock.json index d5c1e0b..b5ac23f 100644 --- a/.github/scripts/gate_drill.lock.json +++ b/.github/scripts/gate_drill.lock.json @@ -9,6 +9,15 @@ "kind": "tier", "what": "risk tier: AGENTS.md is T3 (an agent instruction, not documentation)" }, + "tier-auth-surface": { + "digest": "e088562f719a2e1078611cec0e51c03f827d6cdb8fdc47bf8d42b6723ee02e5c", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "auth_surface:src/permissions.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: an auth/permission surface is T3" + }, "tier-build-system": { "digest": "93c004d858cf23fe38eb1590d4b68b6f758304f8ee35ff4a8518ea3046d34cae", "expect_class": "slice", @@ -18,6 +27,33 @@ "kind": "tier", "what": "risk tier: a build-system bump in pyproject.toml is T3 (not allowlisted)" }, + "tier-capability-network": { + "digest": "f11f310bcc237bec68bb8d8297d54a42636bc8af3c10701ae62adfb93bf151fb", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "capability_network:src/slice.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: network capability on an otherwise-T1 path is T3" + }, + "tier-capability-subprocess": { + "digest": "ea682de9cb09c8c282b86dbf8b75eeea5019958d46d0c3e5facf3b8ca502dcde", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "capability_subprocess:src/slice.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: subprocess capability on an otherwise-T1 path is T3" + }, + "tier-ci-config": { + "digest": "67946148e4baad98c6a9b77fe83eba9a340ffc3303ea1d3e70429865f35b8590", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "ci_config:packages/widget/.github/workflows/ci.yml", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: nested CI configuration is T3" + }, "tier-claude-md": { "digest": "a5a4a5c93b300949e8a5e698e2edd829edc164e3f6883edd5c051b5cbc332d57", "expect_class": "slice", @@ -45,6 +81,15 @@ "kind": "tier", "what": "risk tier: a [tool.coverage] table change is T3" }, + "tier-dependency-manifest": { + "digest": "f2b4fb64cd1137e7b2a4c3bc81ee12d4884e8b4379b81e4e862810f7c6d98a99", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "dependency_manifest:src/requirements.txt", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a dependency manifest is T3" + }, "tier-deploy": { "digest": "d3cc0dba070ec0fac588cedcc4aa13d9438c1f1d3b55a014dfdf2d3b31e90c73", "expect_class": "slice", @@ -261,6 +306,24 @@ "kind": "tier", "what": "risk tier: a leased source change is T1" }, + "tier-test-infra": { + "digest": "88d647fae27be34ad9aded18d101a995feb691b39e54540085a81ca1a0d46ab7", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "test_infra:tests/fixtures/case.json", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a new test fixture is T3 test infrastructure" + }, + "tier-unknown-kind": { + "digest": "957d1391f943d4aa8d6743b94917fa88ea58d2df7a10d7ec20c456aebc2f49ca", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "unknown_kind:src/run.sh", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a shell script is an unknown file kind (T3)" + }, "tier-unknown-repo": { "digest": "04737a87e54b60dd6b01ede9a599ab795b8e0175c37b1d4b42ab4c4ca6226233", "expect_class": "slice", diff --git a/.github/scripts/gate_drill.py b/.github/scripts/gate_drill.py index 82a6e5a..a609535 100644 --- a/.github/scripts/gate_drill.py +++ b/.github/scripts/gate_drill.py @@ -859,6 +859,80 @@ def tier(assigned, changes=None, test_files=None, appends=None, deletes=None, re "T3", "repo_unknown:not-a-known-repository", ), + # The gate-authority allowlist additions: one case per new T3 reason. + Case( + "tier-capability-subprocess", + "risk tier: subprocess capability on an otherwise-T1 path is T3", + "tier", + tier(["src/slice.py"], {"src/slice.py": "import subprocess\n"}), + 0, + "slice", + "T3", + "capability_subprocess:src/slice.py", + ), + Case( + "tier-capability-network", + "risk tier: network capability on an otherwise-T1 path is T3", + "tier", + tier(["src/slice.py"], {"src/slice.py": "import socket\n"}), + 0, + "slice", + "T3", + "capability_network:src/slice.py", + ), + Case( + "tier-dependency-manifest", + "risk tier: a dependency manifest is T3", + "tier", + tier(["src/requirements.txt"], {"src/requirements.txt": "requests==2\n"}), + 0, + "slice", + "T3", + "dependency_manifest:src/requirements.txt", + ), + Case( + "tier-test-infra", + "risk tier: a new test fixture is T3 test infrastructure", + "tier", + tier(["tests/fixtures/case.json"], {"tests/fixtures/case.json": "{}\n"}), + 0, + "slice", + "T3", + "test_infra:tests/fixtures/case.json", + ), + Case( + "tier-ci-config", + "risk tier: nested CI configuration is T3", + "tier", + tier( + ["packages/widget/.github/workflows/ci.yml"], + {"packages/widget/.github/workflows/ci.yml": "on: push\n"}, + ), + 0, + "slice", + "T3", + "ci_config:packages/widget/.github/workflows/ci.yml", + ), + Case( + "tier-auth-surface", + "risk tier: an auth/permission surface is T3", + "tier", + tier(["src/permissions.py"], {"src/permissions.py": "VALUE = 1\n"}), + 0, + "slice", + "T3", + "auth_surface:src/permissions.py", + ), + Case( + "tier-unknown-kind", + "risk tier: a shell script is an unknown file kind (T3)", + "tier", + tier(["src/run.sh"], {"src/run.sh": "echo hi\n"}), + 0, + "slice", + "T3", + "unknown_kind:src/run.sh", + ), ) diff --git a/.github/scripts/lease_tamper.py b/.github/scripts/lease_tamper.py index 7d4abfd..7efb461 100644 --- a/.github/scripts/lease_tamper.py +++ b/.github/scripts/lease_tamper.py @@ -229,7 +229,7 @@ #: re-checked against ``pull_request.head.sha`` for the same reason a push is: #: an approval or a rejection can change a non-slice pull request's answer, so #: the gate must judge the head the review is carried to, not the reviewed commit. -PULL_REQUEST_EVENTS = ("pull_request", "pull_request_review") +PULL_REQUEST_EVENTS = ("pull_request", "pull_request_review", "pull_request_target") # --- BEGIN SHARED GATE POLICY (vendored; keep byte-identical) --------------- # One implementation of the rules the lease/tamper gate and the merge lane both @@ -253,6 +253,13 @@ REVIEW_CHANGES_REQUESTED = "changes_requested" REVIEW_APPROVAL_KINDS = (REVIEW_APPROVE_INDEPENDENT, REVIEW_APPROVE_OWNER) +#: The only logins whose words are an attestation. The review text never names +#: an identity: a coordinator, a bee or any other account can copy the canonical +#: line, and none of them is an approval. A rejection still governs whatever +#: account posted it. +REVIEWER_LOGIN = "rizzstack-reviewer[bot]" +OWNER_LOGIN = "mojomast" + #: How a review matches the head: at the head itself, or carried from an #: earlier head by a base-merge-only update with an unchanged diff. REVIEW_MATCH_EXACT = "exact" @@ -320,6 +327,44 @@ def _policy_text(value): return value if isinstance(value, str) else "" +def _policy_login(review): + """The login GitHub authenticated for a review, or an empty string. + + GitHub's REST review carries ``user.login``; the lane's measured facts carry + the same value as ``author``. Any other shape (a missing user, a non-string + login, an empty login) is not an identity. + """ + if not isinstance(review, dict): + return "" + for key in ("user", "author"): + value = review.get(key) + if isinstance(value, dict): + login = value.get("login") + if isinstance(login, str): + return login + elif isinstance(value, str): + return value + return "" + + +def review_identity_ok(review): + """True only for the authenticated reviewer app login.""" + return _policy_login(review) == REVIEWER_LOGIN + + +def owner_identity_ok(review): + """True only for the authenticated owner login.""" + return _policy_login(review) == OWNER_LOGIN + + +def _approval_identity_ok(review, kind): + if kind == REVIEW_APPROVE_INDEPENDENT: + return review_identity_ok(review) + if kind == REVIEW_APPROVE_OWNER: + return owner_identity_ok(review) + return True + + def _policy_first_line(body): for line in _policy_text(body).splitlines(): if line.strip(): @@ -413,11 +458,20 @@ def review_names_commit(named, commit): def review_is_approval(review, kind=None): + """True when ``review`` is an approval of ``kind`` from the right login. + + An independent approval must come from the reviewer app and an owner + attestation from the owner login; the canonical text alone is never an + identity. A rejection has no login requirement and still governs whoever + posted it. + """ form, named = review_form(review) if form not in REVIEW_APPROVAL_KINDS: return False if kind is not None and form != kind: return False + if not _approval_identity_ok(review, form): + return False return review_names_commit(named, (review or {}).get("commit_id")) @@ -484,6 +538,8 @@ def approvals_at_head(reviews, head, kind): form, named = review_form(review) if form != kind: continue + if not _approval_identity_ok(review, kind): + continue if _policy_text(review.get("commit_id")).strip().lower() != wanted: continue if not review_names_commit(named, wanted): @@ -518,6 +574,8 @@ def approval_chain(reviews, head, kind, ancestor=None): form, named = review_form(review) if form != kind: continue + if not _approval_identity_ok(review, kind): + continue commit = _policy_text(review.get("commit_id")).strip().lower() if not commit or commit == wanted or commit in seen: continue @@ -2006,6 +2064,53 @@ def render_success(contract, contract_path, boundary, boundary_kind, commits, sc re.compile(r"\bunittest\s*\.\s*TestCase\s*\.\s*assert[A-Za-z0-9_]*\s*=(?!=)"), ), ) +#: Capability scanners over added lines. A path that is otherwise T1 becomes +#: T3 when the change introduces a way to run code or reach the network; the +#: language tag keeps a ``fetch(`` in documentation from being mistaken for a +#: JavaScript network call. +TIER_CAPABILITY_PATTERNS = ( + ("py", "capability_subprocess", re.compile(r"^\s*(?:import|from)\s+(?:subprocess|pty|ctypes|multiprocessing|importlib)\b")), + ("py", "capability_subprocess", re.compile(r"\b__import__\s*\(")), + ("py", "capability_subprocess", re.compile(r"\bos\s*\.\s*(?:exec|spawn|posix_spawn|system|popen)")), + ("py", "capability_subprocess", re.compile(r"\b(?:eval|exec)\s*\(")), + ("py", "capability_subprocess", re.compile(r"\bimportlib\s*\.\s*import_module\b")), + ("js", "capability_subprocess", re.compile(r"(?:require|import)\s*\(\s*['\"](?:node:)?child_process['\"]")), + ("js", "capability_subprocess", re.compile(r"\bfrom\s+['\"](?:node:)?child_process['\"]")), + ("js", "capability_subprocess", re.compile(r"\bnew\s+Function\s*\(")), + ("py", "capability_network", re.compile(r"^\s*(?:import|from)\s+(?:socket|ssl|urllib|http|ftplib|smtplib|telnetlib|xmlrpc)\b")), + ("py", "capability_network", re.compile(r"\b(?:asyncio\s*\.\s*)?open_connection\s*\(")), + ("js", "capability_network", re.compile(r"\bfetch\s*\(")), + ("js", "capability_network", re.compile(r"\bnew\s+WebSocket\b|\bWebSocket\s*\(")), + ("js", "capability_network", re.compile(r"\bnavigator\s*\.\s*sendBeacon\b|\bsendBeacon\s*\(")), + ("js", "capability_network", re.compile(r"\bnew\s+XMLHttpRequest\b|\bXMLHttpRequest\b")), + ("js", "capability_network", re.compile(r"\bfrom\s+['\"]node:net['\"]|\brequire\s*\(\s*['\"]node:net['\"]")), +) + +#: File kinds the allowlist never understands: scripts, compiled artifacts, +#: notebooks, makefiles and extensionless files are T3. Executable bits, +#: symlinks and submodules are detected from the raw diff, not the name. +TIER_UNKNOWN_SUFFIXES = ( + ".sh", ".bash", ".zsh", ".ksh", ".fish", ".ps1", ".bat", ".cmd", + ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".obj", ".lib", + ".class", ".jar", ".war", ".whl", ".pyc", ".pyo", ".pyd", ".ipynb", +) +TIER_MAKE_NAMES = frozenset(("makefile", "gnumakefile")) +TIER_DEPENDENCY_NAMES = frozenset(( + "package.json", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", + "pnpm-lock.yaml", "bun.lockb", "pipfile", "pipfile.lock", "poetry.lock", + "uv.lock", "cargo.toml", "cargo.lock", "go.mod", "go.sum", "gemfile", + "gemfile.lock", "composer.json", "composer.lock", "pom.xml", + "build.gradle", "build.gradle.kts", "pyproject.toml", "setup.py", + "setup.cfg", "manifest.in", +)) +TIER_TEST_INFRA_NAMES = frozenset(("__init__.py", "helpers.py", "helper.py", "fixtures.py")) +TIER_TEST_INFRA_SEGMENTS = frozenset(("fixtures", "__fixtures__", "helpers", "support")) +TIER_AUTH_TOKENS = frozenset(( + "auth", "oauth", "credential", "credentials", "secret", "secrets", "token", + "permission", "permissions", "approval", "approvals", "validator", + "validators", "sandbox", "sandboxes", +)) + TIER_PACKAGING_TABLES = ( ("build-system",), ("tool", "hatch", "build"), @@ -2184,6 +2289,110 @@ def _tier_is_scanned(path): return base in TIER_SCAN_NAMES or base.endswith(TIER_SCAN_SUFFIXES) +def _tier_is_dependency_manifest(path): + base = _tier_basename(path).lower() + if base in TIER_DEPENDENCY_NAMES: + return True + return ( + base.endswith(".txt") + and (base.startswith("requirements") or base.startswith("constraints")) + ) + + +def _tier_is_test_infra(path): + normal = _tier_normalise(path).lower() + parts = normal.split("/") + base = parts[-1] + if base in TIER_TEST_INFRA_NAMES: + return True + if not (_tier_is_test_path(normal) or any(segment in TIER_TEST_DIR_SEGMENTS for segment in parts)): + return False + return any(segment in TIER_TEST_INFRA_SEGMENTS for segment in parts[:-1]) + + +def _tier_is_nested_ci(path): + normal = _tier_normalise(path).lower() + padded = "/" + normal + if any( + marker in padded + for marker in ("/.github/workflows/", "/.github/actions/", "/.gitlab/", "/.circleci/") + ): + return True + return _tier_basename(normal) in ( + ".gitlab-ci.yml", + ".travis.yml", + "azure-pipelines.yml", + "jenkinsfile", + ) + + +def _tier_is_auth_surface(path): + normal = _tier_normalise(path).lower() + tokens = set() + for segment in normal.split("/"): + tokens.update(token for token in re.split(r"[^a-z0-9]+", segment) if token) + return bool(tokens & TIER_AUTH_TOKENS) + + +def _tier_is_unknown_kind(path): + base = _tier_basename(path).lower() + if base in TIER_MAKE_NAMES: + return True + if base.endswith(TIER_UNKNOWN_SUFFIXES): + return True + # An extensionless file is a kind the allowlist does not understand. A + # dotfile such as ``.gitignore`` also has no suffix and is not product code. + return "." not in base and bool(base) + + +def _tier_capability_reasons(path, content): + base = _tier_basename(path).lower() + is_py = base.endswith((".py", ".pyi")) + is_js = base.endswith((".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx")) + reasons = [] + for lang, reason, pattern in TIER_CAPABILITY_PATTERNS: + if (lang == "py" and not is_py) or (lang == "js" and not is_js): + continue + if pattern.search(content) and reason not in reasons: + reasons.append(reason) + return reasons + + +def _tier_raw_modes(repo, merge_base, head): + """``{path: (old_mode, new_mode)}`` from the raw diff (symlinks, gitlinks, modes).""" + proc = _run( + repo, "diff", "--raw", "-z", "--no-renames", merge_base, head, check=False + ) + if proc.returncode != 0: + raise GateError("cannot read the raw change between %s and %s" % (merge_base[:12], head[:12])) + fields = proc.stdout.split("\0") + modes = {} + index = 0 + while index + 1 < len(fields): + header, path = fields[index], fields[index + 1] + index += 2 + if not header.startswith(":"): + continue + parts = header[1:].split() + if len(parts) < 5: + continue + modes[_tier_normalise(path)] = (parts[0], parts[1]) + return modes + + +def _tier_mode_reasons(path, modes): + if modes is None: + return ["unknown_kind"] + old_mode, new_mode = modes + if "160000" in (old_mode, new_mode): + return ["unknown_kind"] + if "120000" in (old_mode, new_mode): + return ["unknown_kind"] + if old_mode.endswith("755") or new_mode.endswith("755"): + return ["unknown_kind"] + return [] + + def _tier_blob(repo, revision, path): proc = _run(repo, "show", "%s:%s" % (revision, path), check=False) return proc.stdout if proc.returncode == 0 else None @@ -2389,6 +2598,16 @@ def _tier_path_reasons(repo, merge_base, head, status, path): reasons.append("deploy_config") if _tier_is_contract_path(normal): reasons.append("contracts") + if _tier_is_dependency_manifest(normal): + reasons.append("dependency_manifest") + if _tier_is_test_infra(normal): + reasons.append("test_infra") + if _tier_is_nested_ci(normal): + reasons.append("ci_config") + if _tier_is_auth_surface(normal): + reasons.append("auth_surface") + if _tier_is_unknown_kind(normal): + reasons.append("unknown_kind") if not reasons and sensitive_paths([normal]): # The shared list matches by explicit path, by prefix (machinery # directories, always T3) and by a file-name token. A token match on a @@ -2473,14 +2692,19 @@ def add(reason, path=None): if allowlist is None: add("repo_unknown", name) allowlist = () + modes = _tier_raw_modes(repo, merge_base, head) for status, path in _tier_diff(repo, merge_base, head): for reason in _tier_path_reasons(repo, merge_base, head, status, path): add(reason, path) + for reason in _tier_mode_reasons(path, modes.get(_tier_normalise(path))): + add(reason, path) if _tier_always_three(path): add("always_t3", path) if not _tier_allowlisted(path, status, allowlist): add("not_t1_allowlisted", path) for path, content in _tier_added_lines(repo, merge_base, head): + for reason in _tier_capability_reasons(path, content): + add(reason, _tier_normalise(path)) if not _tier_is_scanned(path): continue for kind, pattern in TIER_SCANNER_PATTERNS: diff --git a/.github/workflows/gate-authority.yml b/.github/workflows/gate-authority.yml new file mode 100644 index 0000000..d782f6e --- /dev/null +++ b/.github/workflows/gate-authority.yml @@ -0,0 +1,30 @@ +name: gate-authority + +on: + pull_request_target: + types: [opened, synchronize, reopened, edited, ready_for_review] + +permissions: + contents: read + +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - name: Check out the base commit without credentials + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: Fetch the pull request head as objects only + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: Run the base gate + env: + GH_TOKEN: ${{ github.token }} + run: | + python3 .github/scripts/lease_tamper.py diff --git a/.github/workflows/review-rerun.yml b/.github/workflows/review-rerun.yml index fafd984..4545777 100644 --- a/.github/workflows/review-rerun.yml +++ b/.github/workflows/review-rerun.yml @@ -1,45 +1,51 @@ name: review rerun -# A submitted review changes what lease-tamper/ci-gate answer, but GitHub keeps -# a failed check from the pull_request run beside any later green run of the same -# name, so the merge box stays blocked. Re-run only the failed GATE jobs for the -# reviewed head: a review must re-judge the review gate, never re-roll a failing -# test. +# A submitted or dismissed review changes what the base gate answers, so re-run +# the newest pull_request_target gate-authority run for this pull request at its +# exact head, whatever its conclusion: a later rejection must be able to turn a +# green gate red. A failed lease-tamper job on a pull_request run is re-run too. on: pull_request_review: - types: [submitted] + types: [submitted, dismissed] permissions: contents: read actions: write jobs: - rerun-failed-gates: - name: rerun failed gate jobs + rerun-base-gate: + name: rerun base gate runs-on: ubuntu-24.04 timeout-minutes: 5 steps: - - name: Rerun lease-tamper on the pull_request runs for this head + - name: Re-run the base-pinned gate and any failed lease-tamper job env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} run: | set -euo pipefail - runs=$(gh api --paginate --slurp \ + gate_runs=$(gh api --paginate --slurp \ + "repos/$REPO/actions/workflows/gate-authority.yml/runs?event=pull_request_target&per_page=100") + gate_id=$(printf '%s' "$gate_runs" | jq -r --argjson pr "$PR_NUMBER" --arg head "$HEAD_SHA" ' + [.[].workflow_runs[] + | select(.path == ".github/workflows/gate-authority.yml") + | select(.status == "completed") + | select(any(.pull_requests[]?; .number == $pr and (.head.sha // "") == $head))] + | sort_by([.created_at, .id]) | last | .id // empty') + if [ -n "$gate_id" ]; then + echo "rerun base gate: $gate_id" + gh api -X POST "repos/$REPO/actions/runs/$gate_id/rerun" + fi + head_runs=$(gh api --paginate --slurp \ "repos/$REPO/actions/runs?event=pull_request&head_sha=$HEAD_SHA&per_page=100") - run_ids=$(printf '%s' "$runs" | jq -r --argjson pr "$PR_NUMBER" ' + run_ids=$(printf '%s' "$head_runs" | jq -r --argjson pr "$PR_NUMBER" ' [.[].workflow_runs[] | select(.status == "completed" and .conclusion == "failure") | select(any(.pull_requests[]?; .number == $pr)) | .id] | unique | .[]') - if [ -z "$run_ids" ]; then - echo "no failed pull_request run for $REPO#$PR_NUMBER at $HEAD_SHA" - exit 0 - fi - reran=0 for run in $run_ids; do jobs=$(gh api --paginate --slurp \ "repos/$REPO/actions/runs/$run/jobs?per_page=100") @@ -51,9 +57,5 @@ jobs: for job in $job_ids; do echo "rerun gate job: $job (run $run)" gh api -X POST "repos/$REPO/actions/jobs/$job/rerun" - reran=$((reran + 1)) done done - if [ "$reran" -eq 0 ]; then - echo "no failed gate job on $REPO#$PR_NUMBER at $HEAD_SHA" - fi diff --git a/scripts/merge_lane_v5.py b/scripts/merge_lane_v5.py index 27759bd..e3f9454 100644 --- a/scripts/merge_lane_v5.py +++ b/scripts/merge_lane_v5.py @@ -66,7 +66,19 @@ SLICE = "slice" NON_SLICE = "non-slice" -MERGE_STATES = ("CLEAN", "BEHIND") +MERGE_STATES = ("CLEAN",) + +#: The gate GitHub runs for a pull request is the base branch's +#: ``pull_request_target`` workflow. Its run reports on the base tip, so the +#: lane proves it through the workflow run, never a same-named head check. +GATE_AUTHORITY_NAME = "gate-authority" +GATE_AUTHORITY_EVENT = "pull_request_target" +GATE_AUTHORITY_PATH = ".github/workflows/gate-authority.yml" +GATE_AUTHORITY_REVIEW_RERUN_PATH = ".github/workflows/review-rerun.yml" +GATE_AUTHORITY_APP = "github-actions" +GATE_AUTHORITY_COMPARE_LIMIT = 300 +GATE_CODE_PREFIXES = (".github/scripts/",) +GATE_CODE_PATHS = (GATE_AUTHORITY_PATH, GATE_AUTHORITY_REVIEW_RERUN_PATH) #: The gate the lane runs itself. It is read from the trusted base revision, #: never from the pull request's head: a PR that edits the gate must not be @@ -129,6 +141,13 @@ REVIEW_CHANGES_REQUESTED = "changes_requested" REVIEW_APPROVAL_KINDS = (REVIEW_APPROVE_INDEPENDENT, REVIEW_APPROVE_OWNER) +#: The only logins whose words are an attestation. The review text never names +#: an identity: a coordinator, a bee or any other account can copy the canonical +#: line, and none of them is an approval. A rejection still governs whatever +#: account posted it. +REVIEWER_LOGIN = "rizzstack-reviewer[bot]" +OWNER_LOGIN = "mojomast" + #: How a review matches the head: at the head itself, or carried from an #: earlier head by a base-merge-only update with an unchanged diff. REVIEW_MATCH_EXACT = "exact" @@ -196,6 +215,44 @@ def _policy_text(value): return value if isinstance(value, str) else "" +def _policy_login(review): + """The login GitHub authenticated for a review, or an empty string. + + GitHub's REST review carries ``user.login``; the lane's measured facts carry + the same value as ``author``. Any other shape (a missing user, a non-string + login, an empty login) is not an identity. + """ + if not isinstance(review, dict): + return "" + for key in ("user", "author"): + value = review.get(key) + if isinstance(value, dict): + login = value.get("login") + if isinstance(login, str): + return login + elif isinstance(value, str): + return value + return "" + + +def review_identity_ok(review): + """True only for the authenticated reviewer app login.""" + return _policy_login(review) == REVIEWER_LOGIN + + +def owner_identity_ok(review): + """True only for the authenticated owner login.""" + return _policy_login(review) == OWNER_LOGIN + + +def _approval_identity_ok(review, kind): + if kind == REVIEW_APPROVE_INDEPENDENT: + return review_identity_ok(review) + if kind == REVIEW_APPROVE_OWNER: + return owner_identity_ok(review) + return True + + def _policy_first_line(body): for line in _policy_text(body).splitlines(): if line.strip(): @@ -289,11 +346,20 @@ def review_names_commit(named, commit): def review_is_approval(review, kind=None): + """True when ``review`` is an approval of ``kind`` from the right login. + + An independent approval must come from the reviewer app and an owner + attestation from the owner login; the canonical text alone is never an + identity. A rejection has no login requirement and still governs whoever + posted it. + """ form, named = review_form(review) if form not in REVIEW_APPROVAL_KINDS: return False if kind is not None and form != kind: return False + if not _approval_identity_ok(review, form): + return False return review_names_commit(named, (review or {}).get("commit_id")) @@ -360,6 +426,8 @@ def approvals_at_head(reviews, head, kind): form, named = review_form(review) if form != kind: continue + if not _approval_identity_ok(review, kind): + continue if _policy_text(review.get("commit_id")).strip().lower() != wanted: continue if not review_names_commit(named, wanted): @@ -394,6 +462,8 @@ def approval_chain(reviews, head, kind, ancestor=None): form, named = review_form(review) if form != kind: continue + if not _approval_identity_ok(review, kind): + continue commit = _policy_text(review.get("commit_id")).strip().lower() if not commit or commit == wanted or commit in seen: continue @@ -1336,6 +1406,268 @@ def fetch_compare(repo_slug, older, newer, token, api_url=DEFAULT_API_URL, http= return payload +def fetch_gate_authority_runs(repo_slug, token, api_url=DEFAULT_API_URL, http=None): + """The gate-authority workflow's ``pull_request_target`` runs.""" + url = "%s/repos/%s/actions/workflows/%s/runs?event=%s&per_page=100" % ( + api_url, + repo_slug, + "gate-authority.yml", + GATE_AUTHORITY_EVENT, + ) + runs = [] + for _ in range(MAX_PAGES): + payload, link = _get(url, token, http) + if not isinstance(payload, dict): + raise FetchError("%s did not return workflow runs" % url) + page = payload.get("workflow_runs") + if not isinstance(page, list): + raise FetchError("%s did not return workflow runs" % url) + runs.extend(item for item in page if isinstance(item, dict)) + url = _next_page(link) + if not url: + return runs + raise FetchError("the workflow-run lookup did not terminate") + + +def fetch_check_suite(repo_slug, suite_id, token, api_url=DEFAULT_API_URL, http=None): + url = "%s/repos/%s/check-suites/%s" % (api_url, repo_slug, int(suite_id)) + payload, _link = _get(url, token, http) + if not isinstance(payload, dict): + raise FetchError("%s did not return a check suite" % url) + return payload + + +def fetch_ref_tip(repo_slug, branch, token, api_url=DEFAULT_API_URL, http=None): + url = "%s/repos/%s/git/ref/heads/%s" % ( + api_url, + repo_slug, + urllib.parse.quote(str(branch or ""), safe="/"), + ) + payload, _link = _get(url, token, http) + if not isinstance(payload, dict): + raise FetchError("%s did not return a git ref" % url) + return payload + + +def _run_pull_request_entry(run, number): + """The run's ``pull_requests[]`` entry for this PR number, or ``None``.""" + entries = run.get("pull_requests") + if not isinstance(entries, list): + return None + for entry in entries: + if not isinstance(entry, dict): + continue + try: + if int(entry.get("number")) == int(number): + return entry + except (TypeError, ValueError): + continue + return None + + +def _full_name(value): + return _text((value or {}).get("full_name") if isinstance(value, dict) else value).strip().lower() + + +def gate_authority_facts(repo_slug, number, pr, runs, token, api_url=DEFAULT_API_URL, http=None, + demanded=False, head_check_present=False, error=False): + """The measured gate-authority run facts ``decide()`` consumes. + + Every candidate's check-suite app is read from the API (a same-named check + from another app is not the gate), and every run's commit is compared with + the pull request's current base tip so the decision can prove both its base + ref and its ancestry without trusting a caller-supplied fact. + """ + base_ref = _text((pr.get("base") or {}).get("ref")).strip() + base_tip = None + if demanded and base_ref: + try: + tip = fetch_ref_tip(repo_slug, base_ref, token, api_url, http) + base_tip = _sha(((tip.get("object") or {}).get("sha"))) + except FetchError: + base_tip = None + error = True + items = [] + for run in runs or []: + if not isinstance(run, dict): + continue + item = { + "id": run.get("id"), + "path": _text(run.get("path")).strip(), + "event": _text(run.get("event")).strip(), + "status": _text(run.get("status")).strip().lower(), + "conclusion": _text(run.get("conclusion")).strip().lower(), + "head_sha": _sha(run.get("head_sha")) or "", + "created_at": _text(run.get("created_at")).strip(), + "run_started_at": _text(run.get("run_started_at")).strip(), + "pull_requests": run.get("pull_requests") if isinstance(run.get("pull_requests"), list) else None, + "repository": {"full_name": _full_name(run.get("repository"))}, + "head_repository": {"full_name": _full_name(run.get("head_repository"))}, + "app": None, + "compare_status": None, + "compare_files_present": False, + "compare_files": None, + } + suite_id = run.get("check_suite_id") + if suite_id is not None: + try: + suite = fetch_check_suite(repo_slug, suite_id, token, api_url, http) + item["app"] = _text((suite.get("app") or {}).get("slug")).strip() + except FetchError: + item["app"] = None + error = True + head_sha = item["head_sha"] + if base_tip and head_sha: + try: + document = fetch_compare(repo_slug, head_sha, base_tip, token, api_url, http) + item["compare_status"] = _text(document.get("status")).strip().lower() + if "files" in document: + item["compare_files_present"] = True + item["compare_files"] = document.get("files") + else: + item["compare_files_present"] = False + except FetchError: + item["compare_status"] = None + item["compare_files_present"] = False + error = True + items.append(item) + return { + "demanded": bool(demanded), + "error": bool(error), + "number": int(number) if number is not None else 0, + "repo": _text(repo_slug).strip().lower(), + "base_ref": base_ref, + "base_tip": base_tip or "", + "head_check_present": bool(head_check_present), + "runs": items, + } + + +def _gate_code_path(name): + normal = _text(name).replace("\\", "/") + while normal.startswith("./"): + normal = normal[2:] + if normal in GATE_CODE_PATHS: + return True + return any(normal.startswith(prefix) for prefix in GATE_CODE_PREFIXES) + + +def _gate_code_changed(entry): + """``(invalid, changed)``: does a compare file entry touch the gate code?""" + if not isinstance(entry, dict): + return True, False + filename = entry.get("filename") + if not isinstance(filename, str) or not filename: + return True, False + status = _text(entry.get("status")).strip().lower() + changed = _gate_code_path(filename) + if status in ("copied", "changed", "renamed"): + previous = entry.get("previous_filename") + if isinstance(previous, str) and _gate_code_path(previous): + changed = True + return False, changed + + +def _parse_stamp(value): + text = _text(value).strip() + if not STAMP_LINE.fullmatch(text): + return None + try: + return datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + + +def gate_authority_state(gate, head, reviews): + """``(ok, reason, run_id)`` for the base-pinned gate run. + + The newest run whose ``pull_requests[]`` names this PR decides, even when it + judged an older head. Its base ref, its ancestry on the current base, its + conclusion, its start time against every submitted review, and the gate code + on the base at the tip are all required; any unreadable fact fails closed. + """ + if not isinstance(gate, dict): + return True, None, None + if gate.get("head_check_present"): + return False, "gate_authority_unproven", None + if not gate.get("demanded"): + return True, None, None + if gate.get("error"): + return False, "gate_authority_unproven", None + wanted = _sha(head) + repo = _text(gate.get("repo")).strip().lower() + number = gate.get("number") + base_ref = _text(gate.get("base_ref")).strip() + if wanted is None or not repo or not base_ref or not gate.get("base_tip"): + return False, "gate_authority_unproven", None + candidates = [] + for run in gate.get("runs") or []: + if not isinstance(run, dict): + continue + if _text(run.get("path")).strip() != GATE_AUTHORITY_PATH: + continue + if _text(run.get("event")).strip() != GATE_AUTHORITY_EVENT: + continue + if _text(run.get("app")).strip() != GATE_AUTHORITY_APP: + continue + if _text((run.get("repository") or {}).get("full_name")).strip().lower() != repo: + continue + if _text((run.get("head_repository") or {}).get("full_name")).strip().lower() != repo: + continue + entry = _run_pull_request_entry(run, number) + if entry is None: + continue + candidates.append((run, entry)) + if not candidates: + return False, "gate_authority_unproven", None + + def order(item): + run = item[0] + try: + run_id = int(run.get("id")) + except (TypeError, ValueError): + run_id = 0 + return (_text(run.get("created_at")), run_id) + + run, entry = max(candidates, key=order) + verdict_run = run.get("id") + entry_head = _sha(((entry.get("head") or {}).get("sha"))) + if entry_head != wanted: + return False, "gate_authority_unproven", verdict_run + entry_base = _text(((entry.get("base") or {}).get("ref"))).strip() + if entry_base != base_ref: + return False, "gate_authority_wrong_base", verdict_run + if _text(run.get("compare_status")).strip().lower() not in ("ahead", "identical"): + return False, "gate_authority_wrong_base", verdict_run + if _text(run.get("status")).strip().lower() != "completed" or _text( + run.get("conclusion") + ).strip().lower() != "success": + return False, "gate_authority_not_green", verdict_run + + started = _parse_stamp(run.get("run_started_at")) + if started is None: + return False, "gate_authority_stale", verdict_run + for review in reviews or []: + if not isinstance(review, dict): + continue + submitted = _parse_stamp(review.get("submitted_at")) + if submitted is None: + continue + if started <= submitted: + return False, "gate_authority_stale", verdict_run + + if not run.get("compare_files_present"): + return False, "gate_authority_stale_gate", verdict_run + files = run.get("compare_files") + if not isinstance(files, list) or len(files) >= GATE_AUTHORITY_COMPARE_LIMIT: + return False, "gate_authority_stale_gate", verdict_run + for entry_file in files: + invalid, changed = _gate_code_changed(entry_file) + if invalid or changed: + return False, "gate_authority_stale_gate", verdict_run + return True, None, verdict_run + + def pr_facts(pr, files): """The pull request facts ``decide()`` consumes, from the REST object.""" head = _sha(((pr.get("head") or {}).get("sha"))) @@ -1384,6 +1716,10 @@ def check_facts(runs): for run in runs or []: if not isinstance(run, dict): continue + # A check run named gate-authority on the head commit is never the + # gate: the pull_request_target workflow reports on the base tip. + if _text(run.get("name")).strip() == GATE_AUTHORITY_NAME: + continue out.append( { "name": _text(run.get("name")).strip(), @@ -1542,6 +1878,23 @@ def required_checks_from_rulesets(repo_slug, root=None, repo=None): return tuple(contexts) if contexts else tuple(DEFAULT_REQUIRED_CHECKS) +def gate_authority_demanded(repo, required_checks): + """True when the base checkout carries the gate workflow or it is required. + + GitHub's ruleset is never the authority here: a required check named + ``gate-authority`` pins only the Actions app, so a same-named job satisfies + it. The base checkout's own workflow file is the stronger fact. + """ + names = [ + _text(name).strip() for name in (required_checks or ()) if isinstance(name, str) + ] + if GATE_AUTHORITY_NAME in names: + return True + if repo: + return (Path(repo) / GATE_AUTHORITY_PATH).is_file() + return False + + def collect_facts(repo_slug, number, repo, token, api_url=DEFAULT_API_URL, http=None, pr=None, gate_record=None, verify_dir=DEFAULT_VERIFY_DIR, plan_path=DEFAULT_PLAN_PATH, required_checks=None): @@ -1555,6 +1908,37 @@ def collect_facts(repo_slug, number, repo, token, api_url=DEFAULT_API_URL, http= reviews = fetch_reviews(repo_slug, number, token, api_url, http) files = fetch_pull_request_files(repo_slug, number, token, api_url, http) runs = fetch_check_runs(repo_slug, head, token, api_url, http) + head_gate_check = any( + isinstance(run, dict) + and _text(run.get("name")).strip() == GATE_AUTHORITY_NAME + and _sha(run.get("head_sha")) == head + for run in runs + ) + required_list = list( + required_checks if required_checks is not None + else required_checks_from_rulesets(repo_slug, repo=repo) + ) + demanded = gate_authority_demanded(repo, required_list) + gate_error = False + gate_runs = [] + if demanded: + try: + gate_runs = fetch_gate_authority_runs(repo_slug, token, api_url, http) + except FetchError: + gate_runs = [] + gate_error = True + gate_authority = gate_authority_facts( + repo_slug, + number, + pr, + gate_runs, + token, + api_url, + http, + demanded=demanded, + head_check_present=head_gate_check, + error=gate_error, + ) records = load_verify_records(verify_dir) compare = collect_compare(repo_slug, head, records, token, api_url, http) pull_class = class_from_gate(gate_record or {}) @@ -1573,10 +1957,8 @@ def collect_facts(repo_slug, number, repo, token, api_url=DEFAULT_API_URL, http= "pr": pr_state, "reviews": review_facts(reviews), "checks": check_facts(runs), - "required_checks": list( - required_checks if required_checks is not None - else required_checks_from_rulesets(repo_slug, repo=repo) - ), + "required_checks": required_list, + "gate_authority": gate_authority, "verify": { "records": records, "compare": compare, @@ -1712,10 +2094,24 @@ def refuse(reason): verdict["tier"] = tier auto_t1 = pull_class == SLICE and tier == "T1" - ok, reason = checks_state(facts.get("checks") or [], head, facts.get("required_checks")) + required = facts.get("required_checks") + if isinstance(required, (list, tuple)): + # gate-authority is proven through its workflow run below, never by a + # same-named head check (which is filtered out of the check facts). + required = [ + name for name in required + if _text(name).strip() != GATE_AUTHORITY_NAME + ] + ok, reason = checks_state(facts.get("checks") or [], head, required) if not ok: return refuse(reason) + gate_ok, gate_reason, _gate_run_id = gate_authority_state( + facts.get("gate_authority"), head, reviews + ) + if not gate_ok: + return refuse(gate_reason) + carry = facts.get("review_carry") review, review_match, review_reason = review_acceptance(reviews, head, carry, ancestor) if auto_t1: diff --git a/tests/fixtures/gate_drill.lock.main.json b/tests/fixtures/gate_drill.lock.main.json new file mode 100644 index 0000000..d5c1e0b --- /dev/null +++ b/tests/fixtures/gate_drill.lock.main.json @@ -0,0 +1,455 @@ +{ + "cases": { + "tier-agents-md": { + "digest": "c1c54b6887e79b924b31e898c24dbdb5d83cfeabf73e34e11252e41719dce173", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:AGENTS.md", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: AGENTS.md is T3 (an agent instruction, not documentation)" + }, + "tier-build-system": { + "digest": "93c004d858cf23fe38eb1590d4b68b6f758304f8ee35ff4a8518ea3046d34cae", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a build-system bump in pyproject.toml is T3 (not allowlisted)" + }, + "tier-claude-md": { + "digest": "a5a4a5c93b300949e8a5e698e2edd829edc164e3f6883edd5c051b5cbc332d57", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:CLAUDE.md", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: CLAUDE.md is T3 (an agent instruction, not documentation)" + }, + "tier-conftest": { + "digest": "a5137f6d30bae3ed6cf48ee1bbe342f3a075befb714d5b6f2ce2df22127a47cb", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: any conftest.py is T3" + }, + "tier-coverage": { + "digest": "a6f2d8b8a66486f651c69514a2af8069580ff1a6c691e78085426e5a4d69aa8b", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a [tool.coverage] table change is T3" + }, + "tier-deploy": { + "digest": "d3cc0dba070ec0fac588cedcc4aa13d9438c1f1d3b55a014dfdf2d3b31e90c73", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a deploy unit is T3" + }, + "tier-docs-only": { + "digest": "a933368b4c49d982992a7b38981bd09506aab1622310e028a356cf3bc57f4fee", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T1", + "kind": "tier", + "what": "risk tier: a documentation-only change is T1 (allowlisted)" + }, + "tier-dotted-keys": { + "digest": "bbd42620dd762bfd580c47b7a211edf61dd3f7cb6ca0e2597bd6cf46eb67aac1", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: dotted keys hiding pytest config are T3" + }, + "tier-entry-points": { + "digest": "6ac749d086888658713d275c148da29405177f376fb4ca1b5b1a4728d72423ab", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a pytest11 entry point is T3" + }, + "tier-existing-test": { + "digest": "db4184aad49be0f1355677a9299057660f547bed3d8fcef6e8ae4b5745afe2d4", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: an edit to an EXISTING test file is T3" + }, + "tier-github": { + "digest": "9557b065f7afe3e06922760948be66432a4ecb996556279dc9d0f043231a3ee9", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a workflow change is T3" + }, + "tier-inline-table-root": { + "digest": "f6cb12a9ba68bfc87ddea894804d8e755950bd66dbfb0c80e070a23e6fc3ed82", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a fully inline root table hiding pytest config is T3" + }, + "tier-inline-table-tool": { + "digest": "0f1a069b6f5dac9404c0c6456223091001f23b5a16a32f24d0f6cf65b9b863db", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: an inline pytest table under [tool] is T3" + }, + "tier-invalid-toml": { + "digest": "3848a56fb18157cd22563d05d6ee5bb2256292b7fab56a6334305186a4f1b08e", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: an unparseable pyproject is T3 (fail closed)" + }, + "tier-lease-store": { + "digest": "c6fbaf00d8031989afe5bfee0675edd6313744564a392eca00751daef025ff7f", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "risk tier: a lease-store change is T3 and non-slice" + }, + "tier-leases-module": { + "digest": "734d3017d0a1809f1b8d290a055bd542a2aa8b03620eeecd45b7484ac07360b1", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:bundlebees_plugin/leases.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: bundlebees_plugin/leases.py is T3 (not allowlisted)" + }, + "tier-new-test": { + "digest": "6ba4623b2771407cc2090857b48a210644e16624be2202eb5bdf7a2faf5831a3", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T1", + "kind": "tier", + "what": "risk tier: a NEW test file is T1" + }, + "tier-non-slice-workflow": { + "digest": "83bcbb1bdc7bde6393cf4b5c92f83faab56795adc90573ad35ec6cc080d10459", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "risk tier: an unleased workflow change is non-slice T3" + }, + "tier-oracle-lock": { + "digest": "ffb8b5dfc81ddff6a6ab3e5d6cf6d3ccbf10e83e6ce1e923abe479b2a01787de", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:bundlebees_plugin/oracle_lock.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: bundlebees_plugin/oracle_lock.py is T3 (not allowlisted)" + }, + "tier-oracle-pytest-ini": { + "digest": "27887402d22aa7ad80a7b2142436bc1db01aec84bf9bd5cd48fe737a4320f1bf", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:.bundlebees-oracle-pytest.ini", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: .bundlebees-oracle-pytest.ini is T3 (not allowlisted)" + }, + "tier-package-json": { + "digest": "a048fe57351a9432dc0051d34cc7629a2835eae8c063d683bf8da9949f6eeef1", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:package.json", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: package.json is T3 (not allowlisted)" + }, + "tier-packaging-schemas": { + "digest": "8a108ea2d4e9c938e203e9c2b35ca6f39fb46cdeddf10124c4f597523c7b59c9", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: packaging that ships runtime schemas is T3" + }, + "tier-pluggy-module": { + "digest": "69f70c6deeff9bc48a6f429f0903cebf1dc979c3ac0086b1a874a6eb7ac0313b", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:pluggy.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a root pluggy.py is T3 (runner shadowing)" + }, + "tier-pytest-package": { + "digest": "da20d3cf30c3992ea2130d3acbaaf39b949d4afd64e3e591d7bd153c6bb426bd", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:_pytest/__init__.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a root _pytest/ package is T3 (runner shadowing)" + }, + "tier-requirements": { + "digest": "c2d3d858b937e2f0135242a6c8c9c6a7026934525fbc221625cede8789e924bc", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:requirements-dev.txt", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: requirements-dev.txt is T3 (not allowlisted)" + }, + "tier-root-pytest-module": { + "digest": "9cd13a6d42522604987c7bd6e8f153eb98a5d5deb601961c99c386c28bb91b4c", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:pytest.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a root pytest.py is T3 (runner shadowing)" + }, + "tier-sandbox": { + "digest": "271646bedd6b2d9475448783085fb7939d1a3cd6cf9f489bb6ec1e501c59c50b", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:bundlebees_plugin/sandbox.py", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: bundlebees_plugin/sandbox.py is T3 (not allowlisted)" + }, + "tier-scanner": { + "digest": "e4e5ce639c1bdb8ae10ecbda0c498c980fae1eb981d0abf0fab1ce8753177cdb", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a scanner finding in a NEW test file is T3" + }, + "tier-src": { + "digest": "59142ac28102de37f660f5b8f7aff922bc79b2ff831c12431e6a09fb6401c7cd", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T1", + "kind": "tier", + "what": "risk tier: a leased source change is T1" + }, + "tier-unknown-repo": { + "digest": "04737a87e54b60dd6b01ede9a599ab795b8e0175c37b1d4b42ab4c4ca6226233", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "repo_unknown:not-a-known-repository", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: a repository with no allowlist entry is T3 (repo_unknown)" + }, + "tier-uv-lock": { + "digest": "ec118cde5f8e12607b0e6e83e7c482be34aa9424ed28d217c47cd89f8e6598c7", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": "not_t1_allowlisted:uv.lock", + "expect_tier": "T3", + "kind": "tier", + "what": "risk tier: uv.lock is T3 (not allowlisted)" + }, + "v1-0": { + "digest": "77ed9c3e54097b52d8ffed88a80558aaf90a337cede9622d57d01b9debd6326d", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v1", + "what": "0 body Lease-Verify:
moves the verify boundary to the head" + }, + "v1-1": { + "digest": "49fda3a6ee2f12674c82a3f59784b80b2ea9f5689d6a97abc078e166bccffbe3", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v1", + "what": "1 label lease-verify: moves the verify boundary to the head" + }, + "v1-2": { + "digest": "c5140df6bf704e8b5e0209ee3182321065f641347845466f8f85bc4284ef8815", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v1", + "what": "2 the PR adds .rizzstack/lease.json on its own branch and is judged by it" + }, + "v1-3": { + "digest": "68c97a8ec68335ec0b56c8d3de7f788826de68dd6c0135f597a97ca480028d94", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v1", + "what": "3 a base lease without review or contract_sha256 grants '*'" + }, + "v1-4": { + "digest": "840cfdcd1a8903e955883e68fafcb6e3ef73ff989f3cd574eb26c90117dc037e", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v1", + "what": "4 a body Lease-Contract: line selects a broader base lease" + }, + "v1-control": { + "digest": "c40d5e3a66d19e50112b32d246faa0fecc6e27b14f8f0c76c0214192a61ef6c4", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v1", + "what": "a legitimate slice changes only its leased file (control)" + }, + "v2-0": { + "digest": "3f1076501e2d05887a9235e42543ec7ab408d4e5be41303e25c73c14eb7195a1", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "frozen test edited (must fail on scope, not non-slice)" + }, + "v2-1": { + "digest": "837173abf6b630aee0387b63bb36754d2c58bfe66f1021e607e98f0c8cbe378d", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "frozen test edited + body 'Lease-Verify: '" + }, + "v2-1b": { + "digest": "f6ae02d3501b7eeb4c306c5257e29d9bb52608037991f2117f3525aec9a95fad", + "expect_class": "slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "frozen test edited + label 'lease-verify:'" + }, + "v2-2": { + "digest": "44304f4d78388064e8318811012ee75ef4d348564e670baacfd4d0c5b4b4fbbd", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "PR adds its own .rizzstack/lease.json and edits the gate" + }, + "v2-3": { + "digest": "1a72f4ece3df8ba98a425dc9005035fc94a9bee61a39a439642018aee10192b1", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "slice PR sneaks a new lease file" + }, + "v2-4": { + "digest": "af91f8e965e10271707bc852b648e15f4c83cc438dca0bb30b7a91888ff8675e", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "body 'Lease-Contract:' picks the gate lease" + }, + "v2-4b": { + "digest": "d23882536d76a2d863f0ad01b9e5ab0a5c7d4eba5863e3e9a846e2abe03e987d", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "label 'lease-contract:' picks the gate lease" + }, + "v2-4c": { + "digest": "bd0bc41b3e6dfb0e7a56b310d4a7ca991a2cb505df446789b916545e912f6a24", + "expect_class": null, + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "branch leaf named 'gate' matches the gate lease id" + }, + "v2-5": { + "digest": "881751497ba27e1c197e085a8b0c797b0f3ae89def2d5c9248d0e19c0b5b0855", + "expect_class": null, + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v2", + "what": "approved contract with glob scope 'src/*'" + }, + "v2-6": { + "digest": "b1d6bdc5725563180dc6972cceb967f50ae3352ee67ae1cc77cfa2e3b53f2cee", + "expect_class": "non-slice", + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v2", + "what": "lease with no review block must not count as frozen" + }, + "v2-7": { + "digest": "3768afd27d89008723fdae52ad626449a4a68bee42cf09e26bf5906ca51113b8", + "expect_class": null, + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T3", + "kind": "v2", + "what": "lease wider than its approved contract" + }, + "v2-8": { + "digest": "a8e9dfb1bdf347cd40d32f7a480870f1186ef3f80d3e59d3ffe6f6b105c5fea8", + "expect_class": null, + "expect_exit": 1, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v2", + "what": "contract text changed after approval (hash mismatch)" + }, + "v2-P": { + "digest": "532396b7846c324843f03fea564880f831cf0cdd5ba13e8a8590d155281a6b9b", + "expect_class": "slice", + "expect_exit": 0, + "expect_reason": null, + "expect_tier": "T1", + "kind": "v2", + "what": "positive control: clean in-lease change" + } + }, + "version": 1 +} diff --git a/tests/fixtures/shared_policy.sha256 b/tests/fixtures/shared_policy.sha256 new file mode 100644 index 0000000..6dfef63 --- /dev/null +++ b/tests/fixtures/shared_policy.sha256 @@ -0,0 +1 @@ +18cdbbaa6d2ce9248d0dc856c3be6c08811c8a11a1df36662257fbbf3355e758 diff --git a/tests/fixtures/workflows/anchors.yml b/tests/fixtures/workflows/anchors.yml new file mode 100644 index 0000000..5638c79 --- /dev/null +++ b/tests/fixtures/workflows/anchors.yml @@ -0,0 +1,27 @@ +# YAML anchors and aliases hide structure from a line reader. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: &perms + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: *perms + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/expression_in_run.yml b/tests/fixtures/workflows/expression_in_run.yml new file mode 100644 index 0000000..bb9a2e4 --- /dev/null +++ b/tests/fixtures/workflows/expression_in_run.yml @@ -0,0 +1,26 @@ +# Untrusted pull request text interpolated into a shell. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: echo "${{ github.event.pull_request.title }}" && python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/git_restore.yml b/tests/fixtures/workflows/git_restore.yml new file mode 100644 index 0000000..f8619ec --- /dev/null +++ b/tests/fixtures/workflows/git_restore.yml @@ -0,0 +1,28 @@ +# The base checkout overwritten with pull request files. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: restore + run: git restore --source=FETCH_HEAD -- .github/scripts + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/github_env.yml b/tests/fixtures/workflows/github_env.yml new file mode 100644 index 0000000..ea812b6 --- /dev/null +++ b/tests/fixtures/workflows/github_env.yml @@ -0,0 +1,28 @@ +# A step that writes GITHUB_ENV before the gate runs. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: env + run: echo PYTHONPATH=. >> "$GITHUB_ENV" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/head_checkout.yml b/tests/fixtures/workflows/head_checkout.yml new file mode 100644 index 0000000..18bf86e --- /dev/null +++ b/tests/fixtures/workflows/head_checkout.yml @@ -0,0 +1,26 @@ +# A pinned checkout of the pull request head instead of the base. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/install_step.yml b/tests/fixtures/workflows/install_step.yml new file mode 100644 index 0000000..52a68ed --- /dev/null +++ b/tests/fixtures/workflows/install_step.yml @@ -0,0 +1,28 @@ +# A dependency install from the pull request before judging. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: deps + run: pip install -r requirements.txt + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/persisted_credentials.yml b/tests/fixtures/workflows/persisted_credentials.yml new file mode 100644 index 0000000..f2e312f --- /dev/null +++ b/tests/fixtures/workflows/persisted_credentials.yml @@ -0,0 +1,26 @@ +# A base checkout that keeps the token in .git/config. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: true + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/pull_request_trigger.yml b/tests/fixtures/workflows/pull_request_trigger.yml new file mode 100644 index 0000000..d847ac9 --- /dev/null +++ b/tests/fixtures/workflows/pull_request_trigger.yml @@ -0,0 +1,26 @@ +# A same-named gate on pull_request runs the head's workflow file. Must be refused. +name: gate-authority +on: + pull_request: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/pwn_request.yml b/tests/fixtures/workflows/pwn_request.yml new file mode 100644 index 0000000..dd7563d --- /dev/null +++ b/tests/fixtures/workflows/pwn_request.yml @@ -0,0 +1,26 @@ +# GROKCHAT's demonstrated pwn request (flow-style job permissions, base checkout, fetch of the +# pull request head, `git reset --hard FETCH_HEAD`, then the PR's own gate copy runs). It passed +# all five regex workflow tests of the first S1 cut. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + permissions: {contents: write, pull-requests: write, actions: write} + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + run: git fetch --no-tags origin refs/pull/${{ github.event.pull_request.number }}/head + - name: swap in the pull request tree + run: git reset --hard FETCH_HEAD + - name: judge + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/pwn_request_block_permissions.yml b/tests/fixtures/workflows/pwn_request_block_permissions.yml new file mode 100644 index 0000000..3abac1f --- /dev/null +++ b/tests/fixtures/workflows/pwn_request_block_permissions.yml @@ -0,0 +1,28 @@ +# The demonstrated pwn request with block-style job permissions: runs the PR's own gate copy +# with write scopes. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + actions: write + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + run: git fetch origin refs/pull/${{ github.event.pull_request.number }}/head + - name: swap in the pull request tree + run: git reset --hard FETCH_HEAD + - name: judge + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/secrets_env.yml b/tests/fixtures/workflows/secrets_env.yml new file mode 100644 index 0000000..c33e854 --- /dev/null +++ b/tests/fixtures/workflows/secrets_env.yml @@ -0,0 +1,26 @@ +# A secret exposed to the gate step. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ secrets.ADMIN_TOKEN }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/types_without_edited.yml b/tests/fixtures/workflows/types_without_edited.yml new file mode 100644 index 0000000..e7cf953 --- /dev/null +++ b/tests/fixtures/workflows/types_without_edited.yml @@ -0,0 +1,31 @@ +name: gate-authority + +# The base branch's gate judges the pull request. pull_request_target runs this +# file from the base commit; the head is fetched as git objects and never run. + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review] + +permissions: + contents: read + +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Check out the base commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: Fetch the pull request head as objects only + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: Judge with the base copy of the gate + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/unpinned_checkout.yml b/tests/fixtures/workflows/unpinned_checkout.yml new file mode 100644 index 0000000..b401cb7 --- /dev/null +++ b/tests/fixtures/workflows/unpinned_checkout.yml @@ -0,0 +1,26 @@ +# An unpinned checkout of the pull request head. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: head + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/working_directory.yml b/tests/fixtures/workflows/working_directory.yml new file mode 100644 index 0000000..3dc7edb --- /dev/null +++ b/tests/fixtures/workflows/working_directory.yml @@ -0,0 +1,27 @@ +# The gate run from a directory holding the pull request tree. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: read +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + working-directory: pr + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/fixtures/workflows/write_permissions.yml b/tests/fixtures/workflows/write_permissions.yml new file mode 100644 index 0000000..33a6dbf --- /dev/null +++ b/tests/fixtures/workflows/write_permissions.yml @@ -0,0 +1,27 @@ +# Top-level write scopes. Must be refused. +name: gate-authority +on: + pull_request_target: + types: [opened, synchronize, reopened] +permissions: + contents: write + statuses: write +jobs: + gate-authority: + name: gate-authority + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: fetch + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: git fetch --no-tags origin "refs/pull/${PR_NUMBER}/head" + - name: judge + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/lease_tamper.py diff --git a/tests/test_gate_authority.py b/tests/test_gate_authority.py new file mode 100644 index 0000000..94b8a41 --- /dev/null +++ b/tests/test_gate_authority.py @@ -0,0 +1,1253 @@ +"""Gate authority (S1): who may approve, which gate runs, what is T1, and stale bases. + +An independent approval counts only when GitHub says the review was submitted by the +authenticated reviewer app login ``rizzstack-reviewer[bot]``. The review text never +names an identity: the coordinator app, the owner's token and any other account can +post the canonical line, and none of them is an approval. A rejection still governs +whatever account posted it. + +The gate GitHub runs must be the base branch's copy: a ``pull_request_target`` +workflow checks out the base commit, fetches the pull request head as git objects +only, and runs nothing from the pull request. The workflow is parsed by a strict +YAML-subset reader and compared with the one allowed structure; must-fail fixtures +(including the demonstrated pwn request) are refused. A review re-runs that base +gate, and the lane counts a ``gate-authority`` check only from that workflow's +``pull_request_target`` run, never from a same-named job or a commit status. + +An owner attestation (``APPROVE (owner)``) counts only from the owner login. + +The T1 allowlist keeps auth, CI, subprocess, network, dependency, test-infra and gate +surfaces out of T1; a file kind the gate does not know is T3. + +The merge lane refuses a pull request whose branch is behind its base. + +Run: python3 -m pytest -q -p no:cacheprovider tests/test_gate_authority.py +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import re +import shutil +import subprocess +import tempfile +import unittest +import urllib.parse +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +GATE_SCRIPT = ROOT / ".github" / "scripts" / "lease_tamper.py" +LANE_SCRIPT = ROOT / "scripts" / "merge_lane_v5.py" +WORKFLOW = ROOT / ".github" / "workflows" / "gate-authority.yml" +RERUN_WORKFLOW = ROOT / ".github" / "workflows" / "review-rerun.yml" +WORKFLOW_FIXTURES = ROOT / "tests" / "fixtures" / "workflows" +DRILL_SCRIPT = ROOT / ".github" / "scripts" / "gate_drill.py" +NEW_T3_REASONS = ("capability_subprocess", "capability_network", "dependency_manifest", "test_infra", + "ci_config", "auth_surface", "unknown_kind") + +HEAD = "1a1d032f98691fb4121d5b9673b36562c77a5627" +BASE = "316087f7da8ea01a206b4c6417c2a1599e84b35c" +LINE = "APPROVE (independent review) at " + HEAD +REVIEWER = "rizzstack-reviewer[bot]" +COORDINATOR = "rizzstack-coordinator[bot]" +OWNER = "mojomast" + + +def _load(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +GATE = _load(GATE_SCRIPT, "lease_tamper_authority_under_test") +LANE = _load(LANE_SCRIPT, "merge_lane_authority_under_test") + + +def _review(login, body=LINE, state="COMMENTED", commit=HEAD): + review = {"state": state, "body": body, "commit_id": commit, + "submitted_at": "2026-11-27T22:00:00Z"} + if login is not None: + review["user"] = {"login": login} + return review + + +def _accepted(reviews): + review, _match, _refusal = GATE.independent_review(None, reviews, BASE, HEAD) + return review + + +# --------------------------------------------------------------- review identity +class ReviewIdentityTest(unittest.TestCase): + def test_reviewer_app_login_is_the_only_independent_approval(self): + self.assertIsNotNone(_accepted([_review(REVIEWER)])) + self.assertIsNotNone(_accepted([_review(REVIEWER, body="", state="APPROVED")])) + + def test_coordinator_app_cannot_approve(self): + self.assertIsNone(_accepted([_review(COORDINATOR)])) + self.assertIsNone(_accepted([_review(COORDINATOR, body="", state="APPROVED")])) + + def test_owner_token_cannot_approve(self): + self.assertIsNone(_accepted([_review(OWNER)])) + self.assertIsNone(_accepted([_review(OWNER, body="", state="APPROVED")])) + + def test_text_naming_the_reviewer_is_not_identity(self): + body = "APPROVE (independent review — rizzstack-reviewer[bot], model family kimi) at " + HEAD + self.assertIsNone(_accepted([_review("someone-else", body=body)])) + self.assertIsNone(_accepted([_review(None, body=body)])) + self.assertIsNone(_accepted([_review("rizzstack-reviewer", body=body)])) # not the [bot] login + + def test_rejection_from_any_login_still_governs(self): + rejection = _review(OWNER, body="CHANGES REQUESTED (finding) at " + HEAD) + rejection["submitted_at"] = "2026-11-27T22:05:00Z" + self.assertIsNone(_accepted([_review(REVIEWER), rejection])) + + def test_identity_rule_lives_in_the_shared_policy_block(self): + for module in (GATE, LANE): + self.assertEqual(module.REVIEWER_LOGIN, REVIEWER) + self.assertTrue(module.review_identity_ok({"user": {"login": REVIEWER}})) + self.assertTrue(module.review_identity_ok({"author": REVIEWER})) + for login in (COORDINATOR, OWNER, "", None): + self.assertFalse(module.review_identity_ok({"user": {"login": login}}), login) + self.assertFalse(module.review_identity_ok({})) + + def test_lane_accepts_only_the_reviewer_app(self): + def facts(author): + return { + "pr": {"state": "OPEN", "is_draft": False, "mergeable": True, + "merge_state_status": "CLEAN", "head": HEAD, "files": ["docs/readme.md"]}, + "class": LANE.NON_SLICE, + "reviews": [{"state": "COMMENTED", "commit_id": HEAD, "author": author, "body": LINE}], + "checks": [{"name": "ci-gate", "status": "completed", "conclusion": "success", "head": HEAD}], + "required_checks": ["ci-gate"], + "verify": {"records": [], "compare": {}, "provenance": {}}, + "lease_tamper": {"ran": True, "ok": True, "reason": "gate_ok", + "output_tail": "lease-tamper: class=non-slice TIER=T3"}, + "owner_held": False, + } + self.assertTrue(LANE.decide(facts(REVIEWER))["merge"]) + for author in (COORDINATOR, OWNER, "reviewer"): + verdict = LANE.decide(facts(author)) + self.assertFalse(verdict["merge"], author) + + +# --------------------------------------------------------------- stale base +class StaleBaseTest(unittest.TestCase): + def test_lane_refuses_a_branch_behind_its_base(self): + facts = { + "pr": {"state": "OPEN", "is_draft": False, "mergeable": True, + "merge_state_status": "BEHIND", "head": HEAD, "files": ["docs/readme.md"]}, + "class": LANE.NON_SLICE, + "reviews": [{"state": "COMMENTED", "commit_id": HEAD, "author": REVIEWER, "body": LINE}], + "checks": [{"name": "ci-gate", "status": "completed", "conclusion": "success", "head": HEAD}], + "required_checks": ["ci-gate"], + "verify": {"records": [], "compare": {}, "provenance": {}}, + "lease_tamper": {"ran": True, "ok": True, "reason": "gate_ok", + "output_tail": "lease-tamper: class=non-slice TIER=T3"}, + "owner_held": False, + } + verdict = LANE.decide(facts) + self.assertFalse(verdict["merge"]) + self.assertEqual(verdict["reason"], "merge_state_behind") + self.assertNotIn("BEHIND", LANE.MERGE_STATES) + + +# --------------------------------------------------------------- strict YAML subset +class StrictYamlError(ValueError): + pass + + +_YAML_FORBIDDEN_START = ("&", "*", "!", "{", "?", "%", "@", "`", "|+", ">", "<<") + + +def _yaml_scalar(text, where): + text = text.strip() + if not text: + return None + if text.startswith(_YAML_FORBIDDEN_START) or text in ("---", "..."): + raise StrictYamlError("%s: unsupported YAML construct %r" % (where, text)) + if text.startswith("["): + if not text.endswith("]"): + raise StrictYamlError("%s: unterminated flow sequence" % where) + inner = text[1:-1].strip() + if not inner: + return [] + if any(c in inner for c in "[]{}&*!"): + raise StrictYamlError("%s: nested flow collection" % where) + return [_yaml_scalar(part, where) for part in inner.split(",")] + if text[0] in "\"'": + quote = text[0] + if len(text) < 2 or text[-1] != quote: + raise StrictYamlError("%s: unterminated quoted scalar" % where) + body = text[1:-1] + if quote == "'": + if "'" in body.replace("''", ""): + raise StrictYamlError("%s: bad single-quoted scalar" % where) + return body.replace("''", "'") + if "\\" in body or '"' in body: + raise StrictYamlError("%s: escapes are not supported" % where) + return body + if text in ("true", "false"): + return text == "true" + if text in ("null", "~", "yes", "no", "on", "off", "True", "False", "Yes", "No", "On", "Off"): + raise StrictYamlError("%s: ambiguous YAML scalar %r" % (where, text)) + if text.isdigit(): + return int(text) + if ": " in text or text.endswith(":") or " #" in text: + raise StrictYamlError("%s: ambiguous plain scalar %r" % (where, text)) + return text + + +def _yaml_strip_comment(line): + if line.lstrip().startswith("#"): + return "" + quote = None + for i, ch in enumerate(line): + if quote: + if ch == quote: + quote = None + elif ch in "\"'": + quote = ch + elif ch == "#" and (i == 0 or line[i - 1] == " "): + return line[:i].rstrip() + return line.rstrip() + + +def strict_yaml(text): + """Parse the block-style YAML subset GitHub workflows here are written in. + + Anything outside the subset (flow mappings, anchors, aliases, tags, merge keys, + folded or keep-chomp scalars, tabs, duplicate keys, multiple documents, YAML 1.1 + booleans) is refused, so a workflow cannot hide structure from this parser. + """ + if "\t" in text: + raise StrictYamlError("tabs are not allowed") + raw = text.splitlines() + + def next_content(index): + while index < len(raw): + stripped = _yaml_strip_comment(raw[index]) + if stripped.strip(): + return index, len(stripped) - len(stripped.lstrip(" ")), stripped.strip() + index += 1 + return index, -1, None + + def block_scalar(index, parent_indent, chomp): + out = [] + body_indent = None + while index < len(raw): + line = raw[index] + if line.strip(): + ind = len(line) - len(line.lstrip(" ")) + if ind <= parent_indent: + break + if body_indent is None: + body_indent = ind + if ind < body_indent: + raise StrictYamlError("line %d: block scalar dedent" % (index + 1)) + out.append(line[body_indent:]) + else: + out.append("") + index += 1 + while out and out[-1] == "": + out.pop() + value = "\n".join(out) + if chomp == "|": + value += "\n" + return value, index + + def parse_value_after_colon(rest, index, indent, where): + rest = rest.strip() + if rest in ("|", "|-"): + return block_scalar(index + 1, indent, rest) + if rest == "": + nxt, ind, content = next_content(index + 1) + if content is None or ind <= indent and not (ind == indent and content.startswith("- ")): + raise StrictYamlError("%s: empty value" % where) + return parse_block(nxt, ind) + return _yaml_scalar(rest, where), index + 1 + + def split_key(content, where): + if content.startswith(("\"", "'")): + raise StrictYamlError("%s: quoted keys are not supported" % where) + if ":" not in content: + raise StrictYamlError("%s: expected 'key: value'" % where) + key, rest = content.split(":", 1) + if rest and not rest.startswith(" "): + raise StrictYamlError("%s: expected 'key: value'" % where) + key = key.strip() + if not key or key.startswith(_YAML_FORBIDDEN_START) or " " in key: + raise StrictYamlError("%s: bad key %r" % (where, key)) + return key, rest + + def parse_mapping(index, indent, first=None): + out = {} + while True: + index, ind, content = next_content(index) + if content is None or ind < indent: + return out, index + if ind > indent: + raise StrictYamlError("line %d: unexpected indent" % (index + 1)) + if content.startswith("- "): + return out, index + where = "line %d" % (index + 1) + key, rest = split_key(content, where) + if key in out: + raise StrictYamlError("%s: duplicate key %r" % (where, key)) + out[key], index = parse_value_after_colon(rest, index, indent, where) + + def parse_sequence(index, indent): + out = [] + while True: + index, ind, content = next_content(index) + if content is None or ind < indent: + return out, index + if ind > indent or not (content.startswith("- ") or content == "-"): + if ind == indent: + return out, index + raise StrictYamlError("line %d: unexpected indent in sequence" % (index + 1)) + where = "line %d" % (index + 1) + item = content[2:] if content.startswith("- ") else "" + item_indent = ind + 2 + if not item.strip(): + raise StrictYamlError("%s: empty sequence item" % where) + head = _yaml_strip_comment(item) + if ":" in head and not head.strip().startswith(("\"", "'", "[")) and ( + head.rstrip().endswith(":") or ": " in head): + # A mapping item: re-read this line as the first key at item_indent. + raw[index] = " " * item_indent + item + value, index = parse_mapping(index, item_indent) + out.append(value) + else: + out.append(_yaml_scalar(head, where)) + index += 1 + + def parse_block(index, indent): + index, ind, content = next_content(index) + if content is None: + raise StrictYamlError("empty block") + if content.startswith("- ") or content == "-": + return parse_sequence(index, ind) + return parse_mapping(index, ind) + + start, ind, content = next_content(0) + if content is None: + raise StrictYamlError("empty document") + if ind != 0: + raise StrictYamlError("document must start at column 0") + doc, end = parse_mapping(start, 0) + end, _, rest = next_content(end) + if rest is not None: + raise StrictYamlError("line %d: trailing content" % (end + 1)) + return doc + + +def yaml_cross_check(text, doc): + """When PyYAML is installed, it must read the same document (YAML 1.1 'on' -> True).""" + try: + import yaml # noqa: PLC0415 + except ImportError: + return None + + def norm(value): + if isinstance(value, dict): + return {("on" if k is True else k): norm(v) for k, v in value.items()} + if isinstance(value, list): + return [norm(v) for v in value] + return value + + return norm(yaml.safe_load(text)) == doc + + +# --------------------------------------------------------------- base-pinned gate workflow +GATE_EVENT_TYPES = {"opened", "synchronize", "reopened", "edited", "ready_for_review"} +#: A retarget (edited) and a push (synchronize) must each re-run the gate from the new base. +GATE_REQUIRED_TYPES = {"opened", "synchronize", "reopened", "edited"} +CHECKOUT_RE = re.compile(r"actions/checkout@[0-9a-f]{40}") +BASE_REF = "${{ github.event.pull_request.base.sha }}" +PR_NUMBER = "${{ github.event.pull_request.number }}" +TOKEN = "${{ github.token }}" +FETCH_RUN = re.compile(r'git fetch --no-tags( --depth=[1-9][0-9]{0,3})? origin "refs/pull/\$\{PR_NUMBER\}/head"\n?') +JUDGE_RUN = re.compile(r"python3 \.github/scripts/lease_tamper\.py\n?") +FORBIDDEN_KEYS = {"working-directory", "shell", "defaults", "container", "services", + "continue-on-error", "strategy", "outputs", "if", "needs", "secrets"} +FORBIDDEN_TEXT = ("GITHUB_ENV", "GITHUB_PATH", "GITHUB_OUTPUT", "secrets.", "ACTIONS_") + + +def _walk(value, path=""): + if isinstance(value, dict): + for key, item in value.items(): + yield path + "/" + str(key), key, item + yield from _walk(item, path + "/" + str(key)) + elif isinstance(value, list): + for index, item in enumerate(value): + yield from _walk(item, "%s[%d]" % (path, index)) + + +def gate_workflow_violations(text): + """Every way ``text`` differs from the one allowed base-pinned gate workflow ([] = allowed).""" + try: + doc = strict_yaml(text) + except StrictYamlError as exc: + return ["unparseable: %s" % exc] + if yaml_cross_check(text, doc) is False: + return ["yaml_divergence"] + bad = [] + for where, key, item in _walk(doc): + if key in FORBIDDEN_KEYS: + bad.append("forbidden_key %s" % where) + if isinstance(item, str) and any(word in item for word in FORBIDDEN_TEXT): + bad.append("forbidden_text %s" % where) + if key == "run" and isinstance(item, str) and "${{" in item: + bad.append("expression_in_run %s" % where) + if key == "permissions" and where != "/permissions": + bad.append("job_permissions %s" % where) + if set(doc) != {"name", "on", "permissions", "jobs"}: + bad.append("top_level_keys %s" % sorted(doc)) + if doc.get("name") != "gate-authority": + bad.append("workflow_name") + on = doc.get("on") + if not (isinstance(on, dict) and set(on) == {"pull_request_target"} + and isinstance(on["pull_request_target"], dict) + and set(on["pull_request_target"]) == {"types"} + and isinstance(on["pull_request_target"]["types"], list) + and on["pull_request_target"]["types"] + and set(on["pull_request_target"]["types"]) <= GATE_EVENT_TYPES): + bad.append("trigger_not_pull_request_target_only") + elif not GATE_REQUIRED_TYPES <= set(on["pull_request_target"]["types"]): + bad.append("trigger_types_incomplete") + if doc.get("permissions") != {"contents": "read"}: + bad.append("permissions_not_contents_read") + jobs = doc.get("jobs") + if not (isinstance(jobs, dict) and set(jobs) == {"gate-authority"}): + return bad + ["jobs_not_exactly_gate_authority"] + job = jobs["gate-authority"] + if not isinstance(job, dict): + return bad + ["job_not_a_mapping"] + if set(job) != {"name", "runs-on", "timeout-minutes", "steps"}: + bad.append("job_keys %s" % sorted(job)) + if job.get("name") != "gate-authority": + bad.append("job_name") + if not (isinstance(job.get("runs-on"), str) and re.fullmatch(r"ubuntu-[0-9.]+", job["runs-on"])): + bad.append("runs_on") + if not (type(job.get("timeout-minutes")) is int and 1 <= job["timeout-minutes"] <= 30): + bad.append("timeout") + steps = job.get("steps") + if not (isinstance(steps, list) and len(steps) == 3 and all(isinstance(s, dict) for s in steps)): + return bad + ["steps_not_exactly_checkout_fetch_judge"] + checkout, fetch, judge = steps + if (set(checkout) != {"name", "uses", "with"} + or not (isinstance(checkout["uses"], str) and CHECKOUT_RE.fullmatch(checkout["uses"])) + or checkout["with"] != {"ref": BASE_REF, "persist-credentials": False}): + bad.append("checkout_not_pinned_base_without_credentials") + if (set(fetch) != {"name", "env", "run"} or fetch["env"] != {"PR_NUMBER": PR_NUMBER} + or not (isinstance(fetch["run"], str) and FETCH_RUN.fullmatch(fetch["run"]))): + bad.append("fetch_step_not_allowlisted") + if (set(judge) != {"name", "env", "run"} or judge["env"] not in ({"GH_TOKEN": TOKEN}, {"GITHUB_TOKEN": TOKEN}) + or not (isinstance(judge["run"], str) and JUDGE_RUN.fullmatch(judge["run"]))): + bad.append("judge_step_not_allowlisted") + return bad + + +class BasePinnedGateWorkflowTest(unittest.TestCase): + def text(self): + self.assertTrue(WORKFLOW.is_file(), "missing .github/workflows/gate-authority.yml") + return WORKFLOW.read_text(encoding="utf-8") + + def test_workflow_is_exactly_the_base_pinned_gate(self): + self.assertEqual(gate_workflow_violations(self.text()), []) + + def test_workflow_parses_strictly_and_agrees_with_pyyaml(self): + text = self.text() + doc = strict_yaml(text) + self.assertIn(yaml_cross_check(text, doc), (True, None)) + + def test_must_fail_workflows_are_refused(self): + fixtures = sorted(WORKFLOW_FIXTURES.glob("*.yml")) + self.assertGreaterEqual(len(fixtures), 14) + for fixture in fixtures: + self.assertNotEqual(gate_workflow_violations(fixture.read_text(encoding="utf-8")), [], + fixture.name) + + def test_grokchat_pwn_request_is_refused(self): + bad = gate_workflow_violations((WORKFLOW_FIXTURES / "pwn_request.yml").read_text(encoding="utf-8")) + self.assertTrue(bad and bad[0].startswith("unparseable"), bad) # flow-style permissions + bad = gate_workflow_violations( + (WORKFLOW_FIXTURES / "pwn_request_block_permissions.yml").read_text(encoding="utf-8")) + self.assertTrue(any(item.startswith("job_permissions") for item in bad), bad) + self.assertTrue(any(item.startswith("expression_in_run") for item in bad), bad) + self.assertIn("steps_not_exactly_checkout_fetch_judge", bad) + + def test_gate_trigger_types_include_edited(self): + # without `edited`, retargeting the PR's base fires no new run (the retarget attack) + text = (WORKFLOW_FIXTURES / "types_without_edited.yml").read_text(encoding="utf-8") + self.assertEqual(gate_workflow_violations(text), ["trigger_types_incomplete"]) + self.assertTrue(WORKFLOW.is_file(), "missing .github/workflows/gate-authority.yml") + doc = strict_yaml(WORKFLOW.read_text(encoding="utf-8")) + self.assertLessEqual(GATE_REQUIRED_TYPES, set(doc["on"]["pull_request_target"]["types"])) + self.assertIn("edited", doc["on"]["pull_request_target"]["types"]) + + def test_strict_parser_refuses_constructs_that_hide_structure(self): + for text in ("a: {b: c}\n", "a: &x 1\nb: *x\n", "a: !tag 1\n", "a: 1\na: 2\n", + "a:\n\tb: 1\n", "on: yes\n", "a: >\n folded\n", "---\na: 1\n", + "a: \"esc\\u0041\"\n", "<<: {}\n"): + with self.assertRaises(StrictYamlError, msg=repr(text)): + strict_yaml(text) + + def test_gate_judges_pull_request_target_like_a_pull_request(self): + self.assertIn("pull_request_target", GATE.PULL_REQUEST_EVENTS) + + +# --------------------------------------------------------------- re-judge after a review +FAKE_GH = r'''#!/usr/bin/env python3 +"""A fake `gh api` serving canned workflow runs, filtered the way GitHub filters them.""" +import json, os, sys, urllib.parse +state = json.load(open(os.environ["FAKE_GH_STATE"])) +args = sys.argv[1:] +assert args and args[0] == "api", args +args = args[1:] +method, slurp, path = "GET", False, None +i = 0 +while i < len(args): + a = args[i] + if a in ("-X", "--method"): + method = args[i + 1]; i += 2; continue + if a == "--slurp": + slurp = True + elif a == "--paginate": + pass + elif a.startswith("-"): + raise SystemExit("fake gh: unsupported flag " + a) + else: + path = a + i += 1 +with open(os.environ["FAKE_GH_LOG"], "a") as log: + log.write(json.dumps([method, path]) + "\n") +url = urllib.parse.urlparse(path) +query = dict(urllib.parse.parse_qsl(url.query)) +parts = url.path.strip("/").split("/") +if method != "GET": + print("{}"); raise SystemExit(0) +def runs(items): + for key in ("event", "head_sha", "status", "branch"): + if key in query: + field = "head_branch" if key == "branch" else key + items = [r for r in items if r.get(field) == query[key] or (key == "status" and r.get("conclusion") == query[key])] + return {"total_count": len(items), "workflow_runs": items} +if parts[-2:] == ["actions", "runs"] or parts[-1] == "runs" and "workflows" in parts: + items = state["runs"] + if "workflows" in parts: + wf = parts[parts.index("workflows") + 1] + items = [r for r in items if r["path"].endswith("/" + wf) or str(r["workflow_id"]) == wf] + body = runs(items) +elif parts[-1] == "jobs": + body = {"total_count": 0, "jobs": state["jobs"].get(parts[-2], [])} +else: + raise SystemExit("fake gh: unexpected path " + path) +print(json.dumps([body] if slurp else body)) +''' + +HEAD_BRANCH = "feat/x" +GATE_RUN = {"id": 9001, "workflow_id": 77, "name": "gate-authority", "event": "pull_request_target", + "path": ".github/workflows/gate-authority.yml", "head_sha": BASE, "head_branch": HEAD_BRANCH, + "status": "completed", "conclusion": "success", + "pull_requests": [{"number": 12, "head": {"sha": HEAD}}]} +SPOOF_RUN = {"id": 9002, "workflow_id": 78, "name": "gate-authority", "event": "pull_request", + "path": ".github/workflows/spoof.yml", "head_sha": HEAD, "head_branch": HEAD_BRANCH, + "status": "completed", "conclusion": "success", + "pull_requests": [{"number": 12, "head": {"sha": HEAD}}]} +OTHER_PR_GATE_RUN = dict(GATE_RUN, id=9003, head_branch="feat/other", + pull_requests=[{"number": 13, "head": {"sha": "b" * 40}}]) +LEASE_RUN = {"id": 9004, "workflow_id": 79, "name": "lease-tamper", "event": "pull_request", + "path": ".github/workflows/lease-tamper.yml", "head_sha": HEAD, "head_branch": HEAD_BRANCH, + "status": "completed", "conclusion": "failure", + "pull_requests": [{"number": 12, "head": {"sha": HEAD}}]} + + +class ReviewRerunTest(unittest.TestCase): + def doc(self): + self.assertTrue(RERUN_WORKFLOW.is_file()) + text = RERUN_WORKFLOW.read_text(encoding="utf-8") + doc = strict_yaml(text) + self.assertIn(yaml_cross_check(text, doc), (True, None)) + return doc + + def step(self): + doc = self.doc() + (job,) = doc["jobs"].values() + runs = [step for step in job["steps"] if "run" in step] + self.assertEqual(len(runs), 1, "one rerun step") + return runs[0] + + def test_rerun_workflow_shape_is_minimal(self): + doc = self.doc() + types = set(doc["on"]["pull_request_review"]["types"]) + self.assertEqual(set(doc["on"]), {"pull_request_review"}) + self.assertLessEqual({"submitted", "dismissed"}, types) + self.assertEqual(doc["permissions"], {"contents": "read", "actions": "write"}) + (job,) = doc["jobs"].values() + self.assertNotIn("permissions", job) + for where, key, item in _walk(doc): + self.assertNotIn(key, FORBIDDEN_KEYS - {"if"}, where) + if key == "run": + self.assertNotIn("${{", item, where) + if isinstance(item, str): + for word in ("GITHUB_ENV", "GITHUB_PATH", "secrets."): + self.assertNotIn(word, item, where) + env = set(self.step()["env"]) + self.assertLessEqual({"GH_TOKEN", "REPO", "PR_NUMBER"}, env) + self.assertLessEqual(env, {"GH_TOKEN", "REPO", "PR_NUMBER", "HEAD_SHA", "HEAD_REF"}) + + def run_step(self, runs, jobs=None): + step = self.step() + tmp = Path(tempfile.mkdtemp(prefix="review-rerun-")) + self.addCleanup(shutil.rmtree, tmp, True) + (tmp / "gh").write_text(FAKE_GH, encoding="utf-8") + os.chmod(tmp / "gh", 0o755) + (tmp / "state.json").write_text(json.dumps({"runs": runs, "jobs": jobs or {}}), encoding="utf-8") + values = {"${{ github.token }}": "fake-token", "${{ github.repository }}": "mojomast/rizzstack", + "${{ github.event.pull_request.head.sha }}": HEAD, + "${{ github.event.pull_request.number }}": "12", + "${{ github.event.pull_request.head.ref }}": HEAD_BRANCH} + env = {"PATH": "%s:%s" % (tmp, os.environ.get("PATH", "")), "FAKE_GH_STATE": str(tmp / "state.json"), + "FAKE_GH_LOG": str(tmp / "log.jsonl"), "HOME": str(tmp)} + for key, value in step["env"].items(): + self.assertIn(value, values, "unexpected env expression %s=%s" % (key, value)) + env[key] = values[value] + proc = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", step["run"]], env=env, + capture_output=True, text=True, timeout=60) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + log = tmp / "log.jsonl" + calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + return [path for method, path in calls if method == "POST"] + + def test_a_review_reruns_the_base_pinned_gate_for_this_pull_request(self): + posts = self.run_step([GATE_RUN, SPOOF_RUN, OTHER_PR_GATE_RUN]) + self.assertIn("repos/mojomast/rizzstack/actions/runs/9001/rerun", [p.lstrip("/") for p in posts]) + + def test_a_green_gate_is_rerun_too_so_a_later_rejection_turns_it_red(self): + posts = [p.lstrip("/") for p in self.run_step([dict(GATE_RUN, conclusion="success")])] + self.assertEqual(posts, ["repos/mojomast/rizzstack/actions/runs/9001/rerun"]) + + def test_same_named_runs_from_other_workflows_or_pull_requests_are_not_rerun(self): + posts = " ".join(self.run_step([GATE_RUN, SPOOF_RUN, OTHER_PR_GATE_RUN])) + self.assertNotIn("9002", posts) + self.assertNotIn("9003", posts) + + def test_failed_lease_tamper_jobs_are_still_rerun(self): + posts = [p.lstrip("/") for p in self.run_step( + [LEASE_RUN], jobs={"9004": [{"id": 55, "name": "lease-tamper", "conclusion": "failure"}]})] + self.assertIn("repos/mojomast/rizzstack/actions/jobs/55/rerun", posts) + + +# --------------------------------------------------------------- the lane's gate-authority run +# A pull_request_target run reports its check on the BASE tip (GITHUB_SHA is the base branch's +# last commit), so the real gate never appears among the PR head's check runs. The lane finds +# the gate through its workflow run instead. GitHub's own required check is not the authority +# (it is pinned only to the Actions app, so a same-named job satisfies it). On these personal- +# account repos no required-workflow rule exists, so native and API merges stay unguarded by the +# gate and the lane is the only merge authority. +REPO = "mojomast/rizzstack" +GATE_WORKFLOW_PATH = ".github/workflows/gate-authority.yml" +REVIEW_AT = "2026-11-27T22:00:00Z" +BASE_TIP = "4" * 40 # main has moved on since the gate run started +FOREIGN = "6" * 40 # a commit that is not on main (another base branch) +RELEASE_TIP = "7" * 40 # tip of a non-main base branch +MISSING = object() # compare payload without a files list +GATE_CODE_FILES = (".github/workflows/gate-authority.yml", ".github/workflows/review-rerun.yml", + ".github/scripts/lease_tamper.py", ".github/scripts/gate_drill.py", + ".github/scripts/gate_drill.lock.json", ".github/scripts/helpers/new_module.py") + + +def _gate_run(**overrides): + run = {"id": 9001, "run_number": 41, "run_attempt": 1, "workflow_id": 77, "name": "gate-authority", + "path": GATE_WORKFLOW_PATH, "event": "pull_request_target", "head_sha": BASE, + "head_branch": HEAD_BRANCH, "status": "completed", "conclusion": "success", + "created_at": "2026-11-27T22:05:00Z", "run_started_at": "2026-11-27T22:05:00Z", + "check_suite_id": 502, + "pull_requests": [{"number": 12, "head": {"sha": HEAD}, "base": {"ref": "main", "sha": BASE}}], + "repository": {"full_name": REPO}, "head_repository": {"full_name": REPO}, + "actor": {"login": "someone"}, "triggering_actor": {"login": "someone"}} + run.update(overrides) + return run + + +def _lane_facts(checks, required=("ci-gate",), files=("docs/readme.md",), reviews=None): + return { + "pr": {"number": 12, "state": "OPEN", "is_draft": False, "mergeable": True, + "merge_state_status": "CLEAN", "head": HEAD, "files": list(files)}, + "class": LANE.NON_SLICE, + "reviews": reviews if reviews is not None else [ + {"state": "COMMENTED", "commit_id": HEAD, "author": REVIEWER, "body": LINE}], + "checks": [{"name": "ci-gate", "status": "completed", "conclusion": "success", "head": HEAD, + "completed_at": "2026-11-27T22:09:00Z"}] + list(checks), + "required_checks": list(required), + "verify": {"records": [], "compare": {}, "provenance": {}}, + "lease_tamper": {"ran": True, "ok": True, "reason": "gate_ok", + "output_tail": "lease-tamper: class=non-slice TIER=T3"}, + "owner_held": False, + } + + +class _FakeLaneApi: + """GitHub-shaped REST for one open PR (#12 at HEAD on BASE).""" + + def __init__(self, case): + self.check_runs = [ + {"name": "ci-gate", "status": "completed", "conclusion": "success", "head_sha": HEAD, + "completed_at": "2026-11-27T22:09:00Z", "app": {"slug": "github-actions"}, + "check_suite": {"id": 501}}] + self.workflow_runs = [] + self.suite_apps = {} + self.reviews = [{"state": "COMMENTED", "commit_id": HEAD, "body": LINE, "user": {"login": REVIEWER}, + "submitted_at": REVIEW_AT}] + tmp = Path(tempfile.mkdtemp(prefix="lane-api-")) + case.addCleanup(shutil.rmtree, tmp, True) + self.tmp = tmp + self.plan = tmp / "plan.json" + self.plan.write_text(json.dumps({"owner_held": {"prs": []}}), encoding="utf-8") + self.paths = [] + self.base_ref = "main" + self.base_tip = BASE_TIP + # compare/board
\n", + "hyvv/cli.py": "VALUE = 1\n", +} + + +class T1AllowlistTest(unittest.TestCase): + def tier(self, changes, repo_name="orbitdesktop", symlinks=(), modes=None, modes_only=None, + gitlinks=()): + root = tempfile.mkdtemp(prefix="gate-authority-") + self.addCleanup(shutil.rmtree, root, True) + repo = GitRepo(root) + for path, text in BASE_FILES.items(): + repo.write(path, text) + base = repo.commit("base") + repo.git("checkout", "-q", "-b", "feat/x") + for path, text in changes.items(): + repo.write(path, text, (modes or {}).get(path)) + for link, target in symlinks: + (repo.path / link).parent.mkdir(parents=True, exist_ok=True) + os.symlink(target, repo.path / link) + for path, mode in (modes_only or {}).items(): + os.chmod(repo.path / path, mode) + for path in gitlinks: + repo.git("update-index", "--add", "--cacheinfo", "160000,%s,%s" % (base, path)) + if gitlinks: + repo.git("commit", "-q", "-m", "change") + head = repo.git("rev-parse", "HEAD") + else: + head = repo.commit("change") + tier, reasons = GATE.risk_tier(str(repo.path), base, head, repo_name=repo_name, environ={}) + return tier, [reason for reason, _ in reasons] + + def assert_t3(self, reason, changes, **kwargs): + tier, reasons = self.tier(changes, **kwargs) + self.assertEqual(tier, "T3", (changes, reasons)) + self.assertIn(reason, reasons) + + def test_plain_source_docs_and_new_test_module_stay_t1(self): + tier, reasons = self.tier({"src/slice.py": "VALUE = 2\n", "docs/readme.md": "# new\n", + "tests/test_more.py": "def test_more():\n assert 1\n"}) + self.assertEqual((tier, reasons), ("T1", [])) + + def test_subprocess_capability_is_t3(self): + self.assert_t3("capability_subprocess", {"src/slice.py": "import subprocess\nVALUE = 2\n"}) + self.assert_t3("capability_subprocess", {"src/slice.py": "import os\nos.system('true')\n"}) + self.assert_t3("capability_subprocess", + {"packages/widget/index.js": "const cp = require('child_process');\n"}) + + def test_network_capability_is_t3(self): + self.assert_t3("capability_network", {"src/slice.py": "import urllib.request\nVALUE = 2\n"}) + self.assert_t3("capability_network", {"src/slice.py": "import socket\nVALUE = 2\n"}) + self.assert_t3("capability_network", + {"packages/widget/index.js": "export const x = fetch('https://example.invalid');\n"}) + + def test_dependency_manifests_are_t3(self): + self.assert_t3("dependency_manifest", {"packages/widget/package.json": '{"name": "w"}\n'}) + self.assert_t3("dependency_manifest", {"src/requirements.txt": "requests==2\n"}) + self.assert_t3("dependency_manifest", {"packages/widget/package-lock.json": "{}\n"}) + + def test_test_infrastructure_is_t3(self): + self.assert_t3("test_infra", {"tests/fixtures/case.json": "{}\n"}) + self.assert_t3("test_infra", {"tests/helpers.py": "VALUE = 1\n"}) + self.assert_t3("test_infra", {"tests/__init__.py": ""}) + + def test_nested_ci_configuration_is_t3(self): + self.assert_t3("ci_config", {"packages/widget/.github/workflows/ci.yml": "on: push\n"}) + + def test_auth_validator_and_approval_surfaces_are_t3(self): + self.assert_t3("auth_surface", {"hyvv/rizzstack_validators.py": "VALUE = 1\n"}, repo_name="hyvv") + self.assert_t3("auth_surface", {"apps/rizzstack-approvals/index.html": "x
\n"}) + self.assert_t3("auth_surface", {"src/sandbox_policy.py": "VALUE = 1\n"}) + + def test_unknown_file_kind_is_t3(self): + self.assert_t3("unknown_kind", {"src/run.sh": "echo hi\n"}) + self.assert_t3("unknown_kind", {"docs/setup.ps1": "Write-Host hi\n"}) + self.assert_t3("unknown_kind", {"src/slice.py": "VALUE = 2\n"}, modes={"src/slice.py": 0o755}) + self.assert_t3("unknown_kind", {}, symlinks=[("src/link.py", "../hyvv/cli.py")]) + + def test_dynamic_subprocess_and_code_execution_are_t3(self): + for text in ("from subprocess import run\n", "m = __import__('subprocess')\n", + "import importlib\nm = importlib.import_module('os')\n", "import os\nos.execv('/bin/true', [])\n", + "import os\nos.posix_spawn('/bin/true', [], {})\n", "eval('1')\n", "exec('x = 1')\n", + "import ctypes\n", "import multiprocessing\n", "import pty\n"): + self.assert_t3("capability_subprocess", {"src/slice.py": text}) + for text in ("const cp = require('node:child_process');\n", "const cp = await import('child_process');\n", + "import { spawn } from 'child_process';\n", "const f = new Function('return 1');\n"): + self.assert_t3("capability_subprocess", {"packages/widget/index.js": text}) + + def test_more_network_capabilities_are_t3(self): + for text in ("from http import client\n", "import ssl\n", "import asyncio\nasyncio.open_connection('x', 1)\n", + "import ftplib\n", "import smtplib\n", "import http.server\n"): + self.assert_t3("capability_network", {"src/slice.py": text}) + for text in ("const ws = new WebSocket('wss://x.invalid');\n", "navigator.sendBeacon('/x');\n", + "const x = new XMLHttpRequest();\n", "import net from 'node:net';\n"): + self.assert_t3("capability_network", {"packages/widget/index.js": text}) + + def test_a_new_test_module_with_a_capability_is_t3(self): + self.assert_t3("capability_subprocess", {"tests/test_new.py": "import subprocess\n\ndef test_x():\n pass\n"}) + + def test_unseen_auth_validator_sandbox_and_approval_variants_are_t3(self): + self.assert_t3("auth_surface", {"hyvv/validators/x.py": "VALUE = 1\n"}, repo_name="hyvv") + self.assert_t3("auth_surface", {"src/sandbox/x.py": "VALUE = 1\n"}) + self.assert_t3("auth_surface", {"apps/rizzstack-approvals-v2/x.html": "x
\n"}) + self.assert_t3("auth_surface", {"src/permissions.py": "VALUE = 1\n"}) + + def test_more_unknown_kinds_are_t3(self): + for path, text in (("docs/run.bat", "echo hi\n"), ("docs/run.cmd", "echo hi\n"), + ("src/blob.bin", "\x00\x01\x02binary\n"), ("src/native.so", "ELF\n"), + ("src/pkg.whl", "PK\n"), ("src/mod.pyc", "x\n"), ("docs/nb.ipynb", "{}\n"), + ("src/Makefile", "all:\n\ttrue\n"), ("src/noext", "x\n")): + self.assert_t3("unknown_kind", {path: text}) + + def test_pure_mode_change_and_outside_symlink_are_t3(self): + self.assert_t3("unknown_kind", {}, modes_only={"src/slice.py": 0o755}) + self.assert_t3("unknown_kind", {}, symlinks=[("src/escape.py", "../../../../etc/passwd")]) + + def test_submodule_is_t3(self): + self.assert_t3("unknown_kind", {}, gitlinks=["src/vendored"]) + + def test_every_new_t3_reason_has_a_gate_drill_case(self): + drill = _load(DRILL_SCRIPT, "gate_drill_authority_under_test") + reasons = [(case.expect_reason or "") for case in drill.CASES + if case.kind == "tier" and case.expect_tier == "T3"] + for reason in NEW_T3_REASONS: + self.assertTrue(any(r.startswith(reason + ":") for r in reasons), reason) + + +# --------------------------------------------------------------- gate drill lock is append-only +DRILL_LOCK = ROOT / ".github" / "scripts" / "gate_drill.lock.json" +DRILL_LOCK_AT_MAIN = ROOT / "tests" / "fixtures" / "gate_drill.lock.main.json" +DRILL_LOCK_AT_MAIN_SHA256 = "560c4509dc49163ca9bf6b7a9bd205590bc3d099302b6df3c1d35873a4fc98fe" + + +def _entry_bytes(entry): + return json.dumps(entry, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8") + + +class GateDrillLockAppendOnlyTest(unittest.TestCase): + """Every drill case pinned at main stays byte-identical: new cases may be added, none weakened.""" + + def main_lock(self): + data = DRILL_LOCK_AT_MAIN.read_bytes() + self.assertEqual(hashlib.sha256(data).hexdigest(), DRILL_LOCK_AT_MAIN_SHA256) + return json.loads(data) + + def test_lock_entries_present_at_main_stay_byte_identical(self): + main = self.main_lock() + lock = json.loads(DRILL_LOCK.read_text(encoding="utf-8")) + self.assertEqual(lock.get("version"), main["version"]) + self.assertGreaterEqual(len(main["cases"]), 1) + for cid, entry in main["cases"].items(): + self.assertIn(cid, lock["cases"], "drill case %s was removed" % cid) + self.assertEqual(_entry_bytes(lock["cases"][cid]), _entry_bytes(entry), cid) + + def test_drill_declarations_present_at_main_are_unchanged(self): + main = self.main_lock() + drill = _load(DRILL_SCRIPT, "gate_drill_append_only_under_test") + declared = drill.expected_lock()["cases"] + for cid, entry in main["cases"].items(): + self.assertIn(cid, declared, "drill case %s is no longer declared" % cid) + self.assertEqual(_entry_bytes(declared[cid]), _entry_bytes(entry), cid) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_lease_tamper.py b/tests/test_lease_tamper.py index e631fcd..53dcea2 100644 --- a/tests/test_lease_tamper.py +++ b/tests/test_lease_tamper.py @@ -24,7 +24,10 @@ #: sha256 of the shared policy block and the shared fixtures. Both repositories #: that vendor this gate (workflow and hyvv) and the merge lane (rizzstack) #: assert the same values, so the copies cannot drift silently. -SHARED_POLICY_SHA256 = "f749821a6170379743a7e440edcb0d90141de8d04bf22ef9a3b6d28a78b83ec8" +# The pinned hash of the shared gate/lane policy block lives in one fixture both suites read. +SHARED_POLICY_SHA256 = (Path(__file__).resolve().parent / "fixtures" / "shared_policy.sha256").read_text( + encoding="ascii").strip() +REVIEWER_LOGIN = "rizzstack-reviewer[bot]" REVIEW_LINES_SHA256 = "ac2de684dd22fceed5aa2f18ac6d7d6f8c101c0fd67a619d2a2c6a663642311b" CARRY_FIXTURES_SHA256 = "33435d738b84742c8e2b5cfa3e153cf20921fb7a1985f808bbde68603941165e" SHARED_BLOCK_BEGIN = "# --- BEGIN SHARED GATE POLICY" @@ -911,7 +914,7 @@ def test_non_slice_pr_with_an_approve_at_head_passes(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) self.api.reviews[12] = [ { - "state": "COMMENTED", + "user": {"login": REVIEWER_LOGIN}, "state": "COMMENTED", "commit_id": head, "body": "APPROVE (independent review at %s)\n\nVERDICT: APPROVE" % head, } @@ -925,7 +928,7 @@ def test_non_slice_pr_with_an_approve_at_head_passes(self): def test_non_slice_pr_with_an_approved_review_at_head_passes(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) - self.api.reviews[12] = [{"state": "APPROVED", "commit_id": head, "body": ""}] + self.api.reviews[12] = [{"user": {"login": REVIEWER_LOGIN}, "state": "APPROVED", "commit_id": head, "body": ""}] proc = self.run_gate(repo, base, head, env=self.api_env()) @@ -936,7 +939,7 @@ def test_non_slice_pr_with_a_review_at_an_older_head_fails(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) repo.write("src/slice.py", "one more commit\n") newer = repo.commit("the head moves after review") - self.api.reviews[12] = [{"state": "APPROVED", "commit_id": head, "body": ""}] + self.api.reviews[12] = [{"user": {"login": REVIEWER_LOGIN}, "state": "APPROVED", "commit_id": head, "body": ""}] proc = self.run_gate(repo, base, newer, env=self.api_env()) @@ -946,7 +949,7 @@ def test_non_slice_pr_with_a_review_at_an_older_head_fails(self): def test_non_slice_changes_requested_is_not_an_approval(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) self.api.reviews[12] = [ - {"state": "COMMENTED", "commit_id": head, "body": "CHANGES REQUESTED: fix the doc"} + {"user": {"login": REVIEWER_LOGIN}, "state": "COMMENTED", "commit_id": head, "body": "CHANGES REQUESTED: fix the doc"} ] proc = self.run_gate(repo, base, head, env=self.api_env()) @@ -976,7 +979,7 @@ def run_event(self, repo, payload, event_name="pull_request_review"): def test_review_event_applies_the_non_slice_review_rule(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) - self.api.reviews[12] = [{"state": "APPROVED", "commit_id": head, "body": ""}] + self.api.reviews[12] = [{"user": {"login": REVIEWER_LOGIN}, "state": "APPROVED", "commit_id": head, "body": ""}] proc = self.run_event( repo, event_payload(base, head, branch="feat/wave-x-x1", reviewed_sha=head) @@ -992,7 +995,7 @@ def test_review_event_refuses_a_review_recorded_at_an_older_head(self): repo, base, head, _path = self.build(lease_extra={"id": "wave-other-slice", "branch": "feat/other", "pull_request": 99}) repo.write("src/slice.py", "one more commit\n") newer = repo.commit("the head moves after review") - self.api.reviews[12] = [{"state": "APPROVED", "commit_id": head, "body": ""}] + self.api.reviews[12] = [{"user": {"login": REVIEWER_LOGIN}, "state": "APPROVED", "commit_id": head, "body": ""}] proc = self.run_event( repo, event_payload(base, newer, branch="feat/wave-x-x1", reviewed_sha=head) @@ -1050,7 +1053,7 @@ def build(self): def review_at(self, sha): self.api.reviews[12] = [ { - "state": "COMMENTED", + "user": {"login": REVIEWER_LOGIN}, "state": "COMMENTED", "commit_id": sha, "body": "APPROVE (independent review at %s)\n\nVERDICT: approve" % sha, } @@ -1221,6 +1224,7 @@ class RejectionGovernsTests(CarryFixtureTests): def review(self, sha, state="COMMENTED", body=None, submitted_at="2026-11-26T00:00:00Z"): return { + "user": {"login": REVIEWER_LOGIN}, "state": state, "commit_id": sha, "body": body if body is not None else "APPROVE (independent review) at %s" % sha, @@ -1470,7 +1474,7 @@ def test_lease_landing_with_an_independent_review_at_head_passes(self): head_with_lease = repo.commit("land another approved contract") api.reviews[12] = [ { - "state": "COMMENTED", + "user": {"login": REVIEWER_LOGIN}, "state": "COMMENTED", "commit_id": head_with_lease, "body": "APPROVE (independent review at %s)" % head_with_lease, } diff --git a/tests/test_merge_lane_v5.py b/tests/test_merge_lane_v5.py index a6b7ef0..0bae7c8 100644 --- a/tests/test_merge_lane_v5.py +++ b/tests/test_merge_lane_v5.py @@ -45,7 +45,9 @@ #: sha256 of the shared policy block and the shared fixtures. The lease/tamper #: gate (workflow, vendored into hyvv) asserts the same values, so the two #: copies cannot drift silently. -SHARED_POLICY_SHA256 = "f749821a6170379743a7e440edcb0d90141de8d04bf22ef9a3b6d28a78b83ec8" +# The pinned hash of the shared gate/lane policy block lives in one fixture both suites read. +SHARED_POLICY_SHA256 = (Path(__file__).resolve().parent / "fixtures" / "shared_policy.sha256").read_text( + encoding="ascii").strip() REVIEW_LINES_SHA256 = "ac2de684dd22fceed5aa2f18ac6d7d6f8c101c0fd67a619d2a2c6a663642311b" CARRY_FIXTURES_SHA256 = "33435d738b84742c8e2b5cfa3e153cf20921fb7a1985f808bbde68603941165e" SHARED_BLOCK_BEGIN = "# --- BEGIN SHARED GATE POLICY" @@ -63,7 +65,7 @@ def approve(head=HEAD, state="COMMENTED", body=None): return { "state": state, "commit_id": head, - "author": "reviewer", + "author": "rizzstack-reviewer[bot]", "body": body if body is not None else "APPROVE (independent review at %s, hermes family)\n\nVERDICT: approve" % head, @@ -74,7 +76,7 @@ def owner_approve(head=HEAD, state="COMMENTED", body=None): return { "state": state, "commit_id": head, - "author": "owner", + "author": "mojomast", "body": body if body is not None else "APPROVE (owner) at %s\n\nOne-time owner decision." % head, @@ -187,7 +189,7 @@ def test_changes_requested_at_head_blocks_even_with_an_approve(self): self.assertEqual(verdict["reason"], "review_changes_requested") def test_github_approved_state_at_head_passes(self): - value = facts(reviews=[{"state": "APPROVED", "commit_id": HEAD, "body": ""}]) + value = facts(reviews=[{"state": "APPROVED", "commit_id": HEAD, "body": "", "author": "rizzstack-reviewer[bot]"}]) verdict = lane.decide(value) self.assertTrue(verdict["merge"], verdict) @@ -687,7 +689,8 @@ def test_pr_state_gates(self): self.assertEqual(lane.decide(facts(pr={"mergeable": "MERGEABLE"}))["merge"], True) self.assertEqual( lane.decide(facts(pr={"merge_state_status": "DIRTY"}))["reason"], "merge_state_dirty") - self.assertTrue(lane.decide(facts(pr={"merge_state_status": "BEHIND"}))["merge"]) + self.assertEqual( + lane.decide(facts(pr={"merge_state_status": "BEHIND"}))["reason"], "merge_state_behind") def test_absent_mergeable_or_draft_key_refuses(self): value = facts() @@ -1012,7 +1015,7 @@ def _facts_payload(self, head, base_ref): }, "class": lane.NON_SLICE, "reviews": [ - {"state": "COMMENTED", "commit_id": self.reviewed, + {"state": "COMMENTED", "commit_id": self.reviewed, "author": "rizzstack-reviewer[bot]", "body": "APPROVE (independent review at %s)" % self.reviewed} ], "checks": [{"name": "ci-gate", "status": "completed", @@ -1219,7 +1222,7 @@ def test_canonical_review_forms_are_accepted(self): self.assertEqual(lane.parse_review_line(body)[0], kind, body) def test_owner_body_never_satisfies_the_independent_rule(self): - review = {"state": "APPROVED", "commit_id": HEAD, + review = {"state": "APPROVED", "commit_id": HEAD, "author": "mojomast", "body": "APPROVE (owner) at %s" % HEAD} self.assertEqual(lane.review_form(review)[0], lane.REVIEW_APPROVE_OWNER) self.assertFalse(lane.review_is_approval(review, lane.REVIEW_APPROVE_INDEPENDENT)) @@ -1262,6 +1265,7 @@ def review(self, sha, state="COMMENTED", body=None, submitted_at="2026-11-26T00: "commit_id": sha, "body": body if body is not None else "APPROVE (independent review) at %s" % sha, "submitted_at": submitted_at, + "author": "rizzstack-reviewer[bot]", } def test_rejection_at_the_approved_commit_refuses_the_carried_review(self): @@ -1392,7 +1396,7 @@ def setUp(self): {"filename": "tests/test_example.py"}] self.api.reviews = [ {"state": "COMMENTED", "commit_id": OLDER, "body": "APPROVE (independent review) at " + OLDER, - "submitted_at": "2026-11-26T00:00:00Z", "user": {"login": "reviewer"}}, + "submitted_at": "2026-11-26T00:00:00Z", "user": {"login": "rizzstack-reviewer[bot]"}}, ] self.api.check_runs = [ {"name": "ci-gate", "status": "completed", "conclusion": "success", @@ -1422,7 +1426,7 @@ def collect(self, **overrides): "ran": True, "ok": True, "reason": "gate_ok", "head": HEAD, "output_tail": "lease-tamper: class=non-slice\n", }) - repo = overrides.pop("repo_path", ".") + repo = overrides.pop("repo_path", self.tmp.name) return lane.collect_facts( "mojomast/workflow", 7, repo, "test-token", api_url="https://api.test", http=self.api, gate_record=gate, @@ -1524,7 +1528,7 @@ def test_collects_the_pull_request_state_reviews_and_checks(self): ["bundlebees_plugin/example.py", "tests/test_example.py"]) self.assertEqual(facts["reviews"][0]["commit_id"], OLDER) self.assertEqual(facts["reviews"][0]["submitted_at"], "2026-11-26T00:00:00Z") - self.assertEqual(facts["reviews"][0]["author"], "reviewer") + self.assertEqual(facts["reviews"][0]["author"], "rizzstack-reviewer[bot]") self.assertEqual(facts["checks"][0]["name"], "ci-gate") self.assertEqual(facts["checks"][0]["head"], HEAD) self.assertEqual(facts["required_checks"], ["ci-gate"])