Skip to content

fix(sensor): close socket on peer EOF and extend CI matrix to macOS and Windows - #141

Closed
kushaldave002 wants to merge 2 commits into
secfoo-com:mainfrom
kushaldave002:fix/ci-macos-windows-matrix
Closed

kushaldave002 wants to merge 2 commits into
secfoo-com:mainfrom
kushaldave002:fix/ci-macos-windows-matrix

Conversation

@kushaldave002

@kushaldave002 kushaldave002 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #113

Root Cause (macOS sensor test failure)

tests/test_sensor/test_python_probe.py::test_sensor_dying_mid_run_drops_events_without_blocking failed deterministically on macOS because SocketTransport._read_control() in src/secfoo/sensor/transport.py did not handle EOF (conn.recv() == b"") when the peer closed the TCP connection cleanly:

  • On Linux loopback, sending into a socket after the peer closes delivers RST quickly enough that subsequent sendall() calls raise OSError.
  • On macOS loopback, conn.recv() immediately returns b"" (EOF from the peer's FIN), but _read_control() iterated over b"".splitlines() and left self._conn open, allowing the three tight sendall() calls to buffer in the kernel and return True.

Fixes

  1. Sensor socket EOF handling (src/secfoo/sensor/transport.py): close self._conn in SocketTransport._read_control() when recv() returns b"" (peer EOF) so the next send() drops and attempts to reconnect instead of writing into a half-closed socket.
  2. Windows skill packs bugs (src/secfoo/skills/packs.py):
    • default_pack_name() now splits on backslashes as well as forward slashes and colons, preventing local Windows paths from turning into 120+ character pack names that exceed Windows MAX_PATH.
    • Added _rmtree() clearing Windows read-only attributes on .git/objects/* before unlinking so remove_pack() and failed install_pack() cleanups actually delete git checkouts on Windows (fixing remove_pack and install_from_lock).
  3. Cross-platform CI matrix (.github/workflows/ci.yml):
  4. Windows test coverage (tests/test_port_guard.py, tests/test_skill_packs.py):
    • Added test_stop_gracefully_uses_taskkill_on_windows verifying the Windows taskkill / taskkill /F path on all OSes.
    • Added a Windows path test case to test_default_pack_name_variants.
    • Updated test_stop_gracefully_gives_up_if_the_process_never_dies to patch _signal instead of only os.kill.

skipif / platform guards added

  • tests/test_cloud.py::test_save_cloud_config_sets_restrictive_permissions: skipif(sys.platform == "win32") — Windows NTFS does not enforce POSIX 0o600 file mode bits.
  • tests/test_port_guard.py::test_stop_gracefully_succeeds_after_sigterm & test_stop_gracefully_falls_back_to_sigkill_when_sigterm_is_ignored: skipif(sys.platform == "win32") — test POSIX SIGTERM/SIGKILL signaling; Windows uses taskkill (covered by test_stop_gracefully_uses_taskkill_on_windows).
  • tests/test_memory.py (2 tests): guarded only the stat.S_IMODE(...) == 0o600 assertion with if sys.platform != "win32": so the rest of both tests still runs on Windows.

try:
os.chmod(target, stat.S_IWRITE)
func(target)
except OSError:
@vsn411

vsn411 commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

Thank you, @kushaldave002. The socket fix is a real improvement: on macOS, test_sensor_dying_mid_run_drops_events_without_blocking fails on main and passes 5/5 on this branch, CI is green on Ubuntu (3.10 and 3.12), macOS and Windows, and the three skipif markers each name their OS limitation. Reconnects run on the flush thread, a refused connect fails fast, and close() runs on every path, so the app isn't blocked and no descriptors leak. I'm closing the PR because the new _rmtree helper introduces two regressions, one of which changes permissions on users' own folders. #113 stays open, and you're very welcome to reopen this PR after pushing the fixes, or open a new one. Reviewed at 49b3a9c; both _rmtree problems were reproduced on macOS with Python 3.13.

Blocking

  1. _rmtree can lock users out of their own folders (skills/packs.py ~L86). On every OS, the error handler sets mode 0o200 on whatever path failed. os.chmod follows symlinks, and on a directory 0o200 removes read and execute. If a skill pack is a symlink to a local checkout, rmtree refuses the symlink, the handler chmods the target checkout from 755 to 200, and the link stays. An unreadable subdirectory is also left behind as d-w-------. The read-only fix is only needed on Windows: gate it on os.name == "nt", never chmod through a symlink (os.lstat / follow_symlinks=False), and use stat.S_IWRITE plus the existing bits rather than replacing them.
  2. _rmtree crashes on Python 3.12+ (~L87). The handler retries with func(target), but 3.12's rmtree can report failures from os.open, which needs a flags argument, so a subdirectory with mode 000 raises TypeError: open() missing required argument flags. That escapes where ignore_errors=True used to swallow everything: remove_pack() crashes before save_lock(), so the lock still lists the pack, and in install_pack's cleanup the TypeError replaces the real git error. Only retry for os.unlink / os.rmdir, and use onexc on 3.12+.

Should fix

  • One batch per sensor restart is still lost and reported as sent (sensor/transport.py ~L151). EOF is noticed only after the batch is written, so the first send into a half-closed socket returns True and isn't counted in probe.dropped, against RUNTIME_PROTOCOL section 5 ("counts the drops"). In particular the final flush at shutdown can vanish. A non-blocking MSG_PEEK check for EOF at the start of send(), reconnecting before writing, fixes the root cause.
  • The new close path races with concurrent sends (~L155). stop() calls flush() on the main thread while the flusher thread may be inside send(), and nothing locks the transport, so self._conn can become None between the check and sendall. A stress run raised AttributeError 129 times on main and 249 times on this branch, which disables the probe ("disabled after an internal error"). Hold a threading.Lock around _StreamTransport.send (or Probe.flush).
  • Reconnect doesn't reset slow or flush_interval (~L103). The protocol says "slow" lasts until reconnecting, and EOF reconnects are now the normal path, so after a sensor restart the probe keeps a doubled interval for the rest of the process.
  • Temp-clone cleanup on Windows isn't fixed (targets/github.py ~L63), although Bug: sensor test fails on macOS; CI only runs on Ubuntu. Add macOS and Windows to the matrix and fix what breaks #113 names it. It still uses shutil.rmtree(ignore_errors=True), so read-only .git/objects files leave every shallow clone in %TEMP%. Once _rmtree is fixed, please move it to a shared helper and use it there and in web/routes/assessments.py (~L93).
  • No test covers the new behaviour. Nothing tests reconnecting to a restarted sensor or what the send right after EOF returns; the existing test passes whether events are dropped or delivered. A test with a sensor that closes and comes back would pin it down.
  • Ruff now runs four times with continue-on-error, adding four red annotations to every PR. Run it once (if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.12') or as a separate job. (Make lint and security scanning blocking in CI: ruff has 133 errors behind || true, bandit findings are unreviewed, pip-audit never runs #114 is making ruff blocking, so coordinate there.)
  • tests/test_port_guard.py (~L98): the SIGTERM skipif can be avoided by setting port_guard.sys.platform to "linux", mirroring your taskkill test. That new test also patches the global sys.platform, which agents/base.py's _kill_process_tree docstring warns against because pytest reads it; inject a parameter instead.
  • tests/test_cloud.py (~L71): the Windows skip is justified (NTFS ignores POSIX mode bits), but it hides that save_cloud_config doesn't restrict the API-key file on Windows at all. Please note that in the skip reason so it can be tracked as a follow-up.

The intermittent py3.10 conformance timeout on main comes from the overhead step's 1,000,000-call loop, not from this code, so it's out of scope here.

Looking forward to the next version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: sensor test fails on macOS; CI only runs on Ubuntu. Add macOS and Windows to the matrix and fix what breaks

3 participants