From bc62b6f03dc022b82a539a35a10129ad3a88257c Mon Sep 17 00:00:00 2001 From: oqyude Date: Tue, 13 Oct 2026 02:48:30 +0300 Subject: [PATCH] =?UTF-8?q?feat(pxe-infra):=20add=20HTTP=20report=20sink?= =?UTF-8?q?=20=E2=80=94=20L6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last layer of the boot-and-report pipeline. Per docs/ARCHITECTURE.md §L6, the report sink must survive the VM disappearing — anything inside the guest is gone the moment the VM tears down. This module provides that place: a minimal HTTP service bound to the bridge IP that accepts run reports and writes them to disk atomically. - modules/options.nix: new options.pxe-infra.reportSink - enable: master switch (default true) - port: TCP port (default 8080; unprivileged so DynamicUser can run the daemon without CAP_NET_BIND_SERVICE) - modules/pxe-infra/report-sink.py: new file, the actual service. Python stdlib only (no third-party deps, no version drift, no extra security surface). Endpoints: POST /report — body is JSON with at least `run_id`; the file is written atomically (temp + rename) to /var/lib/pxe-infra/reports/.json GET /health — returns "ok" for liveness checks A 1 MB body cap is plenty for any structured run report per RUNNER-DESIGN.md. Path-traversal hardening: run_id must match [A-Za-z0-9_-]+. - modules/pxe-infra/report-sink.nix: new file, the Nix module that wraps report-sink.py. systemd service with: - DynamicUser + StateDirectory="pxe-infra/reports": no persistent system-user state, the daemon writes into /var/lib/pxe-infra/reports/ as a throwaway UID - NoNewPrivileges, ProtectSystem=strict, ProtectHome, PrivateTmp, RestrictAddressFamilies=AF_INET{,6}: only needs to bind a TCP socket and write one file - Environment sets REPORTS_BIND to the bridge IP, so the daemon never accidentally listens on 0.0.0.0 - modules/pxe-infra/default.nix: imports the new module. Refs: docs/ARCHITECTURE.md §L6, docs/RUNNER-DESIGN.md "Result object". --- modules/options.nix | 27 +++++++++ modules/pxe-infra/default.nix | 1 + modules/pxe-infra/report-sink.nix | 66 +++++++++++++++++++++ modules/pxe-infra/report-sink.py | 99 +++++++++++++++++++++++++++++++ 4 files changed, 193 insertions(+) create mode 100644 modules/pxe-infra/report-sink.nix create mode 100755 modules/pxe-infra/report-sink.py diff --git a/modules/options.nix b/modules/options.nix index 5809895..bad6ae1 100644 --- a/modules/options.nix +++ b/modules/options.nix @@ -362,5 +362,32 @@ ''; }; }; + + # Report sink: HTTP endpoint that receives the L4 VM's run + # report and writes it to disk. Layer L6 of + # docs/ARCHITECTURE.md. Per the architecture: "Needs to + # survive the VM disappearing, which rules out anything + # inside the guest." + reportSink = { + enable = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Whether to run the report-sink HTTP service. Listens + on the bridge IP only and writes accepted reports to + /var/lib/pxe-infra/reports/.json. Disabling + this drops the only path a report has to land. + ''; + }; + port = lib.mkOption { + type = lib.types.int; + default = 8080; + description = '' + TCP port for the report sink. Bound to the bridge IP + only; an unprivileged port so the daemon can run as a + DynamicUser with no CAP_NET_BIND_SERVICE. + ''; + }; + }; }; } diff --git a/modules/pxe-infra/default.nix b/modules/pxe-infra/default.nix index 89fbcfc..ba1d99b 100644 --- a/modules/pxe-infra/default.nix +++ b/modules/pxe-infra/default.nix @@ -18,6 +18,7 @@ ./dhcp.nix ./http.nix ./ipxe.nix + ./report-sink.nix ./vm.nix ]; diff --git a/modules/pxe-infra/report-sink.nix b/modules/pxe-infra/report-sink.nix new file mode 100644 index 0000000..a3e5709 --- /dev/null +++ b/modules/pxe-infra/report-sink.nix @@ -0,0 +1,66 @@ +# pxe-infra/report-sink — minimal HTTP service that accepts +# run reports from the L4 VM and stores them on disk. +# +# Per docs/ARCHITECTURE.md §L6, the report sink must survive +# the VM's disappearance. The VM pushes (over HTTP to the +# bridge IP) and this service writes the report under +# /var/lib/pxe-infra/reports/, which is the only on-host +# location a report is guaranteed to land. +# +# Design notes: +# - Python stdlib only — no extra dependency, no version +# drift, no additional security surface. The script lives +# in ./report-sink.py, read at eval time. +# - DynamicUser + StateDirectory: the daemon runs as a +# throwaway UID with write access to +# /var/lib/pxe-infra/reports. No persistent system-user +# state to maintain. +# - Hardening: ProtectSystem=strict, NoNewPrivileges, +# PrivateTmp, RestrictAddressFamilies. We only need to +# bind a TCP socket and write a file; everything else is +# denied. +{ + config, + lib, + pkgs, + ... +}: +let + script = pkgs.writeText "report-sink.py" (builtins.readFile ./report-sink.py); +in +{ + config = lib.mkIf (config.pxe-infra.enable && config.pxe-infra.reportSink.enable) { + systemd.services.pxe-infra-report-sink = { + description = "pxe-infra: report sink (L6)"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + RestartSec = "5s"; + DynamicUser = true; + StateDirectory = "pxe-infra/reports"; + # Bind to the bridge IP only — never 0.0.0.0. + Environment = [ + "REPORTS_BIND=${config.pxe-infra.bridge.address}" + "REPORTS_PORT=${toString config.pxe-infra.reportSink.port}" + "REPORTS_DIR=/var/lib/pxe-infra/reports" + "PYTHONUNBUFFERED=1" + ]; + # Hardening. + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ]; + ReadWritePaths = [ "/var/lib/pxe-infra" ]; + }; + + script = '' + exec ${pkgs.python3}/bin/python3 ${script} + ''; + }; + }; +} diff --git a/modules/pxe-infra/report-sink.py b/modules/pxe-infra/report-sink.py new file mode 100755 index 0000000..caac3ec --- /dev/null +++ b/modules/pxe-infra/report-sink.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Minimal report sink for pxe-infra L6. + +POST /report with a JSON body containing at least `run_id`; +the body is validated and written atomically to +REPORTS_DIR/.json. Per docs/ARCHITECTURE.md §L6, this +is the only path a run report has to land — the VM can be +destroyed at any moment, but a report that has reached this +sink survives. + +Why stdlib only: no extra dependency, no Python-package pin +to drift, no additional security surface. A 1 MB body cap is +plenty for any structured run report per RUNNER-DESIGN.md. +""" +import json +import os +import sys +from http.server import BaseHTTPRequestHandler, HTTPServer + +REPORTS_DIR = os.environ.get("REPORTS_DIR", "/var/lib/pxe-infra/reports") +REPORTS_BIND = os.environ.get("REPORTS_BIND", "0.0.0.0") +REPORTS_PORT = int(os.environ.get("REPORTS_PORT", "8080")) +MAX_BODY = 1_000_000 # 1 MB; no legitimate run report is bigger + + +class Handler(BaseHTTPRequestHandler): + def do_POST(self): + if self.path != "/report": + self.send_error(404, "POST only at /report") + return + length = int(self.headers.get("Content-Length", "0")) + if length <= 0: + self.send_error(411, "Length required") + return + if length > MAX_BODY: + self.send_error(413, f"body too large; cap {MAX_BODY}") + return + try: + body = self.rfile.read(length).decode("utf-8") + data = json.loads(body) + except (UnicodeDecodeError, json.JSONDecodeError) as e: + self.send_error(400, f"bad JSON: {e}") + return + if not isinstance(data, dict): + self.send_error(400, "body must be a JSON object") + return + run_id = data.get("run_id") + if not isinstance(run_id, str) or not run_id: + self.send_error(400, "missing run_id") + return + # Path-traversal hardening: only [A-Za-z0-9_-]+ in the id. + if not all(c.isalnum() or c in "-_" for c in run_id): + self.send_error(400, "run_id must match [A-Za-z0-9_-]+") + return + os.makedirs(REPORTS_DIR, exist_ok=True) + path = os.path.join(REPORTS_DIR, f"{run_id}.json") + # Atomic write: temp + rename, so a partial file never + # appears in the directory listing. + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, sort_keys=True) + os.replace(tmp, path) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write( + b'{"status":"ok","path":"' + path.encode() + b'"}' + ) + + def do_GET(self): + if self.path == "/health": + self.send_response(200) + self.send_header("Content-Type", "text/plain") + self.end_headers() + self.wfile.write(b"ok") + return + self.send_error(404) + + def log_message(self, fmt, *args): + # Send to stdout for journald; keep them terse. + sys.stdout.write( + f"report-sink {self.address_string()} {fmt % args}\n" + ) + sys.stdout.flush() + + +def main(): + os.makedirs(REPORTS_DIR, exist_ok=True) + server = HTTPServer((REPORTS_BIND, REPORTS_PORT), Handler) + print( + f"report-sink: serving on {REPORTS_BIND}:{REPORTS_PORT}, " + f"dir={REPORTS_DIR}", + flush=True, + ) + server.serve_forever() + + +if __name__ == "__main__": + main()