#!/usr/bin/env python3 """Black-box edge-case smoke test for RustProxy cache + VCL-style cache rules. Two modes, standard library only: local Start a mock origin and the *real* RustProxy binary in headless mode with the shipped security/session templates, then run ~60 checks (cookie guards, explicit pass, static policy, Vary, HEAD/Range/304, compression variants, malformed/split Cookie headers, request coalescing with concurrent users, ...). tools/dev/cache_edge_smoke.py local --binary target/release/rust-proxy remote Read-only GET/HEAD checks against a staging/production vhost that has diagnostic headers enabled (Settings -> Cache -> Expose status). tools/dev/cache_edge_smoke.py remote --base https://www.example.com \\ --static /sites/all/themes/site/style.css --page / \\ --cookie 'SESSabc=...' [--cookie-b 'SESSdef=...'] Global invariant (local mode): a response body tagged ``who=`` by the origin is only ever delivered to the client holding that session. Any violation is reported as LEAK and fails the run. Exit status: 0 all checks passed, 1 a check failed, 2 setup error. """ from __future__ import annotations import argparse import concurrent.futures as futures import http.client import http.server import json import os import re import shutil import signal import socket import subprocess import sys import tempfile import threading import time import urllib.parse from email.utils import formatdate RESULTS: list[tuple[str, str, str]] = [] # (status, name, detail) LOCK = threading.Lock() WHO = re.compile(r"who=([A-Za-z0-9_\-]+)") def record(ok: bool | None, name: str, detail: str = "") -> bool: status = "INFO" if ok is None else ("PASS" if ok else "FAIL") with LOCK: RESULTS.append((status, name, detail)) return bool(ok) if ok is not None else True # -------------------------------------------------------------------------- # HTTP client with exact header control (repeated / non-UTF-8 Cookie fields) # -------------------------------------------------------------------------- class Reply: def __init__(self, status: int, headers: list[tuple[str, str]], body: bytes): self.status = status self.headers = headers self.body = body def h(self, name: str) -> str: values = [v for k, v in self.headers if k.lower() == name.lower()] return ", ".join(values) @property def cache(self) -> str: return self.h("x-cache") or "-" @property def reason(self) -> str: return self.h("x-cache-reason") or "-" @property def text(self) -> str: return self.body.decode("utf-8", "replace") def __repr__(self) -> str: return f"{self.status} {self.cache}/{self.reason}" def session_of(headers: list[tuple[str, bytes | str]]) -> str | None: for name, value in headers: if name.lower() != "cookie": continue raw = value.decode("latin-1") if isinstance(value, bytes) else value match = re.search(r"(?:^|;\s*)(?:session|SESS[0-9a-f]+)=([A-Za-z0-9_\-]+)", raw) if match: return match.group(1) return None class Client: def __init__(self, base: str, host: str | None = None, check_leaks: bool = True): parsed = urllib.parse.urlsplit(base) self.scheme, self.netloc = parsed.scheme, parsed.netloc self.host = host or parsed.hostname self.check_leaks = check_leaks self.leak_exempt: set[str] = set() def request(self, method: str, path: str, headers: list[tuple[str, bytes | str]] = (), body: bytes | None = None) -> Reply: cls = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection conn = cls(self.netloc, timeout=20) conn.putrequest(method, path, skip_host=True, skip_accept_encoding=True) conn.putheader("Host", self.host) conn.putheader("User-Agent", "rustproxy-cache-edge-smoke/1") for name, value in headers: conn.putheader(name, value) if body is not None: conn.putheader("Content-Length", str(len(body))) conn.endheaders(body) response = conn.getresponse() data = response.read() reply = Reply(response.status, response.getheaders(), data) conn.close() if self.check_leaks and path.split("?")[0] not in self.leak_exempt: mine = session_of(list(headers)) for who in set(WHO.findall(reply.text)): if who != "-" and who != mine: record(False, f"LEAK {method} {path}", f"client session={mine} received body of who={who} ({reply})") return reply def get(self, path: str, *headers: tuple[str, bytes | str]) -> Reply: return self.request("GET", path, list(headers)) def cookie(value: str) -> tuple[str, str]: return ("Cookie", value) ALICE, BOB, CAROL = cookie("session=alice"), cookie("session=bob; _ga=GA1.2"), cookie("session=carol") DRUPAL = cookie("SESS0123456789abcdef0123456789abcd=dave; has_js=1") # -------------------------------------------------------------------------- # Mock origin # -------------------------------------------------------------------------- class Origin(http.server.ThreadingHTTPServer): daemon_threads = True hits: dict[str, int] class Handler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *args) -> None: # quiet pass def _respond(self, head: bool) -> None: path = urllib.parse.urlsplit(self.path).path with LOCK: self.server.hits[path] = self.server.hits.get(path, 0) + 1 who = session_of([("cookie", v) for v in self.headers.get_all("cookie") or []]) or "-" gzip = "gzip" in (self.headers.get("accept-encoding") or "") status, ctype, extra, body = 200, "text/css", [], "" public = [("Cache-Control", "public, max-age=600")] if path in ("/static/app.css", "/static/APP.CSS", "/static/range.css", "/static/slow-public.css"): if path == "/static/slow-public.css": time.sleep(0.4) extra, body = public + [("Vary", "Accept-Encoding")], "body{color:red}" * 4 elif path == "/static/app.js": ctype, extra, body = "application/javascript", [("Cache-Control", "max-age=600")], "var a=1;" elif path == "/static/drupal.js": ctype, extra, body = "application/javascript", [("Cache-Control", "max-age=1209600")], "Drupal={};" elif path == "/static/font.woff2": ctype, body = "font/woff2", "wOF2" extra = [("Expires", formatdate(time.time() + 3600, usegmt=True))] elif path == "/static/enc.css": extra = public + [("Vary", "Accept-Encoding")] if gzip: extra.append(("Content-Encoding", "gzip")) body = "GZ-BYTES" else: body = "PLAIN-BYTES" elif path == "/static/vary-cookie.css": extra, body = public + [("Vary", "Cookie")], "shared-by-vary" elif path == "/static/vary-cookie-personal.css": extra, body = [("Cache-Control", "max-age=600"), ("Vary", "Cookie")], f"who={who}" elif path in ("/static/private.png", "/static/slow-private.css"): if path.endswith(".css"): time.sleep(0.4) ctype = "image/png" if path.endswith(".png") else "text/css" extra, body = [("Cache-Control", "private, max-age=600")], f"who={who}" elif path == "/static/set-cookie.css": extra, body = public + [("Set-Cookie", "refresh=1; Path=/")], f"who={who}" elif path == "/static/spa.js": ctype, extra, body = "text/html", public, f"who={who}" elif path == "/index.php/theme.css": ctype, extra, body = "text/html", public, f"php who={who}" elif path == "/static/nofresh.css": extra, body = [("Last-Modified", "Mon, 01 Jan 2024 00:00:00 GMT")], f"who={who}" elif path == "/static/personal-but-public.css": extra, body = public, f"who={who}" # misconfigured origin (documented limitation) elif path == "/account/avatar.png": if who == "-": status, ctype, body = 403, "text/plain", "forbidden" else: ctype, extra, body = "image/png", public, f"avatar who={who}" elif path == "/static/missing.css": status, extra, body = 404, public, "missing" elif path == "/static/moved.css": status, extra, body = 301, public + [("Location", "/static/app.css")], "moved" else: # HTML pages and anything else: personalised ctype, extra, body = "text/html; charset=utf-8", public, f"

