Skip to content
Closed
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
24 changes: 15 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/secfoo/sensor/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
27 changes: 23 additions & 4 deletions src/secfoo/skills/packs.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import os
import re
import shutil
import stat
import subprocess
import sys
from dataclasses import dataclass
Expand Down Expand Up @@ -65,8 +66,8 @@
"""`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)
Expand All @@ -75,6 +76,24 @@
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")
Expand Down Expand Up @@ -159,7 +178,7 @@
_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
Expand Down Expand Up @@ -197,7 +216,7 @@
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)


Expand Down
2 changes: 2 additions & 0 deletions tests/test_cloud.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
import sys
import urllib.error

import pytest
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 5 additions & 2 deletions tests/test_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import json
import stat
import sys
import urllib.error
from io import BytesIO

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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 ----------
Expand Down
24 changes: 23 additions & 1 deletion tests/test_port_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import socket
import subprocess
import sys

import pytest

Expand Down Expand Up @@ -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}
Expand All @@ -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}
Expand All @@ -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")
Expand Down
1 change: 1 addition & 0 deletions tests/test_skill_packs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ----------
Expand Down
Loading