Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .coverage
Binary file not shown.
31 changes: 30 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,40 @@ jobs:
run: ruff check . || true

- name: Test (secfoo core)
run: pytest tests
# 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.
if: ${{ !cancelled() }}
run: |
{
echo "### Coverage (py${{ matrix.python-version }})"
echo
echo '```'
coverage report --sort=cover --skip-covered || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"

- name: Upload coverage.xml
if: ${{ !cancelled() }}
uses: actions/upload-artifact@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

- 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 6 additions & 3 deletions src/secfoo/sensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
116 changes: 93 additions & 23 deletions src/secfoo/sensor/probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand All @@ -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:
Expand All @@ -61,10 +68,13 @@ 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()
# 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()
Expand All @@ -75,7 +85,14 @@ 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()
self._thread: threading.Thread | None = None

Expand All @@ -95,7 +112,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()
Expand All @@ -111,28 +129,48 @@ 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.

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()
self.flush()
self._active = False
self._recording = False
locked = self._flush_lock.acquire(timeout=STOP_WAIT_SECONDS)
try:
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":
sys.setprofile(None)
threading.setprofile(None) # type: ignore[arg-type]
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."""
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()
Expand All @@ -145,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
Expand Down Expand Up @@ -225,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
Expand All @@ -238,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)

Expand All @@ -251,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:
Expand Down Expand Up @@ -285,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
Expand Down Expand Up @@ -347,8 +395,20 @@ def _loads(self) -> list[dict]:
return loads

def flush(self) -> None:
if self._broken:
"""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.
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 or self._stop.is_set():
return
self._flush_now()

def _flush_now(self) -> None:
"""The flush itself; the caller holds _flush_lock."""
try:
self._load_watchlist()
self._resolve_pending()
Expand All @@ -372,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(".")
Expand Down
41 changes: 39 additions & 2 deletions src/secfoo/sensor/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,29 @@
import gzip
import ipaddress
import json
import math
import os
import socket
import sys
import time
import urllib.parse
import urllib.request

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
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):
Expand Down Expand Up @@ -153,13 +167,36 @@
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

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. 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)
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()

def _connect(self):
family = socket.AF_INET6 if self.scheme == "tcp" and ":" in self.target[0] else socket.AF_INET
if self.scheme == "unix":
Expand Down
Loading