page who={who}

" data = body.encode() etag = '"e-%x"' % (hash((path, body)) & 0xFFFFFFFF) if status == 200 and self.headers.get("if-none-match") == etag: self.send_response(304) self.send_header("ETag", etag) self.send_header("Content-Length", "0") self.end_headers() return self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("ETag", etag) for name, value in extra: self.send_header(name, value) self.send_header("Content-Length", str(len(data))) self.end_headers() if not head: self.wfile.write(data) def do_GET(self) -> None: self._respond(False) def do_HEAD(self) -> None: self._respond(True) def do_POST(self) -> None: length = int(self.headers.get("content-length") or 0) self.rfile.read(length) self._respond(False) def free_port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1] def rule(rid: str, conditions: list, actions: list, stop: bool = False, stage: str = "request") -> dict: return {"id": rid, "stage": stage, "conditions": conditions, "actions": actions, "stop": stop} def proxy_config(origin_port: int) -> dict: cookie_header = {"field": "header", "name": "Cookie", "operator": "exists"} return { "vhosts": [{ "id": "edge", "frontend": {"hosts": ["*"]}, "backends": [{"id": "o", "url": f"http://127.0.0.1:{origin_port}", "allow_private": True}], "load_balancing": {"health_check": {"mode": "off"}}, "cache": {"enabled": True}, }], "cache": { "enabled": True, "expose_status": True, "expose_hits": True, "expose_cache_status": True, "static_ignore_cookies": True, "static_ignore_vary_cookie": True, "collapse_enabled": True, "rules": [ rule("methods", [{"field": "method", "operator": "equals", "values": ["GET", "HEAD"], "negate": True}], [{"type": "pass"}], True), rule("auth", [{"field": "header", "name": "Authorization", "operator": "exists"}], [{"type": "pass"}], True), rule("private-routes", [{"field": "path", "operator": "regex", "values": ["^/(?:account|admin|user)(?:/|[?]|$)"]}], [{"type": "pass"}], True), rule("tracking", [], [{"type": "strip_query", "params": ["utm_*", "fbclid"]}]), rule("drupal", [{"field": "header", "name": "Cookie", "operator": "regex", "values": ["(?:^|;[ \\t]*)(?:S?SESS[a-fA-F0-9]+)="]}], [{"type": "cookie_pass"}], True), rule("remaining-cookies", [cookie_header], [{"type": "cookie_pass"}], True), # Explicit pass placed AFTER a terminal Cookie guard. rule("preview", [{"field": "cookie", "name": "preview", "operator": "exists"}], [{"type": "pass"}]), ], }, } # -------------------------------------------------------------------------- # Local scenarios # -------------------------------------------------------------------------- def expect(name: str, reply: Reply, cache: str | tuple | None = None, reason: str | None = None, status: int | None = None, body: str | None = None) -> bool: problems = [] caches = (cache,) if isinstance(cache, str) else cache if caches and reply.cache not in caches: problems.append(f"X-Cache {reply.cache} not in {caches}") if reason and reply.reason != reason: problems.append(f"reason {reply.reason} != {reason}") if status and reply.status != status: problems.append(f"status {reply.status} != {status}") if body is not None and reply.text != body: problems.append(f"body {reply.text!r} != {body!r}") return record(not problems, name, "; ".join(problems) or repr(reply)) def run_local(binary: str) -> int: origin_port, proxy_port = free_port(), free_port() origin = Origin(("127.0.0.1", origin_port), Handler) origin.hits = {} threading.Thread(target=origin.serve_forever, daemon=True).start() work = tempfile.mkdtemp(prefix="rp-edge-") config_path = os.path.join(work, "config.json") with open(config_path, "w") as handle: json.dump(proxy_config(origin_port), handle) log = open(os.path.join(work, "proxy.log"), "w") proc = subprocess.Popen( [binary, "--headless", "--config", config_path, "--data-dir", os.path.join(work, "data"), "serve", "--proxy-listen", f"127.0.0.1:{proxy_port}"], stdout=log, stderr=subprocess.STDOUT, start_new_session=True) try: for _ in range(100): try: socket.create_connection(("127.0.0.1", proxy_port), timeout=0.2).close() break except OSError: if proc.poll() is not None: break time.sleep(0.1) else: raise RuntimeError("proxy did not start") if proc.poll() is not None: log.flush() print(open(os.path.join(work, "proxy.log")).read()[-3000:]) return 2 client = Client(f"http://127.0.0.1:{proxy_port}", "edge.test") client.leak_exempt.add("/static/personal-but-public.css") hits = lambda path: origin.hits.get(path, 0) scenarios(client, hits) finally: os.killpg(proc.pid, signal.SIGTERM) try: proc.wait(10) except subprocess.TimeoutExpired: os.killpg(proc.pid, signal.SIGKILL) origin.shutdown() log.close() shutil.rmtree(work, ignore_errors=True) return report() def settle() -> None: time.sleep(0.15) # background body drain for HEAD fills / stream completion def scenarios(c: Client, hits) -> None: S = "static policy" # 1. Anonymous then logged-in: one origin fetch, shared object. expect(f"{S}: anon CSS first fill", c.get("/static/app.css"), "MISS", "cache_miss") expect(f"{S}: anon CSS reuse", c.get("/static/app.css"), "HIT") expect(f"{S}: logged CSS reuses anon object", c.get("/static/app.css", ALICE), "HIT") record(hits("/static/app.css") == 1, f"{S}: CSS fetched once", f"origin={hits('/static/app.css')}") # 2. Logged-in first (guard relaxed), max-age without public. expect(f"{S}: logged JS first fill", c.get("/static/app.js", BOB), "MISS", "cache_miss_static_cookie") expect(f"{S}: other user HIT", c.get("/static/app.js", CAROL), "HIT") expect(f"{S}: anonymous HIT", c.get("/static/app.js"), "HIT") # 3. Drupal 6 session + query string. expect(f"{S}: Drupal6 JS ?v=1 MISS", c.get("/static/drupal.js?v=1", DRUPAL), "MISS") expect(f"{S}: Drupal6 JS ?v=1 HIT", c.get("/static/drupal.js?v=1", DRUPAL), "HIT") expect(f"{S}: other version is separate", c.get("/static/drupal.js?v=2", DRUPAL), "MISS") expect(f"{S}: tracking params normalised into same key", c.get("/static/drupal.js?v=1&utm_source=x&fbclid=y", ALICE), "HIT") expect("guards: Drupal6 HTML bypass", c.get("/node/1", DRUPAL), "BYPASS", "cache_rule_cookie") # 4. Expires-only font shared across many cookies. for index, who in enumerate([ALICE, BOB, DRUPAL, cookie("x=1")]): expect(f"{S}: font #{index}", c.get("/static/font.woff2", who), "MISS" if index == 0 else "HIT") # 5. Extension edge cases. expect(f"{S}: uppercase .CSS is static", c.get("/static/APP.CSS", ALICE), "MISS", "cache_miss_static_cookie") expect(f"{S}: trailing slash is not static", c.get("/static/app.css/", ALICE), "BYPASS", "cache_rule_cookie") # Path parameters are rejected by request validation before any cache step. expect(f"{S}: ;jsessionid path rejected", c.get("/static/app.css;jsessionid=1", ALICE), status=400) # %2E is normalised to '.', so this is a static candidate; the origin here # answers with personalised HTML, which the shared-static guard refuses. expect(f"{S}: %2E-encoded extension, HTML reply not stored", c.get("/static/app%2Ecss", ALICE), "MISS", "response_static_dynamic") expect(f"{S}: %2E-encoded extension next user", c.get("/static/app%2Ecss", BOB), "MISS") r = c.get("/index.php/theme.css", ALICE) expect(f"{S}: PATH_INFO .css serving HTML not stored", r, "MISS", "response_static_dynamic") expect(f"{S}: PATH_INFO next user not served", c.get("/index.php/theme.css", BOB), "MISS") # 6. Refused shared storage. for path, reason in [("/static/private.png", "response_cache_control"), ("/static/set-cookie.css", "response_set_cookie"), ("/static/spa.js", "response_static_dynamic"), ("/static/nofresh.css", "response_static_not_public")]: expect(f"storage guard: {path}", c.get(path, ALICE), "MISS", reason) expect(f"storage guard: {path} next user", c.get(path, BOB), "MISS") r = c.get(path) record(r.cache != "HIT" or "who=alice" not in r.text and "who=bob" not in r.text, f"storage guard: {path} anonymous", repr(r)) # 7. Vary: Cookie. expect("vary: public Vary Cookie shared #1", c.get("/static/vary-cookie.css", ALICE), "MISS") r = c.get("/static/vary-cookie.css", BOB) expect("vary: public Vary Cookie shared #2", r, "HIT") record("cookie" not in r.h("vary").lower(), "vary: Cookie removed from public static Vary", r.h("vary")) for who in (ALICE, BOB, ALICE): r = c.get("/static/vary-cookie-personal.css", who) expect(f"vary: non-public Vary Cookie never shared ({session_of([who])})", r, "MISS", body=f"who={session_of([who])}") # 8. Compression variants. gz, ident = ("Accept-Encoding", "gzip"), ("Accept-Encoding", "identity") expect("encoding: anon gzip fill", c.get("/static/enc.css", gz), "MISS") expect("encoding: logged gzip HIT", c.get("/static/enc.css", gz, ALICE), "HIT", body="GZ-BYTES") expect("encoding: logged identity separate", c.get("/static/enc.css", ident, BOB), "MISS", body="PLAIN-BYTES") expect("encoding: anon identity HIT", c.get("/static/enc.css", ident), "HIT", body="PLAIN-BYTES") # 9. Explicit pass semantics. r = c.get("/account/avatar.png", ALICE) expect("explicit pass: private route image", r, "BYPASS", "cache_rule", body="avatar who=alice") expect("explicit pass: private route anonymous", c.get("/account/avatar.png"), "BYPASS", status=403) expect("explicit pass after terminal guard (preview cookie)", c.get("/static/app.css", cookie("preview=1; session=alice")), "BYPASS") expect("explicit pass: Authorization", c.get("/static/app.css", ("Authorization", "Bearer x"), ALICE), "BYPASS", "cache_rule") expect("explicit pass: POST static", c.request("POST", "/static/app.css", [ALICE], b"x=1"), "BYPASS", "cache_rule") # 10. HTML. expect("html: anon fill", c.get("/"), "MISS") expect("html: anon HIT", c.get("/"), "HIT", body="

