aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / pusher / github_stub.py
| 1 | #!/usr/bin/python3 |
| 2 | """github_stub: a local stand-in for the GitHub REST calls omega-projects-pusher makes. |
| 3 | |
| 4 | Test tool only. It listens on 127.0.0.1, accepts one fake fine-grained token, and keeps |
| 5 | issues, pull requests, refs and labels in memory. Issue and PR numbers start at 900001 |
| 6 | so a stub URL can never be mistaken for a real omega-projects issue. |
| 7 | |
| 8 | Failure injection, for retry tests: |
| 9 | POST /_stub/mode {"mode": "ok|401|403|429|500|502|timeout", "count": N} |
| 10 | the next N API requests (or all of them when N is -1) answer with that failure; |
| 11 | "timeout" holds the request for --hold seconds, longer than the pusher's 10 s. |
| 12 | GET /_stub/state -> {"issues", "pulls", "refs", "log", "mode"} |
| 13 | The /_stub/ paths are outside /repos/aien-dev/omega-projects/, so the pusher's request |
| 14 | guard can never reach them. |
| 15 | |
| 16 | python3 github_stub.py --port 18190 [--token github_pat_...] [--log FILE] |
| 17 | """ |
| 18 | |
| 19 | import argparse |
| 20 | import http.server |
| 21 | import re |
| 22 | import json |
| 23 | import sys |
| 24 | import threading |
| 25 | import time |
| 26 | import urllib.parse |
| 27 | |
| 28 | REPO = "aien-dev/omega-projects" |
| 29 | FAKE_PAT = "github_pat_" + "T3st" * 20 |
| 30 | FIRST_NUMBER = 900001 |
| 31 | |
| 32 | |
| 33 | class Stub(http.server.ThreadingHTTPServer): |
| 34 | daemon_threads = True |
| 35 | |
| 36 | def __init__(self, port=0, token=FAKE_PAT, hold=12.0, logfile=None): |
| 37 | super().__init__(("127.0.0.1", port), StubHandler) |
| 38 | self.token, self.hold, self.logfile = token, hold, logfile |
| 39 | self.lock = threading.Lock() |
| 40 | self.log, self.issues, self.pulls, self.comments = [], [], [], [] |
| 41 | # A small git object store: blobs {sha: base64}, trees {sha: {path: blob sha}} (flat, |
| 42 | # recursive listings derive the directories), commits {sha: {tree, parents, message}}. |
| 43 | self.blobs = {"b" * 40: "IyBvbWVnYS1wcm9qZWN0cwo="} |
| 44 | self.trees = {"d" * 40: {"README.md": "b" * 40, "projects/README.md": "b" * 40}} |
| 45 | self.commits = {"c" * 40: {"tree": "d" * 40, "parents": [], "message": "Start"}} |
| 46 | self.refs = {"refs/heads/main": "c" * 40} |
| 47 | self.labels = {"from-aien", "test", "area:unknown"} |
| 48 | self.objects, self.redirect = 0, None |
| 49 | self.mode, self.count = "ok", 0 |
| 50 | |
| 51 | def new_sha(self): |
| 52 | self.objects += 1 |
| 53 | return "%040x" % self.objects |
| 54 | |
| 55 | def files_at(self, ref): |
| 56 | """{path: decoded text} at a branch head, for tests.""" |
| 57 | import base64 |
| 58 | tree = self.trees[self.commits[self.refs["refs/heads/" + ref]]["tree"]] |
| 59 | return {p: base64.b64decode(self.blobs[s]).decode() for p, s in tree.items()} |
| 60 | self.mode, self.count = "ok", 0 |
| 61 | |
| 62 | @property |
| 63 | def base(self): |
| 64 | return "http://127.0.0.1:%d" % self.server_address[1] |
| 65 | |
| 66 | def start(self): |
| 67 | threading.Thread(target=self.serve_forever, daemon=True).start() |
| 68 | return self |
| 69 | |
| 70 | def set_mode(self, mode, count=-1): |
| 71 | with self.lock: |
| 72 | self.mode, self.count = mode, count |
| 73 | |
| 74 | def next_number(self): |
| 75 | return FIRST_NUMBER + len(self.issues) + len(self.pulls) |
| 76 | |
| 77 | def record(self, entry): |
| 78 | self.log.append(entry) |
| 79 | if self.logfile: |
| 80 | with open(self.logfile, "a", encoding="utf-8") as f: |
| 81 | f.write(json.dumps(entry, sort_keys=True) + "\n") |
| 82 | |
| 83 | |
| 84 | class StubHandler(http.server.BaseHTTPRequestHandler): |
| 85 | def log_message(self, *a): |
| 86 | pass |
| 87 | |
| 88 | def reply(self, code, obj=None, headers=()): |
| 89 | # Record the request before the client can see the answer, so a client that has |
| 90 | # its reply always finds the request (with its status) in /_stub/state. |
| 91 | entry = getattr(self, "entry", None) |
| 92 | if entry is not None: |
| 93 | self.entry = None |
| 94 | entry["status"] = code |
| 95 | self.server.record(entry) |
| 96 | raw = json.dumps(obj).encode() if obj is not None else b"" |
| 97 | try: |
| 98 | self.send_response(code) |
| 99 | for k, v in headers: |
| 100 | self.send_header(k, v) |
| 101 | self.send_header("Content-Type", "application/json") |
| 102 | self.send_header("Content-Length", str(len(raw))) |
| 103 | self.end_headers() |
| 104 | self.wfile.write(raw) |
| 105 | except (BrokenPipeError, ConnectionResetError): |
| 106 | pass |
| 107 | return code |
| 108 | |
| 109 | def control(self, method, body): |
| 110 | s = self.server |
| 111 | if method == "POST" and self.path == "/_stub/mode": |
| 112 | s.set_mode(str(body.get("mode", "ok")), int(body.get("count", -1))) |
| 113 | return self.reply(200, {"mode": s.mode, "count": s.count}) |
| 114 | if method == "GET" and self.path == "/_stub/state": |
| 115 | return self.reply(200, {"issues": s.issues, "pulls": s.pulls, "refs": s.refs, |
| 116 | "log": s.log, "mode": s.mode, "count": s.count}) |
| 117 | return self.reply(404, {"message": "Not Found"}) |
| 118 | |
| 119 | def injected(self): |
| 120 | """The failure to answer with, if one is armed.""" |
| 121 | s = self.server |
| 122 | with s.lock: |
| 123 | if s.mode == "ok" or s.count == 0: |
| 124 | return None |
| 125 | if s.count > 0: |
| 126 | s.count -= 1 |
| 127 | return s.mode |
| 128 | |
| 129 | def handle_one(self, method): |
| 130 | s = self.server |
| 131 | n = int(self.headers.get("Content-Length") or 0) |
| 132 | body = json.loads(self.rfile.read(n)) if n else None |
| 133 | if self.path.startswith("/_stub/"): |
| 134 | return self.control(method, body or {}) |
| 135 | entry = {"t": round(time.time(), 3), "method": method, "path": self.path, |
| 136 | "auth_ok": self.headers.get("Authorization") == "Bearer " + s.token} |
| 137 | if method == "POST" and isinstance(body, dict) and "title" in body: |
| 138 | entry["title"] = body["title"] |
| 139 | self.entry = entry |
| 140 | status = self.route(method, body, entry) |
| 141 | if self.entry is not None: # route answered without reply() |
| 142 | self.entry = None |
| 143 | entry["status"] = status |
| 144 | s.record(entry) |
| 145 | |
| 146 | def route(self, method, body, entry): |
| 147 | s = self.server |
| 148 | if s.redirect: |
| 149 | return self.reply(302, headers=[("Location", s.redirect)]) |
| 150 | if not entry["auth_ok"]: |
| 151 | return self.reply(401, {"message": "Bad credentials"}) |
| 152 | fail = self.injected() |
| 153 | if fail: |
| 154 | entry["injected"] = fail |
| 155 | if fail == "timeout": |
| 156 | time.sleep(s.hold) |
| 157 | return self.reply(504, {"message": "held"}) |
| 158 | code = int(fail) |
| 159 | msg = {401: "Bad credentials", 403: "Resource not accessible by personal access token", |
| 160 | 429: "API rate limit exceeded"}.get(code, "Server Error") |
| 161 | return self.reply(code, {"message": msg}) |
| 162 | pre = "/repos/%s/" % REPO |
| 163 | if not self.path.startswith(pre): |
| 164 | return self.reply(404, {"message": "Not Found"}) |
| 165 | rest = self.path[len(pre):] |
| 166 | with s.lock: |
| 167 | if method == "GET" and rest.startswith("labels/"): |
| 168 | name = urllib.parse.unquote(rest[7:]) |
| 169 | if name in s.labels: |
| 170 | return self.reply(200, {"name": name}) |
| 171 | return self.reply(404, {"message": "Not Found"}) |
| 172 | if method == "POST" and rest == "labels": |
| 173 | s.labels.add(body["name"]) |
| 174 | return self.reply(201, {"name": body["name"]}) |
| 175 | if method == "GET" and rest.startswith("git/ref/heads/"): |
| 176 | ref = "refs/heads/" + rest[len("git/ref/heads/"):] |
| 177 | if ref in s.refs: |
| 178 | return self.reply(200, {"ref": ref, "object": {"sha": s.refs[ref]}}) |
| 179 | return self.reply(404, {"message": "Not Found"}) |
| 180 | if method == "GET" and rest.startswith("git/commits/"): |
| 181 | c = s.commits.get(rest[12:]) |
| 182 | if not c: |
| 183 | return self.reply(404, {"message": "Not Found"}) |
| 184 | return self.reply(200, {"sha": rest[12:], "tree": {"sha": c["tree"]}, "message": c["message"], |
| 185 | "parents": [{"sha": p} for p in c["parents"]]}) |
| 186 | if method == "GET" and rest.startswith("git/trees/"): |
| 187 | t = s.trees.get(rest[10:].split("?", 1)[0]) |
| 188 | if t is None: |
| 189 | return self.reply(404, {"message": "Not Found"}) |
| 190 | dirs = sorted({p.rsplit("/", 1)[0] for p in t if "/" in p}) |
| 191 | tree = [{"path": d, "type": "tree", "sha": "e" * 40} for d in dirs] |
| 192 | tree += [{"path": p, "type": "blob", "mode": "100644", "sha": b} for p, b in sorted(t.items())] |
| 193 | return self.reply(200, {"sha": rest[10:], "tree": tree, "truncated": False}) |
| 194 | if method == "GET" and rest.startswith("git/blobs/"): |
| 195 | b = s.blobs.get(rest[10:]) |
| 196 | if b is None: |
| 197 | return self.reply(404, {"message": "Not Found"}) |
| 198 | return self.reply(200, {"sha": rest[10:], "content": b, "encoding": "base64"}) |
| 199 | if method == "POST" and rest == "git/blobs": |
| 200 | sha = s.new_sha() |
| 201 | s.blobs[sha] = body["content"] |
| 202 | return self.reply(201, {"sha": sha}) |
| 203 | if method == "POST" and rest == "git/trees": |
| 204 | t = dict(s.trees.get(body.get("base_tree"), {})) |
| 205 | for e in body["tree"]: |
| 206 | if e["sha"] is None: |
| 207 | t.pop(e["path"], None) |
| 208 | else: |
| 209 | t[e["path"]] = e["sha"] |
| 210 | for sha, old in s.trees.items(): # same content, same sha, as in git |
| 211 | if old == t: |
| 212 | return self.reply(201, {"sha": sha}) |
| 213 | sha = s.new_sha() |
| 214 | s.trees[sha] = t |
| 215 | return self.reply(201, {"sha": sha}) |
| 216 | if method == "POST" and rest == "git/commits": |
| 217 | sha = s.new_sha() |
| 218 | s.commits[sha] = {"tree": body["tree"], "parents": body["parents"], "message": body["message"]} |
| 219 | return self.reply(201, {"sha": sha}) |
| 220 | if method == "POST" and rest == "git/refs": |
| 221 | if body["ref"] in s.refs: |
| 222 | return self.reply(422, {"message": "Reference already exists"}) |
| 223 | s.refs[body["ref"]] = body["sha"] |
| 224 | return self.reply(201, {"ref": body["ref"]}) |
| 225 | if method == "PATCH" and rest.startswith("git/refs/"): |
| 226 | ref = rest[len("git/"):] |
| 227 | if ref not in s.refs: |
| 228 | return self.reply(422, {"message": "Reference does not exist"}) |
| 229 | if s.refs[ref] not in s.commits.get(body["sha"], {}).get("parents", []): |
| 230 | return self.reply(422, {"message": "Update is not a fast forward"}) |
| 231 | s.refs[ref] = body["sha"] |
| 232 | return self.reply(200, {"ref": ref, "object": {"sha": body["sha"]}}) |
| 233 | if method == "GET" and re.fullmatch(r"pulls/[0-9]+", rest): |
| 234 | for p in s.pulls: |
| 235 | if p["number"] == int(rest[6:]): |
| 236 | return self.reply(200, p) |
| 237 | return self.reply(404, {"message": "Not Found"}) |
| 238 | if method == "PATCH" and re.fullmatch(r"pulls/[0-9]+", rest): |
| 239 | for p in s.pulls: |
| 240 | if p["number"] == int(rest[6:]): |
| 241 | p.update(body) |
| 242 | return self.reply(200, p) |
| 243 | return self.reply(404, {"message": "Not Found"}) |
| 244 | if method == "GET" and rest.startswith("pulls"): |
| 245 | q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) |
| 246 | head = q.get("head", [""])[0].split(":", 1)[-1] |
| 247 | state = q.get("state", ["open"])[0] |
| 248 | return self.reply(200, [p for p in s.pulls if (not head or p["head"]["ref"] == head) |
| 249 | and state in ("all", p["state"])]) |
| 250 | if method == "POST" and rest == "pulls": |
| 251 | num = s.next_number() |
| 252 | pr = dict(body, number=num, state="open", head={"ref": body["head"]}, base={"ref": body["base"]}, |
| 253 | html_url="https://github.com/%s/pull/%d" % (REPO, num)) |
| 254 | s.pulls.append(pr) |
| 255 | return self.reply(201, pr) |
| 256 | if method == "POST" and re.fullmatch(r"issues/[0-9]+/comments", rest): |
| 257 | s.comments.append(dict(body, number=int(rest.split("/")[1]))) |
| 258 | return self.reply(201, {"id": len(s.comments)}) |
| 259 | if method == "POST" and rest == "issues": |
| 260 | num = s.next_number() |
| 261 | it = dict(body, number=num, html_url="https://github.com/%s/issues/%d" % (REPO, num)) |
| 262 | s.issues.append(it) |
| 263 | return self.reply(201, it) |
| 264 | if method == "GET" and rest.startswith("issues"): |
| 265 | # GitHub's labels= filter: an issue must carry every listed label. |
| 266 | want = [x for x in urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query).get("labels", [""])[0].split(",") if x] |
| 267 | return self.reply(200, [it for it in s.issues |
| 268 | if all(w in (it.get("labels") or []) for w in want)]) |
| 269 | if method == "POST" and rest.startswith("issues/") and rest.endswith("/labels"): |
| 270 | return self.reply(200, [{"name": x} for x in body["labels"]]) |
| 271 | return self.reply(404, {"message": "Not Found"}) |
| 272 | |
| 273 | def do_GET(self): |
| 274 | self.handle_one("GET") |
| 275 | |
| 276 | def do_POST(self): |
| 277 | self.handle_one("POST") |
| 278 | |
| 279 | def do_PATCH(self): |
| 280 | self.handle_one("PATCH") |
| 281 | |
| 282 | def do_PUT(self): |
| 283 | self.handle_one("PUT") |
| 284 | |
| 285 | def do_DELETE(self): |
| 286 | self.handle_one("DELETE") |
| 287 | |
| 288 | |
| 289 | def main(): |
| 290 | p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 291 | p.add_argument("--port", type=int, required=True) |
| 292 | p.add_argument("--token", default=FAKE_PAT) |
| 293 | p.add_argument("--hold", type=float, default=12.0) |
| 294 | p.add_argument("--log") |
| 295 | a = p.parse_args() |
| 296 | s = Stub(a.port, a.token, a.hold, a.log) |
| 297 | print("github_stub listening on %s" % s.base, flush=True) |
| 298 | try: |
| 299 | s.serve_forever() |
| 300 | except KeyboardInterrupt: |
| 301 | pass |
| 302 | return 0 |
| 303 | |
| 304 | |
| 305 | if __name__ == "__main__": |
| 306 | sys.exit(main()) |