diff --git a/.github/workflows/action-selftest.yml b/.github/workflows/action-selftest.yml new file mode 100644 index 00000000..2e6ee634 --- /dev/null +++ b/.github/workflows/action-selftest.yml @@ -0,0 +1,140 @@ +name: Action Self-Test + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + exit-0-clean: + name: Action self-test (exit 0 clean) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - id: secfoo + uses: ./ + env: + SECFOO_FAKE_AGENT: "1" + SECFOO_FAKE_REPORT_FILE: tests/fixtures/ci/canned_report_clean.md + SECFOO_FAKE_COST_USD: "0.02" + with: + skills: sast + target: examples/sample-output/nodegoat + agent: fake + version: local + fail-on: high + max-cost: "0.50" + upload-sarif: "false" + comment: "false" + cache: "false" + - name: Assert outputs and SARIF 2.1.0 + run: | + python - <<'PY' + import json, os + assert os.environ["OUT_EXIT"] == "0" + assert os.environ["OUT_HIGH"] == "0" + assert os.environ["OUT_COST"] == "0.02" + sarif = json.load(open("secfoo.sarif", encoding="utf-8")) + assert sarif["version"] == "2.1.0" + assert "runs" in sarif + PY + env: + OUT_EXIT: ${{ steps.secfoo.outputs.exit-code }} + OUT_HIGH: ${{ steps.secfoo.outputs.high }} + OUT_COST: ${{ steps.secfoo.outputs.cost-usd }} + + exit-1-failed: + name: Action self-test (exit 1 run failure) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - id: secfoo + continue-on-error: true + uses: ./ + env: + SECFOO_FAKE_AGENT: "1" + SECFOO_FAKE_STATUS: failed + with: + skills: sast + target: examples/sample-output/nodegoat + agent: fake + version: local + upload-sarif: "false" + comment: "false" + cache: "false" + - name: Assert exit code 1 outcome and failed status + run: | + python - <<'PY' + import json, os + assert os.environ["OUTCOME"] == "failure" + doc = json.load(open("secfoo-result.json", encoding="utf-8")) + assert doc["runs"][0]["status"] == "failed" + PY + env: + OUTCOME: ${{ steps.secfoo.outcome }} + + exit-2-findings: + name: Action self-test (exit 2 findings gate) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - id: secfoo + continue-on-error: true + uses: ./ + env: + SECFOO_FAKE_AGENT: "1" + SECFOO_FAKE_REPORT_FILE: tests/fixtures/ci/canned_report_high.md + with: + skills: sast + target: examples/sample-output/nodegoat + agent: fake + version: local + fail-on: high + upload-sarif: "false" + comment: "false" + cache: "false" + - name: Assert exit code 2 outcome, findings gate, and high=1 + run: | + python - <<'PY' + import json, os + assert os.environ["OUTCOME"] == "failure" + doc = json.load(open("secfoo-result.json", encoding="utf-8")) + assert doc["runs"][0]["severity"]["high"] == 1 + assert doc["gates"]["findings"]["passed"] is False + PY + env: + OUTCOME: ${{ steps.secfoo.outcome }} + + exit-3-cost: + name: Action self-test (exit 3 cost gate) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - id: secfoo + continue-on-error: true + uses: ./ + env: + SECFOO_FAKE_AGENT: "1" + SECFOO_FAKE_REPORT_FILE: tests/fixtures/ci/canned_report_clean.md + SECFOO_FAKE_COST_USD: "1.25" + with: + skills: sast + target: examples/sample-output/nodegoat + agent: fake + version: local + max-cost: "0.50" + upload-sarif: "false" + comment: "false" + cache: "false" + - name: Assert exit code 3 outcome and cost gate + run: | + python - <<'PY' + import json, os + assert os.environ["OUTCOME"] == "failure" + doc = json.load(open("secfoo-result.json", encoding="utf-8")) + assert doc["gates"]["cost"]["passed"] is False + PY + env: + OUTCOME: ${{ steps.secfoo.outcome }} diff --git a/action.yml b/action.yml index 09c2314e..149d664a 100644 --- a/action.yml +++ b/action.yml @@ -97,6 +97,15 @@ inputs: Path to a JSON baseline file (e.g. .secfoo/baseline.json). Active entries are excluded from --fail-on and tagged baselineState: unchanged in SARIF. default: "" + comment: + description: >- + Post or update a single sticky PR comment () on + pull_request events (requires pull-requests: write). Never fails the job + if posting is not permitted (e.g. fork PRs). + default: "true" + cache: + description: "Restore and save ~/.secfoo between CI runs with actions/cache." + default: "true" outputs: exit-code: @@ -131,6 +140,15 @@ runs: with: python-version: ${{ inputs.python-version }} + - name: Restore secfoo store cache + if: inputs.cache == 'true' + uses: actions/cache@v4 + with: + path: ~/.secfoo + key: ${{ runner.os }}-secfoo-${{ github.repository }}-${{ github.ref_name }} + restore-keys: | + ${{ runner.os }}-secfoo-${{ github.repository }}- + - name: Install secfoo shell: bash env: @@ -138,7 +156,11 @@ runs: run: | set -euo pipefail python -m pip install --quiet --upgrade pip - python -m pip install --quiet "secfoo${SECFOO_VERSION:+==${SECFOO_VERSION}}" + if [ "$SECFOO_VERSION" = "local" ]; then + python -m pip install --quiet -e . + else + python -m pip install --quiet "secfoo${SECFOO_VERSION:+==${SECFOO_VERSION}}" + fi secfoo --help >/dev/null - name: Install agent CLI @@ -275,6 +297,92 @@ runs: sarif_file: ${{ inputs.sarif-file }} category: ${{ inputs.sarif-category }} + - name: Post sticky PR comment + if: inputs.comment == 'true' && github.event_name == 'pull_request' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + IN_RESULT_FILE: ${{ inputs.result-file }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + run: | + set +e + python - "$IN_RESULT_FILE" <<'PY' + import json, os, sys, urllib.error, urllib.request + + marker = "" + token = os.environ.get("GH_TOKEN", "") + pr_number = os.environ.get("PR_NUMBER", "") + repo = os.environ.get("REPO", "") + if not (token and pr_number and repo): + print("::notice::Skipping secfoo PR comment (missing token or PR context).") + sys.exit(0) + + try: + doc = json.load(open(sys.argv[1], encoding="utf-8")) + except Exception: + doc = {"runs": [], "gates": {}, "total_cost_usd": None} + + lines = [ + marker, + "## secfoo security review", + "", + "| Skill | Status | C / H / M / L | Cost |", + "|---|---|---|---|", + ] + for r in doc.get("runs", []): + s = r.get("severity", {}) + cost = r.get("cost_usd") + cost_str = "-" if cost is None else f"${cost:.2f}" + lines.append( + f"| {r.get('skill_name', r.get('skill_id', ''))} | {r.get('status', '')} | " + f"{s.get('critical', 0)} / {s.get('high', 0)} / {s.get('medium', 0)} / {s.get('low', 0)} | {cost_str} |" + ) + gates = doc.get("gates") or {} + for key, label in (("findings", "Findings gate"), ("cost", "Cost gate")): + g = gates.get(key) + if isinstance(g, dict): + lines.append(f"\n**{label}:** {'passed' if g.get('passed') else 'FAILED'}") + total_cost = doc.get("total_cost_usd") + if total_cost is not None: + lines.append(f"\n**Total agent cost:** ${total_cost:.2f}") + server = os.environ.get("SERVER_URL", "https://github.com").rstrip("/") + lines.append(f"\n[View code-scanning alerts]({server}/{repo}/security/code-scanning)") + body = "\n".join(lines) + + api = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/") + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "User-Agent": "secfoo-action", + } + try: + req = urllib.request.Request(f"{api}/repos/{repo}/issues/{pr_number}/comments?per_page=100", headers=headers) + with urllib.request.urlopen(req, timeout=15) as resp: + comments = json.loads(resp.read().decode("utf-8")) + existing_id = next((c["id"] for c in comments if marker in (c.get("body") or "")), None) + payload = json.dumps({"body": body}).encode("utf-8") + if existing_id: + req2 = urllib.request.Request( + f"{api}/repos/{repo}/issues/comments/{existing_id}", + data=payload, + headers={**headers, "Content-Type": "application/json"}, + method="PATCH", + ) + else: + req2 = urllib.request.Request( + f"{api}/repos/{repo}/issues/{pr_number}/comments", + data=payload, + headers={**headers, "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req2, timeout=15): + pass + except Exception as exc: + print(f"::notice::Could not post secfoo PR comment (non-fatal): {exc}") + PY + - name: Apply secfoo's exit code if: steps.scan.outputs.exit-code != '0' shell: bash diff --git a/src/secfoo/agents/fake.py b/src/secfoo/agents/fake.py new file mode 100644 index 00000000..0edb5d18 --- /dev/null +++ b/src/secfoo/agents/fake.py @@ -0,0 +1,68 @@ +"""Deterministic fake agent adapter for CI self-tests (#108). + +Hidden from `secfoo agents` and rejected by `get_adapter()` unless +`SECFOO_FAKE_AGENT=1` is set in the environment. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from secfoo.agents.base import AgentAdapter, AgentResult + +_DEFAULT_CLEAN_REPORT = ( + "# SAST Report\n\n" + "## 1. Executive Summary\n\n" + "No issues detected in the target.\n\n" + "## 3. Findings Register\n\n" + "| ID | Finding | Severity | CWE | Location |\n" + "|---|---|---|---|---|\n" +) + + +class FakeAdapter(AgentAdapter): + """Canned-report adapter enabled only when `SECFOO_FAKE_AGENT=1`.""" + + name = "fake" + binary = "fake" + default_timeout_seconds = 60 + + def is_available(self) -> bool: + return os.environ.get("SECFOO_FAKE_AGENT") == "1" + + def build_command(self, prompt: str, *, workdir: Path) -> list[str]: + return [self.binary] + + def run( + self, + prompt: str, + *, + workdir: Path, + timeout: int | None = None, + prev_commit: str | None = None, + ) -> AgentResult: + status = os.environ.get("SECFOO_FAKE_STATUS", "success").strip() or "success" + raw_cost = os.environ.get("SECFOO_FAKE_COST_USD", "").strip() + cost_usd = float(raw_cost) if raw_cost else None + + report = "" + report_file = os.environ.get("SECFOO_FAKE_REPORT_FILE", "").strip() + if report_file: + report = Path(report_file).read_text(encoding="utf-8") + elif os.environ.get("SECFOO_FAKE_REPORT"): + report = os.environ["SECFOO_FAKE_REPORT"] + elif status == "success": + report = _DEFAULT_CLEAN_REPORT + + return AgentResult( + agent=self.name, + exit_code=0 if status == "success" else 1, + stdout=report, + stderr="" if status == "success" else f"fake failure ({status})", + duration_seconds=0.01, + timed_out=(status == "timeout"), + status=status, + raw_report=report, + cost_usd=cost_usd, + ) diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index c285007c..b99ca4c8 100644 --- a/src/secfoo/agents/registry.py +++ b/src/secfoo/agents/registry.py @@ -1,5 +1,7 @@ from __future__ import annotations +import os + from secfoo.agents.antigravity import AntigravityAdapter from secfoo.agents.api import ApiAdapter from secfoo.agents.base import AgentAdapter @@ -9,6 +11,7 @@ from secfoo.agents.cursor import CursorAdapter from secfoo.agents.devin import DevinAdapter from secfoo.agents.droid import DroidAdapter +from secfoo.agents.fake import FakeAdapter from secfoo.agents.gemini import GeminiAdapter from secfoo.agents.opencode import OpenCodeAdapter @@ -27,6 +30,8 @@ def get_adapter(agent_id: str) -> AgentAdapter: + if agent_id == FakeAdapter.name and os.environ.get("SECFOO_FAKE_AGENT") == "1": + return FakeAdapter() try: return ADAPTERS[agent_id]() except KeyError: diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 11aa9ed0..c8ef551a 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -348,7 +348,7 @@ def run( "SharePoint, Notion, Google Docs) or a local Markdown, text, PDF, DOCX or PPTX file or " "folder. Repeatable, and added on top of [defaults].context in ~/.secfoo/config.toml.", )] = None, - agent: AgentId | None = typer.Option( + agent: str | None = typer.Option( None, "--agent", "-a", @@ -549,37 +549,47 @@ def run( if agent is None: if file_defaults.agent: - agent = AgentId(file_defaults.agent) + agent_id = AgentId(file_defaults.agent).value else: # First run, no config: use whatever the user already has instead # of insisting on claude -- an installed agent CLI, or the `api` # agent when a provider key is already in the environment. - agent = _detect_agent() - how = "an API key is set" if agent is AgentId.API else "found on PATH" + detected = _detect_agent() + how = "an API key is set" if detected is AgentId.API else "found on PATH" (err_console if json_output else console).print( - f"Using agent [bold]{agent.value}[/] ({how}); pass --agent or set " + f"Using agent [bold]{detected.value}[/] ({how}); pass --agent or set " "[defaults].agent in ~/.secfoo/config.toml to choose another." ) + agent_id = detected.value + elif agent == "fake" and os.environ.get("SECFOO_FAKE_AGENT") == "1": + agent_id = "fake" + else: + try: + agent_id = AgentId(agent).value + except ValueError: + valid = ", ".join(a.value for a in AgentId) + err_console.print(f"[red]Error:[/] Invalid value for '--agent' / '-a': {agent!r} is not one of {valid}.") + raise typer.Exit(code=2) from None if model is not None and not model.strip(): err_console.print("[red]Error:[/] --model must be a non-empty string") raise typer.Exit(code=1) - adapter_instance = get_adapter(agent.value) + adapter_instance = get_adapter(agent_id) resolved_models: dict[str, str | None] = {} cached_available_models = None for s_id in skill_ids: chosen_model, model_source = resolve_model( - file_config, agent_id=agent.value, skill_id=s_id, cli_model=model + file_config, agent_id=agent_id, skill_id=s_id, cli_model=model ) if chosen_model is not None: if not adapter_instance.accepts_model(): if model_source in {"cli", "agent", "agent_skill"}: err_console.print( - f"[red]Error:[/] Agent {agent.value!r} does not support model selection." + f"[red]Error:[/] Agent {agent_id!r} does not support model selection." ) raise typer.Exit(code=1) (err_console if json_output else console).print( - f"[yellow]Warning:[/] Agent {agent.value!r} does not support model selection; " + f"[yellow]Warning:[/] Agent {agent_id!r} does not support model selection; " f"ignoring skill default {chosen_model!r}." ) chosen_model = None @@ -587,7 +597,7 @@ def run( if cached_available_models is None: cached_available_models = discover_models(adapter_instance) validation = validate_model_selection( - agent.value, + agent_id, chosen_model, models=cached_available_models, supports_model=adapter_instance.accepts_model(), @@ -602,7 +612,7 @@ def run( unique_models = set(resolved_models.values()) uniform_model = next(iter(unique_models)) if len(unique_models) == 1 else model if max_input_tokens is None: - max_input_tokens = file_config.agent_max_input_tokens.get(agent.value) + max_input_tokens = file_config.agent_max_input_tokens.get(agent_id) if depth is None: depth = DepthId(file_defaults.depth) if file_defaults.depth else DepthId.QUICK if timeout is None: @@ -665,9 +675,9 @@ def run( def handle_start(skill_name: str) -> None: if live_progress: - task_ids[skill_name] = progress.add_task(f"Running [bold]{skill_name}[/] via {agent.value}...", total=None) + task_ids[skill_name] = progress.add_task(f"Running [bold]{skill_name}[/] via {agent_id}...", total=None) elif not json_output: - console.print(f"Running {skill_name} via {agent.value}...") + console.print(f"Running {skill_name} via {agent_id}...") def handle_complete(skill_name: str, result_status: str) -> None: if not live_progress: @@ -693,7 +703,7 @@ def handle_complete(skill_name: str, result_status: str) -> None: "confluence_urls": run_context.confluence_urls, "context_sources": run_context.sources, "mcp_servers": file_config.mcp_servers, - "agent_id": agent.value, + "agent_id": agent_id, "model": uniform_model, "max_input_tokens": max_input_tokens, "depth": depth.value, @@ -774,7 +784,7 @@ def handle_complete(skill_name: str, result_status: str) -> None: if json_output: document = { - "agent": agent.value, + "agent": agent_id, "depth": depth.value, "runs": [ { diff --git a/tests/fixtures/ci/canned_report_clean.md b/tests/fixtures/ci/canned_report_clean.md new file mode 100644 index 00000000..2e0e8cac --- /dev/null +++ b/tests/fixtures/ci/canned_report_clean.md @@ -0,0 +1,10 @@ +# SAST Report + +## 1. Executive Summary + +No vulnerabilities detected in the fixture target. + +## 3. Findings Register + +| ID | Finding | Severity | CWE | Location | +|---|---|---|---|---| diff --git a/tests/fixtures/ci/canned_report_high.md b/tests/fixtures/ci/canned_report_high.md new file mode 100644 index 00000000..9b3c5114 --- /dev/null +++ b/tests/fixtures/ci/canned_report_high.md @@ -0,0 +1,20 @@ +# SAST Report + +## 1. Executive Summary + +One high-severity SQL injection finding detected in the fixture target. + +## 3. Findings Register + +| ID | Finding | Severity | CWE | Location | +|---|---|---|---|---| +| F1 | Unparameterized SQL query | High | CWE-89 | `app.py:12` | + +## 4. Findings + +### [High] F1: Unparameterized SQL query +- **Severity:** High +- **CWE:** CWE-89 +- **Location:** `app.py:12` +- **Description:** User input is concatenated into a SQL query string. +- **Recommendation:** Use parameterized queries. diff --git a/tests/test_action_selftest.py b/tests/test_action_selftest.py new file mode 100644 index 00000000..a3a15912 --- /dev/null +++ b/tests/test_action_selftest.py @@ -0,0 +1,97 @@ +"""Tests for #108: hidden `fake` agent adapter, `action.yml`, and self-test workflow.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +import yaml +from typer.testing import CliRunner + +from secfoo.agents.registry import ADAPTERS, get_adapter +from secfoo.cli import app + +ROOT = Path(__file__).resolve().parents[1] +FIXTURES = ROOT / "tests" / "fixtures" / "ci" +runner = CliRunner() + + +def test_fake_agent_hidden_unless_env_flag_set(monkeypatch): + assert "fake" not in ADAPTERS + monkeypatch.delenv("SECFOO_FAKE_AGENT", raising=False) + with pytest.raises(ValueError, match="unknown agent id"): + get_adapter("fake") + + monkeypatch.setenv("SECFOO_FAKE_AGENT", "1") + adapter = get_adapter("fake") + assert adapter.name == "fake" + assert adapter.is_available() is True + + +@pytest.mark.parametrize( + ("report_name", "status", "cost_usd", "extra_flags", "expected_code"), + [ + ("canned_report_clean.md", "success", "0.02", ["--fail-on", "high", "--max-cost", "0.50"], 0), + ("canned_report_clean.md", "failed", "", [], 1), + ("canned_report_high.md", "success", "0.02", ["--fail-on", "high"], 2), + ("canned_report_clean.md", "success", "1.25", ["--max-cost", "0.50"], 3), + ], +) +def test_cli_fake_agent_exit_codes_0_1_2_3( + tmp_path: Path, + monkeypatch, + report_name: str, + status: str, + cost_usd: str, + extra_flags: list[str], + expected_code: int, +): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.runner.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.runner.run_dir", lambda run_uuid: tmp_path / "reports" / run_uuid) + monkeypatch.setattr("secfoo.runner._try_cloud_sync", lambda repo, run_uuid: None) + + target = tmp_path / "repo" + target.mkdir() + (target / "app.py").write_text("print('hi')\n", encoding="utf-8") + + monkeypatch.setenv("SECFOO_FAKE_AGENT", "1") + monkeypatch.setenv("SECFOO_FAKE_REPORT_FILE", str(FIXTURES / report_name)) + monkeypatch.setenv("SECFOO_FAKE_STATUS", status) + if cost_usd: + monkeypatch.setenv("SECFOO_FAKE_COST_USD", cost_usd) + else: + monkeypatch.delenv("SECFOO_FAKE_COST_USD", raising=False) + + res = runner.invoke( + app, + [ + "run", + "--agent", + "fake", + "--skill", + "sast", + "--target", + str(target), + "--json", + "--rescan", + *extra_flags, + ], + ) + assert res.exit_code == expected_code, res.output + doc = json.loads(res.stdout) + assert doc["agent"] == "fake" + + +def test_action_yml_and_selftest_workflow_structure(): + action = yaml.safe_load((ROOT / "action.yml").read_text(encoding="utf-8")) + assert "comment" in action["inputs"] + assert "cache" in action["inputs"] + raw_action = (ROOT / "action.yml").read_text(encoding="utf-8") + assert "" in raw_action + assert "actions/cache@v4" in raw_action + + wf = yaml.safe_load((ROOT / ".github" / "workflows" / "action-selftest.yml").read_text(encoding="utf-8")) + assert set(wf["jobs"].keys()) == {"exit-0-clean", "exit-1-failed", "exit-2-findings", "exit-3-cost"}