"""Security layer of the local review dashboard: loopback-only, DNS-rebinding and CSRF defenses, strict CSP. python3 -m leads.local_server --static docs/demo-site --port 8765 * **Bound to 127.0.0.1, always.** There is no flag to bind anywhere else. The corpus names private individuals; a bind address is not the place to be casual. * **No network on read.** The pages load no CDN, no font service, no analytics. A restrictive Content-Security-Policy is served with every response so a future edit that adds a third-party script fails visibly in the browser instead of quietly phoning out. * **Writes are POST-only, same-origin, and token-checked.** A page on another origin can reach 127.0.0.1, and a hostname that resolves to it can be used to smuggle a request past a naive server. So every request's Host header is checked against the loopback names, every write additionally needs a matching Origin and the server-bound CSRF token, and CORS is never granted, including the preflight, which is refused outright. """ from __future__ import annotations import argparse import hmac import json import re import secrets import sys import threading from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import unquote, urlsplit #: Serving only these names, from one directory, is what makes path traversal a #: non-question rather than a regex to get right twice. STATIC_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", } #: The loopback names a browser may legitimately put in a Host header for this #: server. Anything else, including a public hostname that happens to resolve #: to 127.0.0.1 (which is how DNS rebinding reaches a local service), is refused #: before any handler runs. LOOPBACK_NAMES = {"127.0.0.1", "localhost", "::1"} MAX_BODY_BYTES = 64 * 1024 DEFAULT_PORT = 8765 #: One page, one stylesheet, one script. `connect-src 'self'` is the line that #: makes "no telemetry" checkable rather than promised. CSP = ("default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " "connect-src 'self'; font-src 'self'; form-action 'none'; frame-ancestors 'none'; " "base-uri 'none'") class HttpError(Exception): """A refusal with a status code and a message the operator can act on.""" def __init__(self, status: int, message: str, detail: str = ""): super().__init__(message) self.status = status self.message = message self.detail = detail def split_host(header: str) -> tuple[str, str]: """('127.0.0.1', '8765') from a Host header, IPv6 brackets included.""" value = (header or "").strip() if value.startswith("["): close = value.find("]") if close < 0: return "", "" name, rest = value[1:close], value[close + 1:] if rest and not rest.startswith(":"): return "", "" return name.lower(), rest[1:] name, _, port = value.partition(":") return name.lower(), port def host_allowed(header: str, port: int) -> bool: name, host_port = split_host(header) if name not in LOOPBACK_NAMES: return False return host_port in ("", str(port)) def origin_allowed(origin: str, port: int) -> bool: """A write must come from this very page, so the Origin must be ours. An absent Origin is refused rather than trusted: browsers send it on every POST, so its absence means the request did not come from the dashboard. """ if not origin: return False parsed = urlsplit(origin.strip()) if parsed.scheme != "http": return False if (parsed.hostname or "").lower() not in LOOPBACK_NAMES: return False return parsed.port in (None, port) class Workspace: """Server-side state: the static directory, the notes, the CSRF token.""" def __init__(self, static_dir: Path): self.static_dir = Path(static_dir).resolve() #: Bound to this process, never persisted. Restarting the server #: invalidates every token a stale tab is holding, which is the correct #: outcome. self.csrf_token = secrets.token_urlsafe(32) self.notes: list[dict] = [] self._lock = threading.Lock() def add_note(self, subject_id: str, body) -> dict: if not isinstance(body, str) or not body.strip(): raise HttpError(422, "refused", "A note needs a non-empty text body.") record = {"subject_id": subject_id, "body": body.strip(), "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds")} with self._lock: self.notes.append(record) return record class DashboardHandler(BaseHTTPRequestHandler): """Routing, and the checks that run before any route does.""" server_version = "leads-dashboard" sys_version = "" protocol_version = "HTTP/1.1" @property def app(self) -> Workspace: return self.server.app # type: ignore[attr-defined] # ---- plumbing ----------------------------------------------------- def log_message(self, fmt: str, *args) -> None: # Local, minimal, and to stderr: a request log, not telemetry. sys.stderr.write("dashboard %s - %s\n" % (self.address_string(), fmt % args)) def _send(self, status: int, body: bytes, content_type: str) -> None: self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Content-Security-Policy", CSP) self.send_header("X-Content-Type-Options", "nosniff") self.send_header("X-Frame-Options", "DENY") self.send_header("Referrer-Policy", "no-referrer") self.send_header("Cross-Origin-Resource-Policy", "same-origin") self.send_header("Cache-Control", "no-store") self.end_headers() if self.command != "HEAD": self.wfile.write(body) def _json(self, payload: dict, status: int = 200) -> None: self._send(status, json.dumps(payload).encode("utf-8"), "application/json; charset=utf-8") def _fail(self, error: HttpError) -> None: self._json({"error": error.message, "detail": error.detail}, status=error.status) # ---- guards ------------------------------------------------------- def _check_host(self) -> None: """Refuse any Host but loopback, which is what stops DNS rebinding. Binding to 127.0.0.1 keeps *packets* local; it does not stop a page at evil.example from pointing a hostname at 127.0.0.1 and having the browser send same-origin-looking requests here. The Host header is the part of that attack that cannot be forged into looking local. """ if not host_allowed(self.headers.get("Host", ""), self.server.server_address[1]): raise HttpError(403, "host not allowed", "This server answers only to 127.0.0.1 and localhost. Open it at " "the URL the command printed.") def _check_fetch_metadata(self) -> None: site = (self.headers.get("Sec-Fetch-Site") or "").strip().lower() if site and site not in ("same-origin", "none"): raise HttpError(403, "cross-site request refused", f"Sec-Fetch-Site was {site!r}; this server answers its own page only.") def _check_write_guards(self) -> None: port = self.server.server_address[1] if not origin_allowed(self.headers.get("Origin", ""), port): raise HttpError(403, "cross-origin write refused", "A write must carry an Origin header from this dashboard.") token = (self.headers.get("X-CSRF-Token") or "").strip() if not token or not hmac.compare_digest(token, self.app.csrf_token): raise HttpError(403, "missing or stale CSRF token", "Reload the dashboard: the token is bound to this server process.") ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip().lower() if ctype != "application/json": raise HttpError(415, "unsupported content type", "Writes are JSON. A form content type is refused on purpose: it is " "the one a cross-site form could send without a preflight.") def _read_body(self) -> dict: raw = self.headers.get("Content-Length") if raw is None: raise HttpError(411, "length required", "A write must declare its Content-Length.") try: length = int(raw) except ValueError: raise HttpError(400, "bad Content-Length", "Content-Length must be an integer.") if length < 0: raise HttpError(400, "bad Content-Length", "Content-Length must not be negative.") if length > MAX_BODY_BYTES: raise HttpError(413, "request body too large", f"The limit is {MAX_BODY_BYTES} bytes; this workspace stores notes, " "not uploads.") body = self.rfile.read(length) if length else b"" if not body: raise HttpError(400, "empty request body", "Expected a JSON object.") try: payload = json.loads(body.decode("utf-8")) except (UnicodeDecodeError, ValueError) as exc: raise HttpError(400, "body is not valid JSON", str(exc)) if not isinstance(payload, dict): raise HttpError(400, "body must be a JSON object", f"got {type(payload).__name__}") return payload # ---- routes ------------------------------------------------------- def do_OPTIONS(self) -> None: """Refuse the preflight, which is how a cross-origin JSON POST dies early.""" self._send(403, b"", "text/plain; charset=utf-8") def do_HEAD(self) -> None: self.do_GET() def do_GET(self) -> None: try: self._check_host() self._check_fetch_metadata() path = unquote(urlsplit(self.path).path) if path in ("/", "/index.html"): return self._static("index.html") if path.startswith("/static/"): return self._static(path[len("/static/"):]) if path == "/api/session": return self._json({"csrf_token": self.app.csrf_token}) if path == "/api/notes": raise HttpError(405, "writes are POST only", "A GET must never change stored state.") raise HttpError(404, "no such path", path) except HttpError as exc: self._fail(exc) except Exception as exc: # pragma: no cover - last resort self.log_message("unhandled %s: %s", type(exc).__name__, exc) self._fail(HttpError(500, "internal error", type(exc).__name__)) def do_POST(self) -> None: try: self._check_host() self._check_fetch_metadata() self._check_write_guards() path = unquote(urlsplit(self.path).path) if path != "/api/notes": raise HttpError(404, "no such path", path) payload = self._read_body() subject_id = payload.get("subject_id", "") if not isinstance(subject_id, str) or not subject_id.strip(): raise HttpError(400, "subject_id must be a non-empty string") record = self.app.add_note(subject_id.strip(), payload.get("body")) return self._json({"ok": True, "record": record}, status=201) except HttpError as exc: self._fail(exc) except Exception as exc: # pragma: no cover - last resort self.log_message("unhandled %s: %s", type(exc).__name__, exc) self._fail(HttpError(500, "internal error", type(exc).__name__)) # ---- static ------------------------------------------------------- def _static(self, name: str) -> None: """Serve one asset by name, never by a path from the browser.""" if not STATIC_NAME_RE.match(name): raise HttpError(404, "no such asset", "Assets are served by name from one directory.") root = self.app.static_dir path = (root / name).resolve() try: path.relative_to(root) except ValueError: raise HttpError(404, "no such asset", name) if not path.is_file(): raise HttpError(404, "no such asset", name) content_type = CONTENT_TYPES.get(path.suffix) if content_type is None: raise HttpError(404, "no such asset", f"{path.suffix} is not served") self._send(200, path.read_bytes(), content_type) class DashboardServer(ThreadingHTTPServer): daemon_threads = True allow_reuse_address = True def __init__(self, address, app: Workspace): self.app = app super().__init__(address, DashboardHandler) def serve(static_dir: Path, port: int = DEFAULT_PORT, echo=print) -> int: """Run until interrupted. The bind address is not configurable, by design.""" app = Workspace(static_dir) server = DashboardServer(("127.0.0.1", port), app) echo(f"dashboard http://127.0.0.1:{server.server_address[1]}/") echo(" bound to 127.0.0.1 only; no outbound requests. Ctrl-C to stop.") try: server.serve_forever() except KeyboardInterrupt: echo("\nstopped.") finally: server.server_close() return 0 def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="python3 -m leads.local_server", description="Local review dashboard, loopback only.") parser.add_argument("--static", type=Path, required=True, help="directory holding index.html and its assets") parser.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"loopback port (default {DEFAULT_PORT}; 0 picks a free one)") args = parser.parse_args(argv) if args.port < 0 or args.port > 65535: parser.error("--port must be between 0 and 65535") return serve(args.static, args.port) if __name__ == "__main__": sys.exit(main())