feat(pxe-infra): add HTTP report sink — L6

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/<run_id>.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".
This commit is contained in:
oqyude committed 2026-10-13 02:48:30 +03:00
1 parent d7e46a4e89
commit bc62b6f03d
4 files changed
+193

No files matched your search

+27
View File
@@ -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/<run_id>.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.
'';
};
};
};
}
+1
View File
@@ -18,6 +18,7 @@
./dhcp.nix
./http.nix
./ipxe.nix
./report-sink.nix
./vm.nix
];
+66
View File
@@ -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}
'';
};
};
}
+99
View File
@@ -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/<run_id>.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()