diff --git a/.github/scripts/customer_guard_gate.py b/.github/scripts/customer_guard_gate.py new file mode 100644 index 00000000..ed32def8 --- /dev/null +++ b/.github/scripts/customer_guard_gate.py @@ -0,0 +1,129 @@ +"""CI gate for CoderHelm's "Customer details guard" check run. + +CoderHelm sets that check run on every pull request of a public repository +it is installed on, from its own records (services/common/src/customer_guard). +This gate makes the repository's CI wait for it: it fails when the guard's +newest run on the PR's head failed, or when there is none, finished, after +waiting up to five minutes. A skipped run (a pull request from a fork) passes. + +Only the guard's own app counts (GUARD_APP, `coderhelm`): a check of the +same name from anything else, a workflow job included, is ignored. + +An edit to the PR's text after CI finished sets the guard again; the +"Customer details guard rerun" workflow then runs this job again, so the +required CI follows the text. + +Until the guard is deployed (the last successful deploy of the platform +does not yet contain it), the gate passes: nothing could set the check. + +It prints only "pass" or "fail". + + python3 .github/scripts/customer_guard_gate.py # in Actions, on pull_request +""" + +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +CHECK = "Customer details guard" +APP = os.environ.get("GUARD_APP", "coderhelm") +PLATFORM = "CoderHelm/coderhelm-platform" +GUARD_SOURCE = "services/worker/src/passes/customer_guard.rs" +WAIT_SECS = int(os.environ.get("GUARD_WAIT_SECS", "300")) +POLL_SECS = 15 + + +class NotFound(Exception): + pass + + +def api(path): + """GET one GitHub API path; NotFound on a 404, any other failure raises.""" + base = os.environ.get("GITHUB_API_URL", "https://api.github.com") + req = urllib.request.Request(base + path) + req.add_header("Accept", "application/vnd.github+json") + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + if token: + req.add_header("Authorization", f"Bearer {token}") + try: + with urllib.request.urlopen(req, timeout=30) as r: + return json.load(r) + except urllib.error.HTTPError as e: + if e.code == 404: + raise NotFound() from None + raise + + +def latest(runs, app=APP): + """The guard's newest check run from its own app, or None.""" + own = [r for r in runs if r.get("name") == CHECK and (r.get("app") or {}).get("slug") == app] + if not own: + return None + return max(own, key=lambda r: (r.get("started_at") or "", r.get("id") or 0)) + + +def verdict(run): + """'pass', 'fail', or None while there is no finished run.""" + if run is None or run.get("status") != "completed": + return None + return "pass" if run.get("conclusion") in ("success", "neutral", "skipped") else "fail" + + +def guard_live(get=api): + """Is the guard deployed: the last successful deploy's commit has it. A + read that fails counts as deployed, so a failure never waves a PR on.""" + try: + runs = get(f"/repos/{PLATFORM}/actions/workflows/deploy.yml/runs?branch=main&status=success&per_page=1") + sha = (runs.get("workflow_runs") or [{}])[0].get("head_sha") + if not sha: + return True + get(f"/repos/{PLATFORM}/contents/{GUARD_SOURCE}?ref={sha}") + return True + except NotFound: + return False + except Exception: + return True + + +def head_sha(): + sha = os.environ.get("HEAD_SHA", "") + if sha: + return sha + with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as f: + return json.load(f)["pull_request"]["head"]["sha"] + + +def run(repo, sha, get=api, sleep=time.sleep, now=time.monotonic, wait=WAIT_SECS): + """'pass' or 'fail' for the guard on `sha`.""" + if not guard_live(get): + return "pass" + name = urllib.parse.quote(CHECK) + deadline = now() + wait + while True: + try: + runs = get(f"/repos/{repo}/commits/{sha}/check-runs?check_name={name}&filter=all&per_page=100") + v = verdict(latest(runs.get("check_runs") or [])) + if v: + return v + except Exception: + pass + if now() >= deadline: + return "fail" + sleep(POLL_SECS) + + +def main(): + try: + result = run(os.environ["GITHUB_REPOSITORY"], head_sha()) + except Exception: + result = "fail" + print(result) + return 0 if result == "pass" else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test_customer_guard_gate.py b/.github/scripts/test_customer_guard_gate.py new file mode 100644 index 00000000..e49f6329 --- /dev/null +++ b/.github/scripts/test_customer_guard_gate.py @@ -0,0 +1,106 @@ +"""Tests for customer_guard_gate.py, against a fake GitHub API.""" + +import contextlib +import io +import os +import pathlib +import sys +import unittest +from unittest import mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +import customer_guard_gate as g # noqa: E402 + + +def check(conclusion, status="completed", app="coderhelm", started="2026-01-01T00:00:00Z", id=1): + return {"name": g.CHECK, "app": {"slug": app}, "status": status, + "conclusion": conclusion, "started_at": started, "id": id} + + +class Fake: + """GitHub, answering from a list of check-run listings (one per poll).""" + + def __init__(self, polls, live=True): + self.polls, self.live, self.calls = list(polls), live, 0 + + def __call__(self, path): + if "/actions/workflows/deploy.yml/runs" in path: + return {"workflow_runs": [{"head_sha": "d3p10y"}]} + if "/contents/" in path: + if self.live: + return {} + raise g.NotFound() + self.calls += 1 + runs = self.polls.pop(0) if len(self.polls) > 1 else self.polls[0] + return {"check_runs": runs} + + +class Clock: + def __init__(self): + self.t = 0.0 + + def now(self): + return self.t + + def sleep(self, s): + self.t += s + + +def gate(polls, live=True, wait=300): + c = Clock() + return g.run("o/r", "abc", get=Fake(polls, live), sleep=c.sleep, now=c.now, wait=wait) + + +class Gate(unittest.TestCase): + def test_passing_and_skipped_pass(self): + self.assertEqual(gate([[check("success")]]), "pass") + self.assertEqual(gate([[check("neutral")]]), "pass") + + def test_failing_fails(self): + self.assertEqual(gate([[check("failure")]]), "fail") + + def test_missing_fails_after_the_wait(self): + self.assertEqual(gate([[]]), "fail") + + def test_it_waits_for_a_running_guard(self): + polls = [[], [check(None, status="in_progress")], [check("success")]] + self.assertEqual(gate(polls), "pass") + + def test_the_newest_run_counts(self): + runs = [check("failure", id=1), check("success", started="2026-01-01T00:05:00Z", id=2)] + self.assertEqual(gate([runs]), "pass") + runs = [check("success", id=1), check("failure", started="2026-01-01T00:05:00Z", id=2)] + self.assertEqual(gate([runs]), "fail") + + def test_only_the_guards_own_app_counts(self): + self.assertEqual(gate([[check("success", app="github-actions")]]), "fail") + both = [check("success", app="github-actions", started="2026-01-02T00:00:00Z"), check("failure")] + self.assertEqual(gate([both]), "fail") + + def test_before_the_guard_is_deployed_it_passes(self): + self.assertEqual(gate([[]], live=False), "pass") + + def test_a_failed_read_never_passes(self): + def broken(path): + raise OSError("down") + c = Clock() + self.assertTrue(g.guard_live(broken)) + self.assertEqual(g.run("o/r", "abc", get=broken, sleep=c.sleep, now=c.now, wait=60), "fail") + + def test_it_prints_only_pass_or_fail(self): + out = io.StringIO() + env = {"GITHUB_REPOSITORY": "o/r", "HEAD_SHA": "abc"} + with mock.patch.dict(os.environ, env), mock.patch.object(g, "run", return_value="fail"), \ + contextlib.redirect_stdout(out): + code = g.main() + self.assertEqual((code, out.getvalue()), (1, "fail\n")) + out = io.StringIO() + with mock.patch.dict(os.environ, env), mock.patch.object(g, "run", side_effect=RuntimeError("x")), \ + contextlib.redirect_stdout(out): + code = g.main() + self.assertEqual((code, out.getvalue()), (1, "fail\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_text_guard.py b/.github/scripts/test_text_guard.py index 83ff7938..f2f84e47 100644 --- a/.github/scripts/test_text_guard.py +++ b/.github/scripts/test_text_guard.py @@ -7,22 +7,17 @@ import sys import tempfile import unittest -from unittest import mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) import text_guard as g # noqa: E402 -DENY = "# names\nzorbcorp\n\nfrobnitz\\.internal\n" +def hits(text): + return g.scan_lines(g.numbered(text), g.rules_for()) -def hits(text, deny=""): - patterns, _ = g.load_denylist(deny) - return g.scan_lines(g.numbered(text), g.rules_for(patterns)) - - -def rules(text, deny=""): - return {rule for _, rule in hits(text, deny)} +def rules(text): + return {rule for _, rule in hits(text)} class Rules(unittest.TestCase): @@ -32,21 +27,7 @@ def test_clean_text_passes(self): "The worker reads the plan, then writes the patch; SHA-256 and UTF-8 stay as they were.\n" "See CVE-2024-12345 and RFC-7231. Example: arn:aws:iam::123456789012:role/x." ) - self.assertEqual(hits(text, DENY), []) - - def test_denylist_matches_ignoring_case(self): - self.assertEqual(rules("Fixes the run for ZorbCorp", DENY), {"denylisted name or host"}) - self.assertEqual(rules("calls api.frobnitz.internal", DENY), {"denylisted name or host"}) - self.assertEqual(rules("frobnitzXinternal", DENY), set()) - - def test_denylist_skips_comments_and_blank_lines(self): - patterns, problems = g.load_denylist(DENY) - self.assertEqual(len(patterns), 2) - self.assertEqual(problems, []) - - def test_bad_denylist_entry_is_named_by_line_not_text(self): - _, problems = g.load_denylist("ok\nbroken(\n") - self.assertEqual(problems, ["GUARD_DENYLIST line 2 is not a valid regex"]) + self.assertEqual(hits(text), []) def test_aws_account_ids(self): self.assertIn("AWS account id", rules("arn:aws:lambda:us-east-1:418273645091:function:w")) @@ -85,63 +66,16 @@ def test_email_addresses(self): self.assertEqual(rules("uses: actions/checkout@v4.4.0 and @types/node"), set()) def test_line_numbers(self): - self.assertEqual(hits("ok\nok\nmail a@zorbmail.io\nQXZ-11", DENY), [(3, "email address"), (4, "Jira-style key")]) - - -class Hashes(unittest.TestCase): - # Synthetic terms, hashed here: only their digests reach the rule. - TERMS = ["Zorb Corp", "frobnitz", "acme-widget-sales-floor", "418273645091"] - - def setUp(self): - self.hashes = set(g.hash_terms(io.StringIO("\n".join(self.TERMS) + "\n"))) - - def rules(self, text): - return {rule for _, rule in g.scan_lines(g.numbered(text), g.rules_for([], self.hashes))} + self.assertEqual(hits("ok\nok\nmail a@zorbmail.io\nQXZ-11"), [(3, "email address"), (4, "Jira-style key")]) - def test_normalize(self): - self.assertEqual(g.normalize(" Zorb_Corp's API.v2! "), "zorb corp s api v2") - self.assertEqual(g.term_hash("ZORB--corp"), g.term_hash("zorb corp")) - def test_one_to_four_word_runs_match(self): - self.assertEqual(self.rules("Fixed for zorb-corp today"), {"denylisted term"}) - self.assertEqual(self.rules("calls FROBNITZ.example.com"), {"denylisted term"}) - self.assertEqual(self.rules("the Acme widget, sales floor"), {"denylisted term"}) - - def test_parts_and_neighbours_do_not_match(self): - self.assertEqual(self.rules("zorb alone, corp alone, frobnitzer, acme widget sales"), set()) - - def test_twelve_digit_numbers_match(self): - self.assertIn("denylisted term", self.rules("id 4182-7364-5091 in a table")) - self.assertEqual(self.rules("x418273645091y"), {"denylisted term"}) - self.assertEqual(self.rules("4182736450912"), set()) - - def test_hash_file_parsing(self): - with tempfile.NamedTemporaryFile("w", suffix=".sha256", delete=False) as f: - f.write("# header\n\n" + g.term_hash("frobnitz") + " # one\nnot-a-digest\n") - try: - hashes, problems = g.load_hashes(f.name) - finally: - os.unlink(f.name) - self.assertEqual(hashes, {g.term_hash("frobnitz")}) - self.assertEqual(problems, [f"{f.name} line 4 is not a SHA-256 hex digest"]) - - def test_missing_file_is_empty(self): - self.assertEqual(g.load_hashes("/nonexistent/text-guard.sha256"), (set(), [])) - - def test_failure_prints_no_term(self): - with tempfile.TemporaryDirectory() as d: - hf, tf = os.path.join(d, "h.sha256"), os.path.join(d, "t.md") - with open(hf, "w") as f: - f.write("\n".join(sorted(self.hashes)) + "\n") - with open(tf, "w") as f: - f.write("ok\nShipped for Zorb Corp\n") - out = io.StringIO() - env = {"GUARD_DENYLIST": "", "GUARD_HASH_FILE": hf} - with mock.patch.dict(os.environ, env), contextlib.redirect_stdout(out): - code = g.main(["text_guard.py", "--text", tf]) - self.assertEqual(code, 1) - self.assertIn("line 2: denylisted term", out.getvalue()) - self.assertNotIn("zorb", out.getvalue().lower()) +class NoList(unittest.TestCase): + def test_no_list_of_names_hashed_or_plain(self): + src = (pathlib.Path(__file__).resolve().parent / "text_guard.py").read_text() + for gone in ("GUARD_DENYLIST", "sha256", "hashlib", "--hash-terms"): + self.assertNotIn(gone, src) + repo = pathlib.Path(__file__).resolve().parents[1] + self.assertFalse((repo / "text-guard.sha256").exists()) class Diffs(unittest.TestCase): @@ -167,38 +101,31 @@ def test_added_lines_carry_new_line_numbers(self): class Output(unittest.TestCase): - def run_main(self, text, deny): + def run_main(self, text): with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as f: f.write(text) out = io.StringIO() try: - env = {"GUARD_DENYLIST": deny, "GUARD_HASH_FILE": "/nonexistent/text-guard.sha256"} - with mock.patch.dict(os.environ, env), contextlib.redirect_stdout(out): + with contextlib.redirect_stdout(out): code = g.main(["text_guard.py", "--text", f.name]) finally: os.unlink(f.name) return code, out.getvalue() def test_failure_names_line_and_rule_never_the_text(self): - code, out = self.run_main("intro\nShipped for zorbcorp, see QXZ-4821 and pat@zorbmail.io\n", DENY) + code, out = self.run_main("intro\nShipped, see QXZ-4821 and pat@zorbmail.io\n") self.assertEqual(code, 1) - report = [line for line in out.splitlines() if not line.startswith("::add-mask::")] - self.assertTrue(any("line 2: denylisted name or host" in line for line in report)) + report = out.splitlines() self.assertTrue(any("line 2: Jira-style key" in line for line in report)) self.assertTrue(any("line 2: email address" in line for line in report)) joined = "\n".join(report).lower() - for secret in ("zorbcorp", "qxz-4821", "zorbmail", "frobnitz"): + for secret in ("qxz-4821", "zorbmail"): self.assertNotIn(secret, joined) - def test_every_denylist_entry_is_masked_first(self): - _, out = self.run_main("clean\n", DENY) - lines = out.splitlines() - self.assertEqual(lines[:2], ["::add-mask::zorbcorp", "::add-mask::frobnitz\\.internal"]) - - def test_clean_text_passes_and_missing_denylist_warns(self): - code, out = self.run_main("Retries a failed check once.\n", "") + def test_clean_text_passes(self): + code, out = self.run_main("Retries a failed check once.\n") self.assertEqual(code, 0) - self.assertIn("no denylist hashes or GUARD_DENYLIST", out) + self.assertIn("no customer details", out) if __name__ == "__main__": diff --git a/.github/scripts/text_guard.py b/.github/scripts/text_guard.py index f3078583..89e1e5bf 100644 --- a/.github/scripts/text_guard.py +++ b/.github/scripts/text_guard.py @@ -1,15 +1,8 @@ -"""Public text guard: a pull request's words never carry a customer install's details. +"""Public text guard: a pull request's words never carry an install's ids. Scans the PR title, the PR body, every commit message in the PR, and the lines the PR adds under docs/, and fails (exit 1) on: -- a term whose SHA-256 is in .github/text-guard.sha256. A term is - normalized (lowercase, every run of other characters one space), and the - guard hashes every run of 1 to 4 words of each line, and every 12-digit - number, so the file names no term. Add one with - `python3 .github/scripts/text_guard.py --hash-terms < terms.txt`; -- optionally, a name or hostname from GUARD_DENYLIST (one regex per line, - matched ignoring case; blank lines and lines starting with # are skipped); - an AWS account id in an ARN, an ECR host, or after "account", and any other standalone 12-digit number (which is how an account id is written); - a TEAM# id; @@ -17,14 +10,17 @@ - a Jira-style key, apart from the allowlist below; - an email address, apart from example and no-reply domains. +Customer names and hosts are not listed here, hashed or not: CoderHelm +checks those itself from its own records (the "Customer details guard" +check run; .github/scripts/customer_guard_gate.py makes CI wait for it). + It prints where (the source and the line number) and which rule, never the -matched text, and masks every denylist entry in the log first. +matched text. python3 .github/scripts/text_guard.py # in Actions, on pull_request python3 .github/scripts/text_guard.py --text F # one file, for a local check """ -import hashlib import json import os import re @@ -66,72 +62,6 @@ RE_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@((?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,})(?![A-Za-z0-9-])") -HASH_FILE = os.path.join(".github", "text-guard.sha256") -# Terms are matched as runs of up to this many words. -MAX_TERM_WORDS = 4 -RE_HASH_LINE = re.compile(r"^[0-9a-f]{64}$") -RE_NUMBER = re.compile(r"(?> .github/text-guard.sha256 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40bf3a8c..b316bb28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,8 +25,6 @@ jobs: # when the PR's text is edited. Title and body come from the event # file, never from a script. - name: Public text guard - env: - GUARD_DENYLIST: ${{ secrets.GUARD_DENYLIST }} run: | python3 -m unittest discover -s .github/scripts -p test_text_guard.py python3 .github/scripts/text_guard.py @@ -244,3 +242,30 @@ jobs: - run: npm ci # Deploy-safety checks on the synthesized stacks (test/static-site.test.ts). - run: npm test + + # Last: CoderHelm's "Customer details guard" check run on the PR's head + # (customer names, hosts and keys from its own records, never listed + # here) passed or was skipped; failing or missing after five minutes + # fails. An edit to the PR's text after this ran sets the guard again, + # and the Customer details guard rerun workflow runs this job again. + # Prints only pass or fail (.github/scripts/customer_guard_gate.py). + customer-guard: + name: Customer details guard (CI) + needs: [lint-build, dashboard-build, dashboard-e2e, dashboard, docs, selfhost-dashboard, infra] + if: ${{ github.event_name == 'pull_request' && !cancelled() }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + checks: read + contents: read + actions: read + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Gate tests + run: python3 -m unittest discover -s .github/scripts -p test_customer_guard_gate.py + - name: The guard passed on this commit + env: + GH_TOKEN: ${{ github.token }} + run: python3 .github/scripts/customer_guard_gate.py diff --git a/.github/workflows/customer-guard-rerun.yml b/.github/workflows/customer-guard-rerun.yml new file mode 100644 index 00000000..9b7aa1df --- /dev/null +++ b/.github/workflows/customer-guard-rerun.yml @@ -0,0 +1,46 @@ +name: Customer details guard rerun + +# CoderHelm sets its "Customer details guard" check run again whenever a +# pull request's text changes (an edit of the title or body, a push). When +# that happens after CI finished, this runs CI's "Customer details guard +# (CI)" job of that commit again, so the required CI follows the PR's text. +# Only the guard's own app's check runs count. It runs from the default +# branch, checks nothing out and prints no PR text. +on: + check_run: + types: [completed] + +permissions: + actions: write + contents: read + +concurrency: + group: customer-guard-rerun-${{ github.event.check_run.head_sha }} + cancel-in-progress: false + +jobs: + rerun: + name: Run the CI gate again + if: ${{ github.event.check_run.name == 'Customer details guard' && github.event.check_run.app.slug == 'coderhelm' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Run the gate job of this commit's CI again + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + SHA: ${{ github.event.check_run.head_sha }} + run: | + run_id=$(gh api "repos/$REPO/actions/runs?head_sha=$SHA&event=pull_request&per_page=50" \ + --jq '[.workflow_runs[] | select(.path == ".github/workflows/ci.yml")] | max_by(.run_number) | .id // empty') + if [ -z "$run_id" ]; then + echo "pass" + exit 0 + fi + job=$(gh api "repos/$REPO/actions/runs/$run_id/jobs?filter=latest&per_page=100" \ + --jq '[.jobs[] | select(.name == "Customer details guard (CI)" and .status == "completed")][0].id // empty') + # Still queued or running: it reads the guard's newest result itself. + if [ -n "$job" ]; then + gh api -X POST "repos/$REPO/actions/jobs/$job/rerun" > /dev/null + fi + echo "pass" diff --git a/.github/workflows/text-guard.yml b/.github/workflows/text-guard.yml index 79ca4077..77b7796a 100644 --- a/.github/workflows/text-guard.yml +++ b/.github/workflows/text-guard.yml @@ -1,12 +1,12 @@ name: Public text guard # The words a pull request publishes (title, body, commit messages, added -# lines under docs/) carry no details from a customer install: no denylisted -# terms (.github/text-guard.sha256, and GUARD_DENYLIST when it is set), AWS -# account ids, TEAM# ids, ULID run ids, Jira keys or email addresses -# (.github/scripts/text_guard.py). CI's first job runs the same guard on -# every push; this workflow reruns it when the PR's title or body is edited, -# on its own so an edit never cancels or skips the build. +# lines under docs/) carry no ids from an install: AWS account ids, TEAM# +# ids, ULID run ids, Jira keys or email addresses +# (.github/scripts/text_guard.py). Customer names and hosts are CoderHelm's +# own "Customer details guard" check, which CI waits for. CI runs the same +# guard on every push; this workflow reruns it when the PR's title or body +# is edited, on its own so an edit never cancels or skips the build. on: pull_request: branches: [main] @@ -32,10 +32,7 @@ jobs: fetch-depth: 0 - name: Guard tests run: python3 -m unittest discover -s .github/scripts -p test_text_guard.py - # Reads the title and body from the event file, never from a script. - # The denylist is a secret, so the runner masks it; the script masks - # each entry again and prints only the place and the rule of a hit. + # Reads the title and body from the event file, never from a script, + # and prints only the place and the rule of a hit. - name: Scan the PR's text - env: - GUARD_DENYLIST: ${{ secrets.GUARD_DENYLIST }} run: python3 .github/scripts/text_guard.py