From 15aeb94cdbe15500e30c4f02ce813fd2c7ff42ae Mon Sep 17 00:00:00 2001 From: karthickmk2001 Date: Thu, 19 Nov 2026 19:01:06 +0000 Subject: [PATCH 1/2] test(sensor): cover the Python probe in-process and gate CI on coverage The probe runs inside users' applications, but almost every probe test ran it in a subprocess, which coverage cannot see: probe.py sat at 43% and sensor/__init__.py at 52% with nothing in CI to notice a regression. Tests (tests/test_sensor/test_probe_in_process.py, 55 tests): - watched calls: counts, entry frame, stack sample, shared symbols, late imports through the import watcher, no argument values - the sys.monitoring and setprofile callbacks driven directly (coverage cannot trace code inside them) - frame/filename filters, watchlist reload throttling, symbol resolution - flushing, drops, backpressure (welcome / slow), the flusher thread - every line sent to the #73 conformance FakeSensor validates as a protocol message; dead-sensor drops and reconnect - shutdown ordering, fork, no free tool id, the coverage denominator - python -m secfoo.sensor and SECFOO_* configuration, including bad values Coverage: probe.py 43% -> 96%, sensor/__init__.py 52% -> 100%, sensor/__main__.py 0% -> 100%; total 92%. Fixes found by the new tests: - probe: stop() returned early once _disable() had run, leaking the sys.monitoring tool id (only four exist), the import watcher and the transport. It now always releases them. - probe: stop()'s final flush could race the flusher thread on one socket; the transport's non-blocking control read made the other sendall fail and the final session line was dropped. Flushes are now serialised. - transport: closing a socket with an unread welcome sends RST, and the sensor discarded lines it had not read yet. SocketTransport.close() now sends FIN and drains for at most 0.2s first. These two caused the intermittent "no session line" failures of test_reference_python_probe_passes_the_kit (3/12 under load before, 15/15 after). CI: pytest-cov in the dev extra; tests run with --cov-fail-under=90, the per-file table goes to the job summary and coverage.xml is uploaded. .coverage was committed by accident in cb7bf54; untrack and ignore it. Refs #115 Co-Authored-By: Claude Opus 5.5 --- .coverage | Bin 139264 -> 0 bytes .github/workflows/ci.yml | 25 +- .gitignore | 4 + pyproject.toml | 2 +- src/secfoo/sensor/probe.py | 48 +- src/secfoo/sensor/transport.py | 19 + tests/test_sensor/test_probe_in_process.py | 898 +++++++++++++++++++++ 7 files changed, 981 insertions(+), 15 deletions(-) delete mode 100644 .coverage create mode 100644 tests/test_sensor/test_probe_in_process.py diff --git a/.coverage b/.coverage deleted file mode 100644 index f68958a7ef5f7a29791e6de25ad31973294c635b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 139264 zcmeFa3tW>&x<5X7bHA%7UbqBr-~|kdiU<;|t=86xms+>pVt{~AAeaOYLBbo`b-UfJ z?b@wcm2|he+pW8;-D9iuMznToTb1;5&u%X&q1BSMR)fR}k&yX6@B0DilR_)UA{*#O}bQW5+_S1z>UZ!!a#(92m=uY z{?9N#FH(pH4;{*LY_=J4i;OmlAI945;(tvF|q{sq@*Ow zO0bwK5=xDhgaT8MF~L-lZ^|>+OeKX0wzbCY&}CL*KGSA_AGBIbzzOX0j7x9Iho@}D zLU=`~#Z+vtR3@x9RwlCnx_-@O+-T!G;3Y;=VF?o=VNBQKV-qaK0;9!Pl4rDXD8`ub z$I8ZTvCG7RqoR0Qjcl9@mOS_`?-d*HxE+;w1@NLgvn8KFpKCFc%x28LYXp-S(z-uDUU+QaU2B*Kt>K>R z`mHc_Za;jNC%b}oJzN0bO3dA~-hPnzX?U2$TvAq?3zV-bD=uXc2cF=5*k*q~-1S_Darf%9#}9o+>LbZ74JLBz|(j?I)AjXq1?f6PQRq4j3&L4bF(- zA;^`+jn)lC&~?%q%4}x#S`Ue@p9o)yC;CgogEbo7)(vb%Vd&B4nrzk{hqPCw>GAF( z>oE8G&Noac>77ZKQdCrwU@l;b4D)mXmpG7{!^@1en+$`6DQF4iu7H5_N6l>vSiq2w zTV&4do!8hLV>Lnnfx4hOSV37y9#d4TOdRse|u5*cl13&P1tb@B^B@ zvQAGH&`<1f%IKjY@!*&koR^QjK=sDmEIdWtQ%Wf=?bTx*yWJWVu5(@pg}yED-le+#QX_+MS}6UT?FoE2>$c% zOAWTQ2|vWncmwbxp=faCpuT`J5cCt7Z_yL|C>HY1_$>RyQ0X&&{9ce5pWBchHddyT z8;YPdDK(fZP-LMF=30ORCSbk+0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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: coverage-py${{ matrix.python-version }} + path: coverage.xml + if-no-files-found: ignore - name: Runtime probe conformance (reference Python probe, #73) run: secfoo sensor conformance -- python -m secfoo.sensor -m secfoo.runtime.conformance.sample_app diff --git a/.gitignore b/.gitignore index a38ccff..a0ee705 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,10 @@ __pycache__/ *.egg-info/ .pytest_cache/ .ruff_cache/ +# pytest --cov output (CI uploads coverage.xml as an artifact instead). +.coverage +.coverage.* +coverage.xml build/ dist/ .DS_Store diff --git a/pyproject.toml b/pyproject.toml index 1d08faf..d76fa48 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["jsonschema>=4.26.0", "pytest>=9.2.0", "hypothesis>=6.168.5", "httpx>=0.28.1", "ruff>=0.17.5", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.21"] +dev = ["jsonschema>=4.26.0", "pytest>=9.2.0", "pytest-cov>=7.1.0", "hypothesis>=6.168.5", "httpx>=0.28.1", "ruff>=0.17.5", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.21"] build = ["pyinstaller>=6.22.3"] # The `api` agent (secfoo/agents/api.py): a LangGraph workflow that calls OpenAI/Anthropic/Gemini # through LiteLLM with an API key instead of driving an installed agent CLI. diff --git a/src/secfoo/sensor/probe.py b/src/secfoo/sensor/probe.py index e0134c4..cb19274 100644 --- a/src/secfoo/sensor/probe.py +++ b/src/secfoo/sensor/probe.py @@ -65,6 +65,9 @@ def __init__(self, *, watchlist_path: str | None, transport, app_root: str | Non self.backend = backend or ("monitoring" if hasattr(sys, "monitoring") else "profile") self._excluded_dirs = _stdlib_and_site_dirs() self._lock = threading.Lock() + # Serialises flushes: stop()'s final flush and the flusher thread + # must never share the transport's socket at the same moment. + self._flush_lock = threading.Lock() self._active = False self._broken = False self._reset_session() @@ -76,6 +79,7 @@ def __init__(self, *, watchlist_path: str | None, transport, app_root: str | Non self._seen_app_code: set = set() self._app_code_cache: dict = {} # code object -> is app code self._tool_id: int | None = None + self._watcher: _ImportWatcher | None = None self._stop = threading.Event() self._thread: threading.Thread | None = None @@ -95,7 +99,8 @@ def start(self) -> None: self._start_monitoring() else: self._start_profile() - sys.meta_path.insert(0, _ImportWatcher(self)) + self._watcher = _ImportWatcher(self) + sys.meta_path.insert(0, self._watcher) self._active = True self._resolve_pending() self._start_flusher() @@ -111,21 +116,30 @@ def start(self) -> None: self._disable(exc) def stop(self) -> None: - if not self._active: - return + """Final flush (only while healthy), then release every hook. A probe + that `_disable`d itself still holds its sys.monitoring tool id, its + import watcher and its transport, so those are released either way; + stopping twice is a no-op.""" + was_active = self._active self._stop.set() - self.flush() + if was_active: + self.flush() self._active = False try: + if self._watcher is not None: + if self._watcher in sys.meta_path: + sys.meta_path.remove(self._watcher) + self._watcher = None if self._tool_id is not None: sys.monitoring.register_callback(self._tool_id, sys.monitoring.events.PY_START, None) sys.monitoring.set_events(self._tool_id, 0) sys.monitoring.free_tool_id(self._tool_id) self._tool_id = None - elif self.backend == "profile": + elif was_active and self.backend == "profile": sys.setprofile(None) threading.setprofile(None) # type: ignore[arg-type] - self.transport.close() + if was_active or self._broken: + self.transport.close() except Exception: # noqa: BLE001, S110 -- shutting down; never raise into the app pass @@ -133,6 +147,7 @@ def _after_fork(self) -> None: """A forked worker (gunicorn, multiprocessing) is its own session.""" try: self._lock = threading.Lock() + self._flush_lock = threading.Lock() # the parent's flusher may have held it at fork self._reset_session() self._stop = threading.Event() self.transport = self.transport.reopen() @@ -347,15 +362,22 @@ def _loads(self) -> list[dict]: return loads def flush(self) -> None: + """One batch of running totals. Serialised: when stop()'s final flush + overlapped the flusher thread's, the transport's non-blocking control + read made the other thread's sendall fail, the socket was closed as + "sensor gone", and the final session line was lost.""" if self._broken: return - try: - self._load_watchlist() - self._resolve_pending() - if not self.transport.send(self.snapshot()): - self.dropped += 1 - except Exception as exc: # noqa: BLE001 - self._disable(exc) + with self._flush_lock: + if self._broken: + return + try: + self._load_watchlist() + self._resolve_pending() + if not self.transport.send(self.snapshot()): + self.dropped += 1 + except Exception as exc: # noqa: BLE001 + self._disable(exc) def _interval(self) -> float: """The sensor's `welcome` interval if it sent one, doubled while it diff --git a/src/secfoo/sensor/transport.py b/src/secfoo/sensor/transport.py index 2aa60a1..d954fe8 100644 --- a/src/secfoo/sensor/transport.py +++ b/src/secfoo/sensor/transport.py @@ -26,6 +26,7 @@ PROTOCOL_VERSION = 1 DIRECT_TIMEOUT_SECONDS = 0.2 # #73: a cold start or shutdown never waits on the network SOCKET_TIMEOUT_SECONDS = 1.0 +CLOSE_DRAIN_SECONDS = 0.2 # bounded: shutdown never waits on the sensor longer than this class TransportError(ValueError): @@ -160,6 +161,24 @@ def _read_control(self) -> None: flush_interval: float | None = None + def close(self) -> None: + """Graceful close. Closing a socket with unread data in its receive + buffer (a `welcome` the probe never got to read) sends RST instead of + FIN, and the sensor then discards lines it had received but not yet + read -- the final flush's session line among them. So: send FIN, + drain what the sensor wrote back (bounded by CLOSE_DRAIN_SECONDS), + then close.""" + conn = self._conn + if conn is not None: + try: + conn.shutdown(socket.SHUT_WR) + conn.settimeout(CLOSE_DRAIN_SECONDS) + while conn.recv(65536): + pass + except OSError: + pass + super().close() + def _connect(self): family = socket.AF_INET6 if self.scheme == "tcp" and ":" in self.target[0] else socket.AF_INET if self.scheme == "unix": diff --git a/tests/test_sensor/test_probe_in_process.py b/tests/test_sensor/test_probe_in_process.py new file mode 100644 index 0000000..bb7b11f --- /dev/null +++ b/tests/test_sensor/test_probe_in_process.py @@ -0,0 +1,898 @@ +"""#115: the Python probe driven in-process, so coverage sees it. + +test_python_probe.py runs the probe in subprocesses (the real deployment +shape), which coverage cannot measure. These tests drive the same `Probe` +directly and assert behaviour: what a watched call records, what is never +recorded, how flushing reacts to a slow or dead sensor, and that shutdown +releases every hook -- including after the probe disabled itself. +""" +from __future__ import annotations + +import atexit +import importlib +import json +import os +import runpy +import socket +import sys +import threading +import time +import uuid +from pathlib import Path + +import pytest + +from secfoo import sensor as sensor_pkg +from secfoo.runtime.conformance.kit import FakeSensor +from secfoo.runtime.protocol import SENTINEL, forbidden_data, validate_message +from secfoo.sensor import __main__ as sensor_main +from secfoo.sensor import probe as probe_mod +from secfoo.sensor import transport as transport_mod +from secfoo.sensor.probe import Probe, _count_app_functions, _ImportWatcher, _resolve + +BACKENDS = ["profile"] + (["monitoring"] if hasattr(sys, "monitoring") else []) + +VULN = '''\ +import functools + + +def parse(text): + return text.upper() + + +def safe(text): + return text + + +def _logged(fn): + @functools.wraps(fn) + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + return wrapper + + +@_logged +def decorated(text): + return text[::-1] + + +class Codec: + def encode(self, text): + return text * 2 + + @staticmethod + def static(text): + return text + + @classmethod + def build(cls): + return cls() +''' + +APP = '''\ +import {vuln} + + +def handle(secret): + return {vuln}.parse(secret) + + +def harmless(secret): + return {vuln}.safe(secret) +''' + + +# ---------- helpers ---------- + + +class RecordingTransport: + """Records every batch and the order of send/close; `result` is what + send() returns, `error` makes it raise.""" + + def __init__(self, result: bool = True, error: Exception | None = None) -> None: + self.result = result + self.error = error + self.batches: list[list[dict]] = [] + self.calls: list[str] = [] + self.reopened = 0 + + def send(self, events): + self.calls.append("send") + if self.error is not None: + raise self.error + self.batches.append(events) + return self.result + + def reopen(self): + self.reopened += 1 + return self + + def close(self): + self.calls.append("close") + + +def _write_watchlist(path: Path, symbols, *, fingerprint: str = "fp-1", ecosystem: str = "PyPI") -> Path: + path.write_text(json.dumps({"version": 1, "generated_at": "2026-11-12T00:00:00Z", "entries": [ + {"finding_fingerprint": fingerprint, "advisory": None, "ecosystem": ecosystem, "package": "sample-vuln", + "version": "1.0", "granularity": "symbol", "symbols": list(symbols), "source": "osv"}]}), encoding="utf-8") + return path + + +def _hits(events): + return [e for e in events if e["type"] == "hit"] + + +def _session(events): + [session] = [e for e in events if e["type"] == "session"] + return session + + +@pytest.fixture +def modules(tmp_path, monkeypatch): + """Writes a fresh vulnerable module + app module pair under tmp_path. + Unique names per call: sys.monitoring DISABLE state and sys.modules are + process-wide, so tests must never share code objects.""" + monkeypatch.syspath_prepend(str(tmp_path)) + created: list[str] = [] + + def make() -> tuple[str, str]: + tag = uuid.uuid4().hex[:8] + vuln, app = f"vuln_{tag}", f"app_{tag}" + (tmp_path / f"{vuln}.py").write_text(VULN, encoding="utf-8") + (tmp_path / f"{app}.py").write_text(APP.format(vuln=vuln), encoding="utf-8") + importlib.invalidate_caches() + created.extend([vuln, app]) + return vuln, app + + yield make + for name in created: + sys.modules.pop(name, None) + + +@pytest.fixture +def make_probe(tmp_path): + """Builds probes rooted at tmp_path and guarantees they are torn down, + so a failing test can't leave a profiler or monitoring tool installed.""" + probes: list[Probe] = [] + + def make(symbols=(), *, backend="profile", transport=None, flush_seconds=60.0, watchlist=True) -> Probe: + path = str(_write_watchlist(tmp_path / f"w-{uuid.uuid4().hex[:6]}.json", symbols)) if watchlist else None + probe = Probe(watchlist_path=path, transport=transport or RecordingTransport(), + app_root=str(tmp_path), flush_seconds=flush_seconds, backend=backend) + probes.append(probe) + return probe + + yield make + for probe in probes: + probe.stop() + atexit.unregister(probe.stop) + sys.meta_path[:] = [f for f in sys.meta_path if not (isinstance(f, _ImportWatcher) and f.probe is probe)] + sys.setprofile(None) + threading.setprofile(None) # type: ignore[arg-type] + + +# ---------- what a watched call records ---------- + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_watched_calls_are_counted_with_the_app_frame_that_made_them(modules, make_probe, backend): + vuln, app = modules() + app_mod = importlib.import_module(app) + probe = make_probe([f"{vuln}.parse"], backend=backend) + probe.start() + + for _ in range(3): + assert app_mod.handle("abc") == "ABC" # the app's behaviour is unchanged + app_mod.harmless("abc") # unwatched: never a hit + + events = probe.snapshot() + [hit] = _hits(events) + assert hit["symbol"] == f"{vuln}.parse" and hit["finding_fingerprint"] == "fp-1" + assert hit["count"] == 3 and hit["route"] == "unknown" + assert hit["entry_frame"] == f"{app}.py:5" # the line in handle() that called parse() + assert hit["stack_sample"][0].startswith(f"{vuln}.py:") + assert hit["first_seen"] <= hit["last_seen"] + session = _session(events) + assert session["id"] == probe.session_id == hit["session"] + assert session["language"] == "python" and session["source"] == "sensor" + if backend == "monitoring": + # handle(), harmless(), parse() and safe() ran in app code. + assert session["app_functions_executed"] == 4 + assert session["app_functions_total"] >= session["app_functions_executed"] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_one_symbol_shared_by_two_findings_counts_for_both(modules, make_probe, tmp_path, backend): + vuln, app = modules() + app_mod = importlib.import_module(app) + probe = make_probe(backend=backend, watchlist=False) + probe.watchlist_path = str(tmp_path / "two.json") + Path(probe.watchlist_path).write_text(json.dumps({"entries": [ + {"finding_fingerprint": fp, "ecosystem": "PyPI", "symbols": [f"{vuln}.parse"]} for fp in ("fp-a", "fp-b")]}), + encoding="utf-8") + probe.start() + app_mod.handle("x") + app_mod.handle("y") + assert {(h["finding_fingerprint"], h["count"]) for h in _hits(probe.snapshot())} == {("fp-a", 2), ("fp-b", 2)} + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_a_module_imported_after_start_is_watched_once_it_loads(modules, make_probe, backend): + vuln, app = modules() + probe = make_probe([f"{vuln}.parse"], backend=backend) + probe.start() + assert f"{vuln}.parse" in probe._pending_symbols # not importable yet + + app_mod = importlib.import_module(app) # imports vuln through the _ImportWatcher + app_mod.handle("abc") + assert not probe._pending_symbols + assert [h["count"] for h in _hits(probe.snapshot())] == [1] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_argument_values_never_reach_a_snapshot(modules, make_probe, backend): + vuln, app = modules() + app_mod = importlib.import_module(app) + probe = make_probe([f"{vuln}.parse"], backend=backend) + probe.start() + app_mod.handle(f"password={SENTINEL}") + lines = [json.dumps(e) for e in probe.snapshot()] + assert SENTINEL not in "".join(lines) + assert forbidden_data(lines) == [] + + +# ---------- the callbacks themselves ---------- +# +# Coverage cannot trace code running inside a profiler or sys.monitoring +# callback, so the tests above exercise the hot path without it showing up. +# These call the callbacks directly, from an app-root module so the stack +# sample has an app frame to find. + +TRIGGER = '''\ +def via_monitoring(probe, code): + return probe._on_py_start(code, 0) + + +def via_profiler(profiler, frame, event): + return profiler(frame, event, None) +''' + + +@pytest.fixture +def trigger(tmp_path, monkeypatch): + name = f"trigger_{uuid.uuid4().hex[:8]}" + (tmp_path / f"{name}.py").write_text(TRIGGER, encoding="utf-8") + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + yield importlib.import_module(name) + sys.modules.pop(name, None) + + +class _Frame: + def __init__(self, code): + self.f_code = code + + +@pytest.mark.skipif(not hasattr(sys, "monitoring"), reason="sys.monitoring is 3.12+") +def test_monitoring_callback_keeps_watched_code_and_disables_everything_else(modules, make_probe, trigger): + vuln, app = modules() + importlib.import_module(app) + vmod = sys.modules[vuln] + probe = make_probe([f"{vuln}.parse"], backend="monitoring") + probe._load_watchlist(force=True) + probe._resolve_pending() + watched = vmod.parse.__code__ + + assert trigger.via_monitoring(probe, watched) is None # stays enabled: every call counts + assert trigger.via_monitoring(probe, watched) is None + [hit] = _hits(probe.snapshot()) + assert hit["count"] == 2 and hit["stack_sample"][0].startswith(f"{trigger.__name__}.py:2") + assert watched in probe._seen_app_code + + unwatched = vmod.safe.__code__ + assert trigger.via_monitoring(probe, unwatched) is sys.monitoring.DISABLE # one event, then free + assert unwatched in probe._seen_app_code + module_code = compile("x = 1", str(Path(vmod.__file__)), "exec") + assert trigger.via_monitoring(probe, module_code) is sys.monitoring.DISABLE + assert module_code not in probe._seen_app_code # module bodies aren't functions + library = json.dumps.__code__ + assert trigger.via_monitoring(probe, library) is sys.monitoring.DISABLE + assert library not in probe._seen_app_code + + +@pytest.mark.skipif(not hasattr(sys, "monitoring"), reason="sys.monitoring is 3.12+") +def test_monitoring_callback_error_disables_the_probe(make_probe, capsys): + probe = make_probe(backend="monitoring") + probe._active = True + assert probe._on_py_start(object(), 0) is sys.monitoring.DISABLE # no co_name: an internal error + assert probe._broken and "AttributeError" in capsys.readouterr().err + + +def test_profile_callback_counts_calls_only(modules, make_probe, trigger, capsys): + vuln, app = modules() + importlib.import_module(app) + vmod = sys.modules[vuln] + probe = make_probe([f"{vuln}.parse"], backend="profile") + probe.start() + profiler = sys.getprofile() + sys.setprofile(None) # drive it by hand from here + threading.setprofile(None) # type: ignore[arg-type] + + trigger.via_profiler(profiler, _Frame(vmod.parse.__code__), "call") + trigger.via_profiler(profiler, _Frame(vmod.parse.__code__), "return") # not a call: ignored + trigger.via_profiler(profiler, _Frame(vmod.safe.__code__), "call") + [hit] = _hits(probe.snapshot()) + assert hit["count"] == 1 and hit["stack_sample"][0].startswith(f"{trigger.__name__}.py:6") + assert {vmod.parse.__code__, vmod.safe.__code__} <= probe._seen_app_code + + trigger.via_profiler(profiler, object(), "call") # no f_code: an internal error + assert probe._broken and "AttributeError" in capsys.readouterr().err + + +def test_stack_sample_keeps_app_frames_only_and_caps_its_depth(make_probe, tmp_path, monkeypatch): + depth = probe_mod.MAX_STACK_FRAMES + 5 + name = f"deep_{uuid.uuid4().hex[:8]}" + body = "".join(f"def f{i}(probe):\n return f{i + 1}(probe)\n\n" for i in range(depth)) + body += f"def f{depth}(probe):\n return probe._record_hit(probe, ('sym', ['fp']))\n" + (tmp_path / f"{name}.py").write_text(body, encoding="utf-8") + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + mod = importlib.import_module(name) + try: + probe = make_probe() + # _record_hit -> _stack_sample skips three frames (itself, _record_hit, + # the callback); here the "callback" is f{depth} itself. + mod.f0(probe) + mod.f0(probe) + finally: + sys.modules.pop(name, None) + [hit] = _hits(probe.snapshot()) + assert hit["count"] == 2 + assert len(hit["stack_sample"]) == probe_mod.MAX_STACK_FRAMES + assert all(frame.startswith(f"{name}.py:") for frame in hit["stack_sample"]) # no pytest / stdlib frames + assert hit["entry_frame"] == hit["stack_sample"][1] + + +# ---------- frame and filename filters ---------- + + +def test_app_code_filter(tmp_path): + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=str(tmp_path)) + assert probe._is_app_code(str(tmp_path / "pkg" / "views.py")) + assert not probe._is_app_code("") + assert not probe._is_app_code("") + assert not probe._is_app_code("") + assert not probe._is_app_code(str(tmp_path.parent / "elsewhere.py")) + + +def test_stdlib_and_site_packages_are_never_app_code_even_under_the_app_root(): + stdlib = os.path.dirname(os.__file__) + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=os.path.dirname(stdlib)) + assert not probe._is_app_code(os.__file__) + assert not probe._is_app_code(pytest.__file__) + + +def test_app_code_check_is_cached_per_code_object(tmp_path, monkeypatch): + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=str(tmp_path)) + calls = [] + monkeypatch.setattr(probe, "_is_app_code", lambda filename: calls.append(filename) or True) + code = compile("pass", str(tmp_path / "x.py"), "exec") + assert probe._is_app_code_obj(code) and probe._is_app_code_obj(code) + assert len(calls) == 1 + + +# ---------- watchlist loading ---------- + + +def test_watchlist_keeps_only_pypi_entries(tmp_path): + path = tmp_path / "w.json" + path.write_text(json.dumps({"entries": [ + {"finding_fingerprint": "py", "ecosystem": "PyPI", "symbols": ["a.b"]}, + {"finding_fingerprint": "js", "ecosystem": "npm", "symbols": ["lodash.merge"]}, + {"finding_fingerprint": "nosym", "ecosystem": "PyPI"}]}), encoding="utf-8") + probe = Probe(watchlist_path=str(path), transport=RecordingTransport(), app_root=str(tmp_path)) + probe._load_watchlist(force=True) + assert [e["finding_fingerprint"] for e in probe._watch_entries] == ["py", "nosym"] + assert probe._pending_symbols == {"a.b": ["py"]} + + +def test_no_or_missing_watchlist_watches_nothing(tmp_path): + for path in (None, str(tmp_path / "absent.json")): + probe = Probe(watchlist_path=path, transport=RecordingTransport(), app_root=str(tmp_path)) + probe._load_watchlist(force=True) + assert probe._watch_entries == [] and probe._pending_symbols == {} + + +def test_watchlist_is_rechecked_on_an_interval_and_reloaded_only_when_it_changes(tmp_path, monkeypatch): + path = _write_watchlist(tmp_path / "w.json", ["a.first"]) + probe = Probe(watchlist_path=str(path), transport=RecordingTransport(), app_root=str(tmp_path)) + clock = [1000.0] + monkeypatch.setattr(probe_mod.time, "monotonic", lambda: clock[0]) + probe._load_watchlist(force=True) + assert set(probe._pending_symbols) == {"a.first"} + + _write_watchlist(path, ["a.second"], fingerprint="fp-2") + os.utime(path, (time.time() + 5, time.time() + 5)) + probe._load_watchlist() # inside WATCHLIST_RECHECK_SECONDS: not even stat'ed + assert "a.second" not in probe._pending_symbols + + clock[0] += probe_mod.WATCHLIST_RECHECK_SECONDS + 1 + probe._load_watchlist() + assert probe._pending_symbols["a.second"] == ["fp-2"] + + probe._pending_symbols.clear() + clock[0] += probe_mod.WATCHLIST_RECHECK_SECONDS + 1 + probe._load_watchlist() # same mtime: not re-read + assert probe._pending_symbols == {} + + +# ---------- symbol resolution ---------- + + +def test_resolve_finds_functions_methods_and_unwraps_decorators(modules): + vuln, _ = modules() + mod = importlib.import_module(vuln) + assert _resolve(f"{vuln}.parse") is mod.parse.__code__ + assert _resolve(f"{vuln}.Codec.encode") is mod.Codec.encode.__code__ + assert _resolve(f"{vuln}.Codec.static") is mod.Codec.static.__code__ + assert _resolve(f"{vuln}.Codec.build") is mod.Codec.build.__func__.__code__ + # functools.wraps: the watched code is the original function, not the wrapper. + assert _resolve(f"{vuln}.decorated") is mod.decorated.__wrapped__.__code__ + + +def test_resolve_returns_none_for_what_it_cannot_find(modules): + vuln, _ = modules() + importlib.import_module(vuln) + assert _resolve("not_imported_module_xyz.func") is None + assert _resolve(f"{vuln}.missing") is None + assert _resolve(f"{vuln}.Codec.missing") is None + assert _resolve("single") is None + + +# ---------- flushing and backpressure ---------- + + +def test_flush_sends_the_running_totals_and_counts_drops(make_probe): + transport = RecordingTransport(result=False) + probe = make_probe(transport=transport) + probe.flush() + probe.flush() + assert len(transport.batches) == 2 and probe.dropped == 2 + assert _session(transport.batches[0])["id"] == probe.session_id + transport.result = True + probe.flush() + assert probe.dropped == 2 + + +def test_a_transport_that_raises_disables_the_probe_once(make_probe, capsys): + transport = RecordingTransport(error=RuntimeError("boom")) + probe = make_probe(transport=transport) + probe.flush() + probe.flush() # broken: no second attempt + assert probe._broken and transport.calls == ["send"] + assert capsys.readouterr().err.count("disabled after an internal error (RuntimeError)") == 1 + + +def test_flushes_from_two_threads_never_overlap_on_the_transport(make_probe): + """Regression: stop()'s final flush raced the flusher thread on one + socket; the loser's sendall failed and the final session line was lost + (the reference probe's conformance run flaked with 'no session line').""" + inside = threading.Event() + overlaps = [] + + class SlowTransport(RecordingTransport): + def send(self, events): + if inside.is_set(): + overlaps.append(True) + inside.set() + time.sleep(0.005) + inside.clear() + return super().send(events) + + transport = SlowTransport() + probe = make_probe(transport=transport) + threads = [threading.Thread(target=lambda: [probe.flush() for _ in range(10)]) for _ in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + assert overlaps == [] and len(transport.batches) == 40 and not probe._broken + + +def test_flush_interval_follows_welcome_and_doubles_while_slow(make_probe): + transport = RecordingTransport() + probe = make_probe(transport=transport, flush_seconds=4.0) + assert probe._interval() == 4.0 + transport.flush_interval = 0.5 # what a welcome sets + assert probe._interval() == 0.5 + transport.slow = True + assert probe._interval() == 1.0 + + +def test_the_flusher_thread_flushes_periodically_and_stops(make_probe): + transport = RecordingTransport() + probe = make_probe(transport=transport, flush_seconds=0.02) + probe.start() + deadline = time.monotonic() + 10 + while len(transport.batches) < 3 and time.monotonic() < deadline: + time.sleep(0.01) + assert len(transport.batches) >= 3 + assert probe._thread is not None and probe._thread.daemon + probe.stop() + probe._thread.join(5) + assert not probe._thread.is_alive() + + +# ---------- through the #73 conformance kit's fake sensor ---------- + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_every_line_sent_to_a_sensor_is_a_valid_protocol_message(modules, make_probe, backend): + vuln, app = modules() + app_mod = importlib.import_module(app) + fake = FakeSensor() + try: + transport = transport_mod.SocketTransport(fake.address) + probe = make_probe([f"{vuln}.parse"], backend=backend, transport=transport) + probe.start() + app_mod.handle(f"token={SENTINEL}") + deadline = time.monotonic() + 10 + while transport.flush_interval is None and time.monotonic() < deadline: + probe.flush() # the welcome is read on the flush after it arrives + time.sleep(0.02) + assert transport.flush_interval == 0.1 # the sensor's welcome now drives flushing + assert probe._interval() == 0.1 + probe.stop() + deadline = time.monotonic() + 10 + while not any('"type":"hit"' in line for line in fake.lines) and time.monotonic() < deadline: + time.sleep(0.02) + lines = list(fake.lines) + finally: + fake.close() + assert json.loads(lines[0])["type"] == "hello" + for line in lines: + validate_message(json.loads(line)) + assert forbidden_data(lines) == [] + assert any(json.loads(line).get("symbol") == f"{vuln}.parse" for line in lines) + + +def test_a_dead_sensor_drops_batches_without_disabling_the_probe(make_probe): + fake = FakeSensor(kill_after_first_batch=True) + transport = transport_mod.SocketTransport(fake.address) + probe = make_probe(transport=transport) + probe.flush() # hello + first batch; the sensor then dies + deadline = time.monotonic() + 10 + while probe.dropped == 0 and time.monotonic() < deadline: + probe.flush() + time.sleep(0.02) + fake.close() + transport.close() + assert probe.dropped >= 1 and not probe._broken + + +def test_the_probe_reconnects_when_the_sensor_comes_back(make_probe): + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + listener.close() # nothing listening yet: the sensor is down + transport = transport_mod.SocketTransport(f"tcp://127.0.0.1:{port}") + probe = make_probe(transport=transport) + probe.flush() + assert probe.dropped == 1 and not probe._broken + + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + server.bind(("127.0.0.1", port)) + except OSError: + pytest.skip("the ephemeral port was taken in between") + server.listen(1) + server.settimeout(10) + try: + probe.flush() # sensor back: reconnects and says hello again + conn, _ = server.accept() + conn.settimeout(10) + data = b"" + while data.count(b"\n") < 2: + chunk = conn.recv(65536) + if not chunk: + break + data += chunk + conn.close() + finally: + server.close() + transport.close() + first, second = (json.loads(line) for line in data.splitlines()[:2]) + assert first["type"] == "hello" and second["type"] == "session" + assert probe.dropped == 1 + + +def test_closing_with_an_unread_welcome_still_delivers_the_final_batch(make_probe): + """Regression: closing a socket with unread inbound data (the sensor's + welcome) sends RST, and the sensor drops lines it hadn't read yet -- the + exit flush's session line. The conformance kit flaked on exactly this.""" + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(("127.0.0.1", 0)) + server.listen(1) + server.settimeout(10) + received: list[bytes] = [] + errors: list[BaseException] = [] + + def slow_sensor(): + conn, _ = server.accept() + try: + conn.sendall(b'{"type":"welcome","protocol":1,"flush_interval":0.1}\n') # never read by the probe + time.sleep(0.3) # the probe flushes and closes before the sensor reads anything + conn.settimeout(10) + data = b"" + while chunk := conn.recv(65536): + data += chunk + received.append(data) + except OSError as exc: + errors.append(exc) + finally: + conn.close() + + thread = threading.Thread(target=slow_sensor, daemon=True) + thread.start() + transport = transport_mod.SocketTransport(f"tcp://127.0.0.1:{server.getsockname()[1]}") + transport._read_control = lambda: None # the exit flush never gets to read the welcome + probe = make_probe(transport=transport) + probe._active = True # as at exit: stop() does the final flush, then closes + probe.stop() + thread.join(10) + server.close() + assert errors == [] + types = [json.loads(line)["type"] for line in received[0].splitlines()] + assert types[0] == "hello" and "session" in types + + +# ---------- shutdown ordering ---------- + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_stop_flushes_once_then_closes_and_uninstalls_every_hook(modules, make_probe, backend): + vuln, app = modules() + app_mod = importlib.import_module(app) + transport = RecordingTransport() + probe = make_probe([f"{vuln}.parse"], backend=backend, transport=transport) + probe.start() + tool_id = probe._tool_id + app_mod.handle("a") + probe.stop() + probe.stop() # idempotent + + assert transport.calls == ["send", "close"] # final flush strictly before close + assert [h["count"] for h in _hits(transport.batches[-1])] == [1] + assert not any(isinstance(f, _ImportWatcher) and f.probe is probe for f in sys.meta_path) + if backend == "monitoring": + assert probe._tool_id is None and sys.monitoring.get_tool(tool_id) is None + else: + assert sys.getprofile() is None + app_mod.handle("b") # after stop nothing is recorded + assert [h["count"] for h in _hits(probe.snapshot())] == [1] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_a_disabled_probe_still_releases_its_hooks_on_stop(modules, make_probe, backend, monkeypatch, capsys): + """Regression: stop() used to return early once _disable() had cleared + _active, leaking the sys.monitoring tool id (only four exist), the + import watcher and the transport.""" + vuln, app = modules() + app_mod = importlib.import_module(app) + transport = RecordingTransport() + probe = make_probe([f"{vuln}.parse"], backend=backend, transport=transport) + probe.start() + tool_id = probe._tool_id + + def boom(*_a, **_k): + raise RuntimeError("probe bug") + + monkeypatch.setattr(probe, "_record_hit", boom) + assert app_mod.handle("abc") == "ABC" # fail-open: the app still works + assert probe._broken and "disabled after an internal error" in capsys.readouterr().err + + probe.stop() + assert transport.calls == ["close"] # no flush from a broken probe, but the transport is closed + assert not any(isinstance(f, _ImportWatcher) and f.probe is probe for f in sys.meta_path) + if backend == "monitoring": + assert sys.monitoring.get_tool(tool_id) is None + + +def test_stopping_a_probe_that_never_started_touches_nothing(make_probe): + sentinel_profiler = lambda *_a: None + sys.setprofile(sentinel_profiler) + try: + transport = RecordingTransport() + make_probe(transport=transport).stop() + assert transport.calls == [] and sys.getprofile() is sentinel_profiler + finally: + sys.setprofile(None) + + +@pytest.mark.skipif(not hasattr(sys, "monitoring"), reason="sys.monitoring is 3.12+") +def test_no_free_monitoring_tool_id_fails_open(make_probe, monkeypatch, capsys): + monkeypatch.setattr(sys.monitoring, "get_tool", lambda _tool_id: "someone-else") + probe = make_probe(backend="monitoring") + probe.start() # never raises into the app + assert probe._broken and not probe._active and probe._tool_id is None + assert "disabled after an internal error (RuntimeError)" in capsys.readouterr().err + + +# ---------- forked workers ---------- + + +def test_a_forked_child_starts_its_own_session(make_probe): + transport = RecordingTransport() + probe = make_probe(transport=transport) + probe._hits[("fp", "sym")] = [5, 0.0, 0.0, [], None] + parent_session = probe.session_id + probe._after_fork() + try: + assert probe.session_id != parent_session and probe._hits == {} and probe.dropped == 0 + assert transport.reopened == 1 and probe._thread is not None and probe._thread.is_alive() + finally: + probe._stop.set() + + +def test_a_fork_whose_transport_cannot_reopen_disables_the_probe(make_probe, capsys): + transport = RecordingTransport() + transport.reopen = lambda: (_ for _ in ()).throw(OSError("no socket")) + probe = make_probe(transport=transport) + probe._after_fork() + assert probe._broken and "OSError" in capsys.readouterr().err + + +# ---------- coverage denominator and loaded packages ---------- + + +def test_count_app_functions_counts_nested_code_and_caches_by_mtime(tmp_path, monkeypatch): + app = tmp_path / "counted.py" + app.write_text("def a():\n def inner():\n pass\n\nclass K:\n def m(self):\n pass\n", + encoding="utf-8") + (tmp_path / "broken.py").write_text("def (:\n", encoding="utf-8") + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=str(tmp_path)) + probe._seen_app_code = {compile("pass", str(app), "exec"), compile("pass", str(tmp_path / "broken.py"), "exec")} + monkeypatch.setattr(sys, "argv", [str(tmp_path / "gone.py")]) # main script no longer on disk + # a(), inner(), class body K, m() + assert _count_app_functions(probe) == 4 + key = os.path.normcase(os.path.abspath(app)) + assert probe_mod._FUNCTION_COUNTS[key][1] == 4 + + monkeypatch.setattr(probe_mod, "compile", lambda *_a, **_k: pytest.fail("recompiled"), raising=False) + assert _count_app_functions(probe) == 4 # cached: same mtime, not compiled again + + +def test_loads_report_imported_distributions_and_skip_broken_metadata(make_probe, monkeypatch): + from importlib.metadata import version + + probe = make_probe() + loads = {e["package"].lower(): e for e in probe._loads()} + assert loads["pytest"]["version"] == version("pytest") + assert loads["pytest"]["session"] == probe.session_id and loads["pytest"]["ecosystem"] == "PyPI" + + monkeypatch.setattr(probe_mod, "_DISTRIBUTIONS", {"json": ["no-such-distribution-xyz"], "zz_not_imported": ["x"]}) + monkeypatch.setattr(probe_mod, "_VERSIONS", {}) + assert probe._loads() == [] + + +# ---------- the import watcher ---------- + + +def test_import_watcher_ignores_imports_it_is_not_waiting_for(make_probe): + probe = make_probe() + watcher = _ImportWatcher(probe) + assert watcher.find_spec("json") is None # nothing pending at all + probe._pending_symbols["wanted_mod.fn"] = ["fp"] + assert watcher.find_spec("json") is None # unrelated module + assert watcher.find_spec("wanted_mod") is None # wanted, but not importable + watcher._busy.on = True + assert watcher.find_spec("wanted_mod") is None # re-entrant lookup short-circuits + + +def test_import_watcher_disables_the_probe_if_resolving_fails(modules, make_probe, monkeypatch, capsys): + vuln, _ = modules() + probe = make_probe([f"{vuln}.parse"]) + probe._load_watchlist(force=True) + spec = _ImportWatcher(probe).find_spec(vuln) + assert spec is not None + monkeypatch.setattr(probe, "_resolve_pending", lambda: (_ for _ in ()).throw(RuntimeError("bad"))) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) # the module still loads + assert module.parse("a") == "A" and probe._broken + assert "RuntimeError" in capsys.readouterr().err + + +# ---------- `secfoo.sensor` entry points ---------- + + +@pytest.fixture +def fresh_package(monkeypatch): + monkeypatch.setattr(sensor_pkg, "_probe", None) + for name in ("SECFOO_SENSOR", "SECFOO_WATCHLIST", "SECFOO_EVENTS_OUT", "SECFOO_SENSOR_ADDR", + "SECFOO_FLUSH_INTERVAL", "SECFOO_APP_ROOT", "SECFOO_SENSOR_BACKEND"): + monkeypatch.delenv(name, raising=False) + yield + probe = sensor_pkg._probe + if probe is not None: + probe.stop() + atexit.unregister(probe.stop) + sys.setprofile(None) + threading.setprofile(None) # type: ignore[arg-type] + + +@pytest.mark.parametrize(("value", "expected"), [("1", True), (" 1 ", True), ("0", False), ("true", False), ("", False)]) +def test_enabled_only_for_exactly_one(value, expected): + assert sensor_pkg.enabled({"SECFOO_SENSOR": value}) is expected + assert sensor_pkg.enabled({}) is False + + +def test_start_from_env_configures_the_probe_from_secfoo_variables(fresh_package, tmp_path, monkeypatch): + out = tmp_path / "events.ndjson" + _write_watchlist(tmp_path / "w.json", ["x.y"]) + monkeypatch.setenv("SECFOO_SENSOR", "1") + monkeypatch.setenv("SECFOO_WATCHLIST", str(tmp_path / "w.json")) + monkeypatch.setenv("SECFOO_EVENTS_OUT", str(out)) + monkeypatch.setenv("SECFOO_APP_ROOT", str(tmp_path)) + monkeypatch.setenv("SECFOO_FLUSH_INTERVAL", "0.001") + monkeypatch.setenv("SECFOO_SENSOR_BACKEND", "profile") + + probe = sensor_pkg.start_from_env() + assert probe is not None and sensor_pkg.current_probe() is probe + assert sensor_pkg.start_from_env() is probe # started once per process + assert probe.flush_seconds == 0.05 # clamped: a tiny interval can't spin the flusher + assert probe.backend == "profile" and probe.app_root == os.path.normcase(os.path.abspath(tmp_path)) + assert isinstance(probe.transport, transport_mod.FileTransport) + assert probe._pending_symbols == {"x.y": ["fp-1"]} + probe.stop() + events = [json.loads(line) for line in out.read_text(encoding="utf-8").splitlines()] + assert any(e["type"] == "session" and e["id"] == probe.session_id for e in events) # the final flush landed + + +@pytest.mark.parametrize(("name", "value", "reason"), [ + ("SECFOO_FLUSH_INTERVAL", "soon", "could not convert"), + ("SECFOO_SENSOR_ADDR", "ftp://x", "unsupported SECFOO_SENSOR_ADDR"), + ("SECFOO_SENSOR_ADDR", "tcp://10.0.0.5:7461", "loopback"), +]) +def test_bad_configuration_never_stops_the_app(fresh_package, monkeypatch, capsys, name, value, reason): + monkeypatch.setenv("SECFOO_SENSOR", "1") + monkeypatch.setenv(name, value) + assert sensor_pkg.start_from_env() is None and sensor_pkg.current_probe() is None + err = capsys.readouterr().err + assert err.startswith("secfoo sensor: not started") and reason in err + + +def test_python_dash_m_secfoo_sensor_without_arguments_prints_usage(capsys): + with pytest.raises(SystemExit) as exc: + sensor_main.main([]) + assert exc.value.code == 2 and "usage: python -m secfoo.sensor" in capsys.readouterr().err + + +def test_python_dash_m_secfoo_sensor_runs_a_script_like_python_would(fresh_package, tmp_path, monkeypatch, capsys): + script = tmp_path / "script.py" + script.write_text("import sys\nprint('ran', __name__, sys.argv[1:])\n", encoding="utf-8") + monkeypatch.setattr(sys, "argv", ["ignored"]) + sensor_main.main([str(script), "--flag"]) + assert capsys.readouterr().out.strip() == "ran __main__ ['--flag']" + assert sensor_pkg.current_probe() is None # SECFOO_SENSOR unset: inert + + +def test_python_dash_m_secfoo_sensor_runs_a_module(fresh_package, tmp_path, monkeypatch, capsys): + name = f"mod_{uuid.uuid4().hex[:8]}" + (tmp_path / f"{name}.py").write_text("import sys\nprint('module', __name__, sys.argv[1:])\n", encoding="utf-8") + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + monkeypatch.setattr(sys, "argv", ["ignored"]) + try: + sensor_main.main(["-m", name, "a", "b"]) + finally: + sys.modules.pop(name, None) + assert capsys.readouterr().out.strip() == "module __main__ ['a', 'b']" + + +def test_the_package_runs_as_a_module(fresh_package, monkeypatch): + monkeypatch.setattr(sys, "argv", ["secfoo.sensor"]) + monkeypatch.delitem(sys.modules, "secfoo.sensor.__main__") # run it fresh, as `python -m` does + with pytest.raises(SystemExit) as exc: + runpy.run_module("secfoo.sensor", run_name="__main__", alter_sys=False) + assert exc.value.code == 2 From 08ebfa72c44481c84bf17f0a05a54c989442c223 Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Thu, 19 Nov 2026 20:43:14 +0000 Subject: [PATCH 2/2] fix(sensor): bound close, serialise stop, release profiler; test reconnect Review follow-ups for #148 (#115), pushed by the maintainers: - SocketTransport.close(): the drain now has one overall deadline (CLOSE_DRAIN_SECONDS). The per-recv timeout let a sensor that keeps writing hold close(), and so the app's exit, open indefinitely. - Probe.stop() holds the flush lock across the final flush and the close, with a bounded wait (STOP_WAIT_SECONDS); flush() is a no-op once stop() has begun. A flusher that woke just before stop() could otherwise send after the close and leave a second, never-closed socket. - Profile backend: _disable() and stop() remove the profiler from new threads (and all threads on 3.12+), and the profiler records nothing once the probe stops or disables itself. - Flush intervals: NaN/inf from SECFOO_FLUSH_INTERVAL or a sensor welcome are rejected (the flusher spun or died); values are clamped to 0.05-3600 s. - App-code filter compares real paths, so a symlinked interpreter (Homebrew, pyenv) no longer counts the stdlib as app code. - CI: coverage is gated in its own last step, so a coverage-only drop no longer hides the conformance and skills checks. - Tests: reconnect after a live sensor dies, bounded close drain, no send after stop, stack-sample filter on a shallow stack, profiler release on disable, symlinked app root, unusable welcome intervals, nan/inf config. Each was checked by reintroducing the bug. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 14 +- src/secfoo/sensor/__init__.py | 9 +- src/secfoo/sensor/probe.py | 120 +++++++++---- src/secfoo/sensor/transport.py | 30 +++- tests/test_sensor/test_probe_in_process.py | 190 +++++++++++++++++++++ 5 files changed, 314 insertions(+), 49 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6f8075e..a8271de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,10 +47,9 @@ jobs: run: ruff check . || true - name: Test (secfoo core) - # --cov-fail-under is the floor (#115): the job fails if total line - # coverage drops below it. Set just under today's ~92%; raise it when - # a PR lifts coverage, never lower it to make a PR pass. - run: pytest tests --cov=secfoo --cov-report=term --cov-report=xml --cov-fail-under=90 + # Coverage is collected here and gated in its own last step, so a + # coverage-only drop never hides the conformance and skills checks. + run: pytest tests --cov=secfoo --cov-report=term --cov-report=xml - name: Coverage summary # The per-file table, lowest first, so a drop is visible on the PR. @@ -78,3 +77,10 @@ jobs: - name: Validate example custom skills # Same check a team's own skills repo would run (docs/SKILLS.md). run: secfoo skills validate examples/skills + + - name: Coverage floor (#115) + # The job fails if total line coverage drops below the floor. Set just + # under today's ~92%; raise it when a PR lifts coverage, never lower + # it to make a PR pass. + if: ${{ !cancelled() }} + run: coverage report --fail-under=90 diff --git a/src/secfoo/sensor/__init__.py b/src/secfoo/sensor/__init__.py index 8d17d00..e07b81b 100644 --- a/src/secfoo/sensor/__init__.py +++ b/src/secfoo/sensor/__init__.py @@ -28,14 +28,17 @@ def start_from_env(): return _probe try: from secfoo.sensor.probe import DEFAULT_FLUSH_SECONDS, Probe - from secfoo.sensor.transport import from_env + from secfoo.sensor.transport import clamp_flush_interval, from_env - flush = float(os.environ.get("SECFOO_FLUSH_INTERVAL", DEFAULT_FLUSH_SECONDS)) + raw = os.environ.get("SECFOO_FLUSH_INTERVAL") + flush = clamp_flush_interval(DEFAULT_FLUSH_SECONDS if raw is None else float(raw)) + if flush is None: + raise ValueError(f"SECFOO_FLUSH_INTERVAL must be a finite number of seconds, got {raw!r}") _probe = Probe( watchlist_path=os.environ.get("SECFOO_WATCHLIST") or None, transport=from_env(), app_root=os.environ.get("SECFOO_APP_ROOT") or None, - flush_seconds=max(flush, 0.05), + flush_seconds=flush, backend=os.environ.get("SECFOO_SENSOR_BACKEND") or None, ) _probe.start() diff --git a/src/secfoo/sensor/probe.py b/src/secfoo/sensor/probe.py index cb19274..496c2a6 100644 --- a/src/secfoo/sensor/probe.py +++ b/src/secfoo/sensor/probe.py @@ -37,6 +37,10 @@ DEFAULT_FLUSH_SECONDS = 10.0 WATCHLIST_RECHECK_SECONDS = 30.0 MAX_STACK_FRAMES = 10 +# stop() waits at most this long for an in-flight flush (bounded by the +# transport's socket timeout plus its close drain) before giving up on the +# final flush: the app's exit is never held by the sensor. +STOP_WAIT_SECONDS = 2.0 _TOOL_NAME = "secfoo-sensor" @@ -52,7 +56,10 @@ def _stdlib_and_site_dirs() -> tuple[str, ...]: paths = sysconfig.get_paths() dirs = {paths.get(k) for k in ("stdlib", "platstdlib", "purelib", "platlib")} dirs |= {p for p in sys.path if p and ("site-packages" in p or "dist-packages" in p)} - return tuple(sorted(os.path.normcase(os.path.abspath(d)) for d in dirs if d)) + # realpath, not abspath: with a symlinked interpreter (Homebrew, pyenv, + # venvs) code objects carry the resolved path while sysconfig reports the + # symlinked one, and the stdlib would count as app code. + return tuple(sorted(os.path.normcase(os.path.realpath(d)) for d in dirs if d)) class Probe: @@ -61,7 +68,7 @@ def __init__(self, *, watchlist_path: str | None, transport, app_root: str | Non self.watchlist_path = watchlist_path self.transport = transport self.flush_seconds = flush_seconds - self.app_root = os.path.normcase(os.path.abspath(app_root or os.getcwd())) + self.app_root = os.path.normcase(os.path.realpath(app_root or os.getcwd())) self.backend = backend or ("monitoring" if hasattr(sys, "monitoring") else "profile") self._excluded_dirs = _stdlib_and_site_dirs() self._lock = threading.Lock() @@ -78,6 +85,12 @@ def __init__(self, *, watchlist_path: str | None, transport, app_root: str | Non self._pending_symbols: dict = {} # symbol -> [fingerprints], not resolved yet self._seen_app_code: set = set() self._app_code_cache: dict = {} # code object -> is app code + self._paths: dict = {} # filename -> normalised real path + # Profile backend only: the profiler stays installed in threads that + # were already running when the probe stopped or disabled itself + # (sys.setprofile only reaches the calling thread before 3.12), so it + # checks this flag and records nothing once it is cleared. + self._recording = False self._tool_id: int | None = None self._watcher: _ImportWatcher | None = None self._stop = threading.Event() @@ -119,29 +132,39 @@ def stop(self) -> None: """Final flush (only while healthy), then release every hook. A probe that `_disable`d itself still holds its sys.monitoring tool id, its import watcher and its transport, so those are released either way; - stopping twice is a no-op.""" + stopping twice is a no-op. + + The flush lock is held across the final flush AND the close, so the + flusher thread can never send after (or during) the close. The wait + for it is bounded, so a flusher stuck in a slow send never holds up + the app's exit.""" was_active = self._active self._stop.set() - if was_active: - self.flush() - self._active = False + self._recording = False + locked = self._flush_lock.acquire(timeout=STOP_WAIT_SECONDS) try: - if self._watcher is not None: - if self._watcher in sys.meta_path: - sys.meta_path.remove(self._watcher) - self._watcher = None - if self._tool_id is not None: - sys.monitoring.register_callback(self._tool_id, sys.monitoring.events.PY_START, None) - sys.monitoring.set_events(self._tool_id, 0) - sys.monitoring.free_tool_id(self._tool_id) - self._tool_id = None - elif was_active and self.backend == "profile": - sys.setprofile(None) - threading.setprofile(None) # type: ignore[arg-type] - if was_active or self._broken: - self.transport.close() - except Exception: # noqa: BLE001, S110 -- shutting down; never raise into the app - pass + if was_active and locked and not self._broken: + self._flush_now() + self._active = False + try: + if self._watcher is not None: + if self._watcher in sys.meta_path: + sys.meta_path.remove(self._watcher) + self._watcher = None + if self._tool_id is not None: + sys.monitoring.register_callback(self._tool_id, sys.monitoring.events.PY_START, None) + sys.monitoring.set_events(self._tool_id, 0) + sys.monitoring.free_tool_id(self._tool_id) + self._tool_id = None + elif self.backend == "profile" and (was_active or self._broken): + _release_profiler() + if was_active or self._broken: + self.transport.close() + except Exception: # noqa: BLE001, S110 -- shutting down; never raise into the app + pass + finally: + if locked: + self._flush_lock.release() def _after_fork(self) -> None: """A forked worker (gunicorn, multiprocessing) is its own session.""" @@ -160,13 +183,14 @@ def _disable(self, exc: BaseException) -> None: return self._broken = True self._active = False + self._recording = False try: if self._tool_id is not None: sys.monitoring.set_events(self._tool_id, 0) for code in list(self._watched): sys.monitoring.set_local_events(self._tool_id, code, 0) elif self.backend == "profile": - sys.setprofile(None) + _release_profiler() print(f"secfoo sensor: disabled after an internal error ({exc.__class__.__name__}); " "the app is unaffected", file=sys.stderr) except Exception: # noqa: BLE001, S110 -- never raise into the app @@ -240,7 +264,7 @@ def _on_py_start(self, code, _offset): def _start_profile(self) -> None: def profiler(frame, event, _arg): - if event != "call": + if event != "call" or not self._recording: return try: code = frame.f_code @@ -253,6 +277,7 @@ def profiler(frame, event, _arg): except Exception as exc: # noqa: BLE001 self._disable(exc) + self._recording = True sys.setprofile(profiler) threading.setprofile(profiler) @@ -266,10 +291,18 @@ def _is_app_code_obj(self, code) -> bool: known = self._app_code_cache[code] = self._is_app_code(code.co_filename) return known + def _real(self, filename: str) -> str: + """normcase(realpath(filename)), cached: realpath stats every path + component, and the same few files come back on every stack sample.""" + path = self._paths.get(filename) + if path is None: + path = self._paths[filename] = os.path.normcase(os.path.realpath(filename)) + return path + def _is_app_code(self, filename: str) -> bool: if not filename or filename.startswith("<"): return False - path = os.path.normcase(os.path.abspath(filename)) + path = self._real(filename) return path.startswith(self.app_root) and not path.startswith(self._excluded_dirs) def _record_hit(self, code, watched) -> None: @@ -300,7 +333,7 @@ def _stack_sample(self) -> list[str]: while frame is not None and len(frames) < MAX_STACK_FRAMES: filename = frame.f_code.co_filename if self._is_app_code(filename): - rel = os.path.relpath(filename, self.app_root).replace(os.sep, "/") + rel = os.path.relpath(self._real(filename), self.app_root).replace(os.sep, "/") frames.append(f"{rel}:{frame.f_lineno}") frame = frame.f_back return frames @@ -365,19 +398,24 @@ def flush(self) -> None: """One batch of running totals. Serialised: when stop()'s final flush overlapped the flusher thread's, the transport's non-blocking control read made the other thread's sendall fail, the socket was closed as - "sensor gone", and the final session line was lost.""" - if self._broken: + "sensor gone", and the final session line was lost. + Once stop() has begun, only stop() itself flushes (under the lock).""" + if self._broken or self._stop.is_set(): return with self._flush_lock: - if self._broken: + if self._broken or self._stop.is_set(): return - try: - self._load_watchlist() - self._resolve_pending() - if not self.transport.send(self.snapshot()): - self.dropped += 1 - except Exception as exc: # noqa: BLE001 - self._disable(exc) + self._flush_now() + + def _flush_now(self) -> None: + """The flush itself; the caller holds _flush_lock.""" + try: + self._load_watchlist() + self._resolve_pending() + if not self.transport.send(self.snapshot()): + self.dropped += 1 + except Exception as exc: # noqa: BLE001 + self._disable(exc) def _interval(self) -> float: """The sensor's `welcome` interval if it sent one, doubled while it @@ -394,6 +432,16 @@ def loop(): self._thread.start() +def _release_profiler() -> None: + """Remove the profiler from this thread, from threads started later and, + on 3.12+, from every running thread.""" + sys.setprofile(None) + threading.setprofile(None) # type: ignore[arg-type] + setprofile_all = getattr(threading, "setprofile_all_threads", None) + if setprofile_all is not None: + setprofile_all(None) + + def _resolve(symbol: str): """The code object for `module.qualname`, once the module is imported.""" parts = symbol.split(".") diff --git a/src/secfoo/sensor/transport.py b/src/secfoo/sensor/transport.py index d954fe8..fe5000b 100644 --- a/src/secfoo/sensor/transport.py +++ b/src/secfoo/sensor/transport.py @@ -17,9 +17,11 @@ import gzip import ipaddress import json +import math import os import socket import sys +import time import urllib.parse import urllib.request @@ -27,6 +29,17 @@ DIRECT_TIMEOUT_SECONDS = 0.2 # #73: a cold start or shutdown never waits on the network SOCKET_TIMEOUT_SECONDS = 1.0 CLOSE_DRAIN_SECONDS = 0.2 # bounded: shutdown never waits on the sensor longer than this +MIN_FLUSH_SECONDS = 0.05 +MAX_FLUSH_SECONDS = 3600.0 + + +def clamp_flush_interval(value) -> float | None: + """A usable flush interval in seconds, or None. NaN and infinity are + rejected: Event.wait(nan) returns at once (the flusher would spin) and + Event.wait(inf) raises OverflowError inside the flusher thread.""" + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + return None + return min(max(float(value), MIN_FLUSH_SECONDS), MAX_FLUSH_SECONDS) class TransportError(ValueError): @@ -154,8 +167,10 @@ def _read_control(self) -> None: message = json.loads(raw) except ValueError: continue - if message.get("type") == "welcome" and isinstance(message.get("flush_interval"), (int, float)): - self.flush_interval = max(float(message["flush_interval"]), 0.05) + if message.get("type") == "welcome": + interval = clamp_flush_interval(message.get("flush_interval")) + if interval is not None: + self.flush_interval = interval elif message.get("type") == "slow": self.slow = True @@ -167,14 +182,17 @@ def close(self) -> None: FIN, and the sensor then discards lines it had received but not yet read -- the final flush's session line among them. So: send FIN, drain what the sensor wrote back (bounded by CLOSE_DRAIN_SECONDS), - then close.""" + then close. The drain has one overall deadline, not a per-read + timeout: a sensor that keeps writing must not hold the app's exit.""" conn = self._conn if conn is not None: try: conn.shutdown(socket.SHUT_WR) - conn.settimeout(CLOSE_DRAIN_SECONDS) - while conn.recv(65536): - pass + deadline = time.monotonic() + CLOSE_DRAIN_SECONDS + while (remaining := deadline - time.monotonic()) > 0: + conn.settimeout(remaining) + if not conn.recv(65536): + break except OSError: pass super().close() diff --git a/tests/test_sensor/test_probe_in_process.py b/tests/test_sensor/test_probe_in_process.py index bb7b11f..a5663ab 100644 --- a/tests/test_sensor/test_probe_in_process.py +++ b/tests/test_sensor/test_probe_in_process.py @@ -353,6 +353,43 @@ def test_stack_sample_keeps_app_frames_only_and_caps_its_depth(make_probe, tmp_p assert hit["entry_frame"] == hit["stack_sample"][1] +def test_stack_sample_drops_frames_outside_the_app(make_probe, tmp_path, monkeypatch): + """A shallow app call: pytest and stdlib frames are within reach of + MAX_STACK_FRAMES, so the filename filter is what keeps them out.""" + name = f"shallow_{uuid.uuid4().hex[:8]}" + body = "def f0(probe):\n return f1(probe)\n\ndef f1(probe):\n return f2(probe)\n\n" + body += "def f2(probe):\n return probe._record_hit(probe, ('sym', ['fp']))\n" + (tmp_path / f"{name}.py").write_text(body, encoding="utf-8") + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + mod = importlib.import_module(name) + try: + probe = make_probe() + mod.f0(probe) + finally: + sys.modules.pop(name, None) + [hit] = _hits(probe.snapshot()) + assert hit["stack_sample"] and len(hit["stack_sample"]) < probe_mod.MAX_STACK_FRAMES + assert all(frame.startswith(f"{name}.py:") for frame in hit["stack_sample"]) + + +def test_app_code_follows_symlinks(tmp_path): + """A symlinked app root (or a symlinked interpreter) must not change + what counts as app code: both sides are compared as real paths.""" + real = tmp_path / "real" + (real / "pkg").mkdir(parents=True) + link = tmp_path / "link" + try: + link.symlink_to(real, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available here") + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=str(link)) + assert probe._is_app_code(str(real / "pkg" / "views.py")) + assert probe._is_app_code(str(link / "pkg" / "views.py")) + probe = Probe(watchlist_path=None, transport=RecordingTransport(), app_root=str(real)) + assert probe._is_app_code(str(link / "pkg" / "views.py")) + + # ---------- frame and filename filters ---------- @@ -607,6 +644,108 @@ def test_the_probe_reconnects_when_the_sensor_comes_back(make_probe): assert probe.dropped == 1 +def test_the_probe_reconnects_after_a_live_sensor_dies(make_probe): + """#115: the sensor accepts, reads the first batch, then dies (closes + the connection) and comes back on the same address. The probe must drop + the dead socket and say hello on a fresh connection, not keep writing + into the dead one.""" + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(("127.0.0.1", 0)) + server.listen(2) + server.settimeout(10) + transport = transport_mod.SocketTransport(f"tcp://127.0.0.1:{server.getsockname()[1]}") + probe = make_probe(transport=transport) + + def read_lines(conn, count): + conn.settimeout(10) + data = b"" + while data.count(b"\n") < count: + chunk = conn.recv(65536) + if not chunk: + break + data += chunk + return [json.loads(line)["type"] for line in data.splitlines()[:count]] + + try: + assert probe.flush() is None + first, _ = server.accept() + assert read_lines(first, 2) == ["hello", "session"] + first.close() # the sensor dies; the probe's socket is now dead + + server.settimeout(0.2) + second = None + deadline = time.monotonic() + 10 + while second is None and time.monotonic() < deadline: + probe.flush() # the first write after EOF may still "succeed"; a later one fails and reconnects + try: + second, _ = server.accept() + except TimeoutError: + continue + assert second is not None, "the probe never reconnected to the restarted sensor" + assert read_lines(second, 2) == ["hello", "session"] + second.close() + finally: + server.close() + transport.close() + assert probe.dropped >= 1 and not probe._broken + + +def test_close_drain_is_bounded_even_if_the_sensor_keeps_writing(): + """close() runs from stop() at exit: a sensor that keeps talking must + not hold it open past CLOSE_DRAIN_SECONDS.""" + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(("127.0.0.1", 0)) + server.listen(1) + server.settimeout(10) + stop = threading.Event() + + def chatty_sensor(): + conn, _ = server.accept() + give_up = time.monotonic() + 5 # a regression fails the bound below instead of hanging the suite + try: + while not stop.is_set() and time.monotonic() < give_up: + conn.sendall(b'{"type":"slow"}\n') + time.sleep(0.05) + except OSError: + pass + finally: + conn.close() + + thread = threading.Thread(target=chatty_sensor, daemon=True) + thread.start() + transport = transport_mod.SocketTransport(f"tcp://127.0.0.1:{server.getsockname()[1]}") + try: + assert transport.send([{"type": "session", "id": "s"}]) + started = time.monotonic() + transport.close() + elapsed = time.monotonic() - started + finally: + stop.set() + thread.join(5) + server.close() + assert elapsed < transport_mod.CLOSE_DRAIN_SECONDS + 0.5 + + +@pytest.mark.parametrize("value", ["NaN", "Infinity", "-Infinity", "true", "\"1\""]) +def test_a_welcome_with_an_unusable_interval_is_ignored(value): + transport = transport_mod.SocketTransport("tcp://127.0.0.1:9") + ours, theirs = socket.socketpair() + transport._conn = ours + try: + theirs.sendall(b'{"type":"welcome","protocol":1,"flush_interval":' + value.encode() + b"}\n") + time.sleep(0.05) + transport._read_control() + assert transport.flush_interval is None + theirs.sendall(b'{"type":"welcome","protocol":1,"flush_interval":1e308}\n') + time.sleep(0.05) + transport._read_control() + assert transport.flush_interval == transport_mod.MAX_FLUSH_SECONDS + finally: + transport._conn = None + ours.close() + theirs.close() + + def test_closing_with_an_unread_welcome_still_delivers_the_final_batch(make_probe): """Regression: closing a socket with unread inbound data (the sensor's welcome) sends RST, and the sensor drops lines it hadn't read yet -- the @@ -650,6 +789,29 @@ def slow_sensor(): # ---------- shutdown ordering ---------- +def test_the_flusher_never_sends_after_stop_has_closed_the_transport(make_probe): + """stop() holds the flush lock across its final flush and the close, so + a flusher that woke just before stop() cannot send afterwards (which + would reconnect and leave a second, never-closed socket).""" + + class SlowTransport(RecordingTransport): + def send(self, events): + self.calls.append("send") + time.sleep(0.03) + return True + + for _ in range(25): + transport = SlowTransport() + probe = make_probe(transport=transport, flush_seconds=0.01, watchlist=False) + probe._active = True + probe._start_flusher() + time.sleep(0.04) # let the flusher be mid-send or about to wake + probe.stop() + probe._thread.join(2) + assert transport.calls.count("close") == 1 + assert transport.calls[-1] == "close", transport.calls + + @pytest.mark.parametrize("backend", BACKENDS) def test_stop_flushes_once_then_closes_and_uninstalls_every_hook(modules, make_probe, backend): vuln, app = modules() @@ -699,6 +861,32 @@ def boom(*_a, **_k): assert sys.monitoring.get_tool(tool_id) is None +def test_a_disabled_profile_probe_stops_recording_in_every_thread(modules, make_probe, trigger, capsys): + """On the profile backend, _disable() and stop() must remove the + profiler for new threads too, and the profiler must record nothing in + threads that still carry it.""" + vuln, app = modules() + app_mod = importlib.import_module(app) + probe = make_probe([f"{vuln}.parse"], backend="profile") + probe.start() + profiler = sys.getprofile() + probe._disable(RuntimeError("probe bug")) + assert "disabled after an internal error" in capsys.readouterr().err + assert sys.getprofile() is None and threading.getprofile() is None # released on disable, not only on stop + probe.stop() + assert sys.getprofile() is None and threading.getprofile() is None + + before = {k: list(v) for k, v in probe._hits.items()} + [watched_code] = probe._watched + # A thread that was already running still carries the old profiler: it + # must record nothing, even for a watched function. + trigger.via_profiler(profiler, _Frame(watched_code), "call") + worker = threading.Thread(target=app_mod.handle, args=("x",)) + worker.start() + worker.join(5) + assert {k: list(v) for k, v in probe._hits.items()} == before + + def test_stopping_a_probe_that_never_started_touches_nothing(make_probe): sentinel_profiler = lambda *_a: None sys.setprofile(sentinel_profiler) @@ -851,6 +1039,8 @@ def test_start_from_env_configures_the_probe_from_secfoo_variables(fresh_package @pytest.mark.parametrize(("name", "value", "reason"), [ ("SECFOO_FLUSH_INTERVAL", "soon", "could not convert"), + ("SECFOO_FLUSH_INTERVAL", "nan", "finite"), + ("SECFOO_FLUSH_INTERVAL", "inf", "finite"), ("SECFOO_SENSOR_ADDR", "ftp://x", "unsupported SECFOO_SENSOR_ADDR"), ("SECFOO_SENSOR_ADDR", "tcp://10.0.0.5:7461", "loopback"), ])