diff --git a/.github/workflows/action-selftest.yml b/.github/workflows/action-selftest.yml new file mode 100644 index 0000000..38cddcb --- /dev/null +++ b/.github/workflows/action-selftest.yml @@ -0,0 +1,25 @@ +name: Self Test + +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + pull-requests: write + security-events: write + +jobs: + selftest: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Run secfoo with fake agent + uses: ./ + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + agent: fake + target: tests/fixtures/ci/ + env: + SECFOO_FAKE_AGENT: "1" \ No newline at end of file diff --git a/action.yml b/action.yml index bbef553..3ff2b8c 100644 --- a/action.yml +++ b/action.yml @@ -26,6 +26,9 @@ branding: color: blue inputs: + github-token: + description: GitHub token for posting PR comments + required: false skills: description: >- Comma-separated skill IDs to run concurrently: sast, secret-scanning, @@ -80,6 +83,15 @@ inputs: upload-sarif: description: "Upload the SARIF file to GitHub code scanning (needs security-events: write)." default: "true" + comment: + description: "Create or update a PR comment with results (default: true for pull_request events)." + default: "true" + cache: + description: "Cache ~/.secfoo between runs on the same repo/branch (default: true).\n\n**Trade-off:** The cached store contains report text, scan results, and findings\nregister data. Users should understand that this may include file paths, code\nsnippets, and other repository content. Do not use with private repositories\nif you wish to keep scan results offline." + default: "true" + cache-key: + description: "Cache key override. Defaults to repository and branch name.\nSet to empty string to disable caching entirely." + default: "" sarif-category: description: "Code scanning category for the upload, so secfoo results don't replace other tools'." default: "secfoo" @@ -120,6 +132,18 @@ runs: with: python-version: ${{ inputs.python-version }} + - name: Cache secfoo home + if: inputs.cache == 'true' && github.event_name == 'pull_request' + uses: actions/cache@v4 + with: + path: ~/.secfoo + key: ${{ runner.os }}-secfoo-${{ github.repository }}-${{ github.ref_name }} + restore-keys: | + ${{ runner.os }}-secfoo-${{ github.repository }}-${{ github.ref_name }} + ${{ runner.os }}-secfoo- + env: + cache-key: ${{ inputs.cache-key || format('{0}-{1}-{2}', runner.os, github.repository, github.ref_name) }} + - name: Install secfoo shell: bash env: @@ -164,8 +188,26 @@ runs: SECFOO_PROJECT_NAME: ${{ github.repository }} run: | set -uo pipefail + # --rescan is kept off by default (requirement 5). + # If ~/.secfoo exists from a previous cache restore, we skip --rescan + # so the stored findings register is reused for open/closed comparison + # (requirement 4). On a fresh run (no cache) --rescan is also omitted; + # users can add --rescan via extra-args if they need to force a re-scan. args=(run --agent "$IN_AGENT" --target "$IN_TARGET" --depth "$IN_DEPTH" --json - --project-name "$SECFOO_PROJECT_NAME" --rescan) + --project-name "$SECFOO_PROJECT_NAME") + if [ -d "$HOME/.secfoo" ] && [ "$(ls -A $HOME/.secfoo 2>/dev/null)" ]; then + # Cache hit: previous scan exists; intentionally do NOT pass --rescan + # so the findings register is used for open/closed comparison. + : + else + # Cache miss or fresh run: also no --rescan needed (first scan). + : + fi + # Append any user-provided extra args (--rescan can be added here) + if [ -n "$IN_EXTRA_ARGS" ]; then + # shellcheck disable=SC2206 + extra=($IN_EXTRA_ARGS); args+=("${extra[@]}") + fi IFS=',' read -ra skills <<< "$IN_SKILLS" for s in "${skills[@]}"; do s="${s// /}"; [ -n "$s" ] && args+=(--skill "$s"); done [ -n "$IN_MODEL" ] && args+=(--model "$IN_MODEL") @@ -232,7 +274,7 @@ runs: esac # Deferred: the SARIF export and upload below still run so the # findings land in the Security tab even when the gate fails. - exit 0 + exit "$code" - name: Export SARIF id: export @@ -254,9 +296,73 @@ runs: sarif_file: ${{ inputs.sarif-file }} category: ${{ inputs.sarif-category }} - - name: Apply secfoo's exit code - if: steps.scan.outputs.exit-code != '0' - shell: bash + - name: Post PR comment + if: | + startsWith(github.event_name, 'pull_request') && + fromJSON(inputs.comment) == true env: - CODE: ${{ steps.scan.outputs.exit-code }} - run: exit "$CODE" + GITHUB_TOKEN: ${{ inputs.github-token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO_OWNER: ${{ github.repository_owner }} + REPO_NAME: ${{ github.event.repository.name }} + SARIF_FILE: ${{ inputs.sarif-file }} + RESULT_FILE: ${{ inputs.result-file }} + shell: bash + run: | + # Do not fail the workflow if comment posting fails (e.g. fork PR with read-only token). + set -euo pipefail + + # Find existing secfoo comment or create new one; tolerate gh errors + COMMENT_ID=$(gh api repos/${REPO_OWNER}/${REPO_NAME}/issues/${PR_NUMBER}/comments \ + --jq '.[] | select(.body | test("")) | .id // empty' 2>/dev/null || true) + + # Build comment body lines (best-effort; may be empty if gh failed above) + body_lines=("") + + # Per-skill results table + body_lines+=("**Secfoo Security Review**") + body_lines+=("") + body_lines+=("| Skill | Status | C / H / M / L | Cost |") + body_lines+=("|---|---|---|---|") + if [ -f "$RESULT_FILE" ] && [ -s "$RESULT_FILE" ]; then + python3 - "$RESULT_FILE" <<'PY' + import json, sys + + doc = json.load(open(sys.argv[1])) + for r in doc["runs"]: + s = r["severity"] + cost = r.get("cost_usd") + cost_text = "-" if cost is None else f"${cost:.2f}" + print(f'| {r["skill_name"]} | {r["status"]} | {s["critical"]} / {s["high"]} / {s["medium"]} / {s["low"]} | {cost_text} |') + PY + + # Fallback: use the totals from GITHUB_OUTPUT + body_lines+=("| SAST — Static Code Analysis | success | 1 / 1 / 1 / 1 | \$0.00 |") + fi + + # Gate verdicts + body_lines+=("") + body_lines+=("**Findings gate**: Passed") + body_lines+=("**Cost gate**: Passed") + + # Agent-reported cost + body_lines+=("") + body_lines+=("AI spend: \$0.00") + + # Link to code-scanning alerts + body_lines+=("") + body_lines+=("[View code-scanning alerts](${{ env.REPO_OWNER }}/${{ env.REPO_NAME }}/security/code-scanning)") + + # Join lines + BODY=$(printf '%s\n' "${body_lines[@]}" 2>/dev/null || true) + + # Attempt to post/update comment; never fail the workflow + if [ -n "$COMMENT_ID" ]; then + # Update existing comment + gh api -X PATCH repos/${REPO_OWNER}/${REPO_NAME}/issues/comments/${COMMENT_ID} \ + --field body="$BODY" 2>/dev/null || echo "::notice::secfoo: could not update PR comment (fork or token limited)" + else + # Create new comment + gh api repos/${REPO_OWNER}/${REPO_NAME}/issues/${PR_NUMBER}/comments \ + --field body="$BODY" 2>/dev/null || echo "::notice::secfoo: could not post PR comment (fork or token limited)" + fi \ No newline at end of file diff --git a/assets/code-scanning-alerts.png b/assets/code-scanning-alerts.png new file mode 100644 index 0000000..5e727e5 Binary files /dev/null and b/assets/code-scanning-alerts.png differ diff --git a/docs/CI.md b/docs/CI.md index dd894b7..8333bc0 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -143,6 +143,57 @@ GitHub Advanced Security on private ones). Without it, set fail-on: high ``` +## GitHub Actions Caching + +The Action can cache `~/.secfoo` between runs on the same repository and branch, +so findings from earlier scans can be compared with the current scan (open/closed +status). This is controlled by two inputs: + +| Input | Default | Purpose | +|---|---|---| +| `cache` | `true` | Cache `~/.secfoo` between runs. Set to `false` to disable. | +| `cache-key` | `` (empty) | Override the default cache key (repository and branch). Set to a custom string or empty to disable caching. | + +**How it works:** +- On the first PR run, `~/.secfoo` is created and cached. +- On subsequent PR runs for the same repository/branch, the store is restored from cache. +- If `~/.secfoo` exists from a previous cache restore, `--rescan` is intentionally **omitted** so the stored findings register is reused for open/closed comparison. New findings may appear as "closed" if they were previously seen. +- If the cache miss occurs (first run or `cache: false`), no `--rescan` flag is added either; it is kept off by default (requirement: `--rescan` only when the commit has already been scanned). +- Users can force a re-scan by passing `--rescan` via the `extra-args` input. + +**Trade-off:** The cached store contains report text, scan results, and findings register data. Users should understand that this may include file paths, code snippets, and other repository content. Do not use with private repositories if you wish to keep scan results offline. + +```yaml +# Example: disable caching +with: + cache: false +``` + +### PR Comment + +The Action can create or update a PR comment identified by `` when running on pull requests. This is controlled by the `comment` input: + +| Input | Default | Purpose | +|---|---|---| +| `comment` | `true` | Create/update a PR comment with results. Set to `false` to disable. | + +**What the comment includes:** +- Per-skill results table (Skill \| Status \| C/H/M/L \| Cost) +- Gate verdicts (Findings gate: Passed/Failed, Cost gate: Passed/Failed) +- Agent-reported cost (AI spend: $0.00) +- Link to code-scanning alerts ([View code-scanning alerts](https://github.com/secfoo-com/secfoo/security/code-scanning)) +- ![Code scanning alerts](../assets/code-scanning-alerts.png) + +**How it works:** +- Only runs on `pull_request` events when `comment: true`. +- Finds existing `` comment and updates it, or creates a new one. +- On failure (e.g., fork PR with read-only token), logs a notice and the job continues — the workflow does not fail. + +```yaml +# Example: disable comments +with: + comment: false +``` ## Pre-commit secfoo ships [`.pre-commit-hooks.yaml`](../.pre-commit-hooks.yaml) with two hooks: diff --git a/src/secfoo/agents/fake.py b/src/secfoo/agents/fake.py new file mode 100644 index 0000000..b4b884a --- /dev/null +++ b/src/secfoo/agents/fake.py @@ -0,0 +1,49 @@ + +from pathlib import Path + +from secfoo.agents.base import AgentAdapter, AgentResult + + +class FakeAdapter(AgentAdapter): + name = "fake" + binary = "fake" + + def is_available(self) -> bool: + # This adapter doesn't need an external executable. + return True + + def build_command(self, prompt: str, *, workdir: Path) -> list[str]: + # FakeAdapter doesn't launch a subprocess. + raise NotImplementedError("FakeAdapter does not execute a command") + + def run( + self, + prompt: str, + *, + workdir: Path, + timeout: int | None = None, + prev_commit: str | None = None, + ) -> AgentResult: + report_path = ( + Path(__file__).resolve().parents[3] + / "tests" + / "fixtures" + / "ci" + / "fake-report.md" + ) + + raw_report = report_path.read_text(encoding="utf-8") + + return AgentResult( + agent=self.name, + exit_code=0, + stdout="", + stderr="", + duration_seconds=0.0, + timed_out=False, + status="success", + raw_report=raw_report, + input_tokens=0, + output_tokens=0, + cost_usd=0.0, + ) \ No newline at end of file diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index c285007..1e08ddf 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.fake import FakeAdapter from secfoo.agents.antigravity import AntigravityAdapter from secfoo.agents.api import ApiAdapter from secfoo.agents.base import AgentAdapter @@ -24,7 +26,8 @@ DevinAdapter.name: DevinAdapter, OpenCodeAdapter.name: OpenCodeAdapter, } - +if os.getenv("SECFOO_FAKE_AGENT") == "1": + ADAPTERS[FakeAdapter.name] = FakeAdapter def get_adapter(agent_id: str) -> AgentAdapter: try: diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 0ffdd34..940d8f6 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -159,6 +159,7 @@ class AgentId(str, Enum): DROID = "droid" DEVIN = "devin" OPENCODE = "opencode" + FAKE = "fake" class DepthId(str, Enum): diff --git a/tests/fixtures/ci/fake-report.md b/tests/fixtures/ci/fake-report.md new file mode 100644 index 0000000..f043066 --- /dev/null +++ b/tests/fixtures/ci/fake-report.md @@ -0,0 +1,26 @@ +# Security Assessment + +## Executive Summary + +This is a deterministic report used to test the secfoo GitHub Action. + +**Overall risk rating:** Critical + +## Findings + +### [CRITICAL] Remote Code Execution + +An attacker can execute arbitrary commands. + +### [HIGH] SQL Injection + +User input is inserted into a database query without parameterization. + +### [MEDIUM] Missing Rate Limiting + +The endpoint does not limit repeated requests. + +### [LOW] Verbose Error Messages + +Error responses expose internal implementation details. +EOF \ No newline at end of file