Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 63 additions & 3 deletions .github/scripts/test_text_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,12 @@ def test_aws_account_ids(self):
self.assertIn("AWS account id", rules("arn:aws:lambda:us-east-1:418273645091:function:w"))
self.assertIn("AWS account id", rules("pushed to 418273645091.dkr.ecr.us-east-1.amazonaws.com"))
self.assertIn("AWS account id", rules("the install's account 4182-7364-5091"))
self.assertEqual(rules("account 111122223333"), set())
self.assertIn("AWS account id", rules("AWS_ACCOUNT_ID=418273645091"))
self.assertEqual(rules("arn:aws:iam::111122223333:root, account id 123456789012"), set())
self.assertEqual(rules("processed 418273645091 bytes"), set())
self.assertEqual(rules("processed 418273645091 bytes"), {"12-digit number"})
self.assertEqual(rules("ids 4182-7364-5091 and 111122223333"), {"12-digit number"})
self.assertEqual(rules("ALAS2023-2025-1234, v1.418273645091, 4182736450912"), set())

def test_team_ids(self):
self.assertEqual(rules("pk TEAM#9f3a21"), {"TEAM# id"})
Expand Down Expand Up @@ -85,6 +88,62 @@ 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))}

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 Diffs(unittest.TestCase):
DIFF = (
"diff --git a/docs/a.md b/docs/a.md\n"
Expand Down Expand Up @@ -113,7 +172,8 @@ def run_main(self, text, deny):
f.write(text)
out = io.StringIO()
try:
with mock.patch.dict(os.environ, {"GUARD_DENYLIST": deny}), contextlib.redirect_stdout(out):
env = {"GUARD_DENYLIST": deny, "GUARD_HASH_FILE": "/nonexistent/text-guard.sha256"}
with mock.patch.dict(os.environ, env), contextlib.redirect_stdout(out):
code = g.main(["text_guard.py", "--text", f.name])
finally:
os.unlink(f.name)
Expand All @@ -138,7 +198,7 @@ def test_every_denylist_entry_is_masked_first(self):
def test_clean_text_passes_and_missing_denylist_warns(self):
code, out = self.run_main("Retries a failed check once.\n", "")
self.assertEqual(code, 0)
self.assertIn("GUARD_DENYLIST is not available", out)
self.assertIn("no denylist hashes or GUARD_DENYLIST", out)


if __name__ == "__main__":
Expand Down
94 changes: 86 additions & 8 deletions .github/scripts/text_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@
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 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";
- 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;
- a 26-character ULID (a run id);
- a Jira-style key, apart from the allowlist below;
Expand All @@ -18,6 +24,7 @@
python3 .github/scripts/text_guard.py --text F # one file, for a local check
"""

import hashlib
import json
import os
import re
Expand Down Expand Up @@ -52,12 +59,59 @@
RE_ARN = re.compile(r"arn:aws[a-z-]*:[a-z0-9-]*:[a-z0-9-]*:(\d{12}):", re.IGNORECASE)
RE_ECR = re.compile(r"(?<!\d)(\d{12})\.dkr\.ecr\.", re.IGNORECASE)
RE_ACCOUNT = re.compile(r"(?:account|acct)(?:[ _-]?(?:id|ids|number|no))?[^\n\d]{0,30}?" + ACCOUNT_ID, re.IGNORECASE)
RE_TWELVE = re.compile(r"(?<![\w.-])(\d{12}|\d{4}-\d{4}-\d{4})(?![\w.-])")
RE_TEAM = re.compile(r"TEAM#[0-9A-Za-z][0-9A-Za-z_-]*")
RE_ULID = re.compile(r"(?<![0-9A-Za-z])[0-7][0-9A-HJKMNP-TV-Z]{25}(?![0-9A-Za-z])", re.IGNORECASE)
RE_JIRA = re.compile(r"(?<![A-Za-z0-9-])([A-Z]{2,6})-(\d{2,6})(?![0-9])")
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"(?<!\d)(\d{4}-?\d{4}-?\d{4})(?!\d)")


def normalize(text):
"""Lowercase, every run of anything but letters and digits as one space."""
return re.sub(r"[^a-z0-9]+", " ", text.lower()).strip()


def term_hash(term):
return hashlib.sha256(normalize(term).encode("utf-8")).hexdigest()


def load_hashes(path):
"""(hashes, problems) from a file of SHA-256 hex digests; # starts a comment."""
hashes, problems = set(), []
if not os.path.exists(path):
return hashes, problems
with open(path, encoding="utf-8") as f:
for n, line in enumerate(f, 1):
entry = line.split("#", 1)[0].strip().lower()
if not entry:
continue
if RE_HASH_LINE.match(entry):
hashes.add(entry)
else:
problems.append(f"{path} line {n} is not a SHA-256 hex digest")
return hashes, problems


def line_hashes(line):
"""The hash of every 1- to MAX_TERM_WORDS-word run of the line, and of every 12-digit number."""
words = normalize(line).split()
out = set()
for i in range(len(words)):
for k in range(1, MAX_TERM_WORDS + 1):
if i + k <= len(words):
out.add(hashlib.sha256(" ".join(words[i:i + k]).encode("utf-8")).hexdigest())
for m in RE_NUMBER.finditer(line):
out.add(hashlib.sha256(m.group(1).replace("-", "").encode("utf-8")).hexdigest())
return out


def load_denylist(raw):
"""(patterns, problems): compiled entries, and the entries that don't compile, by line."""
patterns, problems = [], []
Expand Down Expand Up @@ -86,6 +140,10 @@ def _account(line):
return False


def _twelve(line):
return any(m.group(1).replace("-", "") not in PLACEHOLDER_ACCOUNTS for m in RE_TWELVE.finditer(line))


def _team(line):
return any(m.group(0) not in TEAM_ALLOW for m in RE_TEAM.finditer(line))

Expand All @@ -106,10 +164,13 @@ def _email(line):
return any(not EMAIL_DOMAIN_ALLOW.search(m.group(1).lower()) for m in RE_EMAIL.finditer(line))


def rules_for(denylist):
def rules_for(denylist, hashes=frozenset()):
rules = [("denylisted name or host", lambda line: any(p.search(line) for p in denylist))]
if hashes:
rules.append(("denylisted term", lambda line: not hashes.isdisjoint(line_hashes(line))))
rules += [
("AWS account id", _account),
("12-digit number", _twelve),
("TEAM# id", _team),
("ULID run id", _ulid),
("Jira-style key", _jira),
Expand Down Expand Up @@ -181,23 +242,40 @@ def report(sources, rules):
return out


def hash_terms(stream):
"""One digest per input line (a plain term), for .github/text-guard.sha256. Prints no term."""
return sorted({term_hash(line) for line in stream if normalize(line)})


def main(argv):
if len(argv) == 2 and argv[1] == "--hash-terms":
for h in hash_terms(sys.stdin):
print(h)
return 0
raw = os.environ.get("GUARD_DENYLIST", "")
for cmd in mask_commands(raw):
print(cmd)
denylist, problems = load_denylist(raw)
for p in problems:
print(f"::error title=Public text guard::{p}")
if not raw.strip():
print("::warning title=Public text guard::GUARD_DENYLIST is not available here; names and hosts are not checked")
rules = rules_for(denylist)
hashes, hash_problems = load_hashes(os.environ.get("GUARD_HASH_FILE", HASH_FILE))
problems += hash_problems
for p in hash_problems:
print(f"::error title=Public text guard::{p}")
if not hashes and not raw.strip():
print("::warning title=Public text guard::no denylist hashes or GUARD_DENYLIST here; names and hosts are not checked")
rules = rules_for(denylist, hashes)

if len(argv) == 3 and argv[1] == "--text":
with open(argv[2], encoding="utf-8") as f:
sources = [(argv[2], None, numbered(f.read()))]
else:
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as f:
sources = sources_from_pr(json.load(f))
event = json.load(f)
if "pull_request" not in event:
print("Not a pull request event: nothing to check")
return 1 if problems else 0
sources = sources_from_pr(event)

failures = report(sources, rules)
for line in failures:
Expand Down
6 changes: 6 additions & 0 deletions .github/text-guard.sha256
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# SHA-256 digests of denylisted terms, one per line; # starts a comment.
# A term is normalized first: lowercase, every run of anything but letters
# and digits as one space. The guard hashes every 1- to 4-word run of each
# line it checks, and every 12-digit number, and fails on a digest listed here.
# Add terms with:
# python3 .github/scripts/text_guard.py --hash-terms < terms.txt >> .github/text-guard.sha256
14 changes: 14 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# Every commit of the PR, for the Public text guard step.
fetch-depth: 0
# The PR's title, body, commits and docs/ additions carry no details
# from a customer install (.github/scripts/text_guard.py); a push to
# main has no PR and passes. The Public text guard workflow reruns it
# 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
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: lts/*
Expand Down
13 changes: 7 additions & 6 deletions .github/workflows/text-guard.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
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 names or
# hosts from GUARD_DENYLIST, AWS account ids, TEAM# ids, ULID run ids, Jira
# keys or email addresses (.github/scripts/text_guard.py). It runs on its own,
# not in CI, so editing a PR's text reruns only this check and never cancels
# or skips the build.
# 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.
on:
pull_request:
branches: [main]
types: [opened, edited, synchronize, reopened]
types: [edited]

permissions:
contents: read
Expand Down
Loading