From 38bd1536ebd0822b2479547041e1850559e7ca33 Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Tue, 1 Dec 2026 18:14:49 +0530 Subject: [PATCH 1/2] feat(sensor): add standalone runtime sensor daemon, spooler, watchlist sync, and service installers --- src/secfoo/cli.py | 105 +++ src/secfoo/sensor/daemon.py | 827 ++++++++++++++++++++++++ src/secfoo/sensor/service.py | 222 +++++++ tests/test_sensor/test_sensor_daemon.py | 449 +++++++++++++ 4 files changed, 1603 insertions(+) create mode 100644 src/secfoo/sensor/daemon.py create mode 100644 src/secfoo/sensor/service.py create mode 100644 tests/test_sensor/test_sensor_daemon.py diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 5640cc5..6bf5c2e 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -2882,6 +2882,111 @@ def sensor_conformance( raise typer.Exit(code=1) +@sensor_app.command(name="run") +def sensor_run( + listen: Annotated[ + list[str] | None, + typer.Option( + "--listen", + help="Local IPC/loopback listener (unix://, tcp://127.0.0.1:7461, npipe:////./pipe/secfoo-sensor). Repeatable.", + ), + ] = None, + flush_interval: Annotated[float, typer.Option("--flush-interval", min=0.05)] = 5.0, + heartbeat_interval: Annotated[float, typer.Option("--heartbeat-interval", min=0.5)] = 30.0, + watchlist_interval: Annotated[float, typer.Option("--watchlist-interval", min=1.0)] = 300.0, + max_spool_mb: Annotated[int, typer.Option("--max-spool-mb", min=1, help="Max disk spool size in MiB.")] = 50, + spool_dir: Annotated[Path | None, typer.Option("--spool-dir", help="Directory for offline spool batches.")] = None, + watchlist_out: Annotated[Path | None, typer.Option("--watchlist-out", help="Where fetched SECFOO_WATCHLIST JSON is written.")] = None, + sensor_key: Annotated[str | None, typer.Option("--sensor-key", help="Optional shared auth key for tcp:// listeners.")] = None, +) -> None: + """Run the standalone runtime sensor sidecar / host daemon (#67).""" + from secfoo.runtime.client import SensorConfigError, load_sensor_config + from secfoo.sensor.daemon import SensorDaemon, SensorListenError + + try: + cfg = load_sensor_config() + daemon = SensorDaemon( + cfg, + listen=listen, + flush_interval=flush_interval, + heartbeat_interval=heartbeat_interval, + watchlist_interval=watchlist_interval, + max_spool_bytes=max_spool_mb * 1024 * 1024, + spool_dir=spool_dir, + watchlist_path=watchlist_out, + sensor_key=sensor_key, + ) + addrs = daemon.start_listeners() + except (SensorConfigError, SensorListenError) as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + console.print(f"Secfoo sensor {daemon.sensor_id} listening on {', '.join(addrs)} -> {cfg.server}") + daemon.run_forever() + + +@sensor_app.command(name="status") +def sensor_status( + json_output: Annotated[bool, typer.Option("--json", help="Emit JSON liveness state.")] = False, +) -> None: + """Inspect standalone runtime sensor health for liveness probes (#67).""" + import json as json_lib + + from secfoo.sensor.service import inspect_sensor_status + + info = inspect_sensor_status() + if json_output: + typer.echo(json_lib.dumps(info, indent=2)) + else: + state_label = "[green]running[/]" if info["running"] else "[yellow]stopped[/]" + reason = f" ({info['reason']})" if info.get("reason") else "" + console.print(f"Sensor status: {state_label}{reason}") + if info.get("pid"): + console.print( + f"PID {info['pid']} | listen={info.get('listen')} | " + f"spool_bytes={info.get('spool_bytes', 0)} | dropped={info.get('dropped_total', 0)}" + ) + if not info["running"]: + raise typer.Exit(code=1) + + +@sensor_app.command(name="install") +def sensor_install( + platform: Annotated[str | None, typer.Option("--platform", help="systemd, launchd, or windows.")] = None, + env_file: Annotated[Path | None, typer.Option("--env-file", help="EnvironmentFile path for systemd.")] = None, + listen: Annotated[str | None, typer.Option("--listen", help="Override --listen address.")] = None, + dry_run: Annotated[bool, typer.Option("--dry-run", help="Render config/command without installing.")] = False, +) -> None: + """Register `secfoo sensor` explicitly as a systemd unit, launchd agent, or Windows Service (#67).""" + import json as json_lib + + from secfoo.sensor.service import install_service + + try: + res = install_service(platform=platform, env_file=env_file, listen=listen, dry_run=dry_run) + except ValueError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + typer.echo(json_lib.dumps(res, indent=2)) + + +@sensor_app.command(name="uninstall") +def sensor_uninstall( + platform: Annotated[str | None, typer.Option("--platform", help="systemd, launchd, or windows.")] = None, + dry_run: Annotated[bool, typer.Option("--dry-run", help="Render uninstall action without changing OS.")] = False, +) -> None: + """Remove `secfoo sensor` service registration (#67).""" + import json as json_lib + + from secfoo.sensor.service import uninstall_service + + try: + res = uninstall_service(platform=platform, dry_run=dry_run) + except ValueError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + typer.echo(json_lib.dumps(res, indent=2)) + + _SITECUSTOMIZE = """\ # Written by `secfoo instrument` (#55): starts the secfoo runtime probe in # every Python process of the wrapped command. Inert unless SECFOO_SENSOR=1. diff --git a/src/secfoo/sensor/daemon.py b/src/secfoo/sensor/daemon.py new file mode 100644 index 0000000..6aa24d2 --- /dev/null +++ b/src/secfoo/sensor/daemon.py @@ -0,0 +1,827 @@ +"""Standalone runtime sensor sidecar / host daemon (#67). + +Receives newline-framed #73 event streams from in-process runtime probes over +Unix sockets, loopback TCP, or Windows named pipes, coalesces running totals in +memory, polls /watchlist with ETag, heartbeats every 30s, and spools gzipped +NDJSON batches to disk when the upstream #66 server is unreachable. +""" + +from __future__ import annotations + +import contextlib +import gzip +import hmac +import ipaddress +import json +import logging +import os +import secrets +import signal +import socket +import sys +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from secfoo.__about__ import __version__ +from secfoo.config import STORE_DIR, write_private_text +from secfoo.runtime.client import SensorConfig, SensorConfigError, load_sensor_config +from secfoo.runtime.evidence import MAX_LINE_BYTES, EvidenceError, validate_event +from secfoo.runtime.protocol import PROTOCOL_VERSION, ProtocolError, validate_control + +logger = logging.getLogger(__name__) + +DEFAULT_FLUSH_SECONDS = 5.0 +DEFAULT_HEARTBEAT_SECONDS = 30.0 +DEFAULT_WATCHLIST_SECONDS = 300.0 +DEFAULT_MAX_SPOOL_BYTES = 50 * 1024 * 1024 # 50 MiB +DEFAULT_HTTP_TIMEOUT_SECONDS = 5.0 +DEFAULT_MAX_BACKOFF_SECONDS = 60.0 +MAX_BUFFERED_HITS = 50_000 +MAX_BUFFERED_LOADS = 10_000 +MAX_BUFFERED_SESSIONS = 5_000 +PRESSURE_RATIO = 0.8 + +DEFAULT_STATE_PATH = STORE_DIR / "sensor-state.json" +DEFAULT_SPOOL_DIR = STORE_DIR / "sensor-spool" +DEFAULT_WATCHLIST_PATH = STORE_DIR / "sensor-watchlist.json" + + +class SensorListenError(ValueError): + """Raised when a `--listen` address is malformed or exposes a non-loopback port.""" + + +def default_listen_address() -> str: + """Return platform-appropriate local IPC listen address.""" + if sys.platform == "win32": + return "npipe:////./pipe/secfoo-sensor" + sock_dir = Path("/var/run/secfoo") + if sock_dir.exists() and os.access(sock_dir, os.W_OK): + return "unix:///var/run/secfoo/sensor.sock" + return f"unix://{(STORE_DIR / 'sensor.sock').as_posix()}" + + +def _is_loopback_host(host: str) -> bool: + clean = host.strip().lower() + if clean in {"localhost", "127.0.0.1", "::1"}: + return True + try: + return ipaddress.ip_address(clean).is_loopback + except ValueError: + return False + + +def parse_listen_address(address: str) -> tuple[str, Any]: + """Validate and parse `--listen` URI into `(scheme, target)`. + + Refuses non-loopback `tcp://` hosts so a sidecar or host daemon never binds + a routable interface accidentally (#67). + """ + raw = (address or "").strip() + parsed = urllib.parse.urlsplit(raw) + scheme = parsed.scheme.lower() + if scheme == "tcp": + host = parsed.hostname or "" + if not _is_loopback_host(host): + raise SensorListenError( + f"Refusing non-loopback tcp:// listen address {address!r}; bind 127.0.0.1, ::1, or localhost." + ) + try: + port = parsed.port + except ValueError as exc: + raise SensorListenError(f"Invalid port in tcp:// listen address {address!r}.") from exc + if port is None: + raise SensorListenError(f"tcp:// listen address requires an explicit port: {address!r}.") + return "tcp", (host, port) + if scheme == "unix": + if not hasattr(socket, "AF_UNIX"): + raise SensorListenError("unix:// listener is not supported on this platform; use tcp:// or npipe://.") + path = urllib.request.url2pathname(parsed.path) + if not path: + raise SensorListenError(f"Empty path in unix:// listen address {address!r}.") + return "unix", path + if scheme == "npipe": + if sys.platform != "win32": + raise SensorListenError("npipe:// listener is only supported on Windows.") + if not raw.startswith("npipe:////"): + raise SensorListenError(f"Windows named pipe must look like npipe:////./pipe/secfoo-sensor, got {address!r}.") + pipe_path = "\\\\" + raw[len("npipe:////") :].replace("/", "\\") + return "npipe", pipe_path + raise SensorListenError( + f"Unsupported --listen scheme in {address!r}; use unix://, tcp://, or npipe://." + ) + + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _gzip_ndjson(lines: list[dict[str, Any]]) -> bytes: + payload = "".join(json.dumps(item, separators=(",", ":")) + "\n" for item in lines).encode("utf-8") + return gzip.compress(payload) + + +def _restrictive_chmod(path: Path, mode: int) -> None: + if os.name == "posix": + with contextlib.suppress(OSError): + os.chmod(path, mode) + + +class EventBuffer: + """Thread-safe bounded coalescer matching #53 replace-by-key running totals.""" + + def __init__( + self, + *, + max_sessions: int = MAX_BUFFERED_SESSIONS, + max_loads: int = MAX_BUFFERED_LOADS, + max_hits: int = MAX_BUFFERED_HITS, + ) -> None: + self._lock = threading.Lock() + self._max_sessions = max_sessions + self._max_loads = max_loads + self._max_hits = max_hits + self._sessions: dict[str, dict[str, Any]] = {} + self._loads: dict[tuple[str, str, str, str], dict[str, Any]] = {} + self._hits: dict[tuple[str, str, str, str], dict[str, Any]] = {} + self.dropped_events = 0 + + def add(self, event: dict[str, Any]) -> bool: + """Merge one validated #53 event into the buffer; returns True if accepted.""" + kind = event.get("type") + with self._lock: + if kind == "session": + sid = str(event["id"]) + if sid not in self._sessions and len(self._sessions) >= self._max_sessions: + self.dropped_events += 1 + return False + self._sessions[sid] = dict(event) + return True + if kind == "load": + lkey = ( + str(event["session"]), + str(event["ecosystem"]), + str(event["package"]), + str(event.get("version") or ""), + ) + if lkey not in self._loads and len(self._loads) >= self._max_loads: + self.dropped_events += 1 + return False + self._loads[lkey] = dict(event) + return True + if kind == "hit": + hkey = ( + str(event["session"]), + str(event["finding_fingerprint"]), + str(event["symbol"]), + str(event.get("route") or ""), + ) + existing = self._hits.get(hkey) + if existing is None and len(self._hits) >= self._max_hits: + self.dropped_events += 1 + return False + if existing is None: + self._hits[hkey] = dict(event) + else: + merged = dict(existing) + merged.update(event) + # Probes send running totals; take the higher observed count across retries. + merged["count"] = max(int(existing.get("count", 0)), int(event.get("count", 0))) + if not event.get("stack_sample") and existing.get("stack_sample"): + merged["stack_sample"] = existing["stack_sample"] + self._hits[hkey] = merged + return True + return False + + def pressure_high(self) -> bool: + with self._lock: + return ( + len(self._hits) >= int(self._max_hits * PRESSURE_RATIO) + or len(self._loads) >= int(self._max_loads * PRESSURE_RATIO) + ) + + def drain(self) -> list[dict[str, Any]]: + with self._lock: + if not (self._sessions or self._loads or self._hits): + return [] + ordered = [ + *self._sessions.values(), + *self._loads.values(), + *self._hits.values(), + ] + self._sessions.clear() + self._loads.clear() + self._hits.clear() + return ordered + + def __len__(self) -> int: + with self._lock: + return len(self._sessions) + len(self._loads) + len(self._hits) + + +class DiskSpool: + """Bounded FIFO on-disk spool of compressed NDJSON batches.""" + + def __init__(self, directory: Path, max_bytes: int = DEFAULT_MAX_SPOOL_BYTES) -> None: + self.directory = Path(directory) + self.max_bytes = max(1024, int(max_bytes)) + self._lock = threading.Lock() + self._seq = 0 + self.dropped_batches = 0 + self.directory.mkdir(parents=True, exist_ok=True) + _restrictive_chmod(self.directory, 0o700) + + def _files(self) -> list[Path]: + return sorted(p for p in self.directory.iterdir() if p.is_file() and p.name.endswith(".ndjson.gz")) + + def total_bytes(self) -> int: + with self._lock: + return sum(p.stat().st_size for p in self._files()) + + def enqueue_gz(self, payload_gz: bytes) -> bool: + """Write one compressed batch to disk, evicting oldest files FIFO if over cap.""" + if len(payload_gz) > self.max_bytes: + with self._lock: + self.dropped_batches += 1 + return False + with self._lock: + files = self._files() + current_bytes = sum(p.stat().st_size for p in files) + while files and current_bytes + len(payload_gz) > self.max_bytes: + oldest = files.pop(0) + with contextlib.suppress(OSError): + current_bytes -= oldest.stat().st_size + oldest.unlink(missing_ok=True) + self.dropped_batches += 1 + self._seq += 1 + name = f"{time.time_ns():020d}-{self._seq:06d}.ndjson.gz" + dest = self.directory / name + tmp = self.directory / f".{name}.tmp" + tmp.write_bytes(payload_gz) + _restrictive_chmod(tmp, 0o600) + os.replace(tmp, dest) + return True + + def peek(self) -> Path | None: + with self._lock: + files = self._files() + return files[0] if files else None + + def ack(self, path: Path) -> None: + with self._lock, contextlib.suppress(OSError): + path.unlink(missing_ok=True) + + +@dataclass +class ListenerHandle: + scheme: str + address: str + bound_target: Any + stop_fn: Any + + +@dataclass +class _DaemonStats: + started_at: str = field(default_factory=_now_iso) + last_flush_at: str | None = None + last_heartbeat_at: str | None = None + last_watchlist_at: str | None = None + active_sessions: set[str] = field(default_factory=set) + forwarded_batches: int = 0 + + +class SensorDaemon: + """Standalone sensor loop coordinating listeners, aggregation, watchlist sync, spooling, and heartbeats.""" + + def __init__( + self, + config: SensorConfig, + *, + listen: list[str] | None = None, + flush_interval: float = DEFAULT_FLUSH_SECONDS, + heartbeat_interval: float = DEFAULT_HEARTBEAT_SECONDS, + watchlist_interval: float = DEFAULT_WATCHLIST_SECONDS, + max_spool_bytes: int = DEFAULT_MAX_SPOOL_BYTES, + spool_dir: Path | None = None, + watchlist_path: Path | None = None, + state_file: Path | None = None, + sensor_key: str | None = None, + sensor_id: str | None = None, + ) -> None: + self.config = config + self.listen_addresses = list(listen) if listen else [default_listen_address()] + # Validate all listen addresses eagerly before binding any socket/pipe. + self._parsed_listens = [parse_listen_address(addr) for addr in self.listen_addresses] + self.flush_interval = max(0.05, float(flush_interval)) + self.heartbeat_interval = max(0.1, float(heartbeat_interval)) + self.watchlist_interval = max(0.5, float(watchlist_interval)) + self.spool = DiskSpool(spool_dir or DEFAULT_SPOOL_DIR, max_bytes=max_spool_bytes) + self.watchlist_path = Path(watchlist_path) if watchlist_path else DEFAULT_WATCHLIST_PATH + self.state_file = Path(state_file) if state_file else DEFAULT_STATE_PATH + self.sensor_key = (sensor_key or os.environ.get("SECFOO_SENSOR_KEY") or "").strip() or None + self.sensor_id = sensor_id or f"secfoo-sensor-{os.getpid()}-{secrets.token_hex(4)}" + + self.buffer = EventBuffer() + self.stats = _DaemonStats() + self._stop = threading.Event() + self._listeners: list[ListenerHandle] = [] + self._threads: list[threading.Thread] = [] + self._watchlist_etag: str | None = None + self._watchlist_version: int | None = None + self._backoff_seconds = 1.0 + self._next_retry_at = 0.0 + self._state_lock = threading.Lock() + + @property + def dropped_total(self) -> int: + return self.buffer.dropped_events + self.spool.dropped_batches + + def bound_addresses(self) -> list[str]: + out: list[str] = [] + for h in self._listeners: + if h.scheme == "tcp": + host, port = h.bound_target + out.append(f"tcp://{host}:{port}") + elif h.scheme == "unix": + out.append(f"unix://{h.bound_target}") + elif h.scheme == "npipe": + out.append(h.address) + return out + + def start_listeners(self) -> list[str]: + """Bind every configured listener cleanly before starting worker loops.""" + for raw_addr, (scheme, target) in zip(self.listen_addresses, self._parsed_listens): + if scheme in ("tcp", "unix"): + handle = self._start_socket_listener(raw_addr, scheme, target) + elif scheme == "npipe": + handle = self._start_npipe_listener(raw_addr, target) + else: # pragma: no cover -- unreachable after parse_listen_address + raise SensorListenError(f"Unsupported scheme {scheme!r}") + self._listeners.append(handle) + self._write_state(running=True) + return self.bound_addresses() + + def _start_socket_listener(self, raw_addr: str, scheme: str, target: Any) -> ListenerHandle: + if scheme == "unix": + sock_path = Path(target) + sock_path.parent.mkdir(parents=True, exist_ok=True) + sock_path.unlink(missing_ok=True) + family = socket.AF_UNIX + srv = socket.socket(family, socket.SOCK_STREAM) + srv.bind(str(sock_path)) + _restrictive_chmod(sock_path, 0o600) + bound = str(sock_path) + else: + host, port = target + family = socket.AF_INET6 if ":" in host else socket.AF_INET + srv = socket.socket(family, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind((host, port)) + bound = srv.getsockname()[:2] + srv.listen(32) + srv.settimeout(0.2) + + def _accept_loop() -> None: + while not self._stop.is_set(): + try: + conn, _ = srv.accept() + except (TimeoutError, OSError): + continue + t = threading.Thread( + target=self._serve_socket_client, + args=(conn, scheme), + daemon=True, + ) + t.start() + + thread = threading.Thread(target=_accept_loop, name=f"secfoo-listen-{scheme}", daemon=True) + thread.start() + self._threads.append(thread) + + def _stop_sock() -> None: + with contextlib.suppress(OSError): + srv.close() + if scheme == "unix": + with contextlib.suppress(OSError): + Path(bound).unlink(missing_ok=True) + + return ListenerHandle(scheme=scheme, address=raw_addr, bound_target=bound, stop_fn=_stop_sock) + + def _serve_socket_client(self, conn: socket.socket, scheme: str) -> None: + conn.settimeout(1.0) + require_auth = scheme == "tcp" and self.sensor_key is not None + hello_seen = False + authed = not require_auth + buf = b"" + + def _send_json(obj: dict[str, Any]) -> None: + with contextlib.suppress(OSError): + conn.sendall((json.dumps(obj, separators=(",", ":")) + "\n").encode("utf-8")) + + try: + while not self._stop.is_set(): + try: + chunk = conn.recv(65536) + except TimeoutError: + continue + except OSError: + break + if not chunk: + break + buf += chunk + if len(buf) > MAX_LINE_BYTES * 8: + buf = b"" + break + *lines, buf = buf.split(b"\n") + for raw in lines: + if not raw.strip() or len(raw) > MAX_LINE_BYTES: + continue + ok, reply, hello_seen, authed = self._process_line( + raw.decode("utf-8", errors="replace"), + hello_seen=hello_seen, + authed=authed, + require_auth=require_auth, + ) + if reply is not None: + _send_json(reply) + if not ok: + return + finally: + with contextlib.suppress(OSError): + conn.close() + + def _start_npipe_listener(self, raw_addr: str, pipe_name: str) -> ListenerHandle: + import ctypes + from ctypes import wintypes + + kernel32 = ctypes.windll.kernel32 + pipe_access_duplex = 0x00000003 + pipe_type_byte = 0x00000000 + pipe_readmode_byte = 0x00000000 + pipe_wait = 0x00000000 + pipe_unlimited_instances = 255 + invalid_handle = ctypes.c_void_p(-1).value + error_pipe_connected = 535 + + kernel32.CreateNamedPipeW.argtypes = [ + wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, + ] + kernel32.CreateNamedPipeW.restype = wintypes.HANDLE + kernel32.ConnectNamedPipe.argtypes = [wintypes.HANDLE, wintypes.LPVOID] + kernel32.ConnectNamedPipe.restype = wintypes.BOOL + kernel32.ReadFile.argtypes = [ + wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), wintypes.LPVOID, + ] + kernel32.ReadFile.restype = wintypes.BOOL + kernel32.DisconnectNamedPipe.argtypes = [wintypes.HANDLE] + kernel32.DisconnectNamedPipe.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + kernel32.CloseHandle.restype = wintypes.BOOL + + def _make_pipe() -> Any: + return kernel32.CreateNamedPipeW( + pipe_name, + pipe_access_duplex, + pipe_type_byte | pipe_readmode_byte | pipe_wait, + pipe_unlimited_instances, + 65536, + 65536, + 0, + None, + ) + + def _serve_pipe_client(handle: Any) -> None: + hello_seen = False + buf = b"" + chunk_buf = ctypes.create_string_buffer(65536) + read_bytes = wintypes.DWORD(0) + try: + while not self._stop.is_set(): + ok = kernel32.ReadFile(handle, chunk_buf, 65536, ctypes.byref(read_bytes), None) + if not ok or read_bytes.value == 0: + break + buf += chunk_buf.raw[: read_bytes.value] + if len(buf) > MAX_LINE_BYTES * 8: + break + *lines, buf = buf.split(b"\n") + for raw in lines: + if not raw.strip() or len(raw) > MAX_LINE_BYTES: + continue + cont, _reply, hello_seen, _authed = self._process_line( + raw.decode("utf-8", errors="replace"), + hello_seen=hello_seen, + authed=True, + require_auth=False, + ) + if not cont: + return + finally: + kernel32.DisconnectNamedPipe(handle) + kernel32.CloseHandle(handle) + + # Bind the first instance synchronously so callers know the pipe exists immediately. + first_handle = _make_pipe() + if first_handle == invalid_handle: + raise SensorListenError(f"Failed to create Windows named pipe {pipe_name!r}.") + + def _accept_pipe_loop() -> None: + next_handle = first_handle + while not self._stop.is_set(): + h = next_handle + if h is None: + h = _make_pipe() + next_handle = None + if h == invalid_handle: + time.sleep(0.05) + continue + connected = bool(kernel32.ConnectNamedPipe(h, None)) + if not connected and kernel32.GetLastError() != error_pipe_connected: + kernel32.CloseHandle(h) + continue + if self._stop.is_set(): + kernel32.DisconnectNamedPipe(h) + kernel32.CloseHandle(h) + break + t = threading.Thread(target=_serve_pipe_client, args=(h,), daemon=True) + t.start() + + thread = threading.Thread(target=_accept_pipe_loop, name="secfoo-listen-npipe", daemon=True) + thread.start() + self._threads.append(thread) + + def _stop_pipe() -> None: + # Unblock blocking ConnectNamedPipe cleanly by opening briefly as a client. + with contextlib.suppress(OSError), open(pipe_name, "wb", buffering=0): + pass + + return ListenerHandle(scheme="npipe", address=raw_addr, bound_target=pipe_name, stop_fn=_stop_pipe) + + def _process_line( + self, + text: str, + *, + hello_seen: bool, + authed: bool, + require_auth: bool, + ) -> tuple[bool, dict[str, Any] | None, bool, bool]: + try: + msg = json.loads(text) + except ValueError: + return True, None, hello_seen, authed + if not isinstance(msg, dict): + return True, None, hello_seen, authed + + kind = msg.get("type") + if kind == "hello": + try: + validate_control(msg) + except ProtocolError: + return False, None, hello_seen, authed + welcome: dict[str, Any] = { + "type": "welcome", + "protocol": PROTOCOL_VERSION, + "flush_interval": self.flush_interval, + } + if self._watchlist_version is not None: + welcome["watchlist_version"] = self._watchlist_version + if self.watchlist_path.exists(): + welcome["watchlist_path"] = str(self.watchlist_path) + return True, welcome, True, authed + + if not hello_seen: + return False, None, hello_seen, authed + + if kind == "auth": + try: + validate_control(msg) + except ProtocolError: + return False, None, hello_seen, authed + if not self.sensor_key or hmac.compare_digest(str(msg.get("key") or ""), self.sensor_key): + return True, None, hello_seen, True + return False, None, hello_seen, False + + if require_auth and not authed: + return False, None, hello_seen, False + + try: + clean = validate_event(msg) + except EvidenceError: + return True, None, hello_seen, authed + + if clean.get("type") == "session": + with self._state_lock: + self.stats.active_sessions.add(str(clean["id"])) + self.buffer.add(clean) + slow_reply = {"type": "slow", "sample_every": 4} if self.buffer.pressure_high() else None + return True, slow_reply, hello_seen, authed + + def _http_post(self, endpoint: str, body: bytes, *, extra_params: dict[str, str | None] | None = None, content_type: str, gzipped: bool = False) -> bool: + params: dict[str, str] = {"project": self.config.project} + for key, value in (extra_params or {}).items(): + if value: + params[key] = value + query = urllib.parse.urlencode(params) + url = f"{self.config.url(endpoint)}?{query}" + headers = { + "Authorization": f"Bearer {self.config.api_key}", + "Content-Type": content_type, + } + if gzipped: + headers["Content-Encoding"] = "gzip" + req = urllib.request.Request(url, data=body, headers=headers, method="POST") # nosec B310 -- https/loopback enforced by load_sensor_config + try: + with urllib.request.urlopen(req, timeout=DEFAULT_HTTP_TIMEOUT_SECONDS) as resp: # nosec B310 + resp.read(256) + return 200 <= resp.status < 300 + except (urllib.error.URLError, OSError): + return False + + def poll_watchlist_once(self) -> bool: + """Fetch /api/runtime/v1/watchlist using ETag caching and update SECFOO_WATCHLIST file cleanly.""" + query = urllib.parse.urlencode({"project": self.config.project}) + url = f"{self.config.url('watchlist')}?{query}" + headers = {"Authorization": f"Bearer {self.config.api_key}"} + if self._watchlist_etag: + headers["If-None-Match"] = self._watchlist_etag + req = urllib.request.Request(url, headers=headers, method="GET") # nosec B310 -- https/loopback enforced by load_sensor_config + try: + with urllib.request.urlopen(req, timeout=DEFAULT_HTTP_TIMEOUT_SECONDS) as resp: # nosec B310 + raw = resp.read() + etag = resp.headers.get("ETag") + except urllib.error.HTTPError as err: + if err.code == 304: + self.stats.last_watchlist_at = _now_iso() + return True + return False + except OSError: + return False + + try: + doc = json.loads(raw.decode("utf-8")) + except ValueError: + return False + self.watchlist_path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.watchlist_path.with_suffix(".tmp") + tmp.write_bytes(raw) + _restrictive_chmod(tmp, 0o644) + os.replace(tmp, self.watchlist_path) + self._watchlist_etag = etag + if isinstance(doc, dict) and isinstance(doc.get("version"), int): + self._watchlist_version = doc["version"] + self.stats.last_watchlist_at = _now_iso() + return True + + def _push_events_gz(self, payload_gz: bytes) -> bool: + return self._http_post( + "events", + payload_gz, + extra_params={"app": self.config.app, "env": self.config.env}, + content_type="application/x-ndjson", + gzipped=True, + ) + + def flush_once(self) -> bool: + """Drain memory buffer and spool oldest-first cleanly; returns True if online/drained.""" + now = time.monotonic() + pending = self.buffer.drain() + if pending: + gz = _gzip_ndjson(pending) + # Respect backoff / existing queued backlog order by spooling first if already backed off. + if self.spool.peek() is not None or now < self._next_retry_at: + self.spool.enqueue_gz(gz) + elif self._push_events_gz(gz): + self._backoff_seconds = 1.0 + self._next_retry_at = 0.0 + self.stats.forwarded_batches += 1 + self.stats.last_flush_at = _now_iso() + else: + self.spool.enqueue_gz(gz) + self._record_backoff() + self._write_state(running=True) + return False + + # Drain any spooled batches oldest-first when retry window allows. + if now >= self._next_retry_at: + while (batch := self.spool.peek()) is not None: + try: + data = batch.read_bytes() + except OSError: + self.spool.ack(batch) + continue + if self._push_events_gz(data): + self.spool.ack(batch) + self._backoff_seconds = 1.0 + self._next_retry_at = 0.0 + self.stats.forwarded_batches += 1 + self.stats.last_flush_at = _now_iso() + else: + self._record_backoff() + self._write_state(running=True) + return False + self._write_state(running=True) + return True + + def _record_backoff(self) -> None: + self._next_retry_at = time.monotonic() + self._backoff_seconds + self._backoff_seconds = min(self._backoff_seconds * 2.0, DEFAULT_MAX_BACKOFF_SECONDS) + + def heartbeat_once(self) -> bool: + with self._state_lock: + instances = max(1, len(self.stats.active_sessions)) + payload = json.dumps( + { + "sensor_id": self.sensor_id, + "version": __version__, + "app": self.config.app, + "env": self.config.env, + "instances": instances, + "dropped": self.dropped_total, + } + ).encode("utf-8") + ok = self._http_post("heartbeat", payload, content_type="application/json") + if ok: + self.stats.last_heartbeat_at = _now_iso() + self._write_state(running=True) + return ok + + def _write_state(self, *, running: bool) -> None: + doc = { + "status": "running" if running else "stopped", + "pid": os.getpid(), + "sensor_id": self.sensor_id, + "server": self.config.server, + "project": self.config.project, + "app": self.config.app, + "env": self.config.env, + "listen": self.bound_addresses() or self.listen_addresses, + "watchlist_path": str(self.watchlist_path), + "spool_dir": str(self.spool.directory), + "spool_bytes": self.spool.total_bytes(), + "dropped_total": self.dropped_total, + "forwarded_batches": self.stats.forwarded_batches, + "started_at": self.stats.started_at, + "last_flush_at": self.stats.last_flush_at, + "last_heartbeat_at": self.stats.last_heartbeat_at, + "last_watchlist_at": self.stats.last_watchlist_at, + "updated_at": _now_iso(), + } + with contextlib.suppress(OSError): + write_private_text(self.state_file, json.dumps(doc, indent=2) + "\n") + + def run_forever(self, *, install_signals: bool = True) -> None: + """Start listeners and run periodic watchlist, flush, and heartbeat loops until stopped.""" + if install_signals and threading.current_thread() is threading.main_thread(): + for sig in (signal.SIGINT, signal.SIGTERM): + with contextlib.suppress(ValueError, OSError): + signal.signal(sig, lambda _s, _f: self.stop()) + + if not self._listeners: + self.start_listeners() + + next_watchlist = 0.0 + next_flush = time.monotonic() + self.flush_interval + next_hb = 0.0 + try: + while not self._stop.is_set(): + now = time.monotonic() + if now >= next_watchlist: + self.poll_watchlist_once() + next_watchlist = now + self.watchlist_interval + if now >= next_hb: + self.heartbeat_once() + next_hb = now + self.heartbeat_interval + if now >= next_flush or len(self.buffer) >= int(MAX_BUFFERED_HITS * PRESSURE_RATIO): + self.flush_once() + next_flush = now + self.flush_interval + wake = min(next_watchlist, next_hb, next_flush) - time.monotonic() + self._stop.wait(timeout=max(0.05, min(0.5, wake))) + finally: + self.flush_once() + for handle in self._listeners: + handle.stop_fn() + self._write_state(running=False) + + def stop(self) -> None: + self._stop.set() + + +def run_daemon_from_env(**kwargs: Any) -> int: + """Entry point used by `secfoo sensor run`.""" + try: + config = load_sensor_config() + except SensorConfigError as exc: + logger.error("%s", exc) + print(f"Error: {exc}", file=sys.stderr) + return 2 + daemon = SensorDaemon(config, **kwargs) + daemon.start_listeners() + daemon.run_forever() + return 0 diff --git a/src/secfoo/sensor/service.py b/src/secfoo/sensor/service.py new file mode 100644 index 0000000..07f90f7 --- /dev/null +++ b/src/secfoo/sensor/service.py @@ -0,0 +1,222 @@ +"""Service registration and status inspection for `secfoo sensor` (#67).""" + +from __future__ import annotations + +import contextlib +import json +import os +import plistlib +import shlex +import subprocess # nosec B404 -- fixed service-manager commands without shell=True +import sys +from pathlib import Path +from typing import Any + +from secfoo.config import STORE_DIR, write_private_text +from secfoo.sensor.daemon import DEFAULT_STATE_PATH + + +def _pid_alive(pid: int) -> bool: + if pid <= 0: + return False + if sys.platform == "win32": + import ctypes + + kernel32 = ctypes.windll.kernel32 + process_query_limited = 0x1000 + handle = kernel32.OpenProcess(process_query_limited, False, pid) + if not handle: + return False + try: + exit_code = ctypes.c_ulong(0) + if kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): + return exit_code.value == 259 # STILL_ACTIVE + return True + finally: + kernel32.CloseHandle(handle) + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + + +def inspect_sensor_status(state_file: Path | None = None) -> dict[str, Any]: + """Read sensor liveness state file and verify process liveness for probes.""" + target = state_file or DEFAULT_STATE_PATH + if not target.is_file(): + return {"running": False, "reason": f"No sensor state file found at {target}."} + try: + data = json.loads(target.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + return {"running": False, "reason": f"Unreadable sensor state file: {exc}"} + pid = int(data.get("pid") or 0) + alive = data.get("status") == "running" and _pid_alive(pid) + return { + "running": alive, + "status": "running" if alive else "stopped", + **{k: v for k, v in data.items() if k != "status"}, + } + + +def detect_service_platform(platform: str | None = None) -> str: + if platform: + normalized = platform.strip().lower() + if normalized in {"systemd", "launchd", "windows"}: + return normalized + raise ValueError(f"Unsupported service platform {platform!r}; choose systemd, launchd, or windows.") + if sys.platform == "win32": + return "windows" + if sys.platform == "darwin": + return "launchd" + return "systemd" + + +def render_systemd_unit( + *, + python_exe: str, + env_file: Path | None = None, + listen: str | None = None, +) -> str: + cmd = f"{shlex.quote(python_exe)} -m secfoo.cli sensor run" + if listen: + cmd += f" --listen {shlex.quote(listen)}" + env_line = f"EnvironmentFile={env_file}\n" if env_file else "" + return ( + "[Unit]\n" + "Description=Secfoo Runtime Sensor\n" + "After=network-online.target\n\n" + "[Service]\n" + "Type=simple\n" + f"{env_line}" + f"ExecStart={cmd}\n" + "Restart=always\n" + "RestartSec=5\n" + "NoNewPrivileges=true\n" + "PrivateTmp=true\n\n" + "[Install]\n" + "WantedBy=default.target\n" + ) + + +def render_launchd_plist( + *, + python_exe: str, + listen: str | None = None, + log_dir: Path = STORE_DIR, +) -> bytes: + args = [python_exe, "-m", "secfoo.cli", "sensor", "run"] + if listen: + args.extend(["--listen", listen]) + payload = { + "Label": "com.secfoo.sensor", + "ProgramArguments": args, + "RunAtLoad": True, + "KeepAlive": True, + "StandardOutPath": str(log_dir / "sensor.out.log"), + "StandardErrorPath": str(log_dir / "sensor.err.log"), + } + return plistlib.dumps(payload) + + +def windows_sc_create_argv(*, python_exe: str, listen: str | None = None) -> list[str]: + bin_path = f'"{python_exe}" -m secfoo.cli sensor run' + if listen: + bin_path += f' --listen "{listen}"' + return [ + "sc.exe", + "create", + "secfoo-sensor", + f"binPath= {bin_path}", + "start= auto", + "DisplayName= Secfoo Runtime Sensor", + ] + + +def install_service( + *, + platform: str | None = None, + env_file: Path | None = None, + listen: str | None = None, + dry_run: bool = False, + systemd_dir: Path | None = None, + launchd_dir: Path | None = None, +) -> dict[str, Any]: + """Install OS service definition for `secfoo sensor` cleanly (opt-in only).""" + target = detect_service_platform(platform) + py = sys.executable + + if target == "systemd": + dest_dir = systemd_dir or (Path.home() / ".config" / "systemd" / "user") + dest_dir.mkdir(parents=True, exist_ok=True) + unit_path = dest_dir / "secfoo-sensor.service" + unit_text = render_systemd_unit(python_exe=py, env_file=env_file, listen=listen) + if not dry_run: + write_private_text(unit_path, unit_text) + return { + "platform": "systemd", + "unit_path": str(unit_path), + "content": unit_text, + "enable_command": ["systemctl", "--user", "enable", "--now", "secfoo-sensor.service"], + "installed": not dry_run, + } + + if target == "launchd": + dest_dir = launchd_dir or (Path.home() / "Library" / "LaunchAgents") + dest_dir.mkdir(parents=True, exist_ok=True) + plist_path = dest_dir / "com.secfoo.sensor.plist" + plist_bytes = render_launchd_plist(python_exe=py, listen=listen) + if not dry_run: + plist_path.write_bytes(plist_bytes) + return { + "platform": "launchd", + "plist_path": str(plist_path), + "load_command": ["launchctl", "load", "-w", str(plist_path)], + "installed": not dry_run, + } + + argv = windows_sc_create_argv(python_exe=py, listen=listen) + if not dry_run: + res = subprocess.run(argv, capture_output=True, text=True, check=False) # nosec B603 -- fixed sc.exe command + return { + "platform": "windows", + "command": argv, + "returncode": res.returncode, + "stdout": res.stdout, + "stderr": res.stderr, + "installed": res.returncode == 0, + } + return {"platform": "windows", "command": argv, "installed": False, "dry_run": True} + + +def uninstall_service( + *, + platform: str | None = None, + dry_run: bool = False, + systemd_dir: Path | None = None, + launchd_dir: Path | None = None, +) -> dict[str, Any]: + target = detect_service_platform(platform) + if target == "systemd": + unit_path = (systemd_dir or (Path.home() / ".config" / "systemd" / "user")) / "secfoo-sensor.service" + if not dry_run: + with contextlib.suppress(OSError): + unit_path.unlink(missing_ok=True) + return {"platform": "systemd", "unit_path": str(unit_path), "removed": not dry_run} + + if target == "launchd": + plist_path = (launchd_dir or (Path.home() / "Library" / "LaunchAgents")) / "com.secfoo.sensor.plist" + if not dry_run: + with contextlib.suppress(OSError): + plist_path.unlink(missing_ok=True) + return {"platform": "launchd", "plist_path": str(plist_path), "removed": not dry_run} + + argv = ["sc.exe", "delete", "secfoo-sensor"] + if not dry_run: + res = subprocess.run(argv, capture_output=True, text=True, check=False) # nosec B603 -- fixed sc.exe delete + return {"platform": "windows", "command": argv, "returncode": res.returncode, "removed": res.returncode == 0} + return {"platform": "windows", "command": argv, "removed": False, "dry_run": True} diff --git a/tests/test_sensor/test_sensor_daemon.py b/tests/test_sensor/test_sensor_daemon.py new file mode 100644 index 0000000..6141499 --- /dev/null +++ b/tests/test_sensor/test_sensor_daemon.py @@ -0,0 +1,449 @@ +"""Tests for standalone runtime sensor daemon (`secfoo sensor`), spooling, ETag watchlist, and service units (#67).""" + +from __future__ import annotations + +import gzip +import json +import secrets +import socket +import sys +import threading +import time +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlsplit + +import pytest +from typer.testing import CliRunner + +from secfoo.cli import app +from secfoo.runtime.client import SensorConfig +from secfoo.runtime.keys import create_key +from secfoo.sensor.daemon import ( + DiskSpool, + EventBuffer, + SensorDaemon, + SensorListenError, + default_listen_address, + parse_listen_address, +) +from secfoo.sensor.service import ( + inspect_sensor_status, + install_service, + uninstall_service, +) +from secfoo.sensor.transport import PipeTransport, SocketTransport +from secfoo.storage.repository import RunRepository + + +def _hello(pid: int = 1234) -> dict: + return { + "type": "hello", + "protocol": 1, + "runtime": "python", + "runtime_version": "3.12.0", + "probe_version": "0.1.0", + "pid": pid, + "host": "test-host", + } + + +def _session(sid: str = "11111111-1111-4111-8111-111111111111") -> dict: + return { + "type": "session", + "id": sid, + "language": "python", + "runtime": "3.12.0", + "source": "sensor", + "started_at": datetime.now(timezone.utc).isoformat(), + } + + +def _hit(sid: str = "11111111-1111-4111-8111-111111111111", fp: str = "fp-1", sym: str = "pkg.fn", count: int = 1) -> dict: + return { + "type": "hit", + "session": sid, + "finding_fingerprint": fp, + "symbol": sym, + "route": "GET /items", + "auth": "authenticated", + "count": count, + "last_seen": datetime.now(timezone.utc).isoformat(), + } + + +def test_refuses_non_loopback_listen_and_missing_env(monkeypatch): + monkeypatch.delenv("SECFOO_API_KEY", raising=False) + monkeypatch.delenv("SECFOO_API_KEY_FILE", raising=False) + monkeypatch.delenv("SECFOO_PROJECT", raising=False) + monkeypatch.delenv("SECFOO_SERVER", raising=False) + + res = CliRunner().invoke(app, ["sensor", "run"], env={"NO_COLOR": "1", "TERM": "dumb"}) + assert res.exit_code == 2 + + with pytest.raises(SensorListenError, match="non-loopback"): + parse_listen_address("tcp://0.0.0.0:7461") + with pytest.raises(SensorListenError, match="non-loopback"): + parse_listen_address("tcp://192.168.1.50:7461") + with pytest.raises(SensorListenError, match="Unsupported"): + parse_listen_address("http://127.0.0.1:7461") + + assert parse_listen_address("tcp://127.0.0.1:7461") == ("tcp", ("127.0.0.1", 7461)) + assert default_listen_address().startswith(("npipe://", "unix://")) + + +def test_event_buffer_coalesces_hits_and_disk_spool_evicts_fifo(tmp_path): + buf = EventBuffer(max_sessions=2, max_loads=2, max_hits=2) + assert buf.add(_session("11111111-1111-4111-8111-111111111111")) is True + assert buf.add(_hit(count=2)) is True + assert buf.add(_hit(count=9)) is True + assert buf.add(_hit(fp="fp-2", count=4)) is True + assert buf.pressure_high() is True + # 3rd unique hit exceeds max_hits=2 + assert buf.add(_hit(fp="fp-3", count=1)) is False + assert buf.dropped_events == 1 + + drained = buf.drain() + hits = [e for e in drained if e["type"] == "hit"] + assert {h["finding_fingerprint"]: h["count"] for h in hits} == {"fp-1": 9, "fp-2": 4} + + spool = DiskSpool(tmp_path / "spool", max_bytes=1200) + assert spool.enqueue_gz(b"x" * 2000) is False # single item bigger than max_bytes + assert spool.dropped_batches == 1 + + for i in range(4): + spool.enqueue_gz(gzip.compress(f'{{"n":{i}}}\n'.encode())) + assert spool.total_bytes() <= 1200 + # FIFO drain returns surviving oldest item first + first = spool.peek() + assert first is not None + spool.ack(first) + + +def test_daemon_tcp_multi_probe_auth_watchlist_etag_spool_and_recovery(tmp_path): + state = {"down": False, "watchlist_calls": 0, "etag": '"v1"', "events": [], "heartbeats": []} + + class _Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + parsed = urlsplit(self.path) + if parsed.path != "/api/runtime/v1/watchlist": + self.send_response(404) + self.end_headers() + return + if state["down"]: + self.send_response(503) + self.end_headers() + return + state["watchlist_calls"] += 1 + if self.headers.get("If-None-Match") == state["etag"]: + self.send_response(304) + self.end_headers() + return + body = json.dumps({"version": 1, "generated_at": "2026-12-01T00:00:00Z", "entries": [{"ecosystem": "PyPI", "package": "pyyaml", "granularity": "symbol", "symbols": ["yaml.load"]}]}).encode() + self.send_response(200) + self.send_header("ETag", state["etag"]) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) + if state["down"]: + self.send_response(503) + self.end_headers() + return + parsed = urlsplit(self.path) + if parsed.path == "/api/runtime/v1/events": + text = gzip.decompress(raw).decode("utf-8") if self.headers.get("Content-Encoding") == "gzip" else raw.decode("utf-8") + for line in text.splitlines(): + if line.strip(): + state["events"].append(json.loads(line)) + elif parsed.path == "/api/runtime/v1/heartbeat": + state["heartbeats"].append(json.loads(raw.decode("utf-8"))) + self.send_response(200) + self.end_headers() + self.wfile.write(b"{}") + + srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + port = srv.server_address[1] + t = threading.Thread(target=srv.serve_forever, daemon=True) + t.start() + try: + cfg = SensorConfig( + api_key="sfc_test_secret", + server=f"http://127.0.0.1:{port}", + project="https://github.com/acme/payments", + app="checkout", + env="prod", + ) + wl_path = tmp_path / "watchlist.json" + daemon = SensorDaemon( + cfg, + listen=["tcp://127.0.0.1:0"], + flush_interval=0.1, + spool_dir=tmp_path / "spool", + watchlist_path=wl_path, + state_file=tmp_path / "state.json", + sensor_key="shared-secret-key", + ) + addrs = daemon.start_listeners() + tcp_addr = addrs[0] + + # Watchlist ETag initial 200 + unchanged 304 + updated 200 + assert daemon.poll_watchlist_once() is True + assert wl_path.is_file() + assert json.loads(wl_path.read_text(encoding="utf-8"))["entries"][0]["package"] == "pyyaml" + assert daemon.poll_watchlist_once() is True + assert state["watchlist_calls"] == 2 + + # Wrong auth key is rejected on tcp:// listener + bad_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + bad_host, bad_port = parse_listen_address(tcp_addr)[1] + bad_sock.connect((bad_host, bad_port)) + bad_sock.sendall((json.dumps(_hello(9001)) + "\n" + json.dumps({"type": "auth", "key": "wrong"}) + "\n").encode()) + # Welcome + closed on bad auth + assert b'"welcome"' in bad_sock.recv(4096) + bad_sock.close() + + # Two authorized probes connected concurrently send hits cleanly + for pid, fp in ((1001, "fp-a"), (1002, "fp-b")): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((bad_host, bad_port)) + lines = [ + _hello(pid), + {"type": "auth", "key": "shared-secret-key"}, + _session(f"22222222-2222-4222-8222-22222222{pid:04d}"), + _hit(sid=f"22222222-2222-4222-8222-22222222{pid:04d}", fp=fp, count=3), + ] + s.sendall("".join(json.dumps(x) + "\n" for x in lines).encode()) + assert b'"welcome"' in s.recv(4096) + s.close() + + time.sleep(0.15) + # Simulate outage -> spools on disk -> then recover & drain automatically + state["down"] = True + assert daemon.flush_once() is False + assert daemon.spool.total_bytes() > 0 + + state["down"] = False + daemon._next_retry_at = 0.0 + assert daemon.flush_once() is True + assert daemon.spool.total_bytes() == 0 + fps = {e["finding_fingerprint"] for e in state["events"] if e["type"] == "hit"} + assert fps == {"fp-a", "fp-b"} + + assert daemon.heartbeat_once() is True + assert state["heartbeats"] and state["heartbeats"][0]["app"] == "checkout" + + # Status reflects active PID while daemon state marks running + status_info = inspect_sensor_status(tmp_path / "state.json") + assert status_info["running"] is True + daemon.stop() + daemon._write_state(running=False) + assert inspect_sensor_status(tmp_path / "state.json")["running"] is False + finally: + srv.shutdown() + srv.server_close() + + +@pytest.mark.parametrize( + "scheme_prefix", + [ + pytest.param("unix", marks=pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="AF_UNIX unavailable")), + pytest.param("npipe", marks=pytest.mark.skipif(sys.platform != "win32", reason="Windows named pipe only")), + ], +) +def test_native_ipc_transport_listener_accepts_probe(tmp_path, scheme_prefix): + addr = ( + f"unix://{(tmp_path / 'secfoo-test.sock').as_posix()}" + if scheme_prefix == "unix" + else f"npipe:////./pipe/secfoo-test-{secrets.token_hex(4)}" + ) + cfg = SensorConfig(api_key="sfc_test", server="https://app.secfoo.com", project="https://github.com/acme/p") + daemon = SensorDaemon(cfg, listen=[addr], spool_dir=tmp_path / "sp", state_file=tmp_path / "st.json") + daemon.start_listeners() + try: + tr = PipeTransport(addr) if scheme_prefix == "npipe" else SocketTransport(addr) + sid = "33333333-3333-4333-8333-333333333333" + assert tr.send([_session(sid), _hit(sid=sid, fp="fp-ipc", count=5)]) is True + tr.close() + deadline = time.monotonic() + 2.0 + while len(daemon.buffer) < 2 and time.monotonic() < deadline: + time.sleep(0.02) + drained = daemon.buffer.drain() + assert any(e.get("finding_fingerprint") == "fp-ipc" for e in drained) + finally: + daemon.stop() + for h in daemon._listeners: + h.stop_fn() + + +def test_end_to_end_probe_sensor_to_secfoo_serve_ingests_within_flush_interval(tmp_path, monkeypatch): + from uvicorn import Config, Server + + from secfoo.web.app import create_app + + home = tmp_path / "secfoo-home" + home.mkdir() + db_path = home / "secfoo.db" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/payments", "payments", "github") + now_iso = datetime.now(timezone.utc).isoformat() + repo.create_completed_run( + run_uuid="run-e2e-1", + project_id=pid, + skill_id="sca-reachability", + skill_name="SCA", + agent_id="claude", + confluence_urls=[], + status="success", + exit_code=0, + started_at=now_iso, + finished_at=now_iso, + duration_seconds=0.1, + report_path="", + ) + completed = repo.get_run("run-e2e-1") + repo.connection.execute( + "INSERT INTO sca_findings (project_id, fingerprint, current_ref, package, version, ecosystem, issue, severity, status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at) " + "VALUES (?, ?, 'D1', 'pyyaml', '5.3', 'PyPI', 'unsafe load', 'high', 'open', ?, '2026-12-01T00:00:00Z', ?, '2026-12-01T00:00:00Z')", + (pid, "fp-e2e-1", completed.id, completed.id), + ) + raw_token, _ = create_key(repo.connection, name="e2e-sensor", scope="runtime", project_id=pid) + repo.connection.commit() + + sock_probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock_probe.bind(("127.0.0.1", 0)) + http_port = sock_probe.getsockname()[1] + sock_probe.close() + + asgi_app = create_app() + server = Server(Config(app=asgi_app, host="127.0.0.1", port=http_port, log_level="error")) + srv_thread = threading.Thread(target=server.run, daemon=True) + srv_thread.start() + deadline = time.monotonic() + 5.0 + while not server.started and time.monotonic() < deadline: + time.sleep(0.05) + assert server.started + + cfg = SensorConfig( + api_key=raw_token, + server=f"http://127.0.0.1:{http_port}", + project="https://github.com/acme/payments", + app="payments", + env="ci", + ) + daemon = SensorDaemon( + cfg, + listen=["tcp://127.0.0.1:0"], + flush_interval=0.2, + heartbeat_interval=0.5, + watchlist_interval=5.0, + spool_dir=tmp_path / "spool", + watchlist_path=tmp_path / "wl.json", + state_file=tmp_path / "state.json", + ) + daemon_thread = threading.Thread(target=lambda: daemon.run_forever(install_signals=False), daemon=True) + addrs = daemon.start_listeners() + daemon_thread.start() + try: + tr = SocketTransport(addrs[0]) + sid = "44444444-4444-4444-8444-444444444444" + assert tr.send([_session(sid), _hit(sid=sid, fp="fp-e2e-1", sym="yaml.load", count=7)]) is True + tr.close() + + # Verify evidence arrives in SQLite within 1 flush interval (+ startup slack) + end = time.monotonic() + 3.0 + stored_count = 0 + while time.monotonic() < end: + with RunRepository() as repo: + row = repo.connection.execute( + "SELECT count FROM runtime_evidence WHERE project_id = ? AND finding_fingerprint = 'fp-e2e-1'", + (pid,), + ).fetchone() + if row: + stored_count = int(row["count"]) + break + time.sleep(0.05) + assert stored_count == 7 + finally: + daemon.stop() + daemon_thread.join(timeout=2.0) + server.should_exit = True + srv_thread.join(timeout=2.0) + + +def test_service_install_uninstall_generation_cross_platform(tmp_path): + sys_res = install_service( + platform="systemd", + env_file=Path("/etc/secfoo/sensor.env"), + listen="unix:///run/secfoo.sock", + systemd_dir=tmp_path / "systemd", + ) + assert sys_res["installed"] is True + assert "ExecStart=" in Path(sys_res["unit_path"]).read_text(encoding="utf-8") + assert uninstall_service(platform="systemd", systemd_dir=tmp_path / "systemd")["removed"] is True + + mac_res = install_service(platform="launchd", listen="unix:///tmp/secfoo.sock", launchd_dir=tmp_path / "launchd") + assert mac_res["installed"] is True + assert Path(mac_res["plist_path"]).is_file() + assert uninstall_service(platform="launchd", launchd_dir=tmp_path / "launchd")["removed"] is True + + win_res = install_service(platform="windows", listen="npipe:////./pipe/secfoo-sensor", dry_run=True) + assert win_res["command"][:3] == ["sc.exe", "create", "secfoo-sensor"] + assert uninstall_service(platform="windows", dry_run=True)["command"] == ["sc.exe", "delete", "secfoo-sensor"] + + res_cli = CliRunner().invoke( + app, + ["sensor", "install", "--platform", "systemd", "--dry-run"], + env={"NO_COLOR": "1", "TERM": "dumb"}, + ) + assert res_cli.exit_code == 0 + assert "secfoo-sensor.service" in res_cli.output + + uninst_cli = CliRunner().invoke( + app, + ["sensor", "uninstall", "--platform", "windows", "--dry-run"], + env={"NO_COLOR": "1", "TERM": "dumb"}, + ) + assert uninst_cli.exit_code == 0 + assert "secfoo-sensor" in uninst_cli.output + + status_cli = CliRunner().invoke( + app, + ["sensor", "status", "--json"], + env={"NO_COLOR": "1", "TERM": "dumb"}, + ) + # Missing/stopped state exits non-zero cleanly for liveness probes + assert status_cli.exit_code == 1 + + +def test_daemon_from_env_and_backpressure_slow_frame(tmp_path, monkeypatch): + from secfoo.sensor.daemon import run_daemon_from_env + + monkeypatch.delenv("SECFOO_API_KEY", raising=False) + monkeypatch.delenv("SECFOO_PROJECT", raising=False) + assert run_daemon_from_env() == 2 + + cfg = SensorConfig(api_key="sfc_test", server="https://app.secfoo.com", project="https://github.com/acme/p") + daemon = SensorDaemon(cfg, listen=["tcp://127.0.0.1:0"], spool_dir=tmp_path / "sp", state_file=tmp_path / "st.json") + daemon.buffer = EventBuffer(max_hits=5) + # Seed 4 hits to reach 80% pressure threshold -> next event returns `slow` frame + for i in range(4): + daemon.buffer.add(_hit(fp=f"fp-{i}", count=1)) + cont, reply, hello_seen, authed = daemon._process_line( + json.dumps(_hit(fp="fp-4", count=1)), + hello_seen=True, + authed=True, + require_auth=True, + ) + assert cont is True and hello_seen is True and authed is True + assert reply == {"type": "slow", "sample_every": 4} From 265fdf9ee9cc2898744a3c6b0441faf19e2dc1cc Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Tue, 1 Dec 2026 18:27:35 +0530 Subject: [PATCH 2/2] feat(deploy): add secfoo sensor manifest, container Dockerfiles, runtime examples, and docs/RUNTIME.md (#71) --- docs/RUNTIME.md | 95 +++++++ examples/runtime/cloud-run/service.yaml | 34 +++ examples/runtime/compose/docker-compose.yml | 54 ++++ examples/runtime/ecs/task-definition.json | 39 +++ .../kubernetes/deployment-sidecar.yaml | 96 +++++++ .../runtime/kubernetes/kustomization.yaml | 4 + examples/runtime/lambda/direct-handler.py | 25 ++ examples/runtime/lambda/extension.sh | 9 + .../runtime/systemd/secfoo-sensor.env.example | 6 + .../runtime/systemd/secfoo-sensor.service | 18 ++ examples/runtime/windows/install-service.ps1 | 12 + .../runtime/windows/uninstall-service.ps1 | 11 + packaging/docker/Dockerfile.probe | 21 ++ packaging/docker/Dockerfile.sensor | 19 ++ src/secfoo/cli.py | 25 ++ src/secfoo/sensor/manifest.py | 249 ++++++++++++++++++ tests/test_sensor/test_manifest.py | 101 +++++++ 17 files changed, 818 insertions(+) create mode 100644 docs/RUNTIME.md create mode 100644 examples/runtime/cloud-run/service.yaml create mode 100644 examples/runtime/compose/docker-compose.yml create mode 100644 examples/runtime/ecs/task-definition.json create mode 100644 examples/runtime/kubernetes/deployment-sidecar.yaml create mode 100644 examples/runtime/kubernetes/kustomization.yaml create mode 100644 examples/runtime/lambda/direct-handler.py create mode 100644 examples/runtime/lambda/extension.sh create mode 100644 examples/runtime/systemd/secfoo-sensor.env.example create mode 100644 examples/runtime/systemd/secfoo-sensor.service create mode 100644 examples/runtime/windows/install-service.ps1 create mode 100644 examples/runtime/windows/uninstall-service.ps1 create mode 100644 packaging/docker/Dockerfile.probe create mode 100644 packaging/docker/Dockerfile.sensor create mode 100644 src/secfoo/sensor/manifest.py create mode 100644 tests/test_sensor/test_manifest.py diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md new file mode 100644 index 0000000..09d68de --- /dev/null +++ b/docs/RUNTIME.md @@ -0,0 +1,95 @@ +# Runtime Sensor Deployment Guide + +The Secfoo runtime sensor (`secfoo sensor`) and language probes measure which open-source packages and watched vulnerable functions execute against live traffic—without modifying application code or changing CI/container builds. + +--- + +## 1. Opt-In by Default (Rule 0) + +Every probe and deployment artifact is strictly opt-in: +- Installing `secfoo` or copying probe packages never activates instrumentation. +- A probe stays **completely inert** unless `SECFOO_SENSOR=1` is explicitly set (zero hooks, threads, or network connections). +- Cluster-wide manifests and init containers act only when explicitly applied (e.g. `secfoo.com/sensor: "enabled"`). +- Setting `SECFOO_SENSOR=0` (or unsetting it) or removing the sidecar completely disables collection. + +--- + +## 2. Deployment Modes × Runtimes Matrix + +| Deployment Mode | Supported Platforms | Probe Transport (`#73`) | Watchlist Source | Best For | +|---|---|---|---|---| +| **Sidecar container** | Kubernetes pods, AWS ECS/Fargate, Google Cloud Run, Azure Container Apps, Nomad, Docker Compose | `unix:///var/run/secfoo/sensor.sock` (shared volume) or `tcp://127.0.0.1:7461` (shared network ns) | Shared volume updated by `secfoo sensor` | Containerized microservices | +| **Host daemon / service** | Linux (`systemd`), macOS (`launchd`), Windows (`sc.exe` / Windows Service) | `unix:///var/run/secfoo/sensor.sock` or `npipe:////./pipe/secfoo-sensor` | Host file written by `secfoo sensor` | VMs, bare metal, multi-worker hosts (`gunicorn`, `puma`, `php-fpm`) | +| **Direct (no sidecar)** | AWS Lambda (direct or Extension layer), Cloud Functions, single-process PaaS | `https://` (`DirectTransport`, 200 ms cap) or Lambda Extension (`tcp://127.0.0.1:7461`) | Bundled `SECFOO_WATCHLIST` or Extension | Serverless & PaaS without multi-container sidecars | +| **Offline / CI file** | CI test runs, air-gapped environments | `file:///path/events.ndjson` or `SECFOO_EVENTS_OUT` (`{pid}` expanded) | Local `secfoo runtime watchlist` JSON | Test runs ingested later with `secfoo runtime ingest` | + +### Supported Language Probes & Zero-Code Hooks + +| Runtime | Environment Injection | Implemented / Status | +|---|---|---| +| **Python** | `PYTHONPATH=/opt/secfoo/probe/python` (`sitecustomize.py`) or `secfoo instrument` | Implemented (`secfoo.sensor`, Python 3.10–3.13) | +| **Node.js** | `NODE_OPTIONS="--require /opt/secfoo/probe/node/index.js"` (CJS) or `--import /opt/secfoo/probe/node/register.mjs` (ESM) | Implemented (`npm/secfoo-sensor`, Node 18+ / ESM 20.6+) | +| **JVM (Java/Kotlin/Scala)** | `JAVA_TOOL_OPTIONS="-javaagent:/opt/secfoo/probe/jvm/secfoo-agent.jar"` | Planned (`#74`) | +| **.NET** | `DOTNET_STARTUP_HOOKS` / `CORECLR_ENABLE_PROFILING=1` | Planned (`#75`) | +| **Ruby** | `RUBYOPT="-r/opt/secfoo/probe/ruby/secfoo_probe"` | Planned (`#77`) | +| **PHP** | `auto_prepend_file` / PHP 8 observer extension | Planned (`#78`) | +| **Go / Rust / Native** | Out-of-process build-metadata inventory + Linux eBPF uprobes (`#76`) | Planned (`#76`) | + +--- + +## 3. Generate Ready-to-Review Manifests + +```bash +secfoo sensor manifest \ + --platform kubernetes \ + --project https://github.com/acme/payments-api \ + --app payments-api \ + --env prod +``` + +Supported values for `--platform`: `kubernetes`, `ecs`, `cloud-run`, `compose`, `systemd`. Checked-in reference examples live under `examples/runtime/` (`kubernetes/`, `ecs/`, `cloud-run/`, `compose/`, `systemd/`, `windows/`, `lambda/`), and non-root container definitions live in `packaging/docker/Dockerfile.sensor` and `packaging/docker/Dockerfile.probe`. + +--- + +## 4. Environment Variables + +| Variable | Target | Purpose | +|---|---|---| +| `SECFOO_SENSOR=1` | App | Master switch. Without `1`, probes do nothing at all. | +| `SECFOO_SENSOR_ADDR` | App | `#73` destination: `unix://...`, `tcp://127.0.0.1:`, `npipe:////./pipe/...`, `https://...`, or `file://...`. | +| `SECFOO_EVENTS_OUT` | App | Fallback NDJSON output file when `SECFOO_SENSOR_ADDR` is unset (`{pid}` expands per process). | +| `SECFOO_WATCHLIST` | App / Sensor | Path to watchlist JSON read by probes and kept updated via `ETag` by `secfoo sensor`. | +| `SECFOO_FLUSH_INTERVAL` | App | Seconds between probe flushes before `welcome` overrides it (default `10`). | +| `SECFOO_SENSOR_KEY` | App & Sensor | Optional shared auth token required on `tcp://` listeners. | +| `SECFOO_API_KEY_FILE` / `SECFOO_API_KEY` | Sensor / Direct | Runtime ingest key (`sfc_...`) minted via `secfoo keys create`. Prefer `SECFOO_API_KEY_FILE`. | +| `SECFOO_SERVER` | Sensor / Direct | URL of `secfoo serve` (`https://...` or loopback `http://`). | +| `SECFOO_PROJECT`, `SECFOO_APP`, `SECFOO_ENV` | Sensor / Direct | Project identifier (`secfoo run` target) plus logical app & environment tags. | + +--- + +## 5. Measured Overhead + +- **Python (`secfoo.sensor`):** Verified via `secfoo sensor conformance` under `50 µs` marginal cost per watched call (`sys.monitoring` on Python 3.12+ touches only watched code objects; < 5 s startup/teardown budget). +- **Node.js (`@rakfortltd/secfoo-sensor`):** Measured **`1.88 µs`** marginal overhead per watched call (`node v24.16.0`, `200,000` vs `1,000,000` iterations); both CJS and ESM pass the 6-check `#73` conformance kit well under the 1 ms/request p99 budget. + +--- + +## 6. Privacy Contract (What Is and Is Not Collected) + +**Collected:** +- Runtime/language metadata (`session`), loaded package name & version (`load`), and hit counts + trimmed `file:line` app stack frames (`hit`). +- Normalized route templates (e.g. `POST /orders`, `GET /items/{id}`) and `authenticated` / `anonymous` / `unknown` auth state when `#69` middleware is enabled. + +**Never collected:** +- Function arguments, return values, local variables, object fields, SQL payloads, or request/response bodies. +- Query strings, cookies, `Authorization` headers, concrete IDs in URL paths (`/users/8675309`), or user identifiers. + +--- + +## 7. Disable & Uninstall + +- **Containers (Kubernetes / ECS / Cloud Run / Compose):** Remove `SECFOO_SENSOR=1` or delete the `secfoo-sensor` sidecar / `secfoo-probe-init` init container. +- **Linux systemd:** `sudo systemctl disable --now secfoo-sensor && secfoo sensor uninstall --platform systemd` +- **macOS launchd:** `launchctl unload -w ~/Library/LaunchAgents/com.secfoo.sensor.plist && secfoo sensor uninstall --platform launchd` +- **Windows Service:** Run `examples/runtime/windows/uninstall-service.ps1` or `secfoo sensor uninstall --platform windows`. +- **Lambda:** Remove the `SECFOO_SENSOR` environment variable and detach the Extension layer. diff --git a/examples/runtime/cloud-run/service.yaml b/examples/runtime/cloud-run/service.yaml new file mode 100644 index 0000000..3fa1896 --- /dev/null +++ b/examples/runtime/cloud-run/service.yaml @@ -0,0 +1,34 @@ +apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: payments-api +spec: + template: + spec: + containers: + - name: app + image: us-docker.pkg.dev/project/repo/payments-api:latest + ports: + - containerPort: 8080 + env: + - name: SECFOO_SENSOR + value: "1" + - name: SECFOO_SENSOR_ADDR + value: "tcp://127.0.0.1:7461" + - name: secfoo-sensor + image: ghcr.io/secfoo-com/secfoo-sensor:latest + args: ["run", "--listen", "tcp://127.0.0.1:7461"] + env: + - name: SECFOO_SERVER + value: "https://app.secfoo.com" + - name: SECFOO_PROJECT + value: "https://github.com/acme/payments-api" + - name: SECFOO_APP + value: "payments-api" + - name: SECFOO_ENV + value: "prod" + - name: SECFOO_API_KEY + valueFrom: + secretKeyRef: + name: secfoo-api-key + key: latest diff --git a/examples/runtime/compose/docker-compose.yml b/examples/runtime/compose/docker-compose.yml new file mode 100644 index 0000000..6304b07 --- /dev/null +++ b/examples/runtime/compose/docker-compose.yml @@ -0,0 +1,54 @@ +services: + secfoo-serve: + image: ghcr.io/secfoo-com/secfoo:latest + command: ["serve", "--host", "0.0.0.0", "--port", "8787", "--allow-insecure-runtime"] + ports: + - "127.0.0.1:8787:8787" + volumes: + - secfoo_data:/root/.secfoo + + secfoo-sensor: + build: + context: ../../.. + dockerfile: packaging/docker/Dockerfile.sensor + read_only: true + tmpfs: + - /tmp + depends_on: + - secfoo-serve + volumes: + - secfoo_ipc:/var/run/secfoo + - secfoo_spool:/var/spool/secfoo + environment: + SECFOO_SERVER: http://127.0.0.1:8787 + SECFOO_PROJECT: https://github.com/acme/payments-api + SECFOO_APP: payments-api + SECFOO_ENV: local + SECFOO_API_KEY: ${SECFOO_RUNTIME_KEY:-replace-with-runtime-key} + command: + - run + - --listen + - unix:///var/run/secfoo/sensor.sock + - --watchlist-out + - /var/run/secfoo/watchlist.json + - --spool-dir + - /var/spool/secfoo + + sample-app: + image: python:3.12-slim + depends_on: + - secfoo-sensor + volumes: + - secfoo_ipc:/var/run/secfoo + - ../../../src:/opt/secfoo-src:ro + environment: + PYTHONPATH: /opt/secfoo-src + SECFOO_SENSOR: "1" + SECFOO_SENSOR_ADDR: unix:///var/run/secfoo/sensor.sock + SECFOO_WATCHLIST: /var/run/secfoo/watchlist.json + command: ["python", "-m", "secfoo.sensor", "-m", "secfoo.runtime.conformance.sample_app"] + +volumes: + secfoo_data: + secfoo_ipc: + secfoo_spool: diff --git a/examples/runtime/ecs/task-definition.json b/examples/runtime/ecs/task-definition.json new file mode 100644 index 0000000..1237223 --- /dev/null +++ b/examples/runtime/ecs/task-definition.json @@ -0,0 +1,39 @@ +{ + "family": "payments-api-secfoo-sensor", + "networkMode": "awsvpc", + "requiresCompatibilities": ["FARGATE"], + "cpu": "512", + "memory": "1024", + "containerDefinitions": [ + { + "name": "app", + "image": "ghcr.io/org/payments-api:latest", + "essential": true, + "portMappings": [{"containerPort": 8000, "protocol": "tcp"}], + "environment": [ + {"name": "SECFOO_SENSOR", "value": "1"}, + {"name": "SECFOO_SENSOR_ADDR", "value": "tcp://127.0.0.1:7461"} + ], + "dependsOn": [{"containerName": "secfoo-sensor", "condition": "START"}] + }, + { + "name": "secfoo-sensor", + "image": "ghcr.io/secfoo-com/secfoo-sensor:latest", + "essential": true, + "readonlyRootFilesystem": true, + "command": ["run", "--listen", "tcp://127.0.0.1:7461"], + "environment": [ + {"name": "SECFOO_SERVER", "value": "https://app.secfoo.com"}, + {"name": "SECFOO_PROJECT", "value": "https://github.com/acme/payments-api"}, + {"name": "SECFOO_APP", "value": "payments-api"}, + {"name": "SECFOO_ENV", "value": "prod"} + ], + "secrets": [ + { + "name": "SECFOO_API_KEY", + "valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:secfoo/api-key" + } + ] + } + ] +} diff --git a/examples/runtime/kubernetes/deployment-sidecar.yaml b/examples/runtime/kubernetes/deployment-sidecar.yaml new file mode 100644 index 0000000..a3f0a7a --- /dev/null +++ b/examples/runtime/kubernetes/deployment-sidecar.yaml @@ -0,0 +1,96 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: payments-api + labels: + app: payments-api + secfoo.com/sensor: "enabled" +spec: + replicas: 1 + selector: + matchLabels: + app: payments-api + template: + metadata: + labels: + app: payments-api + secfoo.com/sensor: "enabled" + spec: + securityContext: + runAsNonRoot: true + volumes: + - name: secfoo-ipc + emptyDir: {} + - name: secfoo-probes + emptyDir: {} + - name: secfoo-spool + emptyDir: {} + - name: secfoo-api-key + secret: + secretName: secfoo-runtime-secret + initContainers: + - name: secfoo-probe-init + image: ghcr.io/secfoo-com/secfoo-probe:latest + command: ["sh", "-c", "cp -r /opt/secfoo/probe/. /secfoo-probes/"] + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - name: secfoo-probes + mountPath: /secfoo-probes + containers: + - name: app + image: ghcr.io/org/payments-api:latest + ports: + - containerPort: 8000 + env: + - name: SECFOO_SENSOR + value: "1" + - name: SECFOO_SENSOR_ADDR + value: "unix:///var/run/secfoo/sensor.sock" + - name: SECFOO_WATCHLIST + value: "/var/run/secfoo/watchlist.json" + - name: PYTHONPATH + value: "/secfoo-probes/python" + - name: NODE_OPTIONS + value: "--require /secfoo-probes/node/index.js" + volumeMounts: + - name: secfoo-ipc + mountPath: /var/run/secfoo + - name: secfoo-probes + mountPath: /secfoo-probes + readOnly: true + - name: secfoo-sensor + image: ghcr.io/secfoo-com/secfoo-sensor:latest + args: + - run + - --listen + - unix:///var/run/secfoo/sensor.sock + - --watchlist-out + - /var/run/secfoo/watchlist.json + - --spool-dir + - /var/spool/secfoo + env: + - name: SECFOO_API_KEY_FILE + value: "/var/run/secrets/secfoo/api-key" + - name: SECFOO_SERVER + value: "https://app.secfoo.com" + - name: SECFOO_PROJECT + value: "https://github.com/acme/payments-api" + - name: SECFOO_APP + value: "payments-api" + - name: SECFOO_ENV + value: "prod" + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - name: secfoo-ipc + mountPath: /var/run/secfoo + - name: secfoo-spool + mountPath: /var/spool/secfoo + - name: secfoo-api-key + mountPath: /var/run/secrets/secfoo + readOnly: true diff --git a/examples/runtime/kubernetes/kustomization.yaml b/examples/runtime/kubernetes/kustomization.yaml new file mode 100644 index 0000000..7a4f2d3 --- /dev/null +++ b/examples/runtime/kubernetes/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - deployment-sidecar.yaml diff --git a/examples/runtime/lambda/direct-handler.py b/examples/runtime/lambda/direct-handler.py new file mode 100644 index 0000000..2084d3e --- /dev/null +++ b/examples/runtime/lambda/direct-handler.py @@ -0,0 +1,25 @@ +"""AWS Lambda / Serverless direct-mode example (#71). + +Configure function environment variables directly (no sidecar required): + SECFOO_SENSOR=1 + SECFOO_SENSOR_ADDR=https://app.secfoo.com + SECFOO_API_KEY=... # or SECFOO_API_KEY_FILE + SECFOO_PROJECT=https://github.com/acme/payments-api + SECFOO_APP=payments-lambda + SECFOO_ENV=prod +""" + +from __future__ import annotations + +import json + +from secfoo.sensor import start_from_env + + +def handler(event: dict, context: object) -> dict: + probe = start_from_env() + try: + return {"statusCode": 200, "body": json.dumps({"ok": True, "probed": probe is not None})} + finally: + if probe is not None: + probe.flush() diff --git a/examples/runtime/lambda/extension.sh b/examples/runtime/lambda/extension.sh new file mode 100644 index 0000000..9d3a1e2 --- /dev/null +++ b/examples/runtime/lambda/extension.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env sh +# Opt-in AWS Lambda Extension launcher (#71). +# Runs `secfoo sensor` in background next to the function runtime using tcp://127.0.0.1:7461 +# so batches flush out-of-band without slowing cold starts or request handlers. +set -eu +if [ "${SECFOO_SENSOR:-0}" != "1" ]; then + exec sleep infinity +fi +exec secfoo sensor run --listen "${SECFOO_SENSOR_ADDR:-tcp://127.0.0.1:7461}" --flush-interval "${SECFOO_FLUSH_INTERVAL:-5.0}" diff --git a/examples/runtime/systemd/secfoo-sensor.env.example b/examples/runtime/systemd/secfoo-sensor.env.example new file mode 100644 index 0000000..ab4d237 --- /dev/null +++ b/examples/runtime/systemd/secfoo-sensor.env.example @@ -0,0 +1,6 @@ +# Copy to /etc/secfoo/sensor.env with mode 0600 +SECFOO_SERVER=https://app.secfoo.com +SECFOO_PROJECT=https://github.com/acme/payments-api +SECFOO_APP=payments-api +SECFOO_ENV=prod +SECFOO_API_KEY_FILE=/etc/secfoo/runtime.key diff --git a/examples/runtime/systemd/secfoo-sensor.service b/examples/runtime/systemd/secfoo-sensor.service new file mode 100644 index 0000000..7db109f --- /dev/null +++ b/examples/runtime/systemd/secfoo-sensor.service @@ -0,0 +1,18 @@ +[Unit] +Description=Secfoo Runtime Sensor +After=network-online.target + +[Service] +Type=simple +User=secfoo +Group=secfoo +NoNewPrivileges=true +ProtectSystem=strict +ReadWritePaths=/var/run/secfoo /var/spool/secfoo +EnvironmentFile=/etc/secfoo/sensor.env +ExecStart=/usr/local/bin/secfoo sensor run --listen unix:///var/run/secfoo/sensor.sock --watchlist-out /var/run/secfoo/watchlist.json --spool-dir /var/spool/secfoo +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/examples/runtime/windows/install-service.ps1 b/examples/runtime/windows/install-service.ps1 new file mode 100644 index 0000000..a3c9119 --- /dev/null +++ b/examples/runtime/windows/install-service.ps1 @@ -0,0 +1,12 @@ +# Explicitly register the Secfoo Windows runtime sensor service (#71) +param( + [string]$Listen = "npipe:////./pipe/secfoo-sensor", + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +if ($DryRun) { + secfoo sensor install --platform windows --listen $Listen --dry-run +} else { + secfoo sensor install --platform windows --listen $Listen +} diff --git a/examples/runtime/windows/uninstall-service.ps1 b/examples/runtime/windows/uninstall-service.ps1 new file mode 100644 index 0000000..f22fd0b --- /dev/null +++ b/examples/runtime/windows/uninstall-service.ps1 @@ -0,0 +1,11 @@ +# Remove the Secfoo Windows runtime sensor service (#71) +param( + [switch]$DryRun +) + +$ErrorActionPreference = "Stop" +if ($DryRun) { + secfoo sensor uninstall --platform windows --dry-run +} else { + secfoo sensor uninstall --platform windows +} diff --git a/packaging/docker/Dockerfile.probe b/packaging/docker/Dockerfile.probe new file mode 100644 index 0000000..7a533b7 --- /dev/null +++ b/packaging/docker/Dockerfile.probe @@ -0,0 +1,21 @@ +# Multi-runtime Secfoo probe distribution image (#71) +# Used as an initContainer or `COPY --from=ghcr.io/secfoo-com/secfoo-probe` to +# place runtime probes under /opt/secfoo/probe/ without changing app builds. +FROM python:3.12-slim@sha256:5b5fe805d367f8f5a359ded6ab2652b7f9a206453ee6ee789c0045ba6ec15016 + +ARG UID=10001 +RUN groupadd --gid "${UID}" secfoo \ + && useradd --uid "${UID}" --gid secfoo --create-home --shell /usr/sbin/nologin secfoo \ + && mkdir -p /opt/secfoo/probe/python /opt/secfoo/probe/node + +COPY src/secfoo/sensor /opt/secfoo/probe/python/secfoo/sensor +COPY src/secfoo/runtime /opt/secfoo/probe/python/secfoo/runtime +COPY src/secfoo/__about__.py /opt/secfoo/probe/python/secfoo/__about__.py +RUN printf '"""Minimal Secfoo probe namespace."""\n' > /opt/secfoo/probe/python/secfoo/__init__.py \ + && printf 'try:\n import secfoo.sensor as _s\n _s.start_from_env()\nexcept Exception:\n pass\n' > /opt/secfoo/probe/python/sitecustomize.py + +COPY npm/secfoo-sensor /opt/secfoo/probe/node + +RUN chown -R secfoo:secfoo /opt/secfoo +USER secfoo +CMD ["true"] diff --git a/packaging/docker/Dockerfile.sensor b/packaging/docker/Dockerfile.sensor new file mode 100644 index 0000000..bc64ce7 --- /dev/null +++ b/packaging/docker/Dockerfile.sensor @@ -0,0 +1,19 @@ +# Multi-arch, non-root Secfoo standalone sensor image (#71) +# Runs strictly local/sidecar: never modifies application code and uses a +# read-only root filesystem with writable mounts limited to IPC & spool dirs. +FROM python:3.12-slim@sha256:5b5fe805d367f8f5a359ded6ab2652b7f9a206453ee6ee789c0045ba6ec15016 + +ARG UID=10001 +RUN groupadd --gid "${UID}" secfoo \ + && useradd --uid "${UID}" --gid secfoo --create-home --shell /usr/sbin/nologin secfoo \ + && mkdir -p /var/run/secfoo /var/spool/secfoo \ + && chown -R secfoo:secfoo /var/run/secfoo /var/spool/secfoo + +WORKDIR /app +COPY pyproject.toml README.md /app/ +COPY src /app/src +RUN pip install --no-cache-dir . + +USER secfoo +ENTRYPOINT ["secfoo", "sensor"] +CMD ["run"] diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 6bf5c2e..cf5c95b 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -2987,6 +2987,31 @@ def sensor_uninstall( typer.echo(json_lib.dumps(res, indent=2)) +@sensor_app.command(name="manifest") +def sensor_manifest( + platform: Annotated[str, typer.Option("--platform", help="kubernetes, ecs, cloud-run, compose, or systemd.")], + project: Annotated[str, typer.Option("--project", help="Project identifier as `secfoo run` recorded it.")], + app_name: Annotated[str, typer.Option("--app", help="Logical service/application name.")], + env_name: Annotated[str, typer.Option("--env", help="Deployment environment (e.g. prod, staging).")] = "prod", + server: Annotated[str, typer.Option("--server", help="Secfoo server URL.")] = "https://app.secfoo.com", +) -> None: + """Print an opt-in sidecar / service deployment snippet for your platform (#71).""" + from secfoo.sensor.manifest import generate_manifest + + try: + rendered = generate_manifest( + platform=platform, + project=project, + app=app_name, + env=env_name, + server=server, + ) + except ValueError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + typer.echo(rendered, nl=False) + + _SITECUSTOMIZE = """\ # Written by `secfoo instrument` (#55): starts the secfoo runtime probe in # every Python process of the wrapped command. Inert unless SECFOO_SENSOR=1. diff --git a/src/secfoo/sensor/manifest.py b/src/secfoo/sensor/manifest.py new file mode 100644 index 0000000..da0c2dd --- /dev/null +++ b/src/secfoo/sensor/manifest.py @@ -0,0 +1,249 @@ +"""Deployment manifest generator for `secfoo sensor manifest` (#71).""" + +from __future__ import annotations + +import json +import shlex + +SUPPORTED_PLATFORMS = ("kubernetes", "ecs", "cloud-run", "compose", "systemd") +SENSOR_IMAGE = "ghcr.io/secfoo-com/secfoo-sensor:latest" +PROBE_IMAGE = "ghcr.io/secfoo-com/secfoo-probe:latest" + + +def _clean_text(value: str, name: str) -> str: + clean = (value or "").strip() + if not clean or "\n" in clean or "\r" in clean: + raise ValueError(f"{name} must be a single non-empty line.") + return clean + + +def generate_manifest( + *, + platform: str, + project: str, + app: str, + env: str = "prod", + server: str = "https://app.secfoo.com", + sensor_image: str = SENSOR_IMAGE, + probe_image: str = PROBE_IMAGE, +) -> str: + """Render an explicit opt-in deployment manifest snippet for `platform` (#71).""" + target = (platform or "").strip().lower() + if target not in SUPPORTED_PLATFORMS: + raise ValueError( + f"Unsupported --platform {platform!r}; choose one of {', '.join(SUPPORTED_PLATFORMS)}." + ) + proj = _clean_text(project, "project") + app_name = _clean_text(app, "app") + env_name = _clean_text(env, "env") + srv = _clean_text(server, "server") + + if target == "kubernetes": + return f"""# Add to your Deployment spec.template (#71) +# Label opts in deliberately; remove label or unset SECFOO_SENSOR to disable. +metadata: + labels: + secfoo.com/sensor: "enabled" +spec: + securityContext: + runAsNonRoot: true + volumes: + - name: secfoo-ipc + emptyDir: {{}} + - name: secfoo-probes + emptyDir: {{}} + - name: secfoo-spool + emptyDir: {{}} + - name: secfoo-api-key + secret: + secretName: secfoo-runtime-secret + initContainers: + - name: secfoo-probe-init + image: {probe_image} + command: ["sh", "-c", "cp -r /opt/secfoo/probe/. /secfoo-probes/"] + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - name: secfoo-probes + mountPath: /secfoo-probes + containers: + - name: app + env: + - name: SECFOO_SENSOR + value: "1" + - name: SECFOO_SENSOR_ADDR + value: "unix:///var/run/secfoo/sensor.sock" + - name: SECFOO_WATCHLIST + value: "/var/run/secfoo/watchlist.json" + - name: PYTHONPATH + value: "/secfoo-probes/python" + - name: NODE_OPTIONS + value: "--require /secfoo-probes/node/index.js" + - name: JAVA_TOOL_OPTIONS + value: "-javaagent:/secfoo-probes/jvm/secfoo-agent.jar" + volumeMounts: + - name: secfoo-ipc + mountPath: /var/run/secfoo + - name: secfoo-probes + mountPath: /secfoo-probes + readOnly: true + - name: secfoo-sensor + image: {sensor_image} + args: ["run", "--listen", "unix:///var/run/secfoo/sensor.sock", "--watchlist-out", "/var/run/secfoo/watchlist.json", "--spool-dir", "/var/spool/secfoo"] + env: + - name: SECFOO_API_KEY_FILE + value: "/var/run/secrets/secfoo/api-key" + - name: SECFOO_SERVER + value: {json.dumps(srv)} + - name: SECFOO_PROJECT + value: {json.dumps(proj)} + - name: SECFOO_APP + value: {json.dumps(app_name)} + - name: SECFOO_ENV + value: {json.dumps(env_name)} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - name: secfoo-ipc + mountPath: /var/run/secfoo + - name: secfoo-spool + mountPath: /var/spool/secfoo + - name: secfoo-api-key + mountPath: /var/run/secrets/secfoo + readOnly: true +""" + + if target == "ecs": + task = { + "family": f"{app_name}-with-secfoo-sensor", + "networkMode": "awsvpc", + "containerDefinitions": [ + { + "name": "app", + "essential": True, + "environment": [ + {"name": "SECFOO_SENSOR", "value": "1"}, + {"name": "SECFOO_SENSOR_ADDR", "value": "tcp://127.0.0.1:7461"}, + ], + "dependsOn": [{"containerName": "secfoo-sensor", "condition": "START"}], + }, + { + "name": "secfoo-sensor", + "image": sensor_image, + "essential": True, + "readonlyRootFilesystem": True, + "command": ["run", "--listen", "tcp://127.0.0.1:7461"], + "environment": [ + {"name": "SECFOO_SERVER", "value": srv}, + {"name": "SECFOO_PROJECT", "value": proj}, + {"name": "SECFOO_APP", "value": app_name}, + {"name": "SECFOO_ENV", "value": env_name}, + ], + "secrets": [ + { + "name": "SECFOO_API_KEY", + "valueFrom": "arn:aws:secretsmanager:REGION:ACCOUNT:secret:secfoo/api-key", + } + ], + }, + ], + } + return json.dumps(task, indent=2) + "\n" + + if target == "cloud-run": + return f"""apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: {app_name} +spec: + template: + spec: + containers: + - name: app + image: YOUR_APP_IMAGE + ports: + - containerPort: 8080 + env: + - name: SECFOO_SENSOR + value: "1" + - name: SECFOO_SENSOR_ADDR + value: "tcp://127.0.0.1:7461" + - name: secfoo-sensor + image: {sensor_image} + args: ["run", "--listen", "tcp://127.0.0.1:7461"] + env: + - name: SECFOO_SERVER + value: {json.dumps(srv)} + - name: SECFOO_PROJECT + value: {json.dumps(proj)} + - name: SECFOO_APP + value: {json.dumps(app_name)} + - name: SECFOO_ENV + value: {json.dumps(env_name)} + - name: SECFOO_API_KEY + valueFrom: + secretKeyRef: + name: secfoo-api-key + key: latest +""" + + if target == "compose": + return f"""services: + secfoo-sensor: + image: {sensor_image} + read_only: true + tmpfs: + - /tmp + volumes: + - secfoo_ipc:/var/run/secfoo + - secfoo_spool:/var/spool/secfoo + environment: + SECFOO_SERVER: {srv} + SECFOO_PROJECT: {proj} + SECFOO_APP: {app_name} + SECFOO_ENV: {env_name} + SECFOO_API_KEY_FILE: /run/secrets/secfoo_api_key + command: ["run", "--listen", "unix:///var/run/secfoo/sensor.sock", "--watchlist-out", "/var/run/secfoo/watchlist.json", "--spool-dir", "/var/spool/secfoo"] + app: + depends_on: + - secfoo-sensor + volumes: + - secfoo_ipc:/var/run/secfoo + environment: + SECFOO_SENSOR: "1" + SECFOO_SENSOR_ADDR: unix:///var/run/secfoo/sensor.sock + SECFOO_WATCHLIST: /var/run/secfoo/watchlist.json + +volumes: + secfoo_ipc: + secfoo_spool: +""" + + # systemd + return f"""# /etc/systemd/system/secfoo-sensor.service +[Unit] +Description=Secfoo Runtime Sensor ({app_name}) +After=network-online.target + +[Service] +Type=simple +User=secfoo +Group=secfoo +NoNewPrivileges=true +ProtectSystem=strict +ReadWritePaths=/var/run/secfoo /var/spool/secfoo +Environment=SECFOO_SERVER={shlex.quote(srv)} +Environment=SECFOO_PROJECT={shlex.quote(proj)} +Environment=SECFOO_APP={shlex.quote(app_name)} +Environment=SECFOO_ENV={shlex.quote(env_name)} +EnvironmentFile=/etc/secfoo/sensor.env +ExecStart=/usr/local/bin/secfoo sensor run --listen unix:///var/run/secfoo/sensor.sock --watchlist-out /var/run/secfoo/watchlist.json --spool-dir /var/spool/secfoo +Restart=always + +[Install] +WantedBy=multi-user.target +""" diff --git a/tests/test_sensor/test_manifest.py b/tests/test_sensor/test_manifest.py new file mode 100644 index 0000000..ebb1120 --- /dev/null +++ b/tests/test_sensor/test_manifest.py @@ -0,0 +1,101 @@ +"""Validation tests for `#71` deployment manifests, containers, examples, and docs/RUNTIME.md.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +import yaml +from typer.testing import CliRunner + +from secfoo.cli import app +from secfoo.sensor.manifest import SUPPORTED_PLATFORMS, generate_manifest + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize("platform", SUPPORTED_PLATFORMS) +def test_sensor_manifest_cli_outputs_valid_config(platform): + res = CliRunner().invoke( + app, + [ + "sensor", + "manifest", + "--platform", + platform, + "--project", + "https://github.com/acme/payments", + "--app", + "payments", + "--env", + "prod", + ], + env={"NO_COLOR": "1", "TERM": "dumb"}, + ) + assert res.exit_code == 0, res.output + assert "payments" in res.output + assert "https://github.com/acme/payments" in res.output + # Must never embed an actual API key value + assert "sfc_live_" not in res.output and "sfc_ingest_" not in res.output + if platform == "ecs": + parsed = json.loads(res.output) + assert parsed["containerDefinitions"][0]["name"] == "app" + elif platform in ("kubernetes", "cloud-run", "compose"): + parsed = yaml.safe_load(res.output) + assert isinstance(parsed, dict) + + +def test_sensor_manifest_rejects_unknown_platform_and_newlines(): + with pytest.raises(ValueError, match="Unsupported --platform"): + generate_manifest(platform="nomad", project="p", app="a") + with pytest.raises(ValueError, match="single non-empty line"): + generate_manifest(platform="compose", project="p\nevil", app="a") + + +def test_examples_runtime_deliverables_and_dockerfiles_parse_cleanly(): + ex = ROOT / "examples" / "runtime" + k8s_dep = yaml.safe_load((ex / "kubernetes" / "deployment-sidecar.yaml").read_text(encoding="utf-8")) + assert k8s_dep["kind"] == "Deployment" + assert k8s_dep["metadata"]["labels"]["secfoo.com/sensor"] == "enabled" + + kustom = yaml.safe_load((ex / "kubernetes" / "kustomization.yaml").read_text(encoding="utf-8")) + assert "deployment-sidecar.yaml" in kustom["resources"] + + ecs = json.loads((ex / "ecs" / "task-definition.json").read_text(encoding="utf-8")) + assert {c["name"] for c in ecs["containerDefinitions"]} == {"app", "secfoo-sensor"} + + cr = yaml.safe_load((ex / "cloud-run" / "service.yaml").read_text(encoding="utf-8")) + assert cr["kind"] == "Service" + + comp = yaml.safe_load((ex / "compose" / "docker-compose.yml").read_text(encoding="utf-8")) + assert {"secfoo-serve", "secfoo-sensor", "sample-app"}.issubset(comp["services"].keys()) + + assert (ex / "systemd" / "secfoo-sensor.service").is_file() + assert (ex / "systemd" / "secfoo-sensor.env.example").is_file() + assert (ex / "windows" / "install-service.ps1").is_file() + assert (ex / "windows" / "uninstall-service.ps1").is_file() + assert (ex / "lambda" / "direct-handler.py").is_file() + assert (ex / "lambda" / "extension.sh").is_file() + + sensor_df = (ROOT / "packaging" / "docker" / "Dockerfile.sensor").read_text(encoding="utf-8") + probe_df = (ROOT / "packaging" / "docker" / "Dockerfile.probe").read_text(encoding="utf-8") + assert "USER secfoo" in sensor_df + assert "@sha256:" in sensor_df and "@sha256:" in probe_df + assert "/opt/secfoo/probe/python" in probe_df + assert "/opt/secfoo/probe/node" in probe_df + + +def test_runtime_docs_cover_required_sections(): + doc = (ROOT / "docs" / "RUNTIME.md").read_text(encoding="utf-8") + for heading in ( + "Opt-In by Default", + "Deployment Modes", + "Environment Variables", + "Measured Overhead", + "Privacy Contract", + "Disable & Uninstall", + ): + assert heading in doc + for env_var in ("SECFOO_SENSOR", "SECFOO_SENSOR_ADDR", "SECFOO_EVENTS_OUT", "SECFOO_WATCHLIST", "SECFOO_API_KEY_FILE"): + assert env_var in doc