Skip to content
Open
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
25 changes: 25 additions & 0 deletions .github/workflows/action-selftest.yml
Original file line number Diff line number Diff line change
@@ -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"
120 changes: 113 additions & 7 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
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,
Expand Down Expand Up @@ -80,6 +83,15 @@
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"
Expand Down Expand Up @@ -120,6 +132,18 @@
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:
Expand Down Expand Up @@ -164,8 +188,26 @@
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")
Expand Down Expand Up @@ -232,7 +274,7 @@
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
Expand All @@ -254,9 +296,73 @@
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("<!-- secfoo -->")) | .id // empty' 2>/dev/null || true)

# Build comment body lines (best-effort; may be empty if gh failed above)
body_lines=("<!-- secfoo -->")

# 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)")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

false positive that is safe. and same comment is coming twice please check

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

false positive that is safe.


# 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
Binary file added assets/code-scanning-alerts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
51 changes: 51 additions & 0 deletions docs/CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!-- secfoo -->` 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 `<!-- secfoo -->` 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:
Expand Down
49 changes: 49 additions & 0 deletions src/secfoo/agents/fake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

from pathlib import Path

from secfoo.agents.base import AgentAdapter, AgentResult


class FakeAdapter(AgentAdapter):
name = "fake"
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
binary = "fake"
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

def is_available(self) -> bool:
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
# This adapter doesn't need an external executable.
return True

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
# FakeAdapter doesn't launch a subprocess.
raise NotImplementedError("FakeAdapter does not execute a command")

def run(
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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,
)
5 changes: 4 additions & 1 deletion src/secfoo/agents/registry.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ class AgentId(str, Enum):
DROID = "droid"
DEVIN = "devin"
OPENCODE = "opencode"
FAKE = "fake"


class DepthId(str, Enum):
Expand Down
26 changes: 26 additions & 0 deletions tests/fixtures/ci/fake-report.md
Original file line number Diff line number Diff line change
@@ -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
Loading