diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd2df7e..dbd535c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,12 +56,9 @@ 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 + # Blocking (#114). ruff is pinned in pyproject.toml's dev extra so a + # new ruff release can't turn an unrelated PR red; bump it on purpose. + run: ruff check . - name: Test (secfoo core) # Coverage is collected here and gated in its own last step, so a @@ -102,6 +99,42 @@ jobs: if: ${{ !cancelled() }} run: coverage report --fail-under=90 + security: + name: Security (bandit, pip-audit) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install package + dev deps + # pip itself is part of the audited environment, so start from the + # latest one rather than whatever the runner image ships. + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + + - name: SAST (bandit, medium and above) + # Blocking (#114). Low findings are reported locally but don't fail + # the build; a reviewed false positive gets `# nosec BXXX -- reason` + # on the flagged line. + run: bandit -r src/secfoo -c .bandit -ll + + - name: Dependency audit (pip-audit) + # Blocking (#114): audits the installed environment, i.e. what + # `pip install -e ".[dev]"` actually resolved today. secfoo itself is + # skipped (editable, may be ahead of the latest release). + # + # Accepted advisories: add one `--ignore-vuln ` per line below, + # each with a comment giving the date it was accepted and why, e.g. + # --ignore-vuln GHSA-xxxx-xxxx-xxxx # 2026-01-31: dev-only, no fix yet + # None are accepted today. + run: pip-audit --skip-editable + docs: name: Docs (links, version) runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2deb789..0eb26d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,6 +24,25 @@ ruff check . CI runs both on every push and PR, on Python 3.10 and 3.12. +### Pre-PR checklist + +CI also runs these and fails the build on any finding, so run them +before opening a PR: + +```sh +ruff check . # lint (ruff is pinned in the dev extra) +bandit -r src/secfoo -c .bandit -ll # SAST, medium severity and above +pip-audit --skip-editable # known vulnerabilities in installed deps +``` + +- **ruff**: fix the finding; if it's intentional, add it to + `[tool.ruff.lint.per-file-ignores]` in `pyproject.toml` with a reason. +- **bandit**: fix real findings. For a reviewed false positive, put + `# nosec BXXX -- ` on the flagged line. +- **pip-audit**: upgrade the dependency. If an advisory has to be + accepted, add `--ignore-vuln ` to the `pip-audit` step in + `.github/workflows/ci.yml` with the date and the reason. + ### Fuzzing Everything that parses untrusted input has a coverage-guided fuzz harness diff --git a/pyproject.toml b/pyproject.toml index 6da24ef..51bd898 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,7 +67,7 @@ dependencies = [ ] [project.optional-dependencies] -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.6", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.24"] +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.6", "bandit>=1.9.4", "pip-audit>=2.10.1", "langgraph>=1.2.24"] build = ["pyinstaller>=6.22.3"] # The `api` agent (secfoo/agents/api.py) needs litellm and langgraph, which are regular # dependencies above, so there is no separate `api` extra to install. diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 25cfbef..21c4d85 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -1845,7 +1845,7 @@ def memory_status() -> None: class FindingsSkill(str, Enum): SAST = "sast" SCA = "sca-reachability" - SECRET = "secret-scanning" + SECRET = "secret-scanning" # nosec B105 -- a skill id, not a password class FindingsStatus(str, Enum): diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index 403103f..be02fd7 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -131,7 +131,7 @@ def _request(url: str, *, api_key: str, payload: dict | None = None) -> dict: if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" - request = urllib.request.Request(url, data=data, headers=headers) + request = urllib.request.Request(url, data=data, headers=headers) # nosec B310 -- user-configured portal URL try: with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- user-configured portal URL, same trust as MCP settings return json.loads(response.read().decode("utf-8")) diff --git a/src/secfoo/memory.py b/src/secfoo/memory.py index 63e1d02..0c2ef73 100644 --- a/src/secfoo/memory.py +++ b/src/secfoo/memory.py @@ -173,7 +173,7 @@ def _request(url: str, *, payload: dict | None = None, api_key: str | None = Non if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" - request = urllib.request.Request(url, data=data, headers=headers) + request = urllib.request.Request(url, data=data, headers=headers) # nosec B310 -- user-configured memory URL try: with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- user-configured memory URL, same trust as MCP settings return json.loads(response.read().decode("utf-8") or "{}") diff --git a/src/secfoo/osv.py b/src/secfoo/osv.py index ca22026..f802a5c 100644 --- a/src/secfoo/osv.py +++ b/src/secfoo/osv.py @@ -73,7 +73,7 @@ def query_osv(ecosystem: str, package: str, version: str) -> list[dict]: """ payload = {"package": {"name": package, "ecosystem": ecosystem}, "version": version} body = json.dumps(payload).encode("utf-8") - request = urllib.request.Request( + request = urllib.request.Request( # nosec B310 -- hardcoded public OSV.dev API URL OSV_API_URL, data=body, headers={"Content-Type": "application/json"}, method="POST" ) try: diff --git a/src/secfoo/report/evidence.py b/src/secfoo/report/evidence.py index ac14b16..b8890a3 100644 --- a/src/secfoo/report/evidence.py +++ b/src/secfoo/report/evidence.py @@ -11,7 +11,7 @@ # macOS hands out per-user temp roots as /var/folders///T and # tempfile.gettempdir() may return either that or the /private/var form. _HOST_PATHS = ( - (re.compile(r'(?:/private)?/var/folders/[^/\s"\\]+/[^/\s"\\]+/T(?=/|\b|$)'), '/tmp/evaluator'), + (re.compile(r'(?:/private)?/var/folders/[^/\s"\\]+/[^/\s"\\]+/T(?=/|\b|$)'), '/tmp/evaluator'), # nosec B108 -- replacement text, never a file path (re.compile(r'(?i)\b([A-Z]):(\\\\|\\|/)Users\2(?!evaluator\b)[^\\/\s"]+'), r'\1:\2Users\2evaluator'), (re.compile(r'/Users/(?!evaluator\b)[^/\s"\\]+'), '/home/evaluator'), (re.compile(r'/home/(?!evaluator\b)[^/\s"\\]+'), '/home/evaluator'), diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 907c818..b83a233 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -429,7 +429,9 @@ def _target_workdir(resolved: ResolvedTarget) -> Iterator[Path]: with clone_forge(resolved.display_name, kind=resolved.kind) as tmp_dir: yield tmp_dir else: - assert resolved.path is not None + # A real check, not an assert: asserts are stripped under `python -O`. + if resolved.path is None: + raise ValueError(f"local target {resolved.display_name!r} has no path") yield resolved.path diff --git a/src/secfoo/sensor/probe.py b/src/secfoo/sensor/probe.py index 496c2a6..8351b1e 100644 --- a/src/secfoo/sensor/probe.py +++ b/src/secfoo/sensor/probe.py @@ -160,7 +160,7 @@ def stop(self) -> None: _release_profiler() if was_active or self._broken: self.transport.close() - except Exception: # noqa: BLE001, S110 -- shutting down; never raise into the app + except Exception: # noqa: BLE001, S110 # nosec B110 -- shutting down; never raise into (or log through) the app pass finally: if locked: @@ -193,7 +193,7 @@ def _disable(self, exc: BaseException) -> 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 + except Exception: # noqa: BLE001, S110 # nosec B110 -- never raise into (or log through) the app pass # ---------- watchlist ---------- diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index f183ce0..f7f5e88 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -299,7 +299,7 @@ def needs_rebuild() -> str | None: new_sql, count=1, flags=re.IGNORECASE) columns = ", ".join(f'"{row["name"]}"' for row in self._conn.execute("PRAGMA table_info(runs)")) self._conn.execute(new_sql) - self._conn.execute(f"INSERT INTO runs_new ({columns}) SELECT {columns} FROM runs") + self._conn.execute(f"INSERT INTO runs_new ({columns}) SELECT {columns} FROM runs") # nosec B608 -- column names from PRAGMA table_info(runs), not user input self._conn.execute("DROP TABLE runs") # Every row keeps its id, so references from other tables stay valid. self._conn.execute("ALTER TABLE runs_new RENAME TO runs") @@ -725,7 +725,7 @@ def cost_summary(self, *, group_by: str, project_id: int | None = None, since: s "project": "projects.display_name", }[group_by] query = ( - f"SELECT {group_sql} AS label, COUNT(*) AS runs, " + f"SELECT {group_sql} AS label, COUNT(*) AS runs, " # nosec B608 -- group_sql comes from the fixed dict above # No COALESCE here: SQLite's SUM() already returns NULL (not 0) # when every value in the group is NULL, and that distinction is # exactly "unknown" vs "zero" -- collapsing it to 0 is SECFOO-34. diff --git a/src/secfoo/web/security.py b/src/secfoo/web/security.py index d0583ec..38941b1 100644 --- a/src/secfoo/web/security.py +++ b/src/secfoo/web/security.py @@ -30,7 +30,7 @@ from starlette.responses import PlainTextResponse LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} -WILDCARD_BINDS = {"", "0.0.0.0", "::"} +WILDCARD_BINDS = {"", "0.0.0.0", "::"} # nosec B104 -- the set used to detect (and guard) wildcard binds, not a bind SAFE_METHODS = {"GET", "HEAD", "OPTIONS"} MACHINE_API_PREFIX = "/api/runtime/" UPLOAD_PATH_RE = re.compile(r"/assessments/[^/]+/attachments/?") diff --git a/tests/test_runner_target_workdir.py b/tests/test_runner_target_workdir.py new file mode 100644 index 0000000..fdda861 --- /dev/null +++ b/tests/test_runner_target_workdir.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from secfoo.runner import _target_workdir +from secfoo.targets.resolver import ResolvedTarget, TargetKind + + +def test_local_target_yields_its_path(tmp_path: Path) -> None: + target = ResolvedTarget(kind=TargetKind.LOCAL, path=tmp_path, display_name=str(tmp_path), is_temporary=False) + with _target_workdir(target) as workdir: + assert workdir == tmp_path + + +def test_local_target_without_path_raises_even_under_optimize() -> None: + # Was an `assert`, which `python -O` strips (bandit B101, #114). + target = ResolvedTarget(kind=TargetKind.LOCAL, path=None, display_name="somewhere", is_temporary=False) + with pytest.raises(ValueError, match="has no path"), _target_workdir(target): + pass