| 1 | #!/usr/bin/env python3 |
| 2 | """tests/e2e.py - viewport and interaction checks for the webhook page. |
| 3 | |
| 4 | Serves the plugin through a small CGI shim on a loopback port, seeds a store |
| 5 | with two hooks, then opens the page with Playwright at 1440 / 1024 / 390 in both |
| 6 | themes and asserts: |
| 7 | |
| 8 | * no console error and no page error at any viewport |
| 9 | * scrollWidth <= innerWidth (no horizontal overflow) |
| 10 | * the hook table renders one row per stored hook, with its method, endpoint |
| 11 | and signature pill - and never a header value or an HMAC secret |
| 12 | * the delivery log renders the requests the page itself fired |
| 13 | * a hook can be created, test-fired and deleted entirely through the UI |
| 14 | * the fly-out editor opens, keeps a stored secret when its value is blank, |
| 15 | and refuses a hook with no name |
| 16 | * the theme toggle flips data-theme and the bot tokens follow |
| 17 | * screenshots land in docs/ for the README |
| 18 | |
| 19 | Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays |
| 20 | dependency-free. |
| 21 | |
| 22 | Screenshots are written to a temp directory by default and only refreshed in |
| 23 | docs/ when --shots is passed (`make e2e`). The PNGs carry the live times of the |
| 24 | deliveries the run fires, so regenerating them on every gate run would leave two |
| 25 | tracked files dirty and make a history audit that refuses a dirty tree report a |
| 26 | violation against an unrelated commit. |
| 27 | |
| 28 | python3 tests/e2e.py # run if Playwright is available |
| 29 | python3 tests/e2e.py --shots # also refresh docs/ui-*.png (commit them) |
| 30 | python3 tests/e2e.py --strict # exit 2 when Playwright is missing |
| 31 | """ |
| 32 | |
| 33 | import argparse |
| 34 | import http.server |
| 35 | import json |
| 36 | import os |
| 37 | import subprocess |
| 38 | import sys |
| 39 | import tempfile |
| 40 | import threading |
| 41 | import time |
| 42 | from urllib.parse import urlparse |
| 43 | |
| 44 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 45 | BIN = os.path.join(ROOT, "plugin_webhook") |
| 46 | DOCS = os.path.join(ROOT, "docs") |
| 47 | VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] |
| 48 | THEMES = ["dark", "light"] |
| 49 | PWD = "e2e-password" |
| 50 | |
| 51 | FAILS = [] |
| 52 | TMP = tempfile.mkdtemp(prefix="webhook-e2e-") |
| 53 | STORE = os.path.join(TMP, "hooks.json") |
| 54 | RECV_LOG = os.path.join(TMP, "recv.jsonl") |
| 55 | |
| 56 | RECV = {"port": None, "proc": None} |
| 57 | |
| 58 | |
| 59 | def ok(desc): |
| 60 | print(" ok %s" % desc) |
| 61 | |
| 62 | |
| 63 | def bad(desc, detail=""): |
| 64 | FAILS.append(desc) |
| 65 | print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) |
| 66 | |
| 67 | |
| 68 | def cgi(query, method="GET", payload=None, pwd=PWD): |
| 69 | env = dict(os.environ) |
| 70 | env["QUERY_STRING"] = query |
| 71 | env["REQUEST_METHOD"] = method |
| 72 | env["WEBHOOK_STORE_PATH"] = STORE |
| 73 | env["WEBHOOK_ALLOW_PRIVATE"] = "1" # the recorder is on 127.0.0.1 |
| 74 | env["BOT_PASSWORD"] = PWD |
| 75 | if pwd: |
| 76 | env["HTTP_X_BOT_PASSWORD"] = pwd |
| 77 | data = payload if isinstance(payload, bytes) else ( |
| 78 | json.dumps(payload).encode() if payload is not None else b"") |
| 79 | env["CONTENT_LENGTH"] = str(len(data)) |
| 80 | out = subprocess.run([BIN], input=data, capture_output=True, env=env, |
| 81 | timeout=90).stdout |
| 82 | sep = out.find(b"\r\n\r\n") |
| 83 | body = out[sep + 4:] if sep >= 0 else out |
| 84 | try: |
| 85 | return json.loads(body) |
| 86 | except ValueError: |
| 87 | return {"raw": body.decode("utf-8", "replace")} |
| 88 | |
| 89 | |
| 90 | def seed(): |
| 91 | hooks = [ |
| 92 | { |
| 93 | "name": "deploy-note", |
| 94 | "url": "http://127.0.0.1:%d/hook" % RECV["port"], |
| 95 | "method": "POST", |
| 96 | "desc": "Deploy notification", |
| 97 | "sig": "github", |
| 98 | "secret": "e2e-hmac-secret", |
| 99 | "headers": [ |
| 100 | {"name": "Authorization", "value": "Bearer e2e-token"}, |
| 101 | {"name": "X-Custom", "value": "alpha"}, |
| 102 | ], |
| 103 | }, |
| 104 | { |
| 105 | "name": "status-probe", |
| 106 | "url": "http://127.0.0.1:%d/echo?tenant=acme" % RECV["port"], |
| 107 | "method": "PUT", |
| 108 | "desc": "Probe with a pasted token", |
| 109 | "headers": [], |
| 110 | }, |
| 111 | ] |
| 112 | for h in hooks: |
| 113 | r = cgi("action=save", "POST", h) |
| 114 | if not r.get("ok"): |
| 115 | bad("seed %s" % h["name"], r) |
| 116 | |
| 117 | |
| 118 | class Handler(http.server.BaseHTTPRequestHandler): |
| 119 | def _run(self, method): |
| 120 | u = urlparse(self.path) |
| 121 | length = int(self.headers.get("Content-Length") or 0) |
| 122 | body = self.rfile.read(length) if length else b"" |
| 123 | env = dict(os.environ) |
| 124 | env["QUERY_STRING"] = u.query |
| 125 | env["REQUEST_METHOD"] = method |
| 126 | env["WEBHOOK_STORE_PATH"] = STORE |
| 127 | env["WEBHOOK_ALLOW_PRIVATE"] = "1" |
| 128 | env.pop("BOT_PASSWORD", None) # the page's own pwd= is what gates it |
| 129 | env["CONTENT_LENGTH"] = str(len(body)) |
| 130 | out = subprocess.run([BIN], input=body, capture_output=True, env=env, |
| 131 | timeout=90).stdout |
| 132 | sep = out.find(b"\r\n\r\n") |
| 133 | headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" |
| 134 | payload = out[sep + 4:] if sep >= 0 else out |
| 135 | status = 200 |
| 136 | ctype = "application/json; charset=utf-8" |
| 137 | for line in headers.splitlines(): |
| 138 | low = line.lower() |
| 139 | if low.startswith("content-type:"): |
| 140 | ctype = line.split(":", 1)[1].strip() |
| 141 | elif low.startswith("status:"): |
| 142 | try: |
| 143 | status = int(line.split(":", 1)[1].strip().split()[0]) |
| 144 | except (IndexError, ValueError): |
| 145 | status = 200 |
| 146 | self.send_response(status) |
| 147 | self.send_header("Content-Type", ctype) |
| 148 | self.send_header("Cache-Control", "no-store") |
| 149 | self.send_header("Content-Length", str(len(payload))) |
| 150 | self.end_headers() |
| 151 | self.wfile.write(payload) |
| 152 | |
| 153 | def do_GET(self): # noqa: N802 |
| 154 | self._run("GET") |
| 155 | |
| 156 | def do_POST(self): # noqa: N802 |
| 157 | self._run("POST") |
| 158 | |
| 159 | def log_message(self, *_a): |
| 160 | pass |
| 161 | |
| 162 | |
| 163 | def start_recorder(): |
| 164 | proc = subprocess.Popen( |
| 165 | [sys.executable, os.path.join(ROOT, "tests", "mockrecv.py"), |
| 166 | "--port", "0", "--log", RECV_LOG], |
| 167 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) |
| 168 | line = proc.stdout.readline().strip() |
| 169 | if not line.startswith("PORT "): |
| 170 | raise RuntimeError("the recording receiver did not start: %r" % line) |
| 171 | RECV["port"] = int(line.split()[1]) |
| 172 | RECV["proc"] = proc |
| 173 | |
| 174 | |
| 175 | def record_count(): |
| 176 | try: |
| 177 | with open(RECV_LOG, encoding="utf-8") as f: |
| 178 | return len([l for l in f if l.strip()]) |
| 179 | except OSError: |
| 180 | return 0 |
| 181 | |
| 182 | |
| 183 | def main(): |
| 184 | ap = argparse.ArgumentParser() |
| 185 | ap.add_argument("--strict", action="store_true") |
| 186 | ap.add_argument("--shots", action="store_true", |
| 187 | help="refresh docs/ui-*.png (they are committed artefacts)") |
| 188 | args = ap.parse_args() |
| 189 | |
| 190 | try: |
| 191 | from playwright.sync_api import sync_playwright |
| 192 | except ImportError: |
| 193 | print("playwright not installed - skipping the viewport suite") |
| 194 | return 2 if args.strict else 0 |
| 195 | |
| 196 | if not os.access(BIN, os.X_OK): |
| 197 | bad("plugin_webhook binary is missing (run make first)") |
| 198 | return 1 |
| 199 | |
| 200 | global DOCS |
| 201 | if not args.shots: |
| 202 | DOCS = tempfile.mkdtemp(prefix="webhook-shots-") |
| 203 | os.makedirs(DOCS, exist_ok=True) |
| 204 | start_recorder() |
| 205 | seed() |
| 206 | |
| 207 | srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 208 | port = srv.server_address[1] |
| 209 | threading.Thread(target=srv.serve_forever, daemon=True).start() |
| 210 | base = "http://127.0.0.1:%d/plugin_webhook?pwd=%s" % (port, PWD) |
| 211 | |
| 212 | try: |
| 213 | with sync_playwright() as p: |
| 214 | browser = p.chromium.launch() |
| 215 | for theme in THEMES: |
| 216 | for w, h in VIEWPORTS: |
| 217 | tag = "%dx%d-%s" % (w, h, theme) |
| 218 | page = browser.new_page(viewport={"width": w, "height": h}) |
| 219 | errors, page_errors = [], [] |
| 220 | page.on("console", lambda m: errors.append(m.text) |
| 221 | if m.type == "error" else None) |
| 222 | page.on("pageerror", lambda e: page_errors.append(str(e))) |
| 223 | page.add_init_script( |
| 224 | "try{localStorage.setItem('bot_theme','%s')}catch(e){}" % theme) |
| 225 | page.goto(base + "&theme=" + theme, wait_until="load") |
| 226 | page.wait_for_function( |
| 227 | "document.getElementById('count').textContent !== '0'", |
| 228 | timeout=15000) |
| 229 | |
| 230 | if page_errors: |
| 231 | bad("%s: page error %r" % (tag, page_errors)) |
| 232 | else: |
| 233 | ok("%s: no page error" % tag) |
| 234 | if errors: |
| 235 | bad("%s: console errors %r" % (tag, errors[:2])) |
| 236 | else: |
| 237 | ok("%s: no console error" % tag) |
| 238 | |
| 239 | sw = page.evaluate("document.documentElement.scrollWidth") |
| 240 | iw = page.evaluate("window.innerWidth") |
| 241 | if sw <= iw: |
| 242 | ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw)) |
| 243 | else: |
| 244 | bad("%s: overflow %d > %d" % (tag, sw, iw)) |
| 245 | |
| 246 | applied = page.evaluate( |
| 247 | "document.documentElement.getAttribute('data-theme')") |
| 248 | if applied == theme: |
| 249 | ok("%s: the requested theme is applied before first paint" % tag) |
| 250 | else: |
| 251 | bad("%s: data-theme is %r" % (tag, applied)) |
| 252 | |
| 253 | # Both seeded hooks render with their method and endpoint. |
| 254 | rows = page.eval_on_selector_all( |
| 255 | "#rows tr", "els => els.map(e => e.innerText)") |
| 256 | if len(rows) == 2: |
| 257 | ok("%s: two hook rows rendered" % tag) |
| 258 | else: |
| 259 | bad("%s: %d hook rows rendered" % (tag, len(rows))) |
| 260 | joined = "\n".join(rows) |
| 261 | for want in ("deploy-note", "status-probe", "POST", "PUT"): |
| 262 | if want in joined: |
| 263 | ok("%s: the table shows %s" % (tag, want)) |
| 264 | else: |
| 265 | bad("%s: the table is missing %s" % (tag, want)) |
| 266 | if "github" in joined: |
| 267 | ok("%s: the signature pill rendered" % tag) |
| 268 | else: |
| 269 | bad("%s: no signature pill in %r" % (tag, joined[:200])) |
| 270 | |
| 271 | # The pasted query token is redacted on the page, and the |
| 272 | # secret header value is nowhere in the DOM. |
| 273 | html = page.content() |
| 274 | if "tenant=acme" in html: |
| 275 | bad("%s: the stored query string was rendered" % tag) |
| 276 | else: |
| 277 | ok("%s: the stored query string is redacted on the page" % tag) |
| 278 | if "Bearer e2e-token" in html: |
| 279 | bad("%s: the stored header value is in the DOM" % tag) |
| 280 | else: |
| 281 | ok("%s: the stored header value is not in the DOM" % tag) |
| 282 | if "e2e-hmac-secret" in html: |
| 283 | bad("%s: the stored HMAC secret is in the DOM" % tag) |
| 284 | else: |
| 285 | ok("%s: the stored HMAC secret is not in the DOM" % tag) |
| 286 | |
| 287 | # Fire the seeded hook from the page. |
| 288 | before = record_count() |
| 289 | page.select_option("#fFire", "deploy-note") |
| 290 | page.fill("#fPayload", '{"event":"e2e","n":1}') |
| 291 | page.click("#btnFire") |
| 292 | page.wait_for_function( |
| 293 | "document.getElementById('fireOut').textContent.indexOf('status')>=0", |
| 294 | timeout=20000) |
| 295 | out = page.inner_text("#fireOut") |
| 296 | if '"status": 200' in out.replace('"status":200', '"status": 200'): |
| 297 | ok("%s: the test fire reported HTTP 200" % tag) |
| 298 | else: |
| 299 | bad("%s: fire output %r" % (tag, out[:200])) |
| 300 | if record_count() > before: |
| 301 | ok("%s: the receiver got the request" % tag) |
| 302 | else: |
| 303 | bad("%s: the receiver recorded nothing" % tag) |
| 304 | |
| 305 | # The delivery log picked it up. |
| 306 | page.wait_for_function( |
| 307 | "document.getElementById('logRows').innerText.indexOf('deploy-note')>=0", |
| 308 | timeout=15000) |
| 309 | logtext = page.inner_text("#logRows") |
| 310 | if "200" in logtext: |
| 311 | ok("%s: the delivery log shows the 200" % tag) |
| 312 | else: |
| 313 | bad("%s: delivery log %r" % (tag, logtext[:200])) |
| 314 | |
| 315 | # Editor: keeps a stored secret when its value is blank. |
| 316 | page.click("#rows tr:first-child button:has-text('Edit')") |
| 317 | page.wait_for_selector("#editor .row", timeout=5000) |
| 318 | ph = page.get_attribute("#fSecret", "placeholder") or "" |
| 319 | if "stored" in ph: |
| 320 | ok("%s: editing says the HMAC secret is stored" % tag) |
| 321 | else: |
| 322 | bad("%s: secret placeholder is %r" % (tag, ph)) |
| 323 | hdr_ph = page.eval_on_selector_all( |
| 324 | ".hdr-value", "els => els.map(e => e.placeholder)") |
| 325 | if any("stored" in (x or "") for x in hdr_ph): |
| 326 | ok("%s: a stored header says its value is kept" % tag) |
| 327 | else: |
| 328 | bad("%s: header placeholders %r" % (tag, hdr_ph)) |
| 329 | page.click("#btnCancel") |
| 330 | page.wait_for_selector("#editor", state="hidden", timeout=5000) |
| 331 | ok("%s: the editor closes on Cancel" % tag) |
| 332 | |
| 333 | shot = os.path.join(DOCS, "ui-%s.png" % tag) |
| 334 | page.screenshot(path=shot, full_page=True) |
| 335 | size = os.path.getsize(shot) |
| 336 | if size < 900 * 1024: |
| 337 | ok("%s: screenshot written (%d bytes)" % (tag, size)) |
| 338 | else: |
| 339 | bad("%s: screenshot is %d bytes" % (tag, size)) |
| 340 | page.close() |
| 341 | |
| 342 | # --------------------------------------------------------------- |
| 343 | # One deeper interaction pass at desktop size. |
| 344 | # --------------------------------------------------------------- |
| 345 | page = browser.new_page(viewport={"width": 1440, "height": 900}) |
| 346 | page.goto(base, wait_until="load") |
| 347 | page.wait_for_function( |
| 348 | "document.getElementById('count').textContent !== '0'", timeout=15000) |
| 349 | |
| 350 | # The theme toggle flips the attribute. |
| 351 | page.click("#themeToggle") |
| 352 | flipped = page.evaluate( |
| 353 | "document.documentElement.getAttribute('data-theme')") |
| 354 | if flipped in ("dark", "light"): |
| 355 | ok("the theme toggle flips data-theme (%s)" % flipped) |
| 356 | else: |
| 357 | bad("the theme toggle left data-theme at %r" % flipped) |
| 358 | |
| 359 | # A hook with no name is refused client-side. |
| 360 | page.click("#btnNew") |
| 361 | page.wait_for_selector("#editor .row", timeout=5000) |
| 362 | page.fill("#fUrl", "https://example.com/hook") |
| 363 | page.click("#btnSave") |
| 364 | msg = page.inner_text("#saveMsg") |
| 365 | if "name" in msg.lower(): |
| 366 | ok("the editor refuses a hook with no name (%s)" % msg) |
| 367 | else: |
| 368 | bad("the editor accepted a nameless hook (msg %r)" % msg) |
| 369 | |
| 370 | # Create a hook from the UI, fire it, then delete it. |
| 371 | page.fill("#fName", "e2e-created") |
| 372 | page.fill("#fUrl", "http://127.0.0.1:%d/hook" % RECV["port"]) |
| 373 | page.select_option("#fMethod", "POST") |
| 374 | page.fill("#fDesc", "made by the e2e suite") |
| 375 | page.click("#btnSave") |
| 376 | page.wait_for_function( |
| 377 | "document.getElementById('rows').innerText.indexOf('e2e-created')>=0", |
| 378 | timeout=15000) |
| 379 | ok("a hook created in the UI appears in the table") |
| 380 | |
| 381 | page.select_option("#fFire", "e2e-created") |
| 382 | page.fill("#fPayload", '{"from":"ui"}') |
| 383 | page.click("#btnFire") |
| 384 | page.wait_for_function( |
| 385 | "document.getElementById('fireOut').textContent.indexOf('200')>=0", |
| 386 | timeout=20000) |
| 387 | ok("the UI-created hook fires") |
| 388 | |
| 389 | page.on("dialog", lambda d: d.accept()) # no confirm() in the page, but harmless |
| 390 | page.click("#rows tr:has-text('e2e-created') button:has-text('Delete')") |
| 391 | page.wait_for_function( |
| 392 | "document.getElementById('rows').innerText.indexOf('e2e-created')<0", |
| 393 | timeout=15000) |
| 394 | ok("a hook deleted in the UI disappears from the table") |
| 395 | |
| 396 | page.close() |
| 397 | browser.close() |
| 398 | finally: |
| 399 | srv.shutdown() |
| 400 | if RECV["proc"]: |
| 401 | RECV["proc"].terminate() |
| 402 | |
| 403 | # The shim deliberately runs the plugin with no BOT_PASSWORD (so the page's |
| 404 | # own ?pwd= is what the browser exercises). The auth gate is asserted |
| 405 | # through the CGI path, where a password IS set. |
| 406 | env = dict(os.environ) |
| 407 | env["WEBHOOK_STORE_PATH"] = STORE |
| 408 | env["BOT_PASSWORD"] = PWD |
| 409 | env["QUERY_STRING"] = "action=list" |
| 410 | out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout |
| 411 | if out.startswith(b"Status: 401"): |
| 412 | ok("an unauthenticated action answers 401") |
| 413 | else: |
| 414 | bad("unauthenticated action answered %r" % out[:80]) |
| 415 | |
| 416 | if FAILS: |
| 417 | print("\n%d failure(s)" % len(FAILS)) |
| 418 | return 1 |
| 419 | print("\nall e2e checks passed") |
| 420 | return 0 |
| 421 | |
| 422 | |
| 423 | if __name__ == "__main__": |
| 424 | sys.exit(main()) |