#!/usr/bin/env python3 """Loopback-only smoke tests using disposable containers and synthetic records.""" import argparse import base64 import json import os from pathlib import Path import re import subprocess import urllib.error import urllib.parse import urllib.request SOURCE = "int filter(int length) { return length <= 8192; }" OLD_JOURNAL = "/var/log/lighthouse/1999-12-31/synthetic-legacy.log" OLD_CONTENT = "synthetic legacy journal; retain these bytes\n" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("seed", "verify")) parser.add_argument("--url", required=True) parser.add_argument("--container", required=True) parser.add_argument("--state", type=Path, required=True) parser.add_argument("--journal", choices=("baseline", "private"), required=True) args = parser.parse_args() parsed = urllib.parse.urlsplit(args.url) if (parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost", "::1") or parsed.username or parsed.password or parsed.query or parsed.fragment): parser.error("tests only accept an explicit loopback HTTP URL") if not re.fullmatch(r"goctf-lighthouse-lab-[a-z0-9-]+", args.container): parser.error("use a disposable container named goctf-lighthouse-lab-...") origin = args.url.rstrip("/") opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) checks = 0 def check(condition, message): nonlocal checks if not condition: raise AssertionError(message) checks += 1 def api(method, path, body=None, key=None, expected=200): headers = {"Content-Type": "application/json"} if key is not None: headers["X-Queue-Key"] = key request = urllib.request.Request(origin + path, method=method, headers=headers, data=None if body is None else json.dumps(body).encode()) try: response = opener.open(request, timeout=12) except urllib.error.HTTPError as error: response = error with response: status = response.status result = json.loads(response.read()) check(status == expected, f"unexpected HTTP status for {method} {path}: {status}") return result def inside(*command, user=None): command_line = ["docker", "exec"] if user: command_line.extend(("--user", user)) return subprocess.run(command_line + [args.container, *command], capture_output=True, text=True, timeout=15) def mode(path): result = inside("stat", "-c", "%a", path) check(result.returncode == 0, "cannot inspect synthetic journal permissions") return result.stdout.strip() check(api("GET", "/api/health")["status"] == "ok", "health response changed") if args.action == "seed": check(not args.state.exists(), "refusing to overwrite a previous test state") queue = api("POST", "/api/queues", {"label": "regression mailbox", "retention_seconds": 3600}, expected=201) check(bool(re.fullmatch(r"[0-9a-f-]{36}", queue["id"])), "invalid generated queue ID") check(bool(re.fullmatch(r"[0-9a-f]{48}", queue["read_key"])), "invalid generated read key") path = "/api/queues/" + queue["id"] other = api("POST", "/api/queues", {"label": "other mailbox"}, expected=201) api("GET", path + "/messages", expected=403) api("GET", path + "/messages", key=other["read_key"], expected=403) api("POST", path + "/messages", {"message": "not-base64"}, expected=400) api("POST", path + "/messages", {"message": "eA==", "topic": "invalid/topic"}, expected=400) compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "length filter"}) check(compiled["ok"] is True, "ordinary C filter did not compile") api("POST", path + f"/filters/{compiled['revision']}/activate", {}, expected=403) api("POST", path + f"/filters/{compiled['revision']}/activate", {}, key=queue["read_key"]) api("GET", path + f"/filters/{compiled['revision']}", expected=403) rejected = api("POST", path + "/filter", {"source": "int filter(int x) { return ; broken }"}, expected=422) check(rejected["ok"] is False and bool(rejected["compiler"]), "compiler diagnostics missing") raw = b"synthetic regression message\x00with binary data" api("POST", path + "/messages", {"message": base64.b64encode(raw).decode(), "topic": "regression"}, expected=201) received = api("GET", path + "/messages", key=queue["read_key"])["messages"] check(len(received) == 1 and received[0]["topic"] == "regression", "normal delivery failed") check(bool(re.fullmatch(r"[0-9a-f]+", received[0]["ciphertext"])), "ciphertext encoding changed") check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [], "reading did not mark the message") journal = f"/var/log/lighthouse/{queue['created_at'][:10]}/{queue['id']}.log" create_old = inside("sh", "-c", 'mkdir -p /var/log/lighthouse/1999-12-31 && ' 'printf "%s\\n" "synthetic legacy journal; retain these bytes" ' '> /var/log/lighthouse/1999-12-31/synthetic-legacy.log && ' 'chmod 755 /var/log/lighthouse/1999-12-31 && ' 'chmod 644 /var/log/lighthouse/1999-12-31/synthetic-legacy.log') check(create_old.returncode == 0, "cannot prepare synthetic legacy journal") state = {"queue": queue, "revision": compiled["revision"], "message": received[0], "journal": journal} args.state.parent.mkdir(mode=0o700, parents=True, exist_ok=True) descriptor = os.open(args.state, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(descriptor, "w") as stream: json.dump(state, stream) else: state = json.loads(args.state.read_text()) queue = state["queue"] path = "/api/queues/" + queue["id"] metadata = api("GET", path) check(metadata["label"] == "regression mailbox" and metadata["filter_installed"], "queue metadata or active filter was lost") messages = api("GET", path + "/messages?show_read=true", key=queue["read_key"])["messages"] check(state["message"] in messages, "old message or ciphertext changed across restart") check(api("GET", path + "/messages", key=queue["read_key"])["messages"] == [], "old read_at state was not retained") details = api("GET", path + f"/filters/{state['revision']}", key=queue["read_key"]) check(details["source"] == SOURCE and details["active"], "old filter was not retained") api("GET", path + "/messages?show_read=true", key="0" * 48, expected=403) api("POST", path + "/messages", {"message": "bmV3IHN5bnRoZXRpYyBtZXNzYWdl"}, expected=201) check(len(api("GET", path + "/messages", key=queue["read_key"])["messages"]) == 1, "old active filter rejected a normal new message") api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, expected=403) api("POST", "/api/queues/00000000-0000-0000-0000-000000000000/filter", {"source": SOURCE, "label": "missing queue"}, expected=404) api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, key="0" * 48, expected=403) compiled = api("POST", path + "/filter", {"source": SOURCE, "label": "post restart"}, key=queue["read_key"]) check(compiled["ok"] is True, "compilation contract changed after restart") paging = api("POST", "/api/queues", {"label": "pagination regression"}, expected=201) paging_path = "/api/queues/" + paging["id"] + "/messages" for index in range(130): api("POST", paging_path, {"message": "eA==", "topic": "page"}, expected=201) first = api("GET", paging_path, key=paging["read_key"]) check(len(first["messages"]) == 128 and first["has_more"], "first page boundary changed") check(first["next_after"] == first["messages"][-1]["id"], "first page cursor changed") second = api("GET", paging_path + "?after_id=" + str(first["next_after"]), key=paging["read_key"]) check(len(second["messages"]) == 2 and not second["has_more"], "unread messages beyond first page were lost") check(second["messages"][0]["id"] > first["messages"][-1]["id"], "page order changed") check(api("GET", paging_path, key=paging["read_key"])["messages"] == [], "paged read did not mark exactly the delivered messages") check(len(api("GET", paging_path + "?show_read=true", key=paging["read_key"])["messages"]) == 128, "history page changed") api("GET", paging_path + "?after_id=-1", key=paging["read_key"], expected=400) api("GET", paging_path + "?after_id=9223372036854775808", key=paging["read_key"], expected=400) expiring = api("POST", "/api/queues", {"label": "expired cleanup"}, expected=201) expiring_path = "/api/queues/" + expiring["id"] api("POST", expiring_path + "/messages", {"message": "eA=="}, expected=201) updated = inside("sqlite3", "/data/lighthouse.db", "UPDATE messages SET expires_at=0 WHERE queue_id='" + expiring["id"] + "'") check(updated.returncode == 0, "cannot prepare synthetic expired row") api("POST", "/api/queues", {"label": "cleanup trigger"}, expected=201) check(api("GET", expiring_path)["stored_count"] == 0, "expired rows were not reclaimed by a public write") capped = api("POST", "/api/queues", {"label": "bounded journal"}, expected=201) capped_path = "/api/queues/" + capped["id"] encoded = base64.b64encode(b"x" * 4096).decode() for index in range(68): api("POST", capped_path + "/messages", {"message": encoded}, expected=201) journal_path = f"/var/log/lighthouse/{capped['created_at'][:10]}/{capped['id']}.log" journal_size = inside("stat", "-c", "%s", journal_path) check(journal_size.returncode == 0 and 0 < int(journal_size.stdout) <= 512 * 1024, "journal exceeded the per-queue cap") check(api("GET", capped_path)["stored_count"] == 68, "journal cap dropped messages from SQLite") old = inside("cat", OLD_JOURNAL) check(old.returncode == 0 and old.stdout == OLD_CONTENT, "legacy journal bytes were altered") diagnostic = api("POST", path + "/filter", { "source": '#include "' + OLD_JOURNAL + '"\nint filter(int length) { return 1; }', "label": "synthetic journal regression", }, key=queue["read_key"] if args.action == "verify" else None, expected=422)["compiler"] check((OLD_CONTENT.strip() in diagnostic) == (args.journal == "baseline"), "unexpected disclosure of the synthetic journal through compiler diagnostics") incbin = '__asm__(".incbin \\"' + OLD_JOURNAL + '\\",0,32");\nint filter(int length) { return 1; }' compiled_bytes = api("POST", path + "/filter", { "source": incbin, "label": "synthetic incbin regression", }, key=queue["read_key"] if args.action == "verify" else None, expected=422 if args.journal == "private" else 200) check(compiled_bytes["ok"] == (args.journal == "baseline"), "unexpected journal embedding result") expected = "700" if args.journal == "private" else "755" check(mode("/var/log/lighthouse") == expected, "unexpected journal root permissions") for journal in (state["journal"], OLD_JOURNAL): result = inside("test", "-r", journal, user="nobody") check((result.returncode != 0) == (args.journal == "private"), "unexpected unprivileged access to a synthetic journal") if args.journal == "private": check(mode(str(Path(state["journal"]).parent)) == "700", "new journal directory is not private") check(mode(state["journal"]) == "600", "new journal file is not private") print(f"PASS: {checks} checks ({args.action}, journal={args.journal}); no record values printed") if __name__ == "__main__": main()