This commit is contained in:
Mateusz Gruszczyński committed 2026-11-25 15:47:34 +01:00
1 parent 6df256cdbb
commit 0d6249e383
159 files changed
+16737 -1971

No files matched your search

-537
View File
@@ -1,537 +0,0 @@
#!/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=<session>`` 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"<html>who={who}</html>"
elif path == "/index.php/theme.css":
ctype, extra, body = "text/html", public, f"<html>php who={who}</html>"
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"<p>page who={who}</p>"
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="<p>page who=-</p>")
expect("html: logged bypass", c.get("/", ALICE), "BYPASS", "cache_rule_cookie", body="<p>page who=alice</p>")
# 11. Malformed / split Cookie headers.
expect("cookie: split fields, session in 2nd", c.request("GET", "/", [("Cookie", "_ga=1"), ("Cookie", "session=bob")]),
"BYPASS", body="<p>page who=bob</p>")
# 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="<p>page who=-</p>")
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()
@@ -0,0 +1,33 @@
# Imported VCL regression fixtures
These are test inputs, including deliberately unsafe and rejected examples;
they are not production configuration recipes.
The `.vcl` files can be imported through the authenticated
`/api/cache/rules/import-vcl` endpoint. Adjacent `.json` files preserve 0.41.4
import snapshots; `.candidate.json` files record the corrected 0.42.0 importer.
Only randomized `vcl_flow.group` identifiers are normalized to `g1`, `g2`, etc.
for comparison. Active configurations must retain their actual identifiers.
The `legacy_mutating_*` examples cover branch selection when a selected branch
changes or removes the header used by its condition. Their baseline snapshots
retain the old flattened structure. `header_stages` and `branches` also cover
later conditions that must observe current header values. Older flattened VCL
conversions need re-import from their original source to acquire branch metadata.
`rejected_protected` must produce import warnings and must not be activated.
`rejected_unclosed` must reject the source. Other examples cover terminal
actions, Cookie and `Vary` handling, TTL, grace and backend-response controls.
The Rust suite has focused tests for the related importer, policy/VCL and
credential-cache behavior. Run them from the source root:
```bash
cargo test --locked --lib cache::vcl_matrix_tests
cargo test --locked --lib proxy::vcl_policy_matrix_tests
cargo test --locked --lib proxy::cache_plan::credential_tests
```
These Rust tests define their cases in source; they do not automatically load
this fixture directory. To validate an actual deployment, also import the
relevant VCL and send requests through the running binary.
@@ -0,0 +1,538 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-2",
"match": "all",
"name": "VCL vcl_backend_response branch line 2",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/toggle"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"type": "no_store"
},
{
"type": "allow_store"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-3",
"match": "all",
"name": "VCL vcl_backend_response line 3",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-6",
"match": "all",
"name": "VCL vcl_backend_response branch line 6",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/no-store"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 2,
"version": 1
}
},
{
"actions": [
{
"type": "allow_store"
},
{
"type": "no_store"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 2
}
],
"index": 3,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-10",
"match": "all",
"name": "VCL vcl_backend_response branch line 10",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/response-pass"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 4,
"version": 1
}
},
{
"actions": [
{
"type": "no_store"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-10-2",
"match": "all",
"name": "VCL vcl_backend_response line 10",
"stage": "response",
"stop": true,
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 5,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-11",
"match": "all",
"name": "VCL vcl_backend_response branch line 11",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/private|^/origin-no-store|^/set-cookie|^/policy-no-store"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 6,
"version": 1
}
},
{
"actions": [
{
"type": "allow_store"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 6
}
],
"index": 7,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-14",
"match": "all",
"name": "VCL vcl_backend_response branch line 14",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/drop-cookie"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 8,
"version": 1
}
},
{
"actions": [
{
"type": "strip_set_cookie"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-14-2",
"match": "all",
"name": "VCL vcl_backend_response line 14",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 8
}
],
"index": 9,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-15",
"match": "all",
"name": "VCL vcl_backend_response branch line 15",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/public-override"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 10,
"version": 1
}
},
{
"actions": [
{
"name": "cache-control",
"type": "set_backend_header",
"value": "public, max-age=300"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-16",
"match": "all",
"name": "VCL vcl_backend_response line 16",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 10
}
],
"index": 11,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-18",
"match": "all",
"name": "VCL vcl_backend_response branch line 18",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/response-stop"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 12,
"version": 1
}
},
{
"actions": [
{
"name": "x-response-stop",
"type": "set_backend_header",
"value": "before"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-20",
"match": "all",
"name": "VCL vcl_backend_response line 20",
"stage": "response",
"stop": true,
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 12
}
],
"index": 13,
"version": 1
}
},
{
"actions": [
{
"name": "x-response-stop",
"type": "set_backend_header",
"value": "after"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-21",
"match": "all",
"name": "VCL vcl_backend_response line 21",
"stage": "response",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 12
}
],
"index": 14,
"version": 1
}
},
{
"actions": [
{
"name": "X-After-Response-Stop",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-25",
"match": "all",
"name": "VCL vcl_deliver line 25",
"stage": "deliver",
"vcl_flow": {
"count": 19,
"group": "g1",
"index": 15,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-26",
"match": "all",
"name": "VCL vcl_deliver branch line 26",
"stage": "deliver",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/deliver-stop"
]
}
]
]
}
],
"count": 19,
"group": "g1",
"index": 16,
"version": 1
}
},
{
"actions": [
{
"name": "X-Deliver-Stop",
"type": "set_header",
"value": "before"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-28",
"match": "all",
"name": "VCL vcl_deliver line 28",
"stage": "deliver",
"stop": true,
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 16
}
],
"index": 17,
"version": 1
}
},
{
"actions": [
{
"name": "X-Deliver-Stop",
"type": "set_header",
"value": "after"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-29",
"match": "all",
"name": "VCL vcl_deliver line 29",
"stage": "deliver",
"vcl_flow": {
"count": 19,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 16
}
],
"index": 18,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,252 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "no_store"
},
{
"type": "allow_store"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/toggle"
]
}
],
"enabled": true,
"id": "vcl-response-3",
"match": "all",
"name": "VCL vcl_backend_response line 3",
"stage": "response"
},
{
"actions": [
{
"type": "allow_store"
},
{
"type": "no_store"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/no-store"
]
}
],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response"
},
{
"actions": [
{
"type": "no_store"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/response-pass"
]
}
],
"enabled": true,
"id": "vcl-response-10",
"match": "all",
"name": "VCL vcl_backend_response line 10",
"stage": "response",
"stop": true
},
{
"actions": [
{
"type": "allow_store"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/private|^/origin-no-store|^/set-cookie|^/policy-no-store"
]
}
],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response"
},
{
"actions": [
{
"type": "strip_set_cookie"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/drop-cookie"
]
}
],
"enabled": true,
"id": "vcl-response-14",
"match": "all",
"name": "VCL vcl_backend_response line 14",
"stage": "response"
},
{
"actions": [
{
"name": "cache-control",
"type": "set_backend_header",
"value": "public, max-age=300"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/public-override"
]
}
],
"enabled": true,
"id": "vcl-response-16",
"match": "all",
"name": "VCL vcl_backend_response line 16",
"stage": "response"
},
{
"actions": [
{
"name": "x-response-stop",
"type": "set_backend_header",
"value": "before"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/response-stop"
]
}
],
"enabled": true,
"id": "vcl-response-20",
"match": "all",
"name": "VCL vcl_backend_response line 20",
"stage": "response",
"stop": true
},
{
"actions": [
{
"name": "x-response-stop",
"type": "set_backend_header",
"value": "after"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/response-stop"
]
}
],
"enabled": true,
"id": "vcl-response-21",
"match": "all",
"name": "VCL vcl_backend_response line 21",
"stage": "response"
},
{
"actions": [
{
"name": "X-After-Response-Stop",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-25",
"match": "all",
"name": "VCL vcl_deliver line 25",
"stage": "deliver"
},
{
"actions": [
{
"name": "X-Deliver-Stop",
"type": "set_header",
"value": "before"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/deliver-stop"
]
}
],
"enabled": true,
"id": "vcl-deliver-28",
"match": "all",
"name": "VCL vcl_deliver line 28",
"stage": "deliver",
"stop": true
},
{
"actions": [
{
"name": "X-Deliver-Stop",
"type": "set_header",
"value": "after"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/deliver-stop"
]
}
],
"enabled": true,
"id": "vcl-deliver-29",
"match": "all",
"name": "VCL vcl_deliver line 29",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1,31 @@
sub vcl_backend_response {
if (bereq.url ~ "^/toggle") {
set beresp.uncacheable = true;
set beresp.uncacheable = false;
}
if (bereq.url ~ "^/no-store") {
set beresp.uncacheable = false;
set beresp.uncacheable = true;
}
if (bereq.url ~ "^/response-pass") { return(pass); }
if (bereq.url ~ "^/private|^/origin-no-store|^/set-cookie|^/policy-no-store") {
set beresp.uncacheable = false;
}
if (bereq.url ~ "^/drop-cookie") { unset beresp.http.Set-Cookie; }
if (bereq.url ~ "^/public-override") {
set beresp.http.Cache-Control = "public, max-age=300";
}
if (bereq.url ~ "^/response-stop") {
set beresp.http.X-Response-Stop = "before";
return(deliver);
set beresp.http.X-Response-Stop = "after";
}
}
sub vcl_deliver {
set resp.http.X-After-Response-Stop = "yes";
if (req.url ~ "^/deliver-stop") {
set resp.http.X-Deliver-Stop = "before";
return(deliver);
set resp.http.X-Deliver-Stop = "after";
}
}
@@ -0,0 +1,254 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv branch line 2",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-Mode",
"operator": "equals",
"values": [
"alpha"
]
},
{
"field": "header",
"name": "X-Skip",
"negate": true,
"operator": "exists"
}
]
]
},
{
"any": [
[
{
"field": "header",
"name": "X-Mode",
"operator": "regex",
"values": [
"^b"
]
}
],
[
{
"field": "header",
"name": "X-Fallback",
"operator": "equals",
"values": [
"yes"
]
}
]
]
},
{
"any": [
[]
]
}
],
"count": 8,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "alpha"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "beta"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 1,
"entry": 0
}
],
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "other"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-7",
"match": "all",
"name": "VCL vcl_recv line 7",
"stage": "request",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 2,
"entry": 0
}
],
"index": 3,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-9",
"match": "all",
"name": "VCL vcl_recv branch line 9",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-Class",
"operator": "equals",
"values": [
"alpha"
]
}
]
]
}
],
"count": 8,
"group": "g1",
"index": 4,
"version": 1
}
},
{
"actions": [
{
"name": "X-Seen",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-9-2",
"match": "all",
"name": "VCL vcl_recv line 9",
"stage": "request",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 5,
"version": 1
}
},
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-10",
"match": "all",
"name": "VCL vcl_recv line 10",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 8,
"group": "g1",
"index": 6,
"version": 1
}
},
{
"actions": [
{
"name": "X-Class",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-12",
"match": "all",
"name": "VCL vcl_hash line 12",
"stage": "request",
"vcl_flow": {
"count": 8,
"group": "g1",
"index": 7,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,297 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "alpha"
}
],
"conditions": [
{
"field": "header",
"name": "X-Mode",
"operator": "equals",
"values": [
"alpha"
]
},
{
"field": "header",
"name": "X-Skip",
"negate": true,
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "beta"
}
],
"conditions": [
{
"field": "header",
"name": "X-Mode",
"negate": true,
"operator": "equals",
"values": [
"alpha"
]
},
{
"field": "header",
"name": "X-Mode",
"operator": "regex",
"values": [
"^b"
]
}
],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "beta"
}
],
"conditions": [
{
"field": "header",
"name": "X-Mode",
"negate": true,
"operator": "equals",
"values": [
"alpha"
]
},
{
"field": "header",
"name": "X-Fallback",
"operator": "equals",
"values": [
"yes"
]
}
],
"enabled": true,
"id": "vcl-request-5-2",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "beta"
}
],
"conditions": [
{
"field": "header",
"name": "X-Skip",
"operator": "exists"
},
{
"field": "header",
"name": "X-Mode",
"operator": "regex",
"values": [
"^b"
]
}
],
"enabled": true,
"id": "vcl-request-5-3",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "beta"
}
],
"conditions": [
{
"field": "header",
"name": "X-Skip",
"operator": "exists"
},
{
"field": "header",
"name": "X-Fallback",
"operator": "equals",
"values": [
"yes"
]
}
],
"enabled": true,
"id": "vcl-request-5-4",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "other"
}
],
"conditions": [
{
"field": "header",
"name": "X-Mode",
"negate": true,
"operator": "equals",
"values": [
"alpha"
]
},
{
"field": "header",
"name": "X-Mode",
"negate": true,
"operator": "regex",
"values": [
"^b"
]
},
{
"field": "header",
"name": "X-Fallback",
"negate": true,
"operator": "equals",
"values": [
"yes"
]
}
],
"enabled": true,
"id": "vcl-request-7",
"match": "all",
"name": "VCL vcl_recv line 7",
"stage": "request"
},
{
"actions": [
{
"name": "X-Class",
"type": "set_request_header",
"value": "other"
}
],
"conditions": [
{
"field": "header",
"name": "X-Skip",
"operator": "exists"
},
{
"field": "header",
"name": "X-Mode",
"negate": true,
"operator": "regex",
"values": [
"^b"
]
},
{
"field": "header",
"name": "X-Fallback",
"negate": true,
"operator": "equals",
"values": [
"yes"
]
}
],
"enabled": true,
"id": "vcl-request-7-2",
"match": "all",
"name": "VCL vcl_recv line 7",
"stage": "request"
},
{
"actions": [
{
"name": "X-Seen",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [
{
"field": "header",
"name": "X-Class",
"operator": "equals",
"values": [
"alpha"
]
}
],
"enabled": true,
"id": "vcl-request-9",
"match": "all",
"name": "VCL vcl_recv line 9",
"stage": "request"
},
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-10",
"match": "all",
"name": "VCL vcl_recv line 10",
"stage": "request",
"stop": true
},
{
"actions": [
{
"name": "X-Class",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-12",
"match": "all",
"name": "VCL vcl_hash line 12",
"stage": "request"
}
],
"warnings": []
}
}
@@ -0,0 +1,12 @@
sub vcl_recv {
if (req.http.X-Mode == "alpha" && !req.http.X-Skip) {
set req.http.X-Class = "alpha";
} elsif (req.http.X-Mode ~ "^b" || req.http.X-Fallback == "yes") {
set req.http.X-Class = "beta";
} else {
set req.http.X-Class = "other";
}
if (req.http.X-Class == "alpha") { set req.http.X-Seen = "yes"; }
return(hash);
}
sub vcl_hash { hash_data(req.http.X-Class); }
@@ -0,0 +1,49 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-1",
"match": "all",
"name": "VCL vcl_recv line 1",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 2,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "Cookie",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_hash line 2",
"stage": "request",
"vcl_flow": {
"count": 2,
"group": "g1",
"index": 1,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,37 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-1",
"match": "all",
"name": "VCL vcl_recv line 1",
"stage": "request",
"stop": true
},
{
"actions": [
{
"name": "Cookie",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_hash line 2",
"stage": "request"
}
],
"warnings": []
}
}
@@ -0,0 +1,2 @@
sub vcl_recv { return(hash); }
sub vcl_hash { hash_data(req.http.Cookie); }
@@ -0,0 +1,116 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv branch line 2",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "Authorization",
"operator": "exists"
}
]
]
}
],
"count": 4,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"type": "pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv branch line 3",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "Cookie",
"operator": "exists"
}
]
]
}
],
"count": 4,
"group": "g1",
"index": 2,
"version": 1
}
},
{
"actions": [
{
"type": "cookie_pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3-2",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 2
}
],
"index": 3,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,48 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "pass"
}
],
"conditions": [
{
"field": "header",
"name": "Authorization",
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"stop": true
},
{
"actions": [
{
"type": "cookie_pass"
}
],
"conditions": [
{
"field": "header",
"name": "Cookie",
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true
}
],
"warnings": []
}
}
@@ -0,0 +1,4 @@
sub vcl_recv {
if (req.http.Authorization) { return(pass); }
if (req.http.Cookie) { return(cookie_pass); }
}
@@ -0,0 +1,105 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"names": [
"parent_analytics",
"SESS*"
],
"type": "remove_named_cookies"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv branch line 3",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "Cookie",
"operator": "exists"
}
]
]
}
],
"count": 4,
"group": "g1",
"index": 1,
"version": 1
}
},
{
"actions": [
{
"type": "pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3-2",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 1
}
],
"index": 2,
"version": 1
}
},
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 3,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,59 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"names": [
"parent_analytics",
"SESS*"
],
"type": "remove_named_cookies"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request"
},
{
"actions": [
{
"type": "pass"
}
],
"conditions": [
{
"field": "header",
"name": "Cookie",
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true
},
{
"actions": [
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request",
"stop": true
}
],
"warnings": []
}
}
@@ -0,0 +1,5 @@
sub vcl_recv {
remove_req_cookies("parent_analytics", "SESS*");
if (req.http.Cookie) { return(pass); }
return(hash);
}
@@ -0,0 +1,31 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "strip_cookies"
},
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 1,
"group": "g1",
"index": 0,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,25 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"type": "strip_cookies"
},
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true
}
],
"warnings": []
}
}
@@ -0,0 +1,4 @@
sub vcl_recv {
unset req.http.Cookie;
return(hash);
}
@@ -0,0 +1,198 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "global"
},
{
"name": "X-Global-Request",
"type": "set_request_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv branch line 4",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/global-pass"
]
}
]
]
}
],
"count": 7,
"group": "g1",
"index": 1,
"version": 1
}
},
{
"actions": [
{
"type": "pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-4-2",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 7,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 1
}
],
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "global"
},
{
"name": "x-global-response",
"type": "set_backend_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 3,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-9",
"match": "all",
"name": "VCL vcl_backend_response branch line 9",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/ttl-priority"
]
}
]
]
}
],
"count": 7,
"group": "g1",
"index": 4,
"version": 1
}
},
{
"actions": [
{
"seconds": 60,
"type": "ttl"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-9-2",
"match": "all",
"name": "VCL vcl_backend_response line 9",
"stage": "response",
"vcl_flow": {
"count": 7,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 5,
"version": 1
}
},
{
"actions": [
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "global"
},
{
"name": "X-Global-Delivery",
"type": "set_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-12",
"match": "all",
"name": "VCL vcl_deliver line 12",
"stage": "deliver",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 6,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,112 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "global"
},
{
"name": "X-Global-Request",
"type": "set_request_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request"
},
{
"actions": [
{
"type": "pass"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/global-pass"
]
}
],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request",
"stop": true
},
{
"actions": [
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "global"
},
{
"name": "x-global-response",
"type": "set_backend_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response"
},
{
"actions": [
{
"seconds": 60,
"type": "ttl"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/ttl-priority"
]
}
],
"enabled": true,
"id": "vcl-response-9",
"match": "all",
"name": "VCL vcl_backend_response line 9",
"stage": "response"
},
{
"actions": [
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "global"
},
{
"name": "X-Global-Delivery",
"type": "set_header",
"value": "global"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-12",
"match": "all",
"name": "VCL vcl_deliver line 12",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1,14 @@
sub vcl_recv {
set req.http.X-Req-Scope = "global";
set req.http.X-Global-Request = "global";
if (req.url ~ "^/global-pass") { return(pass); }
}
sub vcl_backend_response {
set beresp.http.X-Beresp-Scope = "global";
set beresp.http.X-Global-Response = "global";
if (bereq.url ~ "^/ttl-priority") { set beresp.ttl = 60s; }
}
sub vcl_deliver {
set resp.http.X-Deliver-Scope = "global";
set resp.http.X-Global-Delivery = "global";
}
@@ -0,0 +1,224 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "first"
},
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "local"
},
{
"name": "X-Remove",
"type": "remove_request_header"
},
{
"name": "X-Empty",
"type": "set_request_header",
"value": ""
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-6",
"match": "all",
"name": "VCL vcl_recv branch line 6",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-Req-Scope",
"operator": "equals",
"values": [
"local"
]
}
]
]
}
],
"count": 7,
"group": "g1",
"index": 1,
"version": 1
}
},
{
"actions": [
{
"name": "X-Seen",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-6-2",
"match": "all",
"name": "VCL vcl_recv line 6",
"stage": "request",
"vcl_flow": {
"count": 7,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 1
}
],
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "first"
},
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "local"
},
{
"name": "x-origin-remove",
"type": "remove_backend_header"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-9",
"match": "all",
"name": "VCL vcl_backend_response line 9",
"stage": "response",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 3,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response branch line 12",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "response_header",
"name": "X-Beresp-Scope",
"operator": "equals",
"values": [
"local"
]
}
]
]
}
],
"count": 7,
"group": "g1",
"index": 4,
"version": 1
}
},
{
"actions": [
{
"name": "x-beresp-seen",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-12-2",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response",
"vcl_flow": {
"count": 7,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 5,
"version": 1
}
},
{
"actions": [
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "first"
},
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "local"
},
{
"name": "X-Origin-Deliver",
"type": "remove_header"
},
{
"name": "X-Empty-Response",
"type": "set_header",
"value": ""
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-15",
"match": "all",
"name": "VCL vcl_deliver line 15",
"stage": "deliver",
"vcl_flow": {
"count": 7,
"group": "g1",
"index": 6,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,138 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "first"
},
{
"name": "X-Req-Scope",
"type": "set_request_header",
"value": "local"
},
{
"name": "X-Remove",
"type": "remove_request_header"
},
{
"name": "X-Empty",
"type": "set_request_header",
"value": ""
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request"
},
{
"actions": [
{
"name": "X-Seen",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [
{
"field": "header",
"name": "X-Req-Scope",
"operator": "equals",
"values": [
"local"
]
}
],
"enabled": true,
"id": "vcl-request-6",
"match": "all",
"name": "VCL vcl_recv line 6",
"stage": "request"
},
{
"actions": [
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "first"
},
{
"name": "x-beresp-scope",
"type": "set_backend_header",
"value": "local"
},
{
"name": "x-origin-remove",
"type": "remove_backend_header"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-9",
"match": "all",
"name": "VCL vcl_backend_response line 9",
"stage": "response"
},
{
"actions": [
{
"name": "x-beresp-seen",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [
{
"field": "response_header",
"name": "X-Beresp-Scope",
"operator": "equals",
"values": [
"local"
]
}
],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response"
},
{
"actions": [
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "first"
},
{
"name": "X-Deliver-Scope",
"type": "set_header",
"value": "local"
},
{
"name": "X-Origin-Deliver",
"type": "remove_header"
},
{
"name": "X-Empty-Response",
"type": "set_header",
"value": ""
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-15",
"match": "all",
"name": "VCL vcl_deliver line 15",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1,19 @@
sub vcl_recv {
set req.http.X-Req-Scope = "first";
set req.http.X-Req-Scope = "local";
unset req.http.X-Remove;
set req.http.X-Empty = "";
if (req.http.X-Req-Scope == "local") { set req.http.X-Seen = "yes"; }
}
sub vcl_backend_response {
set beresp.http.X-Beresp-Scope = "first";
set beresp.http.X-Beresp-Scope = "local";
unset beresp.http.X-Origin-Remove;
if (beresp.http.X-Beresp-Scope == "local") { set beresp.http.X-Beresp-Seen = "yes"; }
}
sub vcl_deliver {
set resp.http.X-Deliver-Scope = "first";
set resp.http.X-Deliver-Scope = "local";
unset resp.http.X-Origin-Deliver;
set resp.http.X-Empty-Response = "";
}
@@ -0,0 +1,98 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv branch line 2",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-State",
"operator": "equals",
"values": [
"before"
]
}
]
]
},
{
"any": [
[]
]
}
],
"count": 3,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "X-State",
"type": "set_request_header",
"value": "after"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"vcl_flow": {
"count": 3,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [
{
"name": "X-Wrong",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request",
"vcl_flow": {
"count": 3,
"group": "g1",
"guards": [
{
"branch": 1,
"entry": 0
}
],
"index": 2,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,57 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-State",
"type": "set_request_header",
"value": "after"
}
],
"conditions": [
{
"field": "header",
"name": "X-State",
"operator": "equals",
"values": [
"before"
]
}
],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request"
},
{
"actions": [
{
"name": "X-Wrong",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [
{
"field": "header",
"name": "X-State",
"negate": true,
"operator": "equals",
"values": [
"before"
]
}
],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
}
],
"warnings": []
}
}
@@ -0,0 +1,7 @@
sub vcl_recv {
if (req.http.X-State == "before") {
set req.http.X-State = "after";
} else {
set req.http.X-Wrong = "yes";
}
}
@@ -0,0 +1,155 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv branch line 2",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-Flag",
"operator": "exists"
}
]
]
}
],
"count": 5,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "X-Flag",
"type": "remove_request_header"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"vcl_flow": {
"count": 5,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv branch line 4",
"stage": "request",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "header",
"name": "X-Flag",
"negate": true,
"operator": "exists"
}
]
]
}
],
"count": 5,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "X-Nested",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-4-2",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request",
"vcl_flow": {
"count": 5,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
},
{
"branch": 0,
"entry": 2
}
],
"index": 3,
"version": 1
}
},
{
"actions": [
{
"name": "X-Tail",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request",
"vcl_flow": {
"count": 5,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 4,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,76 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Flag",
"type": "remove_request_header"
}
],
"conditions": [
{
"field": "header",
"name": "X-Flag",
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request"
},
{
"actions": [
{
"name": "X-Nested",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [
{
"field": "header",
"name": "X-Flag",
"operator": "exists"
},
{
"field": "header",
"name": "X-Flag",
"negate": true,
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-4",
"match": "all",
"name": "VCL vcl_recv line 4",
"stage": "request"
},
{
"actions": [
{
"name": "X-Tail",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [
{
"field": "header",
"name": "X-Flag",
"operator": "exists"
}
],
"enabled": true,
"id": "vcl-request-5",
"match": "all",
"name": "VCL vcl_recv line 5",
"stage": "request"
}
],
"warnings": []
}
}
@@ -0,0 +1,7 @@
sub vcl_recv {
if (req.http.X-Flag) {
unset req.http.X-Flag;
if (!req.http.X-Flag) { set req.http.X-Nested = "yes"; }
set req.http.X-Tail = "yes";
}
}
@@ -0,0 +1,37 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Before",
"type": "set_request_header",
"value": "yes"
},
{
"name": "X-After",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request",
"vcl_flow": {
"count": 1,
"group": "g1",
"index": 0,
"version": 1
}
}
],
"warnings": [
"line 3: request header authorization cannot be changed by cache rules",
"line 4: request header host cannot be changed by cache rules"
]
}
}
@@ -0,0 +1,31 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Before",
"type": "set_request_header",
"value": "yes"
},
{
"name": "X-After",
"type": "set_request_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-2",
"match": "all",
"name": "VCL vcl_recv line 2",
"stage": "request"
}
],
"warnings": [
"line 3: request header authorization cannot be changed by cache rules",
"line 4: request header host cannot be changed by cache rules"
]
}
}
@@ -0,0 +1,6 @@
sub vcl_recv {
set req.http.X-Before = "yes";
set req.http.Authorization = "unsafe";
set req.http.Host = "unsafe.example";
set req.http.X-After = "yes";
}
@@ -0,0 +1,6 @@
{
"status": 422,
"body": {
"error": "line 2: unterminated string"
}
}
@@ -0,0 +1,6 @@
{
"status": 422,
"body": {
"error": "line 2: unterminated string"
}
}
@@ -0,0 +1,3 @@
sub vcl_recv {
set req.http.X-Broken = "unterminated;
}
@@ -0,0 +1,96 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Flow",
"type": "set_request_header",
"value": "before-hash"
},
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "X-Bucket",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-10",
"match": "all",
"name": "VCL vcl_hash line 10",
"stage": "request",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 1,
"version": 1
}
},
{
"actions": [
{
"name": "x-independent-response",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "X-Independent-Deliver",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-13",
"match": "all",
"name": "VCL vcl_deliver line 13",
"stage": "deliver",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 3,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,72 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Flow",
"type": "set_request_header",
"value": "before-hash"
},
{
"type": "lookup"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true
},
{
"actions": [
{
"name": "X-Bucket",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-10",
"match": "all",
"name": "VCL vcl_hash line 10",
"stage": "request"
},
{
"actions": [
{
"name": "x-independent-response",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-12",
"match": "all",
"name": "VCL vcl_backend_response line 12",
"stage": "response"
},
{
"actions": [
{
"name": "X-Independent-Deliver",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-13",
"match": "all",
"name": "VCL vcl_deliver line 13",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1,13 @@
sub vcl_recv {
set req.http.X-Flow = "before-hash";
return(hash);
set req.http.X-Flow = "after-hash";
return(pass);
}
sub vcl_hash {
hash_data(req.url);
hash_data(req.http.Host);
hash_data(req.http.X-Bucket);
}
sub vcl_backend_response { set beresp.http.X-Independent-Response = "yes"; }
sub vcl_deliver { set resp.http.X-Independent-Deliver = "yes"; }
@@ -0,0 +1,96 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Flow",
"type": "set_request_header",
"value": "before-pass"
},
{
"type": "pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true,
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"name": "X-Bucket",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-7",
"match": "all",
"name": "VCL vcl_hash line 7",
"stage": "request",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 1,
"version": 1
}
},
{
"actions": [
{
"name": "x-independent-response",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-8",
"match": "all",
"name": "VCL vcl_backend_response line 8",
"stage": "response",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 2,
"version": 1
}
},
{
"actions": [
{
"name": "X-Independent-Deliver",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-9",
"match": "all",
"name": "VCL vcl_deliver line 9",
"stage": "deliver",
"vcl_flow": {
"count": 4,
"group": "g1",
"index": 3,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,72 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "X-Flow",
"type": "set_request_header",
"value": "before-pass"
},
{
"type": "pass"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-request-3",
"match": "all",
"name": "VCL vcl_recv line 3",
"stage": "request",
"stop": true
},
{
"actions": [
{
"name": "X-Bucket",
"type": "hash_header"
}
],
"conditions": [],
"enabled": true,
"hash_stage": true,
"id": "vcl-request-7",
"match": "all",
"name": "VCL vcl_hash line 7",
"stage": "request"
},
{
"actions": [
{
"name": "x-independent-response",
"type": "set_backend_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-8",
"match": "all",
"name": "VCL vcl_backend_response line 8",
"stage": "response"
},
{
"actions": [
{
"name": "X-Independent-Deliver",
"type": "set_header",
"value": "yes"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-9",
"match": "all",
"name": "VCL vcl_deliver line 9",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1,9 @@
sub vcl_recv {
set req.http.X-Flow = "before-pass";
return(pass);
set req.http.X-Flow = "after-pass";
return(hash);
}
sub vcl_hash { hash_data(req.http.X-Bucket); }
sub vcl_backend_response { set beresp.http.X-Independent-Response = "yes"; }
sub vcl_deliver { set resp.http.X-Independent-Deliver = "yes"; }
@@ -0,0 +1,253 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-2",
"match": "all",
"name": "VCL vcl_backend_response branch line 2",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/ttl"
]
}
]
]
}
],
"count": 8,
"group": "g1",
"index": 0,
"version": 1
}
},
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 0,
"type": "grace"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-3",
"match": "all",
"name": "VCL vcl_backend_response line 3",
"stage": "response",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 0
}
],
"index": 1,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-6",
"match": "all",
"name": "VCL vcl_backend_response branch line 6",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/grace"
]
}
]
]
}
],
"count": 8,
"group": "g1",
"index": 2,
"version": 1
}
},
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 3,
"type": "grace"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 2
}
],
"index": 3,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-10",
"match": "all",
"name": "VCL vcl_backend_response branch line 10",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "url",
"operator": "regex",
"values": [
"^/validation-no-store"
]
}
]
]
}
],
"count": 8,
"group": "g1",
"index": 4,
"version": 1
}
},
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 0,
"type": "grace"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-11",
"match": "all",
"name": "VCL vcl_backend_response line 11",
"stage": "response",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 5,
"version": 1
}
},
{
"actions": [],
"conditions": [],
"enabled": true,
"id": "vcl-response-13",
"match": "all",
"name": "VCL vcl_backend_response branch line 13",
"stage": "response",
"vcl_flow": {
"branches": [
{
"any": [
[
{
"field": "status",
"operator": "equals",
"values": [
"304"
]
}
]
]
}
],
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
}
],
"index": 6,
"version": 1
}
},
{
"actions": [
{
"type": "no_store"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-13-2",
"match": "all",
"name": "VCL vcl_backend_response line 13",
"stage": "response",
"vcl_flow": {
"count": 8,
"group": "g1",
"guards": [
{
"branch": 0,
"entry": 4
},
{
"branch": 0,
"entry": 6
}
],
"index": 7,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,114 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 0,
"type": "grace"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/ttl"
]
}
],
"enabled": true,
"id": "vcl-response-3",
"match": "all",
"name": "VCL vcl_backend_response line 3",
"stage": "response"
},
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 3,
"type": "grace"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/grace"
]
}
],
"enabled": true,
"id": "vcl-response-7",
"match": "all",
"name": "VCL vcl_backend_response line 7",
"stage": "response"
},
{
"actions": [
{
"seconds": 2,
"type": "ttl"
},
{
"seconds": 0,
"type": "grace"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/validation-no-store"
]
}
],
"enabled": true,
"id": "vcl-response-11",
"match": "all",
"name": "VCL vcl_backend_response line 11",
"stage": "response"
},
{
"actions": [
{
"type": "no_store"
}
],
"conditions": [
{
"field": "url",
"operator": "regex",
"values": [
"^/validation-no-store"
]
},
{
"field": "status",
"operator": "equals",
"values": [
"304"
]
}
],
"enabled": true,
"id": "vcl-response-13",
"match": "all",
"name": "VCL vcl_backend_response line 13",
"stage": "response"
}
],
"warnings": []
}
}
@@ -0,0 +1,15 @@
sub vcl_backend_response {
if (bereq.url ~ "^/ttl") {
set beresp.ttl = 2s;
set beresp.grace = 0s;
}
if (bereq.url ~ "^/grace") {
set beresp.ttl = 2s;
set beresp.grace = 3s;
}
if (bereq.url ~ "^/validation-no-store") {
set beresp.ttl = 2s;
set beresp.grace = 0s;
if (beresp.status == 304) { set beresp.uncacheable = true; }
}
}
@@ -0,0 +1,29 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "vary",
"type": "set_backend_header",
"value": "X-Language"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-1",
"match": "all",
"name": "VCL vcl_backend_response line 1",
"stage": "response",
"vcl_flow": {
"count": 1,
"group": "g1",
"index": 0,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,23 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "vary",
"type": "set_backend_header",
"value": "X-Language"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-1",
"match": "all",
"name": "VCL vcl_backend_response line 1",
"stage": "response"
}
],
"warnings": []
}
}
@@ -0,0 +1 @@
sub vcl_backend_response { set beresp.http.Vary = "X-Language"; }
@@ -0,0 +1,29 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "Vary",
"type": "set_header",
"value": "X-Public"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-1",
"match": "all",
"name": "VCL vcl_deliver line 1",
"stage": "deliver",
"vcl_flow": {
"count": 1,
"group": "g1",
"index": 0,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,23 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "Vary",
"type": "set_header",
"value": "X-Public"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-deliver-1",
"match": "all",
"name": "VCL vcl_deliver line 1",
"stage": "deliver"
}
],
"warnings": []
}
}
@@ -0,0 +1 @@
sub vcl_deliver { set resp.http.Vary = "X-Public"; }
@@ -0,0 +1,28 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "vary",
"type": "remove_backend_header"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-1",
"match": "all",
"name": "VCL vcl_backend_response line 1",
"stage": "response",
"vcl_flow": {
"count": 1,
"group": "g1",
"index": 0,
"version": 1
}
}
],
"warnings": []
}
}
@@ -0,0 +1,22 @@
{
"status": 200,
"body": {
"rules": [
{
"actions": [
{
"name": "vary",
"type": "remove_backend_header"
}
],
"conditions": [],
"enabled": true,
"id": "vcl-response-1",
"match": "all",
"name": "VCL vcl_backend_response line 1",
"stage": "response"
}
],
"warnings": []
}
}
@@ -0,0 +1 @@
sub vcl_backend_response { unset beresp.http.Vary; }
-183
View File
@@ -1,183 +0,0 @@
#!/usr/bin/env python3
"""Concurrent persistent-connection HTTP load + optional Linux RustProxy RSS sampler.
This script issues REAL HTTP requests only when pointed at a RUNNING service.
A Python test origin can verify the load generator but cannot validate RustProxy
memory. Use an isolated staging instance, not a production endpoint by default.
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import http.client
import json
from pathlib import Path
import ssl
import threading
import time
from urllib.parse import urlsplit
def proc_sample(pid: int) -> dict | None:
path = Path(f"/proc/{pid}")
try:
status = (path / "status").read_text(encoding="utf-8")
counters: dict[str, int] = {}
for row in status.splitlines():
if row.startswith(("VmRSS:", "VmHWM:", "Threads:")):
name, value = row.split(":", 1)
counters[name.lower()] = int(value.split()[0]) * (1024 if name != "Threads" else 1)
counters["open_fds"] = len(list((path / "fd").iterdir()))
return counters
except (OSError, ValueError, IndexError):
return None
def run_load(
*, url: str, requests: int, concurrency: int, unique_paths: int,
timeout: float, host_header: str | None = None, pid: int | None = None,
sample_interval: float = 1.0, cooldown: float = 0.0, insecure: bool = False,
) -> dict:
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password:
raise ValueError("URL must be http(s)://host[:port]/path without credentials")
if requests < 1 or not (1 <= concurrency <= 2048) or unique_paths < 0:
raise ValueError("requests >= 1, concurrency 1..2048 and unique_paths >= 0 are required")
if not (0 < timeout <= 120) or sample_interval <= 0 or cooldown < 0:
raise ValueError("invalid timeout/sampling/cooldown")
base_target = parsed.path or "/"
if parsed.query:
base_target += "?" + parsed.query
if unique_paths and parsed.query:
raise ValueError("unique-path mode expects a URL without query parameters")
port = parsed.port or (443 if parsed.scheme == "https" else 80)
tls = ssl._create_unverified_context() if insecure else ssl.create_default_context()
connection_type = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
headers = {"user-agent": "RustProxy-Memory-Stress/0.31.5", "accept": "*/*"}
if host_header:
headers["host"] = host_header
sampler_stop = threading.Event()
trace: list[dict] = []
started = time.monotonic()
def sampler() -> None:
while not sampler_stop.is_set():
point = proc_sample(pid) if pid is not None else None
if point is not None:
trace.append({"elapsed_seconds": round(time.monotonic() - started, 2), **point})
sampler_stop.wait(sample_interval)
sampler_thread = threading.Thread(target=sampler, daemon=True)
if pid is not None:
sampler_thread.start()
index_lock = threading.Lock()
cursor = 0
def next_index() -> int | None:
nonlocal cursor
with index_lock:
if cursor >= requests:
return None
index = cursor
cursor += 1
return index
def worker() -> tuple[Counter, int]:
statuses: Counter = Counter()
total_bytes = 0
connection = None
while True:
index = next_index()
if index is None:
break
if unique_paths:
target = base_target.rstrip("/") + f"/memory-{index % unique_paths}"
else:
target = base_target
try:
if connection is None:
options = {"timeout": timeout}
if parsed.scheme == "https":
options["context"] = tls
connection = connection_type(parsed.hostname, port, **options)
connection.request("GET", target, headers=headers)
response = connection.getresponse()
statuses[str(response.status)] += 1
while chunk := response.read(64 * 1024):
total_bytes += len(chunk)
if response.will_close:
connection.close()
connection = None
except (OSError, TimeoutError, http.client.HTTPException) as error:
statuses["error:" + type(error).__name__] += 1
if connection is not None:
connection.close()
connection = None
if connection is not None:
connection.close()
return statuses, total_bytes
try:
with ThreadPoolExecutor(max_workers=concurrency) as executor:
results = list(executor.map(lambda _: worker(), range(concurrency)))
traffic_end = time.monotonic()
if cooldown:
time.sleep(cooldown)
end = time.monotonic()
finally:
sampler_stop.set()
if pid is not None:
sampler_thread.join(timeout=sample_interval + 1)
statuses: Counter = Counter()
received = 0
for codes, response_bytes in results:
statuses.update(codes)
received += response_bytes
report = {
"target": f"{parsed.scheme}://{parsed.hostname}:{port}{base_target}",
"requests_sent": sum(statuses.values()),
"concurrency": concurrency,
"unique_paths": unique_paths,
"statuses": dict(sorted(statuses.items())),
"response_bytes_read": received,
"traffic_seconds": round(traffic_end - started, 3),
"requests_per_second": round(requests / max(0.001, traffic_end - started), 1),
"wall_seconds": round(end - started, 3),
"sampler_pid": pid,
"rss_start_mib": round(trace[0]["vmrss"] / (1024 * 1024), 2) if trace else None,
"rss_peak_mib": round(max(t["vmrss"] for t in trace) / (1024 * 1024), 2) if trace else None,
"rss_end_mib": round(trace[-1]["vmrss"] / (1024 * 1024), 2) if trace else None,
"open_fds_peak": max((t["open_fds"] for t in trace), default=None),
"threads_peak": max((t.get("threads", 0) for t in trace), default=None),
"rss_samples": trace,
"note": "Process RSS values apply only to --pid. No PID means no RustProxy memory measurement.",
}
return report
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", required=True, help="Staging URL (use your configured vhost route)")
parser.add_argument("--host-header", help="HTTP Host for a named vhost")
parser.add_argument("--pid", type=int, help="Linux PID of the RustProxy process to sample from /proc")
parser.add_argument("--requests", type=int, default=100_000)
parser.add_argument("--concurrency", type=int, default=64)
parser.add_argument("--unique-paths", type=int, default=0, help="Cycle this many distinct URL paths; 0 repeats the same path")
parser.add_argument("--timeout", type=float, default=8.0)
parser.add_argument("--sample-interval", type=float, default=1.0)
parser.add_argument("--cooldown", type=float, default=30.0, help="Observe RSS after traffic stops")
parser.add_argument("--insecure", action="store_true", help="Ignore TLS verification for self-signed STAGING only")
parser.add_argument("--output", type=Path, help="Optional machine-readable JSON report path")
args = parser.parse_args()
report = run_load(url=args.url, host_header=args.host_header, pid=args.pid, requests=args.requests,
concurrency=args.concurrency, unique_paths=args.unique_paths, timeout=args.timeout,
sample_interval=args.sample_interval, cooldown=args.cooldown, insecure=args.insecure)
print(json.dumps({k: v for k, v in report.items() if k != "rss_samples"}, indent=2))
if args.output:
args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()
-147
View File
@@ -1,147 +0,0 @@
#!/usr/bin/env python3
"""LOOPBACK-ONLY fake Tinyauth protocol peer. NEVER use this as real authentication.
A cookie named mock_auth with value allow approves a request. Any client can mint it.
This exists to test RustProxy auth_request, identity forwarding and fail-closed paths.
"""
from __future__ import annotations
import argparse
from collections import deque
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
import threading
import time
from urllib.parse import urlsplit
class State:
def __init__(self):
self.lock = threading.Lock()
self.status = None
self.delay_ms = 0
self.location = None
self.calls = 0
self.recent = deque(maxlen=16)
class Server(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, address, state=None):
if not ipaddress.ip_address(address[0]).is_loopback:
raise ValueError("The fake auth server may bind only a numeric loopback address")
self.state = state or State()
super().__init__(address, Handler)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "RustProxy-Mock-Auth/0.4.0"
sys_version = ""
def log_message(self, *_):
pass
def setup(self):
super().setup()
self.connection.settimeout(5)
def reply(self, status, value=None, headers=()):
data = b"" if value is None else json.dumps(value, ensure_ascii=True).encode()
self.send_response(status)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Type", "application/json")
for key, value in headers:
self.send_header(key, value)
self.end_headers()
if self.command != "HEAD":
try:
self.wfile.write(data)
except (BrokenPipeError, ConnectionResetError):
pass
def do_GET(self):
path = urlsplit(self.path).path
if self.headers.get("Transfer-Encoding") or self.headers.get("Content-Length", "0") != "0":
self.close_connection = True
return self.reply(400, {"error":"GET verification requests must have no body"})
state = self.server.state
if path == "/api/auth/nginx":
cookie = SimpleCookie()
try:
cookie.load(self.headers.get("Cookie", ""))
except Exception:
pass
allowed = "mock_auth" in cookie and cookie["mock_auth"].value == "allow"
with state.lock:
state.calls += 1
# Do not store Cookie, Authorization, API keys, or query strings.
state.recent.append({"method":self.headers.get("X-Original-Method"),
"client":self.headers.get("X-Real-IP"), "host":self.headers.get("X-Forwarded-Host"),
"proto":self.headers.get("X-Forwarded-Proto"),
"forwarded":self.headers.get("Forwarded"),"xff":self.headers.get("X-Forwarded-For")})
status = state.status if state.status is not None else (204 if allowed else 401)
delay_ms, location = state.delay_ms, state.location
time.sleep(delay_ms / 1000)
headers = []
if 200 <= status < 300:
headers = [("Remote-User", "mock-user"), ("Remote-Email", "mock@example.test"), ("Remote-Groups", "testers")]
if location:
headers.append(("X-Tinyauth-Location", location))
return self.reply(status, headers=headers)
if path == "/state":
with state.lock:
return self.reply(200, {"calls":state.calls,"status":state.status,"delay_ms":state.delay_ms,"recent":list(state.recent)})
if path == "/login":
return self.reply(200, {"warning":"Fake login fixture, not authentication", "test_cookie":"mock_auth=allow", "instructions":"Send this cookie to the protected local test vhost."})
self.reply(404, {"error":"not found"})
def do_POST(self):
if urlsplit(self.path).path != "/control":
self.close_connection = True
return self.reply(405, {"error":"only POST /control is supported"})
try:
if self.headers.get("Transfer-Encoding") or len(self.headers.get_all("Content-Length", [])) != 1:
raise ValueError("one Content-Length is required")
size = int(self.headers["Content-Length"])
if not 0 <= size <= 4096:
raise ValueError("body limit is 4096 bytes")
data = self.rfile.read(size)
if len(data) != size:
raise ValueError("incomplete request")
payload = json.loads(data)
if not isinstance(payload, dict) or set(payload) - {"status", "delay_ms", "location", "reset"}:
raise ValueError("invalid fields")
status = payload.get("status")
if status is not None and (type(status) is not int or status not in (200, 204, 401, 403, 500, 503)):
raise ValueError("unsupported verification status")
delay = payload.get("delay_ms", 0)
if type(delay) is not int or not 0 <= delay <= 15000:
raise ValueError("delay must be 0..15000 ms")
location = payload.get("location")
if location is not None and (not isinstance(location, str) or len(location) > 2048
or any(ord(c) < 32 or ord(c) > 126 for c in location)):
raise ValueError("invalid redirect header")
with self.server.state.lock:
state = self.server.state
if payload.get("reset"):
state.calls = 0
state.recent.clear()
state.status, state.delay_ms, state.location = status, delay, location
except (ValueError, KeyError, TimeoutError, OSError) as error:
self.close_connection = True
return self.reply(400, {"error":str(error)})
self.reply(200, {"updated":True})
def do_HEAD(self):
self.do_GET()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=9300)
args = parser.parse_args()
if not 1 <= args.port <= 65535:
parser.error("port must be 1..65535")
server = Server(("127.0.0.1", args.port))
print(f"FAKE AUTH - LOCAL TESTING ONLY: http://127.0.0.1:{args.port}/api/auth/nginx", flush=True)
print("Approve with Cookie: mock_auth=allow. /control configures failures/delays. Ctrl+C stops.", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()
-191
View File
@@ -1,191 +0,0 @@
#!/usr/bin/env python3
"""Local HTTP/1.1 origin for manual cache, health, compression and pool tests.
Only Python's standard library is used. This is not a production application.
"""
from __future__ import annotations
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
import secrets
import threading
import time
from urllib.parse import parse_qs, urlsplit
MAX_BODY = 2 * 1024 * 1024
MAX_WORKERS = 32
class State:
def __init__(self, name="origin-a", ttl=30):
self.name, self.ttl = name, ttl
self.healthy, self.delay_ms, self.sequence = True, 0, 0
self.lock = threading.Lock()
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, address, state):
self.state = state
self.slots = threading.BoundedSemaphore(MAX_WORKERS)
super().__init__(address, Handler)
def process_request(self, request, client_address):
if not self.slots.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.slots.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.slots.release()
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "RustProxy-Mock/0.3.0"
def setup(self):
super().setup()
self.connection.settimeout(15)
def log_message(self, *_):
pass
def send(self, status, body=b"", content_type="application/json; charset=utf-8", control="no-store", extra=None):
if isinstance(body, dict):
body = (json.dumps(body, ensure_ascii=False) + "\n").encode()
if isinstance(body, str):
body = body.encode()
if status in (204, 304):
body = b""
self.send_response(status)
self.send_header("Content-Type", content_type)
if status != 204:
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", control)
self.send_header("X-Mock-Origin", self.server.state.name)
for name, value in (extra or {}).items():
self.send_header(name, value)
self.end_headers()
if self.command != "HEAD":
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError, TimeoutError):
self.close_connection = True
def integer(self, query, key, default, maximum):
value = int(query.get(key, [str(default)])[0])
if not 0 <= value <= maximum:
raise ValueError(key)
return value
def do_HEAD(self):
self.do_GET()
def do_GET(self):
target = urlsplit(self.path)
q = parse_qs(target.query)
state = self.server.state
try:
delay = self.integer(q, "ms", 800 if target.path == "/slow" else 0, 10000)
size = self.integer(q, "size", 65536, MAX_BODY)
ttl = self.integer(q, "ttl", state.ttl, 604800)
except ValueError:
return self.send(400, {"error":"invalid query parameter"})
with state.lock:
state.sequence += 1
sequence, healthy = state.sequence, state.healthy
delay += state.delay_ms
if delay:
time.sleep(min(delay, 10000) / 1000)
payload = {"origin":state.name, "sequence":sequence, "generated_at_ns":time.time_ns(),
"nonce":secrets.token_hex(16), "path":target.path,
"accept_language":self.headers.get("Accept-Language", ""), "healthy":healthy}
if target.path == "/health":
return self.send(200 if healthy else 503, payload)
if target.path == "/state":
return self.send(200, {**payload, "delay_ms":state.delay_ms, "ttl":state.ttl})
if target.path == "/":
return self.send(200, """<!doctype html><meta charset="utf-8"><title>RustProxy mock origin</title>
<h1>RustProxy test origin</h1><p>Each uncached request generates a new sequence and nonce.</p>
<ul><li><a href="/cache">/cache</a> - public JSON, 30-second freshness by default</li>
<li><a href="/nocache">/nocache</a> - no-store JSON</li><li><a href="/private">/private</a> - private JSON</li>
<li><a href="/cookie">/cookie</a> - Set-Cookie, bypass shared cache</li><li><a href="/large">/large?size=65536</a> - compressible bytes</li>
<li><a href="/slow">/slow?ms=800</a> - controlled delay</li><li><a href="/health">/health</a> - active probe target</li>
<li><a href="/status/503">/status/503</a> - custom error page test</li></ul>
<p>POST /control with JSON {"healthy":false,"delay_ms":0} to test failover/recovery.</p>""", "text/html; charset=utf-8")
if target.path == "/large":
prefix = (json.dumps(payload) + "\n").encode()
body = (prefix + b"RustProxy compression and cache fixture.\n" * (size // 30 + 1))[:size]
return self.send(200, body, "text/plain; charset=utf-8", f"public, max-age={ttl}")
if target.path.startswith("/status/"):
try:
status = int(target.path.rsplit("/", 1)[1])
if status not in [200, 204, 400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504]:
raise ValueError()
except ValueError:
return self.send(400, {"error":"unsupported status"})
return self.send(status, payload, extra={"WWW-Authenticate":'Basic realm="mock"'} if status == 401 else None)
if target.path == "/cache":
return self.send(200, payload, control=f"public, max-age={ttl}", extra={"Vary":"Accept-Language"})
if target.path == "/private":
return self.send(200, payload, control="private, max-age=60")
if target.path == "/cookie":
return self.send(200, payload, control=f"public, max-age={ttl}", extra={"Set-Cookie":"mock-session=demo; HttpOnly; SameSite=Lax; Path=/"})
self.send(200 if target.path in ("/nocache", "/slow") else 404, payload)
def do_POST(self):
# Always consume or close a body before reusing an HTTP/1.1 connection.
if self.headers.get("Transfer-Encoding") or len(self.headers.get_all("Content-Length", [])) != 1:
self.close_connection = True
return self.send(411, {"error":"one Content-Length is required"})
try:
length = int(self.headers["Content-Length"])
if not 0 <= length <= 4096:
raise ValueError()
raw = self.rfile.read(length)
if len(raw) != length:
raise ValueError()
data = json.loads(raw)
if self.path != "/control" or not isinstance(data, dict) or set(data) - {"healthy", "delay_ms"}:
raise ValueError()
if "healthy" in data and not isinstance(data["healthy"], bool):
raise ValueError()
if "delay_ms" in data and (type(data["delay_ms"]) is not int or not 0 <= data["delay_ms"] <= 10000):
raise ValueError()
except (ValueError, TimeoutError):
self.close_connection = True
return self.send(400, {"error":"expected healthy: boolean and/or delay_ms: 0..10000"})
with self.server.state.lock:
for key, value in data.items():
setattr(self.server.state, key, value)
self.send(200, {"updated":True})
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=9001)
parser.add_argument("--name", default="origin-a")
parser.add_argument("--ttl", type=int, default=30)
parser.add_argument("--allow-remote", action="store_true", help="Explicitly expose this development-only server on a non-loopback IPv4 address")
args = parser.parse_args()
try:
ip = ipaddress.ip_address(args.host)
except ValueError:
parser.error("--host must be an IPv4 address")
if ip.version != 4:
parser.error("this development helper accepts IPv4 bindings only")
if not ip.is_loopback and not args.allow_remote:
parser.error("non-loopback binding requires --allow-remote; /control is unauthenticated")
if not 0 <= args.port <= 65535 or not 0 <= args.ttl <= 604800:
parser.error("invalid port or TTL")
if not args.name or len(args.name) > 64 or any(ord(c) < 32 or ord(c) > 126 for c in args.name):
parser.error("--name must contain 1..64 printable ASCII characters")
server = Server((args.host, args.port), State(args.name, args.ttl))
print(f"Mock origin {args.name}: http://{args.host}:{server.server_port} (development only)", flush=True)
print("Endpoints: /cache /nocache /private /cookie /large /slow /health /status/503; POST /control", flush=True)
try:
server.serve_forever(poll_interval=0.2)
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()