diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4443490..7686db6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,12 +14,20 @@ permissions: jobs: test: - name: Test (py${{ matrix.python-version }}) - runs-on: ubuntu-latest + name: Test (${{ matrix.os }}, py${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - python-version: ["3.10", "3.12"] + include: + - os: ubuntu-latest + python-version: "3.10" + - os: ubuntu-latest + python-version: "3.12" + - os: macos-15 + python-version: "3.12" + - os: windows-latest + python-version: "3.12" steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 @@ -39,12 +47,10 @@ jobs: run: secfoo vendor mermaid - name: Lint (ruff) - # Non-blocking for now: 102 pre-existing findings (mostly Optional[X] - # vs X | None style, plus a few unused test fixtures) predate this - # workflow. Reporting them here for visibility without turning every - # unrelated PR red; flip to a hard failure once that backlog is - # cleared (tracked separately from this CI/CD setup). - run: ruff check . || true + # Non-blocking for now: pre-existing lint backlog tracked in #114. + # Using continue-on-error instead of `|| true` so it works on Windows too. + continue-on-error: true + run: ruff check . - name: Test (secfoo core) run: pytest tests diff --git a/src/secfoo/sensor/transport.py b/src/secfoo/sensor/transport.py index 2aa60a1..1370a1e 100644 --- a/src/secfoo/sensor/transport.py +++ b/src/secfoo/sensor/transport.py @@ -148,6 +148,12 @@ def _read_control(self) -> None: finally: if self._conn is not None: self._conn.settimeout(SOCKET_TIMEOUT_SECONDS) + if not data: + # Peer closed the connection (EOF). Close our end so the next + # send() drops and tries to reconnect instead of writing into a + # half-closed socket until the OS eventually signals EPIPE. + self.close() + return for raw in data.splitlines(): try: message = json.loads(raw) diff --git a/src/secfoo/skills/packs.py b/src/secfoo/skills/packs.py index bd0dbd3..574f8a0 100644 --- a/src/secfoo/skills/packs.py +++ b/src/secfoo/skills/packs.py @@ -14,6 +14,7 @@ import os import re import shutil +import stat import subprocess import sys from dataclasses import dataclass @@ -65,8 +66,8 @@ def default_pack_name(url: str) -> str: """`https://github.com/acme/appsec-skills(.git)` -> `acme-appsec-skills`, the example name from the issue. Falls back to asking for `--name` rather than guessing at something unreadable.""" - trimmed = url.rstrip("/").removesuffix(".git") - parts = [part for part in re.split(r"[/:]", trimmed) if part] + trimmed = url.rstrip("/\\").removesuffix(".git") + parts = [part for part in re.split(r"[/\\:]", trimmed) if part] tail = parts[-2:] if len(parts) >= 2 else parts name = re.sub(r"[^a-z0-9-]+", "-", "-".join(tail).lower()).strip("-") name = re.sub(r"-+", "-", name) @@ -75,6 +76,24 @@ def default_pack_name(url: str) -> str: return name +def _rmtree(path: Path) -> None: + """Remove a directory tree, clearing Windows read-only attributes on .git objects.""" + if not path.exists(): + return + + def _make_writable(func, target, _exc): + try: + os.chmod(target, stat.S_IWRITE) + func(target) + except OSError: + pass + + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=_make_writable) + else: + shutil.rmtree(path, onerror=_make_writable) + + def _toml_escape(value: str) -> str: if "\n" in value or "\r" in value: raise PackError("a pack's url/ref/commit must not contain newlines") @@ -159,7 +178,7 @@ def install_pack( _run_git(["checkout", "--quiet", "--detach", ref], cwd=target, timeout=timeout) commit = _run_git(["rev-parse", "HEAD"], cwd=target, timeout=timeout) except PackError: - shutil.rmtree(target, ignore_errors=True) + _rmtree(target) raise pack = Pack(name=resolved_name, url=url, ref=ref or "HEAD", commit=commit) packs[resolved_name] = pack @@ -197,7 +216,7 @@ def remove_pack(name: str) -> None: pack = packs.pop(name, None) if pack is None: raise PackError(f"no installed pack named {name!r} (see `secfoo skills list`)") - shutil.rmtree(pack.path, ignore_errors=True) + _rmtree(pack.path) save_lock(packs) diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 0190726..ac0e16d 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import sys import urllib.error import pytest @@ -67,6 +68,7 @@ def test_save_and_load_cloud_config_roundtrip(tmp_path): assert loaded == config +@pytest.mark.skipif(sys.platform == "win32", reason="Windows NTFS does not enforce POSIX 0o600 file mode bits") def test_save_cloud_config_sets_restrictive_permissions(tmp_path): path = tmp_path / "cloud.toml" cloud.save_cloud_config(cloud.CloudConfig(api_key="sfc_ingest_abc123"), path) diff --git a/tests/test_memory.py b/tests/test_memory.py index 9ec377a..7c725f2 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -5,6 +5,7 @@ import json import stat +import sys import urllib.error from io import BytesIO @@ -45,7 +46,8 @@ def test_save_and_load_round_trip_with_private_permissions(tmp_path): path = tmp_path / "m.toml" memory.save_memory_config(memory.MemoryConfig(api_key='k"ey', url="https://x"), path) assert memory.load_memory_config(path) == memory.MemoryConfig(api_key='k"ey', url="https://x") - assert stat.S_IMODE(path.stat().st_mode) == 0o600 + if sys.platform != "win32": # Windows NTFS does not enforce POSIX 0o600 mode bits + assert stat.S_IMODE(path.stat().st_mode) == 0o600 def test_load_returns_none_without_a_file_and_rejects_a_keyless_one(tmp_path): @@ -122,7 +124,8 @@ def test_claude_command_includes_memory_server_and_writes_a_private_config( assert cmd[cmd.index("--mcp-config") + 1] == str(config_path) payload = json.loads(config_path.read_text()) assert payload["mcpServers"]["secfoo-memory"]["headers"] == {"Authorization": "Bearer sfm_free_test"} - assert stat.S_IMODE(config_path.stat().st_mode) == 0o600 + if sys.platform != "win32": # Windows NTFS does not enforce POSIX 0o600 mode bits + assert stat.S_IMODE(config_path.stat().st_mode) == 0o600 # ---------- prompt guidance ---------- diff --git a/tests/test_port_guard.py b/tests/test_port_guard.py index 0a74ec5..d64d32d 100644 --- a/tests/test_port_guard.py +++ b/tests/test_port_guard.py @@ -4,6 +4,7 @@ import socket import subprocess +import sys import pytest @@ -94,6 +95,7 @@ def _raise(*args, **kwargs): # ---------- stop_gracefully ---------- +@pytest.mark.skipif(sys.platform == "win32", reason="Tests POSIX SIGTERM signaling; Windows uses taskkill") def test_stop_gracefully_succeeds_after_sigterm(monkeypatch): killed = [] alive = {"value": True} @@ -110,6 +112,7 @@ def _fake_kill(pid, sig): assert killed == [port_guard.signal.SIGTERM] +@pytest.mark.skipif(sys.platform == "win32", reason="Tests POSIX SIGKILL fallback; Windows uses taskkill /F") def test_stop_gracefully_falls_back_to_sigkill_when_sigterm_is_ignored(monkeypatch): signals_sent = [] alive = {"value": True} @@ -127,8 +130,27 @@ def _fake_kill(pid, sig): assert signals_sent == [port_guard.signal.SIGTERM, port_guard.signal.SIGKILL] +def test_stop_gracefully_uses_taskkill_on_windows(monkeypatch): + calls: list[list[str]] = [] + alive = {"value": True} + + def _fake_run(args, *, timeout): + calls.append(args) + if "/F" in args: + alive["value"] = False + return subprocess.CompletedProcess(args, 0, "", "") + + monkeypatch.setattr(port_guard.sys, "platform", "win32") + monkeypatch.setattr(port_guard, "_run", _fake_run) + monkeypatch.setattr(port_guard, "_process_alive", lambda pid: alive["value"]) + + owner = PortOwner(pid=4242, command="secfoo serve") + assert stop_gracefully(owner, timeout=0.3) is True + assert calls == [["taskkill", "/PID", "4242"], ["taskkill", "/F", "/PID", "4242"]] + + def test_stop_gracefully_gives_up_if_the_process_never_dies(monkeypatch): - monkeypatch.setattr(port_guard.os, "kill", lambda pid, sig: None) + monkeypatch.setattr(port_guard, "_signal", lambda pid, *, force: None) monkeypatch.setattr(port_guard, "_process_alive", lambda pid: True) owner = PortOwner(pid=4242, command="secfoo serve") diff --git a/tests/test_skill_packs.py b/tests/test_skill_packs.py index e653e2f..8ac92a1 100644 --- a/tests/test_skill_packs.py +++ b/tests/test_skill_packs.py @@ -66,6 +66,7 @@ def test_default_pack_name_variants(): assert default_pack_name("https://github.com/acme/appsec-skills") == "acme-appsec-skills" assert default_pack_name("https://github.com/acme/appsec-skills.git") == "acme-appsec-skills" assert default_pack_name("git@github.com:acme/appsec-skills.git") == "acme-appsec-skills" + assert default_pack_name(r"C:\Users\alice\acme\appsec-skills") == "acme-appsec-skills" # ---------- install / update / remove / list ----------