omega-projects
aien-dev/omega-projects
Brought by drakestapleton
omega-projects / .github / check_projects.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Checks every pull request to main: the files Allen's visitors build must stay inside their |
| 3 | home, be plain allowlisted text, load nothing from elsewhere and carry no secret or personal data. |
| 4 | |
| 5 | Run by .github/workflows/project-checks.yml from the main branch's copy of this file (the |
| 6 | pull request's copy is used only while main has none), with no token and no secrets: |
| 7 | |
| 8 | check_projects.py BASE_REV PR_REV HEAD_REF |
| 9 | |
| 10 | Rules (kept in step with allen_build.py / allen_spool.py in aien-dev/aienos.com, which apply |
| 11 | them before anything is pushed; this check is the second, independent look): |
| 12 | - projects/<handle>/<project>/<file> only; handle and project are lowercase names; |
| 13 | files: index.html, README.md, meta.json, name.om|js|css|md|txt|patch; no folders below; |
| 14 | - UTF-8 text, no control characters, at most 64 KiB a file and 12 files a project; |
| 15 | - index.html, .js and .css load or send nothing from elsewhere (no remote script, link, |
| 16 | frame, fetch, WebSocket, beacon, import...); |
| 17 | - nothing shaped like a key, token or password; no email address anywhere and no phone |
| 18 | number in prose or the meta.json title and description (Allen removes them before filing; one here is a leak); |
| 19 | - meta.json is the pusher's: exactly its fields, matching the folder, no personal data; |
| 20 | - every touched project still has README.md, meta.json and index.html or an .om file; |
| 21 | - a branch named u/<handle> or p/<handle>/<project> (Allen's) changes nothing else. |
| 22 | Exit 0 when every rule holds, 1 with one line per finding otherwise. |
| 23 | """ |
| 24 | |
| 25 | import json |
| 26 | import re |
| 27 | import subprocess |
| 28 | import sys |
| 29 | |
| 30 | HANDLE = r"(?:[a-z](?:[a-z0-9]|-(?=[a-z0-9])){1,23}-[0-9a-f]{8}|anon-[0-9a-f]{10})" |
| 31 | NAME = r"[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?" |
| 32 | PATH = re.compile(r"^projects/(%s)/(%s)/([^/]+)$" % (HANDLE, NAME)) |
| 33 | FILENAME = re.compile(r"^(?:index\.html|README\.md|meta\.json|[a-z0-9][a-z0-9_-]{0,39}\.(?:om|js|css|md|txt|patch))$") |
| 34 | WEB = (".html", ".js", ".css") |
| 35 | PROSE = (".md", ".txt") |
| 36 | MAX_FILE = 64 * 1024 |
| 37 | MAX_FILES = 12 |
| 38 | META = {"v", "handle", "project", "title", "description", "saved", "item", "built_with", "files"} |
| 39 | SECRET = [re.compile(p) for p in ( |
| 40 | r"gh[pousr]_[A-Za-z0-9]{20,}", r"github_pat_[A-Za-z0-9_]{20,}", r"\bsk-[A-Za-z0-9_-]{20,}", |
| 41 | r"\bsk-ant-[A-Za-z0-9_-]{10,}", r"\bAKIA[0-9A-Z]{16}\b", r"\bAIza[0-9A-Za-z_-]{30,}", |
| 42 | r"xox[abprs]-[A-Za-z0-9-]{10,}", r"-----BEGIN [A-Z ]*PRIVATE KEY-----", |
| 43 | r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.", |
| 44 | r"(?i)\b(api[_-]?key|secret|passw(or)?d|access[_-]?token|auth[_-]?token)\b\s*[:=]\s*['\"]?[^\s'\"]{12,}")] |
| 45 | EXTERNAL = [re.compile(p, re.I) for p in ( |
| 46 | r"<script\b[^>]*\bsrc\s*=", r"<link\b", r"<iframe\b", r"<object\b", r"<embed\b", r"<base\b", |
| 47 | r"<meta\b[^>]*http-equiv", r"\b(src|href|action|formaction|poster|data)\s*=\s*['\"]?\s*(https?:)?//", |
| 48 | r"url\(\s*['\"]?\s*(https?:)?//", r"@import\b", r"\bfetch\s*\(", r"XMLHttpRequest", r"WebSocket", |
| 49 | r"EventSource", r"sendBeacon", r"\bimport\s*\(", r"\bimportScripts\b", r"\bwindow\.open\b")] |
| 50 | EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}") |
| 51 | PHONE = re.compile(r"(?<![\w.])\+?\d[\d ().-]{7,}\d(?!\w|\.\d)") |
| 52 | |
| 53 | |
| 54 | def git(*args): |
| 55 | return subprocess.run(("git",) + args, check=True, capture_output=True).stdout |
| 56 | |
| 57 | |
| 58 | def bad_text(text): |
| 59 | for ch in text: |
| 60 | o = ord(ch) |
| 61 | if ((o < 32 and ch not in "\n\t\r") or o == 127 or 0xD800 <= o <= 0xDFFF or 0xFDD0 <= o <= 0xFDEF |
| 62 | or (o & 0xFFFE) == 0xFFFE or o == 0xFFFD): |
| 63 | return "a control or binary character" |
| 64 | return None |
| 65 | |
| 66 | |
| 67 | def check_file(path, name, handle, project, raw): |
| 68 | out = [] |
| 69 | if not FILENAME.match(name): |
| 70 | out.append("file name not allowed (index.html, README.md, meta.json, name.om|js|css|md|txt|patch)") |
| 71 | return out |
| 72 | if len(raw) > MAX_FILE: |
| 73 | out.append("larger than %d KiB" % (MAX_FILE // 1024)) |
| 74 | try: |
| 75 | text = raw.decode("utf-8") |
| 76 | except UnicodeDecodeError: |
| 77 | return out + ["not UTF-8 text"] |
| 78 | why = bad_text(text) |
| 79 | if why: |
| 80 | out.append("contains " + why) |
| 81 | for pat in SECRET: |
| 82 | if pat.search(text): |
| 83 | out.append("looks like it contains a secret (%s)" % pat.pattern[:30]) |
| 84 | break |
| 85 | if name.endswith(WEB): |
| 86 | for pat in EXTERNAL: |
| 87 | if pat.search(text): |
| 88 | out.append("loads or sends something from elsewhere (%s)" % pat.pattern[:40]) |
| 89 | break |
| 90 | if EMAIL.search(text): |
| 91 | out.append("contains an email address") |
| 92 | if name.endswith(PROSE) and PHONE.search(text): |
| 93 | out.append("contains a phone number") |
| 94 | if name == "meta.json": |
| 95 | try: |
| 96 | m = json.loads(text) |
| 97 | except ValueError: |
| 98 | return out + ["meta.json is not JSON"] |
| 99 | if not isinstance(m, dict) or set(m) != META: |
| 100 | out.append("meta.json fields must be exactly %s" % ", ".join(sorted(META))) |
| 101 | elif m.get("handle") != handle or m.get("project") != project: |
| 102 | out.append("meta.json names another home or project") |
| 103 | elif any(PHONE.search(str(m.get(k, ""))) for k in ("title", "description")): |
| 104 | out.append("meta.json contains a phone number") |
| 105 | return out |
| 106 | |
| 107 | |
| 108 | def main(base, pr, head_ref): |
| 109 | findings = [] |
| 110 | changed = git("diff", "--name-status", "--no-renames", "-z", base, pr).decode().split("\0") |
| 111 | entries = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)] |
| 112 | allen = re.fullmatch(r"u/(%s)|p/(%s)/(%s)" % (HANDLE, HANDLE, NAME), head_ref) |
| 113 | touched = set() |
| 114 | for status, path in entries: |
| 115 | m = PATH.match(path) |
| 116 | if not path.startswith("projects/") or path == "projects/README.md": |
| 117 | if allen: |
| 118 | findings.append("%s: a branch from Allen may only change its own project folder" % path) |
| 119 | elif path.startswith(".github/"): |
| 120 | print("note: %s changes the repository's automation; review it by hand" % path) |
| 121 | continue |
| 122 | if not m: |
| 123 | findings.append("%s: outside projects/<handle>/<project>/<file>" % path) |
| 124 | continue |
| 125 | handle, project, name = m.groups() |
| 126 | if allen and allen.group(2) and (handle, project) != (allen.group(2), allen.group(3)): |
| 127 | findings.append("%s: branch %s may only change projects/%s/%s/" % (path, head_ref, allen.group(2), |
| 128 | allen.group(3))) |
| 129 | if allen and allen.group(1) and handle != allen.group(1): |
| 130 | findings.append("%s: branch %s may only change projects/%s/" % (path, head_ref, allen.group(1))) |
| 131 | touched.add((handle, project)) |
| 132 | if status == "D": |
| 133 | continue |
| 134 | mode = git("ls-tree", pr, "--", path).decode().split(" ", 1)[0] |
| 135 | if mode != "100644": |
| 136 | findings.append("%s: must be a plain file (mode %s)" % (path, mode or "?")) |
| 137 | continue |
| 138 | for f in check_file(path, name, handle, project, git("show", "%s:%s" % (pr, path))): |
| 139 | findings.append("%s: %s" % (path, f)) |
| 140 | for handle, project in sorted(touched): |
| 141 | d = "projects/%s/%s/" % (handle, project) |
| 142 | names = [p[len(d):] for p in git("ls-tree", "-r", "--name-only", pr, "--", d).decode().splitlines()] |
| 143 | if not names: |
| 144 | continue # the project was removed |
| 145 | if any("/" in n for n in names): |
| 146 | findings.append("%s: no folders inside a project" % d) |
| 147 | if len(names) > MAX_FILES + 1: |
| 148 | findings.append("%s: more than %d files" % (d, MAX_FILES)) |
| 149 | for need in ("README.md", "meta.json"): |
| 150 | if need not in names: |
| 151 | findings.append("%s: needs %s" % (d, need)) |
| 152 | if not any(n == "index.html" or n.endswith(".om") for n in names): |
| 153 | findings.append("%s: needs index.html or an .om file" % d) |
| 154 | for f in findings: |
| 155 | print("FAIL " + f) |
| 156 | print("%d changed file(s), %d project(s), %d finding(s)" % (len(entries), len(touched), len(findings))) |
| 157 | return 1 if findings else 0 |
| 158 | |
| 159 | |
| 160 | if __name__ == "__main__": |
| 161 | if len(sys.argv) != 4: |
| 162 | sys.exit(__doc__) |
| 163 | sys.exit(main(*sys.argv[1:])) |