Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/pusher/test_pusher.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / pusher / test_pusher.py` 751 lines ยท 38657 bytes Raw Blame History 1 #!/usr/bin/python3 2 """Tests for omega_projects_pusher.py. Every rejection has an accepted control next to it. 3 4 Offline tests record every call and forward it through the real client and the request 5 guard to an in-process stand-in for the GitHub API (github_stub.py, 127.0.0.1) that keeps 6 a small git object store, so saves, publishes, declines and the index are checked against 7 real trees and refs. StubEndToEnd runs the pusher program as a subprocess against the stub 8 with a fake fine-grained token. Nothing reaches GitHub. 9 Live tests (LIVE=1) use the operator's own gh login, never the pusher's credential: they 10 read the ruleset and Actions settings, try a direct push to main (must fail with GH013) 11 and push a u/ branch (must succeed, then deleted). 12 13 nice -n 19 python3 test_pusher.py # offline + stub 14 LIVE=1 nice -n 19 python3 test_pusher.py # plus live repository settings 15 """ 16 17 import base64 18 import json 19 import os 20 import shutil 21 import subprocess 22 import sys 23 import tempfile 24 import unittest 25 26 HERE = os.path.dirname(os.path.abspath(__file__)) 27 GW = os.environ.get("ALLEN_GW", "/tmp/allenchat/gw") 28 sys.path.insert(0, HERE) 29 sys.path.insert(0, GW) 30 import allen_build # noqa: E402 31 import allen_spool # noqa: E402 32 import omega_projects_pusher as P # noqa: E402 33 from github_stub import FAKE_PAT, Stub # noqa: E402 34 35 P.spool = allen_spool 36 P.build = allen_build 37 REPO = "aien-dev/omega-projects" 38 ADA = "ada-`0a1b2c3d`" 39 BOB = "anon-`0123456789`" 40 41 42 class FakeGitHub: 43 """Records calls, then sends them through the real client (and so the request guard) to an 44 in-process stub. `fail` is raised instead for the first `fail_count` calls (-1: always).""" 45 46 def __init__(self, fail=None, fail_count=-1): 47 self.calls, self.fail, self.fail_count = [], fail, fail_count 48 self.stub = Stub().start() 49 self.client = P.GitHub(FAKE_PAT, api=self.stub.base) 50 51 def call(self, method, path, body=None): 52 P._check_request(method, path, body) 53 self.calls.append((method, path, body)) 54 if self.fail and self.fail_count != 0: 55 self.fail_count -= 1 56 raise self.fail 57 return self.client.call(method, path, body) 58 59 def posts(self, rest, method="POST"): 60 return [c for c in self.calls if c[0] == method and c[1] == P.REPO_PREFIX + rest] 61 62 def close(self): 63 self.stub.shutdown() 64 self.stub.server_close() 65 66 67 def issue(**kw): 68 it = {"v": 1, "kind": "issue", "template": "feature", "title": "Add a sine word to Omega", 69 "body": "It would help to have sin and cos available in IR mode.", "area": "omega-mv"} 70 it.update(kw) 71 return it 72 73 74 README = "# Calculator\n\nAdds and multiplies. It helps students check homework.\n" 75 76 77 def project(files=None, kind="publish", **kw): 78 """A save or publish item; README.md is added when the files lack one.""" 79 files = files or [{"name": "index.html", "content": "
calc
"}, 80 {"name": "calc.om", "content": "fn add(a: i64, b: i64) -> i64 { a + b }\n"}] 81 if not any(f["name"] == "README.md" for f in files): 82 files = files + [{"name": "README.md", "content": README}] 83 it = {"v": 1, "kind": kind, "handle": ADA, "project": "calc", "title": "Calculator", 84 "description": "A small calculator compiled from Omega.", "files": files} 85 it.update(kw) 86 return it 87 88 89 def save(files=None, **kw): 90 return project(files, kind="save", **kw) 91 92 93 class Env: 94 def __init__(self, areas=("omega-mv",)): 95 self.root = tempfile.mkdtemp(prefix="pusher-test-") 96 self.spool_in = os.path.join(self.root, "in") 97 self.status = os.path.join(self.root, "status") 98 self.state = os.path.join(self.root, "state") 99 for d in (self.spool_in, self.status, self.state): 100 os.makedirs(d, mode=0o700) 101 self.areas = os.path.join(self.root, "areas.txt") 102 with open(self.areas, "w") as f: 103 f.write("\n".join(areas) + "\n") 104 105 def args(self, test_label=False): 106 class A: 107 pass 108 a = A() 109 a.spool_in, a.spool_status, a.state_dir, a.areas = self.spool_in, self.status, self.state, self.areas 110 a.test_label = test_label 111 a.backoff = (0.0, 0.0, 0.0, 0.0) 112 return a 113 114 def drop(self, item, iid=None, raw=None): 115 iid = iid or allen_spool.item_id(item) 116 with open(os.path.join(self.spool_in, iid + ".json"), "wb") as f: 117 f.write(raw if raw is not None else json.dumps(item, ensure_ascii=False, sort_keys=True).encode()) 118 return iid 119 120 def status_of(self, iid): 121 with open(os.path.join(self.status, iid + ".json")) as f: 122 return json.load(f) 123 124 def run(self, gh, test_label=False): 125 return P.process(self.args(test_label), gh) 126 127 def cleanup(self): 128 shutil.rmtree(self.root) 129 130 131 class Offline(unittest.TestCase): 132 def setUp(self): 133 self.env = Env() 134 self.gh = FakeGitHub() 135 136 def tearDown(self): 137 self.gh.close() 138 self.env.cleanup() 139 140 def outcome(self, item, **kw): 141 iid = self.env.drop(item, **kw) 142 self.env.run(self.gh) 143 self.assertFalse(os.path.exists(os.path.join(self.env.spool_in, iid + ".json"))) 144 return self.env.status_of(iid) 145 146 def assertRejected(self, item, needle, **kw): 147 st = self.outcome(item, **kw) 148 self.assertEqual(st["state"], "rejected", st) 149 self.assertIn(needle, st["reason"]) 150 return st 151 152 def assertFiled(self, item, **kw): 153 st = self.outcome(item, **kw) 154 self.assertEqual(st["state"], "filed", st) 155 self.assertRegex(st["url"], r"^https://github\.com/aien-dev/omega-projects/(issues/\d+|pull/\d+|commit/[0-9a-f]{40})$") 156 return st 157 158 # paths: handle and project are names, never paths 159 def test_path_traversal_rejected(self): 160 for name in ("../x", "a/b", ".github"): 161 self.assertRejected(project(project=name), "project name") 162 for handle in ("../ada-`0a1b2c3d`", "ada", "ada-`0a1b2c3d`/x", "Ada-`0a1b2c3d`", "anon-xyz"): 163 self.assertRejected(project(handle=handle), "unknown handle") 164 for fname in ("../x.om", ".github/workflows/x.js", "a/b.om", "x.exe", "meta.json", ".env"): 165 self.assertRejected(project([{"name": fname, "content": "x"}]), "file names allowed") 166 self.assertEqual(self.gh.calls, []) 167 168 def test_path_control_accepted(self): 169 self.assertFiled(project(project="calc")) 170 trees = self.gh.posts("git/trees") 171 self.assertEqual(len(trees), 1) 172 paths = sorted(t["path"] for t in trees[0][2]["tree"]) 173 d = "projects/%s/calc/" % ADA 174 self.assertEqual(paths, [d + "README.md", d + "calc.om", d + "index.html", d + "meta.json"]) 175 176 # size 177 def test_oversized_rejected(self): 178 big = "" + "x" * (65 * 1024) + "
" 179 self.assertRejected(project([{"name": "index.html", "content": big}]), "larger than 64 KiB") 180 self.assertEqual(self.gh.calls, []) 181 182 def test_small_accepted(self): 183 small = "" + "x" * 1000 + "
" 184 self.assertFiled(project([{"name": "index.html", "content": small}])) 185 186 # binary 187 def test_binary_rejected(self): 188 for bad in ("a\x00b", "a\ufffeb", "a\uffffb", "a\ufdd0b", "a\ufffdb"): 189 self.assertRejected(project([{"name": "index.html", "content": "%s
" % bad}]), 190 "binary") 191 raw = b'{"v":1,"kind":"issue","template":"bug","title":"\xff\xfe broken title","body":"x","area":"a"}' 192 self.assertRejected(None, "UTF-8", iid="0" * 20, raw=raw) 193 self.assertEqual(self.gh.calls, []) 194 195 def test_text_accepted(self): 196 self.assertFiled(project([{"name": "index.html", "content": "caf\u00e9 \u2014 \u03c0 \U0001f600
"}])) 197 198 # secrets 199 def test_secret_rejected(self): 200 self.assertRejected(issue(body="my token is ghp_" + "A1b2C3d4E5" * 3 + "abcdef please"), "secret") 201 self.assertRejected(issue(body="-----BEGIN PRIVATE KEY-----\nMIIEvQ\n-----END PRIVATE KEY-----"), 202 "secret") 203 self.assertRejected(issue(body="see key -----BEGIN OPENSSH PRIVATE KEY----- here"), "secret") 204 self.assertEqual(self.gh.calls, []) 205 206 def test_plain_body_accepted(self): 207 self.assertFiled(issue(body="The ghp prefix is how GitHub tokens start; private keys too.")) 208 209 # external loads in index.html 210 def test_external_script_rejected(self): 211 for html in ('', 212 '', 213 '
', '',
214 ''):
215 self.assertRejected(project([{"name": "index.html", "content": html}]), "elsewhere")
216 self.assertEqual(self.gh.calls, [])
217
218 def test_inline_script_accepted(self):
219 self.assertFiled(project([{"name": "index.html",
220 "content": ""}]))
221
222 # scrub
223 def test_emails_phones_scrubbed(self):
224 it = issue(title="Help from ann@example.org please",
225 body="Write to ann.lee+x@example.co.uk or call +1 (555) 123-4567 about this.")
226 self.assertFiled(it)
227 body = self.gh.posts("issues")[0][2]
228 text = body["title"] + body["body"]
229 for leak in ("ann@example.org", "ann.lee+x@example.co.uk", "555", "4567"):
230 self.assertNotIn(leak, text)
231 self.assertIn("[email removed]", text)
232 self.assertIn("[phone removed]", text)
233 self.assertTrue(body["title"].startswith("[feature] "))
234 self.assertIn(P.FOOTER, body["body"])
235 self.assertEqual(body["labels"], ["from-aien", "area:omega-mv"])
236
237 def test_scrub_control_plain_text_unchanged(self):
238 self.assertFiled(issue())
239 body = self.gh.posts("issues")[0][2]
240 self.assertTrue(body["body"].startswith(issue()["body"]))
241 self.assertNotIn("removed]", body["body"])
242
243 def test_project_prose_scrubbed_code_untouched(self):
244 code = "// the answer\nfn k() -> i64 { `1234567890` }\n"
245 files = [{"name": "README.md", "content": "Contact bob@example.com or 555-123-4567."},
246 {"name": "calc.om", "content": code}]
247 self.assertFiled(project(files, description="Made by bob@example.com, call +44 20 7946 0958."))
248 blobs = [base64.b64decode(c[2]["content"]).decode() for c in self.gh.posts("git/blobs")]
249 self.assertIn(code, blobs) # code is published byte-for-byte; Drake reviews it
250 prose = "\n".join(b for b in blobs if b != code)
251 self.assertNotIn("bob@example.com", prose)
252 self.assertNotIn("7946", prose)
253 self.assertNotIn("0958", prose)
254 self.assertNotIn("555-123", prose)
255 meta = json.loads([b for b in blobs if b.startswith("{")][0])
256 self.assertEqual(set(meta), {"v", "handle", "project", "title", "description", "saved", "item",
257 "built_with", "files"})
258
259 def test_email_in_code_rejected(self):
260 self.assertRejected(project([{"name": "calc.om", "content": "// by bob@example.com\nfn k() -> i64 { 1 }\n"}]),
261 "email address")
262 self.assertRejected(project([{"name": "index.html", "content": "calc
"}, 263 {"name": "app.js", "content": "fetch('/x')"}]), "elsewhere") 264 no_readme = dict(project(), files=[{"name": "index.html", "content": "calc
"}]) 265 self.assertRejected(no_readme, "README.md") 266 self.assertEqual(self.gh.calls, []) 267 268 # unknown areas 269 def test_area_unknown(self): 270 self.assertFiled(issue(area="not-a-repo")) 271 self.assertEqual(self.gh.posts("issues")[0][2]["labels"], ["from-aien", "area:unknown"]) 272 273 def test_no_areas_file_means_unknown(self): 274 os.unlink(self.env.areas) 275 self.assertFiled(issue(area="omega-mv")) 276 self.assertEqual(self.gh.posts("issues")[0][2]["labels"], ["from-aien", "area:unknown"]) 277 278 # id 279 def test_id_mismatch_rejected(self): 280 self.assertRejected(issue(), "id does not match", iid="f" * 20) 281 self.assertEqual(self.gh.calls, []) 282 283 # one issue / one PR per item, dedupe 284 def test_exactly_one_issue_and_dedupe(self): 285 it = issue() 286 st = self.assertFiled(it) 287 self.assertEqual(len(self.gh.posts("issues")), 1) 288 n = len(self.gh.calls) 289 self.env.drop(it) 290 self.env.run(self.gh) 291 self.assertEqual(len(self.gh.calls), n) 292 self.assertEqual(self.env.status_of(allen_spool.item_id(it))["url"], st["url"]) 293 294 def test_dedupe_from_ledger_when_status_lost(self): 295 it = issue() 296 self.assertFiled(it) 297 os.unlink(os.path.join(self.env.status, allen_spool.item_id(it) + ".json")) 298 n = len(self.gh.calls) 299 self.env.drop(it) 300 self.env.run(self.gh) 301 self.assertEqual(len(self.gh.calls), n) 302 303 def test_exactly_one_pr_never_main(self): 304 self.assertFiled(project()) 305 self.assertEqual(len(self.gh.posts("pulls")), 1) 306 refs = self.gh.posts("git/refs") 307 self.assertEqual([r[2]["ref"] for r in refs], ["refs/heads/p/%s/calc" % ADA]) 308 pr = self.gh.posts("pulls")[0][2] 309 self.assertEqual((pr["base"], pr["head"]), ("main", "p/%s/calc" % ADA)) 310 self.assertIn(P.FOOTER, pr["body"]) 311 self.assertEqual(self.gh.stub.refs["refs/heads/main"], "c" * 40) 312 self.assertFalse([c for c in self.gh.calls if "heads/main" in c[1] and c[0] != "GET"]) 313 314 # the build loop 315 def test_save_twice_two_commits_on_user_branch(self): 316 s = self.gh.stub 317 first = self.assertFiled(save())["url"] 318 files2 = [{"name": "index.html", "content": "calc v2
"}, 319 {"name": "calc.om", "content": "fn mul(a: i64, b: i64) -> i64 { a * b }\n"}] 320 second = self.assertFiled(save(files2, title="Calculator two"))["url"] 321 head = s.refs["refs/heads/u/" + ADA] 322 self.assertEqual(second.rsplit("/", 1)[1], head) 323 self.assertEqual(s.commits[head]["parents"], [first.rsplit("/", 1)[1]]) # two commits, in order 324 self.assertEqual(s.commits[first.rsplit("/", 1)[1]]["parents"], ["c" * 40]) # branched from main 325 files = s.files_at("u/" + ADA) 326 self.assertIn("calc v2", files["projects/%s/calc/index.html" % ADA]) 327 self.assertEqual(s.refs["refs/heads/main"], "c" * 40) 328 self.assertEqual(s.pulls, []) # saving never opens a pull request 329 # a file dropped from the project is removed from the home, nothing else changes 330 self.assertFiled(save([{"name": "index.html", "content": "only html
"}])) 331 files = s.files_at("u/" + ADA) 332 self.assertNotIn("projects/%s/calc/calc.om" % ADA, files) 333 self.assertIn("projects/README.md", files) 334 335 def test_two_users_two_homes(self): 336 s = self.gh.stub 337 self.assertFiled(save()) 338 self.assertFiled(save(handle=BOB)) 339 ada = {p for p in s.files_at("u/" + ADA) if p.startswith("projects/") and p != "projects/README.md"} 340 bob = {p for p in s.files_at("u/" + BOB) if p.startswith("projects/") and p != "projects/README.md"} 341 self.assertTrue(ada and all(p.startswith("projects/%s/" % ADA) for p in ada), ada) 342 self.assertTrue(bob and all(p.startswith("projects/%s/" % BOB) for p in bob), bob) 343 for c in self.gh.posts("git/trees"): 344 handles = {e["path"].split("/")[1] for e in c[2]["tree"]} 345 self.assertEqual(len(handles), 1) 346 347 def test_republish_reuses_open_pr_then_decline_closes(self): 348 s = self.gh.stub 349 url = self.assertFiled(project())["url"] 350 url2 = self.assertFiled(project(title="Calculator v2"))["url"] 351 self.assertEqual(url, url2) 352 self.assertEqual(len(s.pulls), 1) 353 head = s.refs["refs/heads/p/%s/calc" % ADA] 354 self.assertEqual(len(s.commits[head]["parents"]), 1) # main did not move: plain child 355 idx = allen_build.read_index(self.env.status) 356 self.assertEqual([o["number"] for o in idx["open"]], [s.pulls[0]["number"]]) 357 n = s.pulls[0]["number"] 358 self.assertFiled({"v": 1, "kind": "decline", "pr": n, "reason": "Needs a README that says who it helps."}) 359 self.assertEqual(s.pulls[0]["state"], "closed") 360 self.assertIn("Declined by Drake", s.comments[0]["body"]) 361 self.assertEqual(allen_build.read_index(self.env.status)["open"], []) 362 363 def test_decline_refuses_other_pulls(self): 364 s = self.gh.stub 365 s.pulls.append({"number": 7, "state": "open", "head": {"ref": "feature/x"}, "base": {"ref": "main"}, 366 "html_url": "https://github.com/%s/pull/7" % REPO}) 367 self.assertRejected({"v": 1, "kind": "decline", "pr": 7, "reason": ""}, "not a project publish") 368 self.assertEqual(s.pulls[0]["state"], "open") 369 self.assertFalse(self.gh.posts("pulls/7", method="PATCH")) 370 371 def test_gallery_lists_merged_projects(self): 372 s = self.gh.stub 373 self.assertFiled(project()) 374 s.refs["refs/heads/main"] = s.refs["refs/heads/p/%s/calc" % ADA] # Drake merged it 375 s.pulls[0]["state"] = "closed" 376 iid = self.env.drop({"v": 1, "kind": "refresh", "nonce": "`0123456789abcdef`"}) 377 self.env.run(self.gh) 378 self.assertEqual(self.env.status_of(iid)["state"], "filed") 379 idx = allen_build.read_index(self.env.status) 380 self.assertEqual(idx["open"], []) 381 self.assertEqual([(g["handle"], g["project"], g["title"]) for g in idx["gallery"]], [(ADA, "calc", "Calculator")]) 382 self.assertEqual(os.stat(os.path.join(self.env.status, "index.json")).st_mode & 0o777, 0o640) 383 384 # caps 385 def test_daily_caps(self): 386 st = P.State(self.env.state) 387 st.take("issue") 388 st.d["issues"] = P.CAPS["issue"][1] 389 st.d["prs"] = P.CAPS["publish"][1] - 1 390 st.save() 391 iid = self.env.drop(issue()) 392 self.env.run(self.gh) 393 st = self.env.status_of(iid) 394 self.assertEqual((st["state"], st["url"]), ("failed", None)) 395 self.assertIn("limit for issues", st["reason"]) 396 self.assertFiled(project()) # control: one publish left 397 iid = self.env.drop(project(project="calc2")) 398 self.env.run(self.gh) 399 self.assertEqual(self.env.status_of(iid)["state"], "failed") 400 self.assertEqual(json.load(open(os.path.join(self.env.state, "state.json")))["prs"], P.CAPS["publish"][1]) 401 402 # tmp files and odd entries 403 def test_tmp_skipped_and_symlink_refused(self): 404 tmp = os.path.join(self.env.spool_in, ".tmp-abc") 405 open(tmp, "w").write("{}") 406 target = os.path.join(self.env.root, "secret") 407 open(target, "w").write("{}") 408 os.symlink(target, os.path.join(self.env.spool_in, "1" * 20 + ".json")) 409 self.env.run(self.gh) 410 self.assertTrue(os.path.exists(tmp)) 411 self.assertEqual(self.env.status_of("1" * 20)["state"], "rejected") 412 self.assertTrue(os.path.exists(target)) 413 414 # transient errors 415 def test_github_errors_retry_then_failed(self): 416 cases = [(P.HTTPRefused(401, "Bad credentials"), "GitHub refused the credential (HTTP 401)"), 417 (P.HTTPRefused(403, "Resource not accessible"), "GitHub refused the request (HTTP 403)"), 418 (P.HTTPRefused(403, "API rate limit exceeded"), "GitHub rate limit (HTTP 403)"), 419 (P.HTTPRefused(502), "GitHub server error (HTTP 502)"), 420 (P.GitHubError("GitHub did not answer within 10 s"), "GitHub did not answer within 10 s"), 421 (RuntimeError("boom"), "an internal error (RuntimeError)")] 422 for k, (err, cause) in enumerate(cases): 423 gh = FakeGitHub(fail=err) 424 iid = self.env.drop(issue(title="Retry case number %d here" % k)) 425 for n in range(1, 5): 426 run = self.env.run(gh) 427 st = self.env.status_of(iid) 428 self.assertEqual(st["state"], "queued", cause) 429 self.assertEqual(st["reason"], "retrying: %s (attempt %d of 5)" % (cause, n)) 430 self.assertTrue(os.path.exists(os.path.join(self.env.spool_in, iid + ".json"))) 431 self.assertIsNotNone(run.next_due) 432 self.env.run(gh) 433 st = self.env.status_of(iid) 434 self.assertEqual(st, {"id": iid, "state": "failed", "url": None, 435 "reason": "%s after 5 attempts" % cause}) 436 self.assertFalse(os.path.exists(os.path.join(self.env.spool_in, iid + ".json"))) 437 state = json.load(open(os.path.join(self.env.state, "state.json"))) 438 self.assertEqual((state["issues"], state["pending"], state["attempts"]), (0, {}, {})) # slots returned 439 440 def test_crash_recovery_finds_pre_rename_issue(self): 441 gh = FakeGitHub() 442 iid = "`0123456789abcdef0123`" 443 old = gh.client.call("POST", P.REPO_PREFIX + "issues", {"title": "t", "labels": ["from-allen"], 444 "body": "b\n" + P.marker(iid)}) 445 gh.client.call("POST", P.REPO_PREFIX + "issues", {"title": "u", "labels": ["test"], 446 "body": "b\n" + P.marker("f" * 20)}) 447 self.assertEqual(P.find_issue(gh, iid), old["html_url"]) 448 self.assertIsNone(P.find_issue(gh, "f" * 20)) # control: unlabelled issue is not recovered 449 gh.close() 450 451 def test_planted_marker_is_not_recovered(self): 452 # security survey F3: a visitor who pastes another item's marker into a labelled issue 453 # must not take over that item's status URL; only the marker at the end counts. 454 gh = FakeGitHub() 455 victim = "`abcdefabcdefabcdef01`" 456 gh.client.call("POST", P.REPO_PREFIX + "issues", {"title": "spoof", "labels": ["from-aien"], 457 "body": "x " + P.marker(victim) + "\n\n---\nfooter\n" + P.marker("1" * 20)}) 458 self.assertIsNone(P.find_issue(gh, victim)) 459 self.assertIsNotNone(P.find_issue(gh, "1" * 20)) # control: its own trailing marker 460 gh.close() 461 462 def test_issue_markdown_is_inert(self): 463 body = "hi @drake see calc
"}, 604 {"name": "README.md", "content": "Calculator by a.b@example.org."}]) 605 ids = [self.env.drop(it), self.env.drop(pr)] 606 self.pusher("--token-file", self.token) 607 self.assertEqual(len(self.stub.issues), 1) 608 self.assertEqual(len(self.stub.pulls), 1) 609 self.assertEqual(sorted(self.stub.refs), ["refs/heads/main", "refs/heads/p/%s/calc" % ADA]) 610 self.assertEqual(self.stub.refs["refs/heads/main"], "c" * 40) # main untouched 611 iss = self.stub.issues[0] 612 self.assertEqual(iss["labels"], ["from-aien", "area:omega-mv"]) 613 self.assertTrue(iss["title"].startswith("[feature] ")) 614 self.assertNotIn("a.b@example.org", iss["body"]) 615 self.assertNotIn("9999", iss["body"]) 616 self.assertIn(P.FOOTER, iss["body"]) 617 self.assertEqual(self.stub.pulls[0]["base"], {"ref": "main"}) 618 self.assertEqual({e["method"] for e in self.stub.log}, {"GET", "POST"}) 619 readme = self.stub.files_at("p/%s/calc" % ADA)["projects/%s/calc/README.md" % ADA] 620 self.assertNotIn("a.b@example.org", readme) 621 self.assertTrue(all(e["auth_ok"] for e in self.stub.log)) 622 for i in ids: 623 self.assertEqual(self.env.status_of(i)["state"], "filed") 624 self.assertEqual(os.stat(os.path.join(self.env.status, i + ".json")).st_mode & 0o777, 0o640) 625 self.assertEqual(os.listdir(self.env.spool_in), []) 626 # dedupe: the same items again file nothing and make no request at all 627 n = len(self.stub.log) 628 self.env.drop(it) 629 self.env.drop(pr) 630 self.pusher("--token-file", self.token) 631 self.assertEqual(len(self.stub.log), n) 632 self.assertEqual((len(self.stub.issues), len(self.stub.pulls)), (1, 1)) 633 # dedupe without the local ledger: the GitHub-side lookup finds the existing PR 634 os.unlink(os.path.join(self.env.state, "state.json")) 635 for i in ids: 636 os.unlink(os.path.join(self.env.status, i + ".json")) 637 self.env.drop(pr) 638 self.pusher("--token-file", self.token) 639 self.assertEqual(len(self.stub.pulls), 1) 640 self.assertEqual(self.env.status_of(ids[1])["url"], self.stub.pulls[0]["html_url"]) 641 642 def test_no_token_queues_without_any_request(self): 643 iid = self.env.drop(issue()) 644 self.pusher() # no --token-file, no CREDENTIALS_DIRECTORY 645 bad = os.path.join(self.env.root, "gho") 646 with open(bad, "w") as f: 647 f.write("gho_" + "a" * 36) 648 self.pusher("--token-file", bad) 649 self.assertEqual(self.stub.log, []) 650 self.assertEqual(self.env.status_of(iid)["reason"], P.AWAITING) 651 self.assertTrue(os.path.exists(os.path.join(self.env.spool_in, iid + ".json"))) 652 self.pusher("--token-file", self.token) # control 653 self.assertEqual(len(self.stub.issues), 1) 654 655 def test_redirect_not_followed(self): 656 other = Stub().start() 657 try: 658 self.stub.redirect = other.base + "/repos/%s/issues" % REPO 659 client = P.GitHub(FAKE_PAT, api=self.stub.base) 660 with self.assertRaises(P.HTTPRefused): 661 client.call("POST", P.REPO_PREFIX + "issues", {"title": "x"}) 662 self.assertEqual(other.log, []) # the token never reached the redirect target 663 self.assertEqual(len(self.stub.log), 1) 664 finally: 665 other.shutdown() 666 other.server_close() 667 668 def test_api_failures_end_failed_in_one_run(self): 669 for mode, cause in (("401", "GitHub refused the credential (HTTP 401)"), 670 ("403", "GitHub refused the request (HTTP 403)"), 671 ("500", "GitHub server error (HTTP 500)"), 672 ("502", "GitHub server error (HTTP 502)")): 673 self.stub.set_mode(mode, -1) 674 before = len(self.api_log()) 675 iid = self.env.drop(issue(title="Failure mode %s probe item" % mode)) 676 err = self.pusher("--token-file", self.token) 677 st = self.env.status_of(iid) 678 self.assertEqual(st, {"id": iid, "state": "failed", "url": None, 679 "reason": "%s after 5 attempts" % cause}, err) 680 self.assertEqual(len(self.api_log()) - before, 5) # one request per attempt, then stop 681 self.assertEqual(os.listdir(self.env.spool_in), []) 682 self.assertEqual(self.stub.issues, []) 683 # control: the same kind of item with the API healthy is filed 684 self.stub.set_mode("ok") 685 iid = self.env.drop(issue(title="Healthy API control item")) 686 self.pusher("--token-file", self.token) 687 self.assertEqual(self.env.status_of(iid)["state"], "filed") 688 self.assertEqual(len(self.stub.issues), 1) 689 690 def test_timeout_then_filed_once(self): 691 self.stub.set_mode("timeout", 1) 692 iid = self.env.drop(issue()) 693 err = self.pusher("--token-file", self.token) 694 self.assertIn("GitHub did not answer within 10 s; next in", err) 695 self.assertEqual(self.env.status_of(iid)["state"], "filed") 696 self.assertEqual(len(self.stub.issues), 1) 697 698 def test_server_error_then_filed_once(self): 699 self.stub.set_mode("502", 2) 700 iid = self.env.drop(issue()) 701 err = self.pusher("--token-file", self.token) 702 self.assertIn("attempt 2 of 5 failed: GitHub server error (HTTP 502)", err) 703 self.assertEqual(self.env.status_of(iid)["state"], "filed") 704 self.assertEqual(len(self.stub.issues), 1) 705 706 707 @unittest.skipUnless(os.environ.get("LIVE") == "1", "LIVE=1 checks aien-dev/omega-projects settings") 708 class Live(unittest.TestCase): 709 """Operator setup checks with the normal session credential, never the pusher's.""" 710 711 def test_live_ruleset_settings(self): 712 r = subprocess.run(["gh", "api", "repos/%s/rules/branches/main" % REPO], capture_output=True, text=True) 713 rules = {x["type"]: x.get("parameters") for x in json.loads(r.stdout)} 714 self.assertEqual(set(rules), {"deletion", "non_fast_forward", "pull_request"}) 715 self.assertEqual(rules["pull_request"]["required_approving_review_count"], 1) 716 self.assertTrue(rules["pull_request"]["require_code_owner_review"]) 717 # Actions run only the project checks: no actions usable, read-only token, cannot approve. 718 r = subprocess.run(["gh", "api", "repos/%s/actions/permissions" % REPO], capture_output=True, text=True) 719 self.assertEqual({k: json.loads(r.stdout)[k] for k in ("enabled", "allowed_actions")}, 720 {"enabled": True, "allowed_actions": "local_only"}) 721 r = subprocess.run(["gh", "api", "repos/%s/actions/permissions/workflow" % REPO], capture_output=True, text=True) 722 self.assertEqual(json.loads(r.stdout), {"default_workflow_permissions": "read", 723 "can_approve_pull_request_reviews": False}) 724 725 def test_live_direct_push_to_main_rejected(self): 726 d = tempfile.mkdtemp(prefix="pusher-push-") 727 try: 728 run = lambda *a: subprocess.run(a, cwd=d, capture_output=True, text=True) # noqa: E731 729 self.assertEqual(run("git", "clone", "-q", "--depth", "1", 730 "git@github.com:%s.git" % REPO, ".").returncode, 0) 731 open(os.path.join(d, "CONTROL"), "w").write("x\n") 732 run("git", "add", "CONTROL") 733 self.assertEqual(run("git", "-c", "user.name=control", "-c", "user.email=control@example.invalid", 734 "commit", "-qm", "control").returncode, 0) 735 r = run("git", "push", "origin", "HEAD:refs/heads/main") 736 print("\nLIVE push main rc=%d: %s" % (r.returncode, " | ".join( 737 ln for ln in r.stderr.splitlines() if "GH013" in ln or "rule" in ln.lower())[:400]), file=sys.stderr) 738 self.assertNotEqual(r.returncode, 0) 739 self.assertIn("GH013", r.stderr) 740 br = "u/push-control-%d" % os.getpid() 741 r2 = run("git", "push", "origin", "HEAD:refs/heads/" + br) 742 print("LIVE push %s rc=%d" % (br, r2.returncode), file=sys.stderr) 743 self.assertEqual(r2.returncode, 0, r2.stderr[-300:]) 744 r3 = run("git", "push", "origin", "--delete", br) 745 self.assertEqual(r3.returncode, 0, r3.stderr[-300:]) 746 finally: 747 shutil.rmtree(d) 748 749 750 if __name__ == "__main__": 751 unittest.main(verbosity=2)