#!/usr/bin/env python3 """tests/e2e.py - viewport and interaction checks for the webhook page. Serves the plugin through a small CGI shim on a loopback port, seeds a store with two hooks, then opens the page with Playwright at 1440 / 1024 / 390 in both themes and asserts: * no console error and no page error at any viewport * scrollWidth <= innerWidth (no horizontal overflow) * the hook table renders one row per stored hook, with its method, endpoint and signature pill - and never a header value or an HMAC secret * the delivery log renders the requests the page itself fired * a hook can be created, test-fired and deleted entirely through the UI * the fly-out editor opens, keeps a stored secret when its value is blank, and refuses a hook with no name * the theme toggle flips data-theme and the bot tokens follow * screenshots land in docs/ for the README Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays dependency-free. Screenshots are written to a temp directory by default and only refreshed in docs/ when --shots is passed (`make e2e`). The PNGs carry the live times of the deliveries the run fires, so regenerating them on every gate run would leave two tracked files dirty and make a history audit that refuses a dirty tree report a violation against an unrelated commit. python3 tests/e2e.py # run if Playwright is available python3 tests/e2e.py --shots # also refresh docs/ui-*.png (commit them) python3 tests/e2e.py --strict # exit 2 when Playwright is missing """ import argparse import http.server import json import os import subprocess import sys import tempfile import threading import time from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_webhook") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] PWD = "e2e-password" FAILS = [] TMP = tempfile.mkdtemp(prefix="webhook-e2e-") STORE = os.path.join(TMP, "hooks.json") RECV_LOG = os.path.join(TMP, "recv.jsonl") RECV = {"port": None, "proc": None} def ok(desc): print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) def cgi(query, method="GET", payload=None, pwd=PWD): env = dict(os.environ) env["QUERY_STRING"] = query env["REQUEST_METHOD"] = method env["WEBHOOK_STORE_PATH"] = STORE env["WEBHOOK_ALLOW_PRIVATE"] = "1" # the recorder is on 127.0.0.1 env["BOT_PASSWORD"] = PWD if pwd: env["HTTP_X_BOT_PASSWORD"] = pwd data = payload if isinstance(payload, bytes) else ( json.dumps(payload).encode() if payload is not None else b"") env["CONTENT_LENGTH"] = str(len(data)) out = subprocess.run([BIN], input=data, capture_output=True, env=env, timeout=90).stdout sep = out.find(b"\r\n\r\n") body = out[sep + 4:] if sep >= 0 else out try: return json.loads(body) except ValueError: return {"raw": body.decode("utf-8", "replace")} def seed(): hooks = [ { "name": "deploy-note", "url": "http://127.0.0.1:%d/hook" % RECV["port"], "method": "POST", "desc": "Deploy notification", "sig": "github", "secret": "e2e-hmac-secret", "headers": [ {"name": "Authorization", "value": "Bearer e2e-token"}, {"name": "X-Custom", "value": "alpha"}, ], }, { "name": "status-probe", "url": "http://127.0.0.1:%d/echo?tenant=acme" % RECV["port"], "method": "PUT", "desc": "Probe with a pasted token", "headers": [], }, ] for h in hooks: r = cgi("action=save", "POST", h) if not r.get("ok"): bad("seed %s" % h["name"], r) class Handler(http.server.BaseHTTPRequestHandler): def _run(self, method): u = urlparse(self.path) length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env["WEBHOOK_STORE_PATH"] = STORE env["WEBHOOK_ALLOW_PRIVATE"] = "1" env.pop("BOT_PASSWORD", None) # the page's own pwd= is what gates it env["CONTENT_LENGTH"] = str(len(body)) out = subprocess.run([BIN], input=body, capture_output=True, env=env, timeout=90).stdout sep = out.find(b"\r\n\r\n") headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" payload = out[sep + 4:] if sep >= 0 else out status = 200 ctype = "application/json; charset=utf-8" for line in headers.splitlines(): low = line.lower() if low.startswith("content-type:"): ctype = line.split(":", 1)[1].strip() elif low.startswith("status:"): try: status = int(line.split(":", 1)[1].strip().split()[0]) except (IndexError, ValueError): status = 200 self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def do_GET(self): # noqa: N802 self._run("GET") def do_POST(self): # noqa: N802 self._run("POST") def log_message(self, *_a): pass def start_recorder(): proc = subprocess.Popen( [sys.executable, os.path.join(ROOT, "tests", "mockrecv.py"), "--port", "0", "--log", RECV_LOG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) line = proc.stdout.readline().strip() if not line.startswith("PORT "): raise RuntimeError("the recording receiver did not start: %r" % line) RECV["port"] = int(line.split()[1]) RECV["proc"] = proc def record_count(): try: with open(RECV_LOG, encoding="utf-8") as f: return len([l for l in f if l.strip()]) except OSError: return 0 def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") ap.add_argument("--shots", action="store_true", help="refresh docs/ui-*.png (they are committed artefacts)") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except ImportError: print("playwright not installed - skipping the viewport suite") return 2 if args.strict else 0 if not os.access(BIN, os.X_OK): bad("plugin_webhook binary is missing (run make first)") return 1 global DOCS if not args.shots: DOCS = tempfile.mkdtemp(prefix="webhook-shots-") os.makedirs(DOCS, exist_ok=True) start_recorder() seed() srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/plugin_webhook?pwd=%s" % (port, PWD) try: with sync_playwright() as p: browser = p.chromium.launch() for theme in THEMES: for w, h in VIEWPORTS: tag = "%dx%d-%s" % (w, h, theme) page = browser.new_page(viewport={"width": w, "height": h}) errors, page_errors = [], [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: page_errors.append(str(e))) page.add_init_script( "try{localStorage.setItem('bot_theme','%s')}catch(e){}" % theme) page.goto(base + "&theme=" + theme, wait_until="load") page.wait_for_function( "document.getElementById('count').textContent !== '0'", timeout=15000) if page_errors: bad("%s: page error %r" % (tag, page_errors)) else: ok("%s: no page error" % tag) if errors: bad("%s: console errors %r" % (tag, errors[:2])) else: ok("%s: no console error" % tag) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") if sw <= iw: ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw)) else: bad("%s: overflow %d > %d" % (tag, sw, iw)) applied = page.evaluate( "document.documentElement.getAttribute('data-theme')") if applied == theme: ok("%s: the requested theme is applied before first paint" % tag) else: bad("%s: data-theme is %r" % (tag, applied)) # Both seeded hooks render with their method and endpoint. rows = page.eval_on_selector_all( "#rows tr", "els => els.map(e => e.innerText)") if len(rows) == 2: ok("%s: two hook rows rendered" % tag) else: bad("%s: %d hook rows rendered" % (tag, len(rows))) joined = "\n".join(rows) for want in ("deploy-note", "status-probe", "POST", "PUT"): if want in joined: ok("%s: the table shows %s" % (tag, want)) else: bad("%s: the table is missing %s" % (tag, want)) if "github" in joined: ok("%s: the signature pill rendered" % tag) else: bad("%s: no signature pill in %r" % (tag, joined[:200])) # The pasted query token is redacted on the page, and the # secret header value is nowhere in the DOM. html = page.content() if "tenant=acme" in html: bad("%s: the stored query string was rendered" % tag) else: ok("%s: the stored query string is redacted on the page" % tag) if "Bearer e2e-token" in html: bad("%s: the stored header value is in the DOM" % tag) else: ok("%s: the stored header value is not in the DOM" % tag) if "e2e-hmac-secret" in html: bad("%s: the stored HMAC secret is in the DOM" % tag) else: ok("%s: the stored HMAC secret is not in the DOM" % tag) # Fire the seeded hook from the page. before = record_count() page.select_option("#fFire", "deploy-note") page.fill("#fPayload", '{"event":"e2e","n":1}') page.click("#btnFire") page.wait_for_function( "document.getElementById('fireOut').textContent.indexOf('status')>=0", timeout=20000) out = page.inner_text("#fireOut") if '"status": 200' in out.replace('"status":200', '"status": 200'): ok("%s: the test fire reported HTTP 200" % tag) else: bad("%s: fire output %r" % (tag, out[:200])) if record_count() > before: ok("%s: the receiver got the request" % tag) else: bad("%s: the receiver recorded nothing" % tag) # The delivery log picked it up. page.wait_for_function( "document.getElementById('logRows').innerText.indexOf('deploy-note')>=0", timeout=15000) logtext = page.inner_text("#logRows") if "200" in logtext: ok("%s: the delivery log shows the 200" % tag) else: bad("%s: delivery log %r" % (tag, logtext[:200])) # Editor: keeps a stored secret when its value is blank. page.click("#rows tr:first-child button:has-text('Edit')") page.wait_for_selector("#editor .row", timeout=5000) ph = page.get_attribute("#fSecret", "placeholder") or "" if "stored" in ph: ok("%s: editing says the HMAC secret is stored" % tag) else: bad("%s: secret placeholder is %r" % (tag, ph)) hdr_ph = page.eval_on_selector_all( ".hdr-value", "els => els.map(e => e.placeholder)") if any("stored" in (x or "") for x in hdr_ph): ok("%s: a stored header says its value is kept" % tag) else: bad("%s: header placeholders %r" % (tag, hdr_ph)) page.click("#btnCancel") page.wait_for_selector("#editor", state="hidden", timeout=5000) ok("%s: the editor closes on Cancel" % tag) shot = os.path.join(DOCS, "ui-%s.png" % tag) page.screenshot(path=shot, full_page=True) size = os.path.getsize(shot) if size < 900 * 1024: ok("%s: screenshot written (%d bytes)" % (tag, size)) else: bad("%s: screenshot is %d bytes" % (tag, size)) page.close() # --------------------------------------------------------------- # One deeper interaction pass at desktop size. # --------------------------------------------------------------- page = browser.new_page(viewport={"width": 1440, "height": 900}) page.goto(base, wait_until="load") page.wait_for_function( "document.getElementById('count').textContent !== '0'", timeout=15000) # The theme toggle flips the attribute. page.click("#themeToggle") flipped = page.evaluate( "document.documentElement.getAttribute('data-theme')") if flipped in ("dark", "light"): ok("the theme toggle flips data-theme (%s)" % flipped) else: bad("the theme toggle left data-theme at %r" % flipped) # A hook with no name is refused client-side. page.click("#btnNew") page.wait_for_selector("#editor .row", timeout=5000) page.fill("#fUrl", "https://example.com/hook") page.click("#btnSave") msg = page.inner_text("#saveMsg") if "name" in msg.lower(): ok("the editor refuses a hook with no name (%s)" % msg) else: bad("the editor accepted a nameless hook (msg %r)" % msg) # Create a hook from the UI, fire it, then delete it. page.fill("#fName", "e2e-created") page.fill("#fUrl", "http://127.0.0.1:%d/hook" % RECV["port"]) page.select_option("#fMethod", "POST") page.fill("#fDesc", "made by the e2e suite") page.click("#btnSave") page.wait_for_function( "document.getElementById('rows').innerText.indexOf('e2e-created')>=0", timeout=15000) ok("a hook created in the UI appears in the table") page.select_option("#fFire", "e2e-created") page.fill("#fPayload", '{"from":"ui"}') page.click("#btnFire") page.wait_for_function( "document.getElementById('fireOut').textContent.indexOf('200')>=0", timeout=20000) ok("the UI-created hook fires") page.on("dialog", lambda d: d.accept()) # no confirm() in the page, but harmless page.click("#rows tr:has-text('e2e-created') button:has-text('Delete')") page.wait_for_function( "document.getElementById('rows').innerText.indexOf('e2e-created')<0", timeout=15000) ok("a hook deleted in the UI disappears from the table") page.close() browser.close() finally: srv.shutdown() if RECV["proc"]: RECV["proc"].terminate() # The shim deliberately runs the plugin with no BOT_PASSWORD (so the page's # own ?pwd= is what the browser exercises). The auth gate is asserted # through the CGI path, where a password IS set. env = dict(os.environ) env["WEBHOOK_STORE_PATH"] = STORE env["BOT_PASSWORD"] = PWD env["QUERY_STRING"] = "action=list" out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout if out.startswith(b"Status: 401"): ok("an unauthenticated action answers 401") else: bad("unauthenticated action answered %r" % out[:80]) if FAILS: print("\n%d failure(s)" % len(FAILS)) return 1 print("\nall e2e checks passed") return 0 if __name__ == "__main__": sys.exit(main())