page who=-

") expect("html: logged bypass", c.get("/", ALICE), "BYPASS", "cache_rule_cookie", body="

page who=alice

") # 11. Malformed / split Cookie headers. expect("cookie: split fields, session in 2nd", c.request("GET", "/", [("Cookie", "_ga=1"), ("Cookie", "session=bob")]), "BYPASS", body="

page who=bob

") # A Cookie field that is not valid UTF-8 is dropped before forwarding: the # backend sees an anonymous request, so the anonymous object is correct. expect("cookie: non-UTF-8 Cookie treated as anonymous end to end", c.request("GET", "/", [("Cookie", b"session=x\xff")]), ("HIT", "MISS"), body="

page who=-

") expect("cookie: empty Cookie header on HTML", c.request("GET", "/", [("Cookie", "")]), ("BYPASS", "HIT")) # 12. HEAD / Range / conditional / reload. r = c.request("HEAD", "/static/app.css", [BOB]) expect("head: logged HEAD on cached object", r, "HIT") record(r.body == b"", "head: empty body", repr(r.body[:20])) expect("head: HEAD-first fill (logged)", c.request("HEAD", "/static/range.css", [ALICE]), "MISS") settle() expect("head: following GET reuses HEAD fill", c.get("/static/range.css", CAROL), "HIT") r = c.get("/static/range.css", ("Range", "bytes=0-3"), BOB) expect("range: logged range from cache", r, "HIT", status=206, body="body") etag = c.get("/static/app.css").h("etag") expect("conditional: logged If-None-Match", c.get("/static/app.css", ("If-None-Match", etag), ALICE), "HIT", status=304) expect("reload: no-cache from logged browser (compat mode)", c.get("/static/app.css", ("Cache-Control", "no-cache"), ALICE), ("HIT", "MISS")) # 13. Non-200. for path in ("/static/missing.css", "/static/moved.css"): c.get(path, ALICE) expect(f"status: {path} not stored", c.get(path, BOB), "MISS") # 14. Concurrency with request coalescing (collapse) and mixed users. users = [cookie(f"session=u{i}") for i in range(12)] def fetch(args): path, who = args r = c.get(path, who) return who, r with futures.ThreadPoolExecutor(12) as pool: replies = list(pool.map(fetch, [("/static/slow-private.css", u) for u in users])) ok = all(r.status == 200 and r.text == f"who={session_of([u])}" for u, r in replies) record(ok, "concurrency: 12 users on private static each get own body", ", ".join(sorted({repr(r) for _, r in replies}))) before = hits("/static/slow-public.css") with futures.ThreadPoolExecutor(12) as pool: replies = list(pool.map(fetch, [("/static/slow-public.css", u if i % 2 else ("X-N", "1")) for i, u in enumerate(users)])) fetched = hits("/static/slow-public.css") - before record(all(r.status == 200 for _, r in replies) and fetched <= 2, "concurrency: 12 mixed anon/logged on public static coalesced", f"origin fetches={fetched}") # 15. Documented limitation: origin marks a personalised .css public. c.get("/static/personal-but-public.css", ALICE) r = c.get("/static/personal-but-public.css", BOB) record(None, "limitation: personalised body labelled public by origin", f"BOB got {r.text!r} ({r}); fix such resources at the origin (private/no-store) or with a path pass rule") # -------------------------------------------------------------------------- # Remote (staging/production) read-only checks # -------------------------------------------------------------------------- def run_remote(args) -> int: c = Client(args.base, args.host, check_leaks=False) a = cookie(args.cookie) b = cookie(args.cookie_b) if args.cookie_b else None probe = c.get(args.static) if probe.cache == "-": record(False, "diagnostics", "X-Cache missing: enable Settings -> Cache -> Expose status for this test") return report() for path in args.static_list or [args.static]: first = c.get(path) second = c.get(path) expect(f"static {path}: anonymous reuse", second, "HIT") expect(f"static {path}: logged reuse", c.get(path, a), "HIT") if b: expect(f"static {path}: second user reuse", c.get(path, b), "HIT") expect(f"static {path}: logged HEAD", c.request("HEAD", path, [a]), "HIT") record(None, f"static {path}: first anonymous", repr(first)) for page in args.page_list or [args.page]: r = c.get(page, a) record(r.cache != "HIT", f"page {page}: logged never HIT", repr(r)) if b: r2 = c.get(page, b) record(r2.cache != "HIT", f"page {page}: second user not HIT", repr(r2)) return report() def report() -> int: width = max((len(name) for _, name, _ in RESULTS), default=10) failed = 0 for status, name, detail in RESULTS: failed += status == "FAIL" print(f"{status:5} {name:<{width}} {detail}") passed = sum(1 for status, _, _ in RESULTS if status == "PASS") print(f"\n{passed} passed, {failed} failed, {sum(1 for s, _, _ in RESULTS if s == 'INFO')} info") return 1 if failed else 0 def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest="mode", required=True) local = sub.add_parser("local", help="start origin + headless RustProxy and run all edge cases") local.add_argument("--binary", default="target/release/rust-proxy") remote = sub.add_parser("remote", help="read-only checks against a deployed vhost") remote.add_argument("--base", required=True, help="e.g. https://www.example.com") remote.add_argument("--host", help="Host header if different from --base") remote.add_argument("--static", required=True, help="public static path, e.g. /theme/style.css") remote.add_argument("--static-list", nargs="*", help="several static paths") remote.add_argument("--page", default="/", help="session-dependent HTML path") remote.add_argument("--page-list", nargs="*") remote.add_argument("--cookie", required=True, help="logged-in Cookie header value (user A)") remote.add_argument("--cookie-b", help="Cookie header value of a different user (user B)") args = parser.parse_args() try: code = run_local(args.binary) if args.mode == "local" else run_remote(args) except Exception as error: # setup problems print(f"setup error: {error}", file=sys.stderr) code = 2 sys.exit(code) if __name__ == "__main__": main()