#!/usr/bin/env python3 """tests/mockapi.py - a loopback mock of the GitHub REST API. One process serves every endpoint plugin_github calls, so the plugin's real request builders are exercised end to end: GET /user the credential's account GET /repos/{owner}/{repo} repository record (404 for repo "nope") GET /repos/{owner}/{repo}/issues?state= issues array (a PR entry is embedded to prove the PR filter works) POST /repos/{owner}/{repo}/issues creates issue #4221 GET /repos/{owner}/{repo}/pulls/{n} pull request record GET /search/code?q=... code search shape GET /flaky 503 + Retry-After once, then 200 Every request is appended to `--log` as one JSON line *before* the reply is written, recording method, path, query, the Authorization header and the parsed body. The suite compares that record against what each tool's request should have been - a reply-only assertion cannot see a wrong path, a dropped query parameter or a missing credential. The mock also implements the failure paths GitHub has: an unknown repo is 404 {"message":"Not Found"}, a wrong token is 401 with GitHub's own message ("Bad credentials"), a POST without a title is 422 with the errors array, and `?fail=401|403|404|422` forces any endpoint's error shape. Usage: python3 tests/mockapi.py --port 0 --portfile /tmp/p --log /tmp/log.jsonl """ import argparse import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs LOCK = threading.Lock() STATE = {"flaky_hits": 0} # Deliberately not real-looking: a suite that uses plausible PAT text ends up # shipping it in a screenshot one day. GOOD_TOKEN = "GHPAT-MOCK-TOKEN-1" # a second accepted credential: the suite's config-resolution test needs a # stored token that is distinctive (so a leak check can grep for it) AND # valid on the mock STORED_TOKEN = "STORED-TOKEN-AAA" # the token tests/e2e.py types into the page: distinctive (the DOM-leak # assertion greps for it) and valid on the mock E2E_TOKEN = "GHPAT-E2E-SAVED-1" # saving a request whose FIRST answer is a 503 + Retry-After proves the # plugin's single honest retry: this token makes /user flaky exactly once. FLAKY_TOKEN = "GHPAT-MOCK-RETRY-1" VALID_TOKENS = {GOOD_TOKEN, FLAKY_TOKEN, STORED_TOKEN, E2E_TOKEN} def repo(owner, repo_name): return { "id": 123456, "name": repo_name, "full_name": "%s/%s" % (owner, repo_name), "description": "A mocked repository, with \"quotes\" and\nnewlines", "html_url": "https://github.test/%s/%s" % (owner, repo_name), "default_branch": "main", "language": "C", "visibility": "public", "archived": False, "license": {"spdx_id": "MIT"}, "stargazers_count": 1234, "forks_count": 77, "open_issues_count": 9, "pushed_at": "2026-11-01T00:00:00Z", } def issues(owner, repo_name): return [ {"number": 12, "title": "Buffer overflow in parser", "state": "open", "html_url": "https://github.test/%s/%s/issues/12" % (owner, repo_name)}, {"number": 11, "title": "Docs\tTAB and ctrl\x01chars", "state": "open", "html_url": "https://github.test/%s/%s/issues/11" % (owner, repo_name)}, # a pull request embedded in /issues exactly like the real API: {"number": 10, "title": "MUST BE FILTERED (this is a PR)", "state": "open", "pull_request": {"url": "https://api.github.test/x"}, "html_url": "https://github.test/%s/%s/pull/10" % (owner, repo_name)}, ] def pull(owner, repo_name, n): return { "number": int(n), "title": "Add the mocked thing", "state": "open", "html_url": "https://github.test/%s/%s/pull/%s" % (owner, repo_name, n), "user": {"login": "mockuser", "type": "User"}, "head": {"label": "%s:feature" % owner, "ref": "feature"}, "base": {"label": "%s:main" % owner, "ref": "main"}, "draft": False, "merged_at": None, "commits": 3, "comments": 2, "additions": 120, "deletions": 40, "created_at": "2026-11-02T10:00:00Z", } def search(query): return { "total_count": 137, "incomplete_results": False, "items": [ {"name": "thing.c", "path": "src/thing.c", "html_url": "https://github.test/acme/widgets/blob/main/src/thing.c", "repository": {"full_name": "acme/widgets"}}, {"name": "thing.h", "path": "include/thing.h", "html_url": "https://github.test/other/thing/blob/main/include/thing.h", "repository": {"full_name": "other/thing"}}, ], } class Handler(BaseHTTPRequestHandler): log_message = lambda *a: None # silence def _reply(self, code, obj): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def _record(self, body_obj): u = urlparse(self.path) rec = { "method": self.command, "path": u.path, "query": {k: v[0] for k, v in parse_qs(u.query).items()}, "auth": self.headers.get("Authorization") or "", "accept": self.headers.get("Accept") or "", "api_version": self.headers.get("X-GitHub-Api-Version") or "", "body": body_obj, } with LOCK: with open(self.logpath, "a") as f: f.write(json.dumps(rec) + "\n") def _check_auth(self, need): auth = self.headers.get("Authorization") or "" if auth[len("Bearer "):] in VALID_TOKENS: return True if need: self._reply(401, {"message": "Bad credentials", "documentation_url": "https://docs.github.test/401"}) return False return True # unauthenticated public reads work like GitHub's public GETs def do_GET(self): self._handle("GET") def do_POST(self): self._handle("POST") def _handle(self, method): u = urlparse(self.path) q = {k: v[0] for k, v in parse_qs(u.query).items()} length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"" try: body_obj = json.loads(raw.decode()) if raw else None except Exception: body_obj = {"__unparseable__": raw.decode(errors="replace")} self._record(body_obj) if q.get("fail"): code = int(q["fail"]) msg = {401: "Bad credentials", 403: "Resource not accessible by integration", 404: "Not Found", 422: "Validation Failed"}.get(code, "Err") self._reply(code, {"message": msg}) return parts = [p for p in u.path.split("/") if p] # The flaky credential 503s its FIRST request (any path) with # Retry-After: 1, then answers normally: exactly the upstream # secondary-rate-limit shape the plugin must survive once. if (self.headers.get("Authorization") or "") == "Bearer " + FLAKY_TOKEN: with LOCK: STATE["flaky_hits"] += 1 hits = STATE["flaky_hits"] if hits == 1: self.send_response(503) self.send_header("Retry-After", "1") self.send_header("Content-Length", "0") self.end_headers() return self._reply(200, {"login": "mockuser", "type": "User", "retry_proved": True}) return # The suite reuses one mock process for the native pass, the CGI # pass and the ASan pass. The flaky counter is process state, so a # reset endpoint is the only way each pass can honestly observe # "the FIRST request 503s" instead of inheriting pass #1's history. if u.path == "/__reset": with LOCK: STATE["flaky_hits"] = 0 self._reply(200, {"ok": True, "flaky_hits": 0}) return if u.path == "/user": if not self._check_auth(True): return self._reply(200, {"login": "mockuser", "type": "User"}) return if len(parts) == 3 and parts[0] == "repos" and method == "GET": if parts[2] == "nope": self._reply(404, {"message": "Not Found"}) return self._reply(200, repo(parts[1], parts[2])) return if len(parts) >= 4 and parts[0] == "repos": owner, repo_name = parts[1], parts[2] tail = parts[3] if repo_name == "nope": self._reply(404, {"message": "Not Found"}) return if tail == "issues" and method == "GET" and len(parts) == 4: self._reply(200, issues(owner, repo_name)) return if tail == "issues" and method == "POST" and len(parts) == 4: if not self._check_auth(True): return if not body_obj or not body_obj.get("title"): self._reply(422, {"message": "Validation Failed", "errors": [{"message": "title is missing"}]}) return self._reply(201, { "number": 4221, "title": body_obj.get("title"), "state": "open", "html_url": "https://github.test/%s/%s/issues/4221" % (owner, repo_name), }) return if tail == "pulls" and len(parts) == 5 and method == "GET": self._reply(200, pull(owner, repo_name, parts[4])) return if u.path == "/search/code" and method == "GET": if not self._check_auth(True): # /search/code requires auth upstream return self._reply(200, search(q.get("q", ""))) return self._reply(404, {"message": "Not Found"}) def main(): ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=0) ap.add_argument("--portfile", required=True) ap.add_argument("--log", required=True) args = ap.parse_args() srv = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) Handler.logpath = args.log with open(args.portfile, "w") as f: f.write(str(srv.server_address[1])) srv.serve_forever() if __name__ == "__main__": main()