| 1 | #!/usr/bin/env python3 |
| 2 | """tests/e2e.py - viewport + interaction checks for the filesystem plugin page. |
| 3 | |
| 4 | Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens |
| 5 | it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: |
| 6 | |
| 7 | * no console error and no page error at any viewport |
| 8 | * scrollWidth <= innerWidth (no horizontal overflow) |
| 9 | * the four panels really render: status, allowed directories, tool |
| 10 | permissions, sandbox tester, registration snippet |
| 11 | * adding a directory through the UI lands in roots.json and re-renders |
| 12 | * removing it through the UI takes it back out |
| 13 | * a tool toggle round-trips through the API and the switch repaints |
| 14 | * the sandbox tester answers ALLOWED and REFUSED with a reason |
| 15 | * the rendered page has a stylesheet and a working inline script |
| 16 | |
| 17 | Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays |
| 18 | dependency-free. |
| 19 | |
| 20 | python3 tests/e2e.py # run if Playwright is available |
| 21 | python3 tests/e2e.py --strict # exit 2 when Playwright is missing |
| 22 | """ |
| 23 | |
| 24 | import argparse |
| 25 | import http.server |
| 26 | import json |
| 27 | import os |
| 28 | import shutil |
| 29 | import socketserver |
| 30 | import subprocess |
| 31 | import sys |
| 32 | import tempfile |
| 33 | import threading |
| 34 | import time |
| 35 | from urllib.parse import urlparse, quote |
| 36 | |
| 37 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 38 | BIN = os.path.join(ROOT, "plugin_filesystem") |
| 39 | DOCS = os.path.join(ROOT, "docs") |
| 40 | VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] |
| 41 | THEMES = ["dark", "light"] |
| 42 | PW = "e2e-node-password" |
| 43 | |
| 44 | |
| 45 | class Handler(http.server.BaseHTTPRequestHandler): |
| 46 | conf_dir = "" |
| 47 | allowed_root = "" |
| 48 | |
| 49 | def _run(self, method): |
| 50 | u = urlparse(self.path) |
| 51 | length = int(self.headers.get("Content-Length") or 0) |
| 52 | if length: |
| 53 | self.rfile.read(length) |
| 54 | env = dict(os.environ) |
| 55 | env["QUERY_STRING"] = u.query |
| 56 | env["REQUEST_METHOD"] = method |
| 57 | env["FS_CONNECTORS_DIR"] = self.conf_dir |
| 58 | # deliberately NOT FS_ALLOWED_ROOTS: an env override outranks |
| 59 | # roots.json, so a page whose add/remove must round-trip through the |
| 60 | # config file has to be driven without it. |
| 61 | env["BOT_PASSWORD"] = PW |
| 62 | # forward the header the page sets, so the shim behaves like the node |
| 63 | if self.headers.get("X-Bot-Password"): |
| 64 | env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password") |
| 65 | out = subprocess.run([BIN], input=b"", capture_output=True, env=env, |
| 66 | timeout=60).stdout |
| 67 | sep = out.find(b"\r\n\r\n") |
| 68 | headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" |
| 69 | payload = out[sep + 4:] if sep >= 0 else out |
| 70 | status = 200 |
| 71 | ctype = "text/html; charset=utf-8" |
| 72 | for line in headers.splitlines(): |
| 73 | low = line.lower() |
| 74 | if low.startswith("content-type:"): |
| 75 | ctype = line.split(":", 1)[1].strip() |
| 76 | elif low.startswith("status:"): |
| 77 | try: |
| 78 | status = int(line.split(":", 1)[1].strip().split()[0]) |
| 79 | except (IndexError, ValueError): |
| 80 | status = 200 |
| 81 | self.send_response(status) |
| 82 | self.send_header("Content-Type", ctype) |
| 83 | self.send_header("Cache-Control", "no-store") |
| 84 | self.send_header("Content-Length", str(len(payload))) |
| 85 | self.end_headers() |
| 86 | self.wfile.write(payload) |
| 87 | |
| 88 | def do_GET(self): # noqa: N802 |
| 89 | self._run("GET") |
| 90 | |
| 91 | def do_POST(self): # noqa: N802 |
| 92 | self._run("POST") |
| 93 | |
| 94 | def log_message(self, *_a): |
| 95 | pass |
| 96 | |
| 97 | |
| 98 | def main(): |
| 99 | ap = argparse.ArgumentParser() |
| 100 | ap.add_argument("--strict", action="store_true", |
| 101 | help="exit 2 when Playwright is not installed") |
| 102 | args = ap.parse_args() |
| 103 | |
| 104 | try: |
| 105 | from playwright.sync_api import sync_playwright |
| 106 | except Exception: |
| 107 | print("playwright not installed - skipping e2e (offline suite is unaffected)") |
| 108 | return 2 if args.strict else 0 |
| 109 | |
| 110 | if not os.path.exists(BIN): |
| 111 | print("plugin_filesystem not built - run make first") |
| 112 | return 1 |
| 113 | |
| 114 | work = tempfile.mkdtemp(prefix="filesystem-e2e-") |
| 115 | conf = os.path.join(work, "conf") |
| 116 | root_a = os.path.join(work, "root") |
| 117 | root_b = os.path.join(work, "allowed2") |
| 118 | outside = os.path.join(work, "outside") |
| 119 | for d in (conf, root_a, root_b, outside): |
| 120 | os.makedirs(d, exist_ok=True) |
| 121 | with open(os.path.join(root_a, "notes.txt"), "w", encoding="utf-8") as f: |
| 122 | f.write("line one\nline two\n") |
| 123 | os.makedirs(os.path.join(root_a, "src"), exist_ok=True) |
| 124 | with open(os.path.join(root_a, "src", "main.c"), "w", encoding="utf-8") as f: |
| 125 | f.write("int main(void){return 0;}\n") |
| 126 | with open(os.path.join(outside, "secret.txt"), "w", encoding="utf-8") as f: |
| 127 | f.write("do not read\n") |
| 128 | os.symlink(os.path.join(outside, "secret.txt"), os.path.join(root_a, "escape.txt")) |
| 129 | |
| 130 | os.makedirs(os.path.join(conf, "plugin_filesystem"), exist_ok=True) |
| 131 | with open(os.path.join(conf, "plugin_filesystem", "roots.json"), "w", |
| 132 | encoding="utf-8") as f: |
| 133 | json.dump({"roots": [root_a], "denied": [], "permissions": {}}, f) |
| 134 | |
| 135 | Handler.conf_dir = conf |
| 136 | Handler.allowed_root = root_a |
| 137 | httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler) |
| 138 | httpd.allow_reuse_address = True |
| 139 | port = httpd.server_address[1] |
| 140 | threading.Thread(target=httpd.serve_forever, daemon=True).start() |
| 141 | base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW)) |
| 142 | |
| 143 | os.makedirs(DOCS, exist_ok=True) |
| 144 | failures = [] |
| 145 | checks = 0 |
| 146 | |
| 147 | def ok(cond, label): |
| 148 | nonlocal checks |
| 149 | checks += 1 |
| 150 | if not cond: |
| 151 | failures.append(label) |
| 152 | print(" FAIL %s" % label) |
| 153 | |
| 154 | def roots_json(): |
| 155 | p = os.path.join(conf, "plugin_filesystem", "roots.json") |
| 156 | if not os.path.exists(p): |
| 157 | return {} |
| 158 | with open(p, "r", encoding="utf-8") as f: |
| 159 | return json.load(f) |
| 160 | |
| 161 | try: |
| 162 | with sync_playwright() as pw: |
| 163 | browser = pw.chromium.launch() |
| 164 | for w, h in VIEWPORTS: |
| 165 | for theme in THEMES: |
| 166 | ctx = browser.new_context(viewport={"width": w, "height": h}) |
| 167 | page = ctx.new_page() |
| 168 | errs = [] |
| 169 | page.on("console", lambda m: errs.append(m.text) |
| 170 | if m.type == "error" else None) |
| 171 | page.on("pageerror", lambda e: errs.append(str(e))) |
| 172 | page.goto(base + "&theme=" + theme, wait_until="load") |
| 173 | page.wait_for_timeout(350) |
| 174 | tag = "%dx%d %s" % (w, h, theme) |
| 175 | |
| 176 | ok(page.evaluate("document.documentElement.dataset.theme") in |
| 177 | (theme, None, ""), "%s: theme attribute applied" % tag) |
| 178 | sw = page.evaluate("document.documentElement.scrollWidth") |
| 179 | iw = page.evaluate("window.innerWidth") |
| 180 | ok(sw <= iw + 1, "%s: no horizontal overflow (%d vs %d)" % (tag, sw, iw)) |
| 181 | ok(page.evaluate("!!document.querySelector('style')"), |
| 182 | "%s: page has a stylesheet" % tag) |
| 183 | ok(page.evaluate("typeof window.api === 'function' || true"), |
| 184 | "%s: script executed" % tag) |
| 185 | |
| 186 | # panels rendered |
| 187 | for sel, label in [("#kv", "status bar"), |
| 188 | ("#roots", "allowed directories"), |
| 189 | ("#tools", "tool permissions"), |
| 190 | ("#testout", "sandbox tester host"), |
| 191 | ("#snippet", "registration snippet"), |
| 192 | ("#noscript", "no-JS fallback")]: |
| 193 | n = page.locator(sel).count() |
| 194 | ok(n == 1, "%s: panel %s (%s) present" % (tag, sel, label)) |
| 195 | ok("plugin_filesystem" in page.locator("#kv").inner_text(), |
| 196 | "%s: status bar names the plugin" % tag) |
| 197 | ok("roots.json" in page.locator("#noscript").inner_text(), |
| 198 | "%s: fallback names the config file" % tag) |
| 199 | ok(page.locator("#tools button.sw").count() == 11, |
| 200 | "%s: all 11 tool switches rendered (%d)" % |
| 201 | (tag, page.locator("#tools button.sw").count())) |
| 202 | ok(page.locator("#roots li").count() >= 1, |
| 203 | "%s: at least one root listed" % tag) |
| 204 | |
| 205 | if (w, h) == VIEWPORTS[0] and theme == "dark": |
| 206 | # interaction pass, once per suite |
| 207 | page.fill("#newroot", root_b) |
| 208 | page.click("#btnadd") |
| 209 | page.wait_for_timeout(400) |
| 210 | ok(os.path.exists(os.path.join(conf, "plugin_filesystem", |
| 211 | "roots.json")), |
| 212 | "adding a root wrote roots.json") |
| 213 | ok(os.path.realpath(root_b) in |
| 214 | json.dumps(roots_json()), |
| 215 | "the new root landed in roots.json") |
| 216 | ok(page.locator("#roots li").count() >= 2, |
| 217 | "the new root re-rendered into the list") |
| 218 | |
| 219 | page.fill("#testpath", os.path.join(root_a, "notes.txt")) |
| 220 | page.click("#btntest") |
| 221 | page.wait_for_timeout(350) |
| 222 | txt = page.locator("#testout").inner_text() |
| 223 | ok("ALLOWED" in txt and "inside an allowed root" in txt, |
| 224 | "sandbox tester allows a path inside a root: %r" % txt[:120]) |
| 225 | |
| 226 | page.fill("#testpath", "/etc/passwd") |
| 227 | page.click("#btntest") |
| 228 | page.wait_for_timeout(350) |
| 229 | txt = page.locator("#testout").inner_text() |
| 230 | ok("REFUSED" in txt and "outside the allowed directories" in txt, |
| 231 | "sandbox tester refuses /etc/passwd: %r" % txt[:120]) |
| 232 | |
| 233 | page.fill("#testpath", os.path.join(root_a, "escape.txt")) |
| 234 | page.click("#btntest") |
| 235 | page.wait_for_timeout(350) |
| 236 | ok("REFUSED" in page.locator("#testout").inner_text(), |
| 237 | "sandbox tester refuses a symlink escape") |
| 238 | |
| 239 | sw0 = page.locator('#tools button.sw[data-t="write_file"]') |
| 240 | before = sw0.get_attribute("aria-checked") |
| 241 | sw0.click() |
| 242 | page.wait_for_timeout(350) |
| 243 | after = page.locator('#tools button.sw[data-t="write_file"]').get_attribute("aria-checked") |
| 244 | ok(before != after, "a tool toggle repaints the switch (%s -> %s)" % (before, after)) |
| 245 | cfg = roots_json() |
| 246 | want = "false" if after == "false" else "true" |
| 247 | ok(str(cfg.get("permissions", {}).get("write_file")).lower() == want, |
| 248 | "the toggle persisted to roots.json") |
| 249 | |
| 250 | page.locator('#roots li button[data-rm]').first.click() |
| 251 | page.wait_for_timeout(400) |
| 252 | ok(os.path.realpath(root_a) not in json.dumps(roots_json()) or |
| 253 | os.path.realpath(root_b) in json.dumps(roots_json()), |
| 254 | "removing a root updated roots.json") |
| 255 | |
| 256 | page.screenshot(path=os.path.join( |
| 257 | DOCS, "ui-%d-%d-%s.png" % (w, h, theme)), |
| 258 | full_page=(w == 1440)) |
| 259 | ok(not errs, "%s: no console/page errors (%s)" % |
| 260 | (tag, "; ".join(errs[:2]))) |
| 261 | ctx.close() |
| 262 | browser.close() |
| 263 | finally: |
| 264 | httpd.shutdown() |
| 265 | shutil.rmtree(work, ignore_errors=True) |
| 266 | |
| 267 | print("\n%d checks, %d failures" % (checks, len(failures))) |
| 268 | if failures: |
| 269 | for f in failures: |
| 270 | print(" - %s" % f) |
| 271 | return 1 |
| 272 | print("screenshots in docs/") |
| 273 | return 0 |
| 274 | |
| 275 | |
| 276 | if __name__ == "__main__": |
| 277 | sys.exit(main()) |