diff --git a/action.yml b/action.yml index bbef553..2a759bc 100644 --- a/action.yml +++ b/action.yml @@ -62,6 +62,20 @@ inputs: extra-args: description: "Extra arguments appended verbatim to `secfoo run`." default: "" + changed-only: + description: >- + On pull_request events, review only the paths changed since the PR base + (using git merge-base). Passes github.event.pull_request.base.sha + automatically; other events stay full scans. Requires a checkout with + fetch-depth: 0. Pair with extra-args: "--fail-scope changed" to gate on + changed findings only. + default: "false" + baseline: + description: >- + Path to a findings baseline JSON (e.g. .secfoo/baseline.json). Matching + open findings are excluded from --fail-on but still exported; expired + entries count again. The file must be present in the checkout. + default: "" version: description: "secfoo version to install from PyPI. Empty = latest." default: "" @@ -159,6 +173,9 @@ runs: IN_TIMEOUT: ${{ inputs.timeout }} IN_EXCLUDE: ${{ inputs.exclude }} IN_EXTRA_ARGS: ${{ inputs.extra-args }} + IN_CHANGED_ONLY: ${{ inputs.changed-only }} + IN_BASELINE: ${{ inputs.baseline }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} IN_RESULT_FILE: ${{ inputs.result-file }} # Non-interactive: no project-name prompt, no "scan again?" prompt. SECFOO_PROJECT_NAME: ${{ github.repository }} @@ -172,6 +189,10 @@ runs: [ -n "$IN_FAIL_ON" ] && args+=(--fail-on "$IN_FAIL_ON") [ -n "$IN_MAX_COST" ] && args+=(--max-cost "$IN_MAX_COST") [ -n "$IN_TIMEOUT" ] && args+=(--timeout "$IN_TIMEOUT") + if [ "$IN_CHANGED_ONLY" = "true" ] && [ -n "$PR_BASE_SHA" ]; then + args+=(--changed-since "$PR_BASE_SHA") + fi + [ -n "$IN_BASELINE" ] && args+=(--baseline "$IN_BASELINE") if [ -n "$IN_EXCLUDE" ]; then IFS=',' read -ra excludes <<< "$IN_EXCLUDE" for x in "${excludes[@]}"; do x="${x## }"; x="${x%% }"; [ -n "$x" ] && args+=(--exclude "$x"); done @@ -240,11 +261,14 @@ runs: shell: bash env: SARIF_FILE: ${{ inputs.sarif-file }} + IN_BASELINE: ${{ inputs.baseline }} run: | set -euo pipefail # The runner's store only holds this job's scan, so no --project filter # is needed: every exported finding belongs to the checked-out repo. - secfoo findings export --format sarif --output "$SARIF_FILE" + export_args=(--format sarif --output "$SARIF_FILE") + [ -n "$IN_BASELINE" ] && export_args+=(--baseline "$IN_BASELINE") + secfoo findings export "${export_args[@]}" echo "sarif-file=$SARIF_FILE" >> "$GITHUB_OUTPUT" - name: Upload SARIF to code scanning diff --git a/docs/CI.md b/docs/CI.md index 528fef0..6f194f6 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -15,8 +15,55 @@ pipeline can gate on. Flags that matter in CI: `--json` (one JSON document on stdout, progress on stderr, no interactive prompts), `--rescan` (never ask "scan this commit again?"), `--project-name` (so the dashboard shows a repo name rather than a -runner path), `--fail-on`, `--max-cost`, `--exclude`, `--timeout`. The full -list is in [REFERENCE.md](REFERENCE.md#ci-gates-and-machine-readable-output). +runner path), `--fail-on`, `--max-cost`, `--exclude`, `--timeout`, and, for +pull requests, `--changed-since`, `--fail-scope` and `--baseline` (below). +The full list is in +[REFERENCE.md](REFERENCE.md#ci-gates-and-machine-readable-output). + +## Adopting secfoo in an existing repo + +A first full audit of a mature codebase usually finds dozens of issues. If +you turn on `--fail-on high` immediately, every PR goes red and the check +gets disabled. The baseline workflow avoids that without throwing the +findings away: + +1. Run once over the whole repository and write a baseline: + + ```bash + secfoo run --skill sast --skill secret-scanning --agent api --target . --rescan + secfoo findings baseline write .secfoo/baseline.json --reason "initial triage" + ``` + + Commit `.secfoo/baseline.json`. It is plain JSON — edit an entry's + `reason` or give it an `expires` date (`YYYY-MM-DD`) when you know when + the exception should be revisited. `baseline write` keeps those edits on + a later rewrite when you omit `--reason`/`--expires`. + +2. On subsequent PRs, review only what changed and gate on the diff: + + ```bash + secfoo run --changed-since origin/main --fail-scope changed \ + --fail-on high --baseline .secfoo/baseline.json + ``` + + Known findings stop failing the build; expired baseline entries start + failing again and are listed in the run output. Nothing is hidden: the + findings remain in the store, in the SARIF/JSONL exports, and the SAST + dashboard marks them **Accepted in baseline**. + +3. As you fix the known findings, run `secfoo findings baseline check` to + list entries that are now closed or missing, and prune them from the + JSON. Then tighten `--fail-on` (or drop `--fail-scope`) once the baseline + is small enough. + +`--changed-since` uses git's merge base, so a long-lived branch does not +pick up unrelated commits from `main`. It requires a local git checkout +with the base ref available: use `fetch-depth: 0` on GitHub Actions (the +Action's `changed-only` input wires `github.event.pull_request.base.sha` +automatically) and `GIT_DEPTH: "0"` on GitLab. If your CI already knows the +diff, pass it with `--changed-files` instead (newline-separated paths). +The two flags are mutually exclusive, and a missing ref or a non-git target +is an error before any agent is started. ## Which agent in CI @@ -78,6 +125,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 # needed for changed-only / --changed-since on PRs - uses: secfoo-com/secfoo@main env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} # or ANTHROPIC_API_KEY / GEMINI_API_KEY @@ -85,6 +134,9 @@ jobs: skills: sast,secret-scanning fail-on: high max-cost: "2.00" + changed-only: true # PR runs review the diff + baseline: .secfoo/baseline.json # commit this file after the first run + extra-args: "--fail-scope changed" # findings in unchanged files stay visible, not gating ``` Pin to a release tag (`secfoo-com/secfoo@v0.3.1`) once you are happy with @@ -104,6 +156,8 @@ and, without the Action, [examples/ci/github-actions-manual.yml](../examples/ci/ | `max-cost` | | USD cap on agent-reported spend. | | `timeout` | | Per-skill timeout in seconds. | | `exclude` | | Comma-separated paths to skip. | +| `changed-only` | `false` | On `pull_request` events, review only the paths changed since the PR base (via git merge-base). Passes `github.event.pull_request.base.sha` automatically; other events stay full scans. Needs `fetch-depth: 0`. Pair with `extra-args: "--fail-scope changed"` to gate on changed findings only. | +| `baseline` | | Path to a committed findings baseline JSON. Matching findings are excluded from `fail-on` but still exported; expired entries count again. | | `extra-args` | | Appended to `secfoo run` verbatim. | | `version` | latest | secfoo version from PyPI. | | `python-version` | `3.12` | Python used to install secfoo. | @@ -177,18 +231,26 @@ Full example: [examples/ci/pre-commit-config.yaml](../examples/ci/pre-commit-con secfoo: stage: test image: python:3.12-slim + variables: + GIT_DEPTH: "0" # merge-base needs full history on merge requests before_script: - apt-get update -qq && apt-get install -y -qq --no-install-recommends git >/dev/null - pip install --quiet secfoo script: - | + # On merge requests, review only what changed; branch pipelines are full scans. + extra=() + if [ -n "${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}" ]; then + extra+=(--changed-since "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --fail-scope changed) + fi secfoo run --agent api --target . --depth quick --json --rescan \ --project-name "$CI_PROJECT_PATH" \ --skill sast --skill secret-scanning \ - --fail-on high --max-cost 2.00 > secfoo-result.json || code=$? - - secfoo findings export --format gitlab-sast -o gl-sast-report.json - - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json - - secfoo findings export --format sarif -o secfoo.sarif + --fail-on high --max-cost 2.00 \ + --baseline .secfoo/baseline.json "${extra[@]}" > secfoo-result.json || code=$? + - secfoo findings export --format gitlab-sast -o gl-sast-report.json --baseline .secfoo/baseline.json + - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json --baseline .secfoo/baseline.json + - secfoo findings export --format sarif -o secfoo.sarif --baseline .secfoo/baseline.json - exit ${code:-0} artifacts: when: always diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index b303ac4..54dc04d 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -286,6 +286,14 @@ Open rows keyed with the legacy fingerprint are **rekeyed** automatically on the first rescan that computes a region hash. There is no post-hoc embedding similarity on finding text. +A **diff-scoped run** (`--changed-since` / `--changed-files`, below) keeps +this identity: the code-region hash is computed from the checkout exactly as +in a full scan. A rename contributes both the old and the new path to the +changed set, so a finding in a moved file is still recognised. Crucially, +stale-finding closure is limited to the scanned paths — a finding in a file +the run did not look at keeps its `open` state instead of being closed. Each +finding also carries a `scope` (`changed` or `context`) for the CI gate. + ### Structured findings (SAST, SCA, secret scanning) SCA and secret-scanning runs get the same open/closed lifecycle as SAST, @@ -300,6 +308,13 @@ records: code-free description of the vulnerable construct ("YAML loader without a safe loader applied to an uploaded config file"). Because it has no paths or identifiers, findings can be compared across repos. +- **`scope`** (#109): `changed` in a full scan, or `changed`/`context` in a + diff-scoped run. A `context` finding is still stored and exported but can + be excluded from `--fail-on` with `--fail-scope changed`. +- **`baseline_accepted`** (#109): JSON `{"reason", "expires"}` when a run + with `--baseline` saw the finding as an active baseline entry. The SAST + dashboard shows an **Accepted in baseline** badge; it never hides the + finding. Expired entries clear the badge on the next such run. - **`locations`** (SAST and secret scanning): every site the report's Location cell names, as a list of `{"path", "start_line", "end_line"}`. The cell may hold `path:line`, `path:start-end`, `path:line,line`, @@ -324,6 +339,7 @@ stored, even when a report includes more. secfoo findings export # open findings, every skill, JSON Lines to stdout secfoo findings export -s sast --status all # one skill, open and closed secfoo findings export --no-locations -o findings.jsonl # drop paths/lines/region hashes +secfoo findings export --baseline .secfoo/baseline.json -o findings.jsonl # annotate baseline state ``` @@ -381,6 +397,42 @@ score. CWE tags use `external/cwe/cwe-N`. Findings without a CWE still get a rul `--no-locations` removes the same structured location fields as JSONL and omits SARIF locations; free-text finding titles and descriptions are not redacted. +With `--baseline `, every exported finding is annotated without being +hidden: SARIF results get a `baselineState` of `"unchanged"` for an active +entry and `"new"` otherwise; JSON Lines records get the same `baselineState` +plus `baseline: {reason, expires}` (with `null` values when the entry has +none). Expired entries read as `"new"`. The GitLab report formats ignore +baseline annotations. See [CI.md](CI.md#adopting-secfoo-in-an-existing-repo) +for the workflow that writes and maintains the file. + +### Findings baseline + +```bash +secfoo findings baseline write .secfoo/baseline.json --reason "issue #42" --expires 2026-12-31 +secfoo findings baseline check .secfoo/baseline.json +secfoo run --baseline .secfoo/baseline.json --fail-on high +``` + +`baseline write` records the fingerprint, skill, severity and title of every +**open** finding in a small JSON file. `--reason` and `--expires` are applied +to all entries when given; the file is plain JSON and meant to be edited by +hand afterwards. Re-running `write` without those flags preserves an +existing entry's edited reason and expiry. Only `--skill` and `--project` +limit which findings are written. + +`baseline check` lists entries whose finding is now closed or no longer in +the store, plus entries whose expiry has passed, so the file can be pruned. +It never changes the file itself. + +`secfoo run --baseline ` excludes active entries from the `--fail-on` +count. It does not suppress the run, the stored finding, or any export. +Expired entries are reported in the run output and count toward the gate +again; an invalid file (bad JSON, missing `entries`, or a non-`YYYY-MM-DD` +expiry) fails with exit code `2` before any agent starts. In `--json` mode +the summary adds `gates.findings.expired_entries` and a `baseline` object +with the path and active/expired entry counts. Combine with +`--fail-scope changed` to gate only on findings in files the PR touched. + ### Runtime evidence Runtime evidence records what a running app actually did with a vulnerable @@ -799,7 +851,11 @@ secfoo run --skill sast --skill secret-scanning --agent api --target . \ | Flag | Effect | |---|---| -| `--fail-on critical\|high\|medium\|low` | Exit `2` if any run reports a finding at that severity or worse. Counts come from the report contract's `### [SEVERITY] Fn:` headings, not from prose. | +| `--fail-on critical\|high\|medium\|low` | Exit `2` if any run reports a finding at that severity or worse. Counts come from the report contract's `### [SEVERITY] Fn:` headings, not from prose. Active baseline entries and (with `--fail-scope changed`) `context` findings are excluded from the count. | +| `--fail-scope all\|changed` | With `--fail-on`, `changed` counts only findings in files the PR touched; `all` (default) counts them all. Findings in unchanged files stay stored and exported as `scope: context` — only the gate ignores them. Requires `--changed-since` or `--changed-files` to have any effect. | +| `--changed-since ` | Diff-aware run: review the paths changed between `ref` and HEAD, using git's **merge base**. The brief names the changed files and asks the agent to review those paths and their callers. Needs a local git checkout with that ref available; a missing ref or non-git target fails with exit code `2` before runs start. Mutually exclusive with `--changed-files`. | +| `--changed-files ` | Diff-aware run from a newline-separated list of paths supplied by CI. Same scope behaviour as `--changed-since`; needs a local git target because structured findings are scoped by path. | +| `--baseline ` | Exclude findings whose fingerprint has an active entry in this baseline from `--fail-on` (see [Findings baseline](#findings-baseline)). Expired entries are listed and count again. | | `--max-cost ` | Exit `3` if the summed agent-reported spend for this invocation exceeds the cap. Evaluated after the runs complete. | | `--max-input-tokens ` | `api` agent only. Checked **before** the model is called: if the assembled prompt (brief + target source) is larger than `n` input tokens, the run fails without sending anything, and the error says how large the prompt was and which limit applied. Token counts come from LiteLLM's tokenizer for the model, or ~4 characters per token when it has none. Falls back to `[agents.api].max_input_tokens`. Other agents read the target themselves, so they warn and ignore it. | | `--json` | Write one JSON document to stdout (per-skill status, severity counts, tokens, USD, gate verdicts, resolved exit code); progress and notes go to stderr. Also suppresses the interactive project-name prompt. | diff --git a/examples/ci/github-actions-manual.yml b/examples/ci/github-actions-manual.yml index a8f3c4e..c750427 100644 --- a/examples/ci/github-actions-manual.yml +++ b/examples/ci/github-actions-manual.yml @@ -16,6 +16,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 # --changed-since needs the PR base and merge base - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" @@ -26,14 +28,21 @@ jobs: id: scan env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} # Keep going on exit 2 (gate tripped) so the SARIF still uploads. + # PR_BASE_SHA is empty on push events; use --changed-files there if + # your workflow computes the diff itself. run: | + extra=() + [ -n "$PR_BASE_SHA" ] && extra+=(--changed-since "$PR_BASE_SHA" --fail-scope changed) secfoo run --agent api --target . --depth quick --json --rescan \ --project-name "$GITHUB_REPOSITORY" \ - --skill sast --skill secret-scanning --fail-on high > secfoo-result.json || echo "code=$?" >> "$GITHUB_OUTPUT" + --skill sast --skill secret-scanning --fail-on high \ + --baseline .secfoo/baseline.json "${extra[@]}" > secfoo-result.json \ + || echo "code=$?" >> "$GITHUB_OUTPUT" - name: Export SARIF - run: secfoo findings export --format sarif -o secfoo.sarif + run: secfoo findings export --format sarif -o secfoo.sarif --baseline .secfoo/baseline.json - uses: github/codeql-action/upload-sarif@5895b2c9be147bc7f1c75ce72c5cb577febb1907 # v4 with: diff --git a/examples/ci/github-actions.yml b/examples/ci/github-actions.yml index df5446a..03a88ab 100644 --- a/examples/ci/github-actions.yml +++ b/examples/ci/github-actions.yml @@ -21,6 +21,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 # --changed-since needs the PR base and merge base - uses: secfoo-com/secfoo@main env: @@ -30,6 +32,9 @@ jobs: fail-on: high # exit 2 -> red check when a High+ finding appears max-cost: "2.00" # exit 3 if the agent reports more than $2 of spend exclude: vendor,fixtures + changed-only: true # PR runs review the diff; push/schedule stay full + baseline: .secfoo/baseline.json # commit this file after the first run + extra-args: "--fail-scope changed" # unchanged files stay visible, not gating # Prefer Claude Code / Codex / Gemini as the reviewer? Install the CLI # on the runner and point the action at it instead of `api`: diff --git a/examples/ci/gitlab-ci.yml b/examples/ci/gitlab-ci.yml index 5c7a8d8..79a58cf 100644 --- a/examples/ci/gitlab-ci.yml +++ b/examples/ci/gitlab-ci.yml @@ -13,21 +13,27 @@ secfoo: stage: test image: python:3.12-slim variables: - GIT_DEPTH: "50" + GIT_DEPTH: "0" # MR diff-base needs full history for git merge-base before_script: - apt-get update -qq && apt-get install -y -qq --no-install-recommends git >/dev/null - pip install --quiet secfoo script: # Exit codes: 0 clean, 1 a run failed, 2 the --fail-on gate tripped, 3 the --max-cost gate tripped. - | + # On merge requests, review only what changed. Branch pipelines are full scans. + extra=() + if [ -n "${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}" ]; then + extra+=(--changed-since "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --fail-scope changed) + fi secfoo run --agent api --target . --depth quick --json --rescan \ --project-name "$CI_PROJECT_PATH" \ --skill sast --skill secret-scanning \ - --fail-on high --max-cost 2.00 > secfoo-result.json || code=$? - - secfoo findings export --format gitlab-sast -o gl-sast-report.json - - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json - - secfoo findings export --format sarif -o secfoo.sarif - - secfoo findings export -o secfoo-findings.jsonl + --fail-on high --max-cost 2.00 \ + --baseline .secfoo/baseline.json "${extra[@]}" > secfoo-result.json || code=$? + - secfoo findings export --format gitlab-sast -o gl-sast-report.json --baseline .secfoo/baseline.json + - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json --baseline .secfoo/baseline.json + - secfoo findings export --format sarif -o secfoo.sarif --baseline .secfoo/baseline.json + - secfoo findings export -o secfoo-findings.jsonl --baseline .secfoo/baseline.json - exit ${code:-0} artifacts: when: always diff --git a/src/secfoo/baseline.py b/src/secfoo/baseline.py new file mode 100644 index 0000000..d0627e4 --- /dev/null +++ b/src/secfoo/baseline.py @@ -0,0 +1,170 @@ +"""Findings baseline (#109): a small, human-editable JSON file that records +known findings by fingerprint. + +A baseline never deletes or hides a finding: it only changes what the +``--fail-on`` gate counts. Exports still carry every finding, with the +baseline reason/expiry attached and a SARIF ``baselineState``. Expired +entries stop suppressing the gate and are reported on every run. + +File shape (entries can be edited by hand -- unknown keys are preserved on +re-serialisation only when rewriting through this module):: + + {"version": 1, "created_at": "...", "entries": [ + {"fingerprint": "...", "skill": "sast", "severity": "high", + "title": "...", "reason": "triaged by @alice", "expires": "2026-12-31"}]} +""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass, field +from datetime import date, datetime, timezone +from pathlib import Path + +from secfoo import storage +from secfoo.storage.repository import RunRepository + + +class BaselineError(ValueError): + """The baseline file is missing, malformed, or has an invalid entry.""" + + +@dataclass(frozen=True) +class BaselineEntry: + fingerprint: str + skill: str = "" + severity: str = "" + title: str = "" + reason: str | None = None + expires: str | None = None + + def is_expired(self, today: date | None = None) -> bool: + if not self.expires: + return False + try: + expiry = date.fromisoformat(self.expires) + except ValueError: + # An invalid date must not silently suppress a gate forever. + return True + return expiry < (today or date.today()) + + def as_dict(self) -> dict: + return {key: value for key, value in asdict(self).items() if value not in (None, "")} + + +@dataclass +class Baseline: + entries: dict[str, BaselineEntry] = field(default_factory=dict) + created_at: str | None = None + + @classmethod + def load(cls, path: Path | str) -> Baseline: + file_path = Path(path) + try: + data = json.loads(file_path.read_text(encoding="utf-8")) + except OSError as exc: + raise BaselineError(f"Cannot read baseline {file_path}: {exc}") from None + except json.JSONDecodeError as exc: + raise BaselineError(f"Invalid JSON in baseline {file_path}: {exc}") from None + if not isinstance(data, dict) or not isinstance(data.get("entries"), list): + raise BaselineError(f"Baseline {file_path} needs an 'entries' list") + entries: dict[str, BaselineEntry] = {} + for item in data["entries"]: + if not isinstance(item, dict) or not str(item.get("fingerprint") or "").strip(): + raise BaselineError(f"Baseline {file_path} has an entry without a fingerprint") + entry = BaselineEntry( + fingerprint=str(item["fingerprint"]).strip(), + skill=str(item.get("skill") or ""), + severity=str(item.get("severity") or ""), + title=str(item.get("title") or ""), + reason=str(item["reason"]) if item.get("reason") else None, + expires=str(item["expires"]) if item.get("expires") else None, + ) + if entry.expires: + try: + date.fromisoformat(entry.expires) + except ValueError: + raise BaselineError( + f"Baseline {file_path}: expires on {entry.fingerprint[:10]} must be YYYY-MM-DD" + ) from None + entries[entry.fingerprint] = entry + return cls(entries=entries, created_at=data.get("created_at")) + + def write(self, path: Path | str) -> None: + file_path = Path(path) + file_path.parent.mkdir(parents=True, exist_ok=True) + document = { + "version": 1, + "created_at": self.created_at or datetime.now(timezone.utc).isoformat(), + "entries": [entry.as_dict() for entry in sorted(self.entries.values(), key=lambda e: e.fingerprint)], + } + file_path.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + + def active(self, today: date | None = None) -> dict[str, BaselineEntry]: + return {fp: entry for fp, entry in self.entries.items() if not entry.is_expired(today)} + + def expired(self, today: date | None = None) -> list[BaselineEntry]: + return [entry for entry in self.entries.values() if entry.is_expired(today)] + + def matches(self, fingerprint: str | None, today: date | None = None) -> BaselineEntry | None: + return self.active(today).get(fingerprint) if fingerprint else None + + +def title_for_row(skill_id: str, row: dict) -> str: + """Stable, human-readable title for a finding row from any skill.""" + return str( + row.get("title") + or row.get("issue") + or row.get("secret_type") + or row.get("package") + or row.get("cwe") + or "Finding" + ) + + +def entries_from_rows(rows, *, reason: str | None = None, expires: str | None = None) -> list[BaselineEntry]: + """Build baseline entries from ``list_structured_findings`` tuples. + + Only open findings are written: a closed one does not need acknowledging. + Existing entries are kept as-is so a user's hand-edited reason/expiry + survives a later rewrite with no flags. + """ + if expires: + try: + date.fromisoformat(expires) + except ValueError: + raise BaselineError(f"--expires must be YYYY-MM-DD, got {expires!r}") from None + entries = [] + for skill_id, row in rows: + if row.get("status") != "open": + continue + entries.append( + BaselineEntry( + fingerprint=str(row["fingerprint"]), + skill=skill_id, + severity=str(row.get("severity") or ""), + title=title_for_row(skill_id, row), + reason=reason, + expires=expires, + ) + ) + return entries + + +def stale_entries(repo: RunRepository, baseline: Baseline) -> list[tuple[BaselineEntry, str]]: + """``(entry, state)`` pairs for entries whose finding is closed or gone. + + ``baseline check`` reports these so the file can be pruned; a stale + entry is harmless (it suppresses nothing, since the finding is closed). + """ + known: dict[str, str] = {} + for _skill_id, row in repo.list_structured_findings(status=None): + known[str(row["fingerprint"])] = str(row.get("status") or "open") + result = [] + for entry in sorted(baseline.entries.values(), key=lambda e: e.fingerprint): + state = known.get(entry.fingerprint) + if state == "closed": + result.append((entry, "closed")) + elif state is None: + result.append((entry, "missing")) + return result diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 6e49f2c..1f438e8 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -24,11 +24,19 @@ from secfoo.agents.registry import ADAPTERS, get_adapter from secfoo.aibom import AIBOMParseError, parse_ai_bom from secfoo.attachments import infer_attachment_kind +from secfoo.baseline import ( + Baseline, + BaselineError, + entries_from_rows, + stale_entries, + title_for_row, +) from secfoo.cloud import CloudConfig, CloudError from secfoo.config import CLOUD_CONFIG_PATH, STORE_DIR, attachment_dir from secfoo.context_run import resolve_run_context from secfoo.context_sources import ContextSourceError from secfoo.cost import format_cost, format_tokens, sum_optional +from secfoo.diff_scope import DiffScopeError, validate_diff_scope from secfoo.report.gitlab import REPORT_TYPES as GITLAB_REPORT_TYPES from secfoo.report.gitlab import findings_to_gitlab from secfoo.report.jsonl import findings_to_jsonl @@ -56,6 +64,8 @@ vendor_app = typer.Typer(name="vendor", help="Fetch optional local assets for the dashboard.") memory_app = typer.Typer(name="memory", help="Connect to secfoo-memory, the vulnerability pattern service.") findings_app = typer.Typer(name="findings", help="Query the structured findings recorded by past runs.") +baseline_app = typer.Typer(name="baseline", help="Record and check acknowledged findings (a CI-friendly baseline).") +findings_app.add_typer(baseline_app, name="baseline") app.add_typer(mcp_app, name="mcp") app.add_typer(memory_app, name="memory") app.add_typer(findings_app, name="findings") @@ -174,6 +184,11 @@ class FailOn(str, Enum): LOW = "low" +class FailScope(str, Enum): + ALL = "all" + CHANGED = "changed" + + # Exit codes for `secfoo run`, so CI can tell "the scan broke" from "the # scan worked and the policy gate failed" without parsing output. EXIT_RUN_FAILED = 1 @@ -183,8 +198,30 @@ class FailOn(str, Enum): _SEVERITY_ORDER = ("critical", "high", "medium", "low") -def _findings_at_or_above(outcome, threshold: str) -> int: - """Count of findings in `outcome` at `threshold` severity or worse.""" +def _findings_at_or_above( + outcome, + threshold: str, + *, + scope: FailScope = FailScope.ALL, + baseline: Baseline | None = None, +) -> int: + """Count of findings in `outcome` at `threshold` severity or worse. + + Per-finding metadata (fingerprint + #109 scope) wins when the runner + supplied it; callers that build an outcome directly still work through + the aggregate severity counts. + """ + details = getattr(outcome, "gate_findings", ()) + if details: + active = baseline.active() if baseline is not None else {} + allowed = _SEVERITY_ORDER[: _SEVERITY_ORDER.index(threshold) + 1] + return sum( + 1 + for finding in details + if ("info" if finding.severity == "informational" else finding.severity) in allowed + and (scope is FailScope.ALL or finding.scope == scope.value) + and (finding.fingerprint not in active) + ) total = 0 for level in _SEVERITY_ORDER: total += getattr(outcome, f"{level}_count", 0) @@ -401,6 +438,30 @@ def run( help="Scan even when this exact commit was already scanned for a skill. Without it, " "a run on a terminal asks first; a non-interactive run (CI, --json) always scans.", ), + changed_since: str | None = typer.Option( + None, + "--changed-since", + help="Diff-aware run: review paths changed since this git ref (uses the merge base). " + "Unchanged files stay in scope as context but don't trip --fail-scope changed. " + "Needs a local git checkout.", + ), + changed_files: str | None = typer.Option( + None, + "--changed-files", + help="Diff-aware run from a newline-separated list of paths (for CI systems that " + "already know the diff). Mutually exclusive with --changed-since.", + ), + fail_scope: FailScope = typer.Option( + FailScope.ALL, + "--fail-scope", + help="With --fail-on: 'changed' ignores findings in unchanged files, 'all' counts them.", + ), + baseline_file: str | None = typer.Option( + None, + "--baseline", + help="Path to a findings baseline written by `secfoo findings baseline write`. " + "Active entries are excluded from --fail-on; expired ones count again.", + ), ) -> None: """Run one or more security skills against a target using the chosen agent. @@ -410,6 +471,30 @@ def run( but the --fail-on gate tripped, 3 all runs succeeded but the --max-cost gate tripped. """ + if changed_since and changed_files: + err_console.print("[red]Error:[/] --changed-since and --changed-files are mutually exclusive.") + raise typer.Exit(code=2) + try: + validate_diff_scope(target=target, changed_since=changed_since, changed_files=changed_files) + except DiffScopeError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + + baseline: Baseline | None = None + expired_baseline_entries = [] + if baseline_file: + try: + baseline = Baseline.load(Path(baseline_file)) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + expired_baseline_entries = baseline.expired() + for entry in expired_baseline_entries: + (err_console if json_output else console).print( + f"[yellow]Note:[/] baseline entry {entry.fingerprint[:10]} expired " + f"on {entry.expires}; it will fail --fail-on again." + ) + skill_file_entries = skill_file or [] skill_sha256_entries = skill_sha256 or [] if len(skill_sha256_entries) > len(skill_file_entries): @@ -585,6 +670,9 @@ def handle_complete(skill_name: str, result_status: str) -> None: exclude_paths=exclude_paths, project_display_name=project_name, assessment_application_id=app_id, + changed_since=changed_since, + changed_files=changed_files, + baseline=baseline, ) except TargetResolutionError as exc: err_console.print(f"[red]Error:[/] {exc}") @@ -602,9 +690,18 @@ def handle_complete(skill_name: str, result_status: str) -> None: if fail_on is not None: gate_findings = { "threshold": fail_on.value, - "count": sum(_findings_at_or_above(o, fail_on.value) for o in outcomes), + "count": sum( + _findings_at_or_above(o, fail_on.value, scope=fail_scope, baseline=baseline) for o in outcomes + ), } gate_findings["passed"] = gate_findings["count"] == 0 + # Keep the old three-key shape for ordinary runs; only add the #109 + # metadata when a caller actually opted into a scope/baseline. + if fail_scope is not FailScope.ALL: + gate_findings["scope"] = fail_scope.value + if baseline is not None: + gate_findings["baseline"] = Path(baseline_file).name + gate_findings["expired_entries"] = [entry.fingerprint for entry in expired_baseline_entries] gate_cost = None if max_cost is not None: gate_cost = { @@ -658,6 +755,18 @@ def handle_complete(skill_name: str, result_status: str) -> None: "total_cost_usd": total_cost, "unpriced_runs": unpriced_runs, "gates": {"findings": gate_findings, "cost": gate_cost}, + "diff_scope": ( + {"ref": changed_since, "changed_files": changed_files} + if changed_since or changed_files else None + ), + "baseline": ( + { + "path": baseline_file, + "active_entries": len(baseline.active()), + "expired_entries": [entry.fingerprint for entry in expired_baseline_entries], + } + if baseline is not None else None + ), "any_run_failed": any_failed, "exit_code": exit_code, } @@ -692,9 +801,12 @@ def handle_complete(skill_name: str, result_status: str) -> None: console.print(f"AI spend for this run: [bold]{format_cost(total_cost)}[/]") if gate_findings is not None: verdict = "[green]passed[/]" if gate_findings["passed"] else "[red]FAILED[/]" + scope_note = f", scope: {gate_findings['scope']}" if "scope" in gate_findings else "" + baseline_note = f", baseline: {gate_findings['baseline']}" if "baseline" in gate_findings else "" console.print( f"Findings gate (--fail-on {gate_findings['threshold']}): {verdict} " f"-- {gate_findings['count']} finding(s) at or above threshold" + f"{scope_note}{baseline_note}" ) if gate_cost is not None: verdict = "[green]passed[/]" if gate_cost["passed"] else "[red]FAILED[/]" @@ -1910,6 +2022,9 @@ def findings_export( runtime_priority: Annotated[bool, typer.Option( "--runtime-priority", help="SARIF: raise findings reached in production to level 'error'.", )] = False, + baseline_file: Annotated[str | None, typer.Option( + "--baseline", help="Mark entries present in this baseline as unchanged (SARIF baselineState / JSONL baseline).", + )] = None, ) -> None: """Export structured findings (SAST, SCA, secret scanning) as JSONL, SARIF or a GitLab report. @@ -1920,6 +2035,14 @@ def findings_export( """ from secfoo.runtime.developer import RuntimeLookup + baseline = None + if baseline_file: + try: + baseline = Baseline.load(Path(baseline_file)) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + records = [] with RunRepository() as repo: rows = repo.list_structured_findings( @@ -1939,6 +2062,16 @@ def findings_export( record[column] = value if skill_id == "sca-reachability" and not no_runtime: record["runtime"] = runtime.as_sarif() + if baseline is not None: + entry = baseline.matches(record.get("fingerprint")) + # #109: baselined findings stay visible in every format; + # only their state changes. Expired entries read as 'new'. + record["baselineState"] = "unchanged" if entry else "new" + if entry is not None: + record["baseline"] = { + "reason": entry.reason, + "expires": entry.expires, + } records.append(record) for note in lookup.notes: err_console.print(f"[yellow]Note:[/] {note}") @@ -2082,6 +2215,74 @@ def findings_check( raise typer.Exit(code=EXIT_RUNTIME_REACHED) +@baseline_app.command(name="write") +def findings_baseline_write( + path: Annotated[Path, typer.Argument(help="Where to write the baseline JSON (e.g. .secfoo/baseline.json).")], + reason: Annotated[str | None, typer.Option("--reason", help="Reason recorded on every entry, e.g. an issue link.")] = None, + expires: Annotated[str | None, typer.Option( + "--expires", callback=_validate_date, help="Apply this YYYY-MM-DD expiry to every entry.", + )] = None, + skill: Annotated[list[FindingsSkill] | None, typer.Option("--skill", "-s", help="Limit to these skills.")] = None, + project: Annotated[int | None, typer.Option("--project", help="Limit to one project id.")] = None, +) -> None: + """Record every open finding in a baseline file. + + The file is plain JSON: edit an entry's reason or expires by hand at any + time. Rewriting it keeps those edits when --reason/--expires are omitted. + """ + from dataclasses import replace + + try: + previous = Baseline.load(path) if path.exists() else Baseline() + entries = [] + with RunRepository() as repo: + rows = repo.list_structured_findings( + skill_ids=[s.value for s in (skill or [])] or None, project_id=project, status="open" + ) + entries = entries_from_rows(rows, reason=reason, expires=expires) + entries = [ + replace(entry, reason=entry.reason or previous.entries[entry.fingerprint].reason, + expires=entry.expires or previous.entries[entry.fingerprint].expires) + if entry.fingerprint in previous.entries else entry + for entry in entries + ] + baseline = Baseline(entries={entry.fingerprint: entry for entry in entries}) + baseline.write(path) + except (BaselineError, OSError) as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=1) from None + err_console.print(f"Wrote {len(entries)} open finding(s) to {path}.") + + +@baseline_app.command(name="check") +def findings_baseline_check( + path: Annotated[Path, typer.Argument(help="Baseline JSON to check.")], +) -> None: + """List baseline entries whose finding is closed or no longer stored.""" + try: + baseline = Baseline.load(path) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + with RunRepository() as repo: + stale = stale_entries(repo, baseline) + expired = baseline.expired() + if not stale and not expired: + console.print(f"Baseline {path}: {len(baseline.entries)} entry(ies), nothing to prune.") + return + for entry, state in stale: + console.print( + f"[yellow]{state}[/] {entry.fingerprint[:10]} {entry.skill} " + f"{title_for_row(entry.skill, {'title': entry.title})} (reason: {entry.reason or '-'})" + ) + for entry in expired: + console.print(f"[yellow]expired[/] {entry.fingerprint[:10]} on {entry.expires}") + err_console.print( + f"{len(stale)} stale and {len(expired)} expired entry(ies). " + "Remove them from the JSON to keep the baseline tight." + ) + + @runtime_app.command(name="ingest") def runtime_ingest( events: Annotated[ diff --git a/src/secfoo/diff_scope.py b/src/secfoo/diff_scope.py new file mode 100644 index 0000000..0de75dc --- /dev/null +++ b/src/secfoo/diff_scope.py @@ -0,0 +1,227 @@ +"""Diff-aware scans (#109): turn a git ref or a CI-supplied file list into +the set of paths a PR touched, and tag findings that sit outside that set. + +The changed paths are computed once per target with +``git diff --name-status --merge-base``. Renames contribute *both* the old +and the new path: a finding in the pre-rename file must not be closed just +because the PR moved it. Callers get plain strings relative to the workdir, +normalised the same way ``repository.close_stale_findings`` normalises them. + +Nothing here runs a scan or writes to the store. Bad refs and non-git +targets raise ``DiffScopeError`` before the runner does any work, so a typo +in a CI variable fails fast instead of quietly turning into a full scan. +""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +from secfoo.report.markdown import FINDING, headings + +SCOPE_CHANGED = "changed" +SCOPE_CONTEXT = "context" + +_AUTHORIZED_SCOPE_MARKER = re.compile(r"\bscope\s*:\s*(changed|context)\b", re.IGNORECASE) + + +class DiffScopeError(ValueError): + """A diff scope could not be resolved (non-git target or bad ref).""" + + +def _normalize(path: str) -> str: + """Comparison form: forward slashes, no leading './' or '/', lowercase.""" + cleaned = path.strip().replace("\\", "/") + while cleaned.startswith("./"): + cleaned = cleaned[2:] + return cleaned.lstrip("/").lower() + + +def normalize_paths(paths) -> list[str]: + """Deduplicated, sorted changed paths. Order of the input is irrelevant.""" + return sorted({_normalize(path) for path in paths if path and path.strip()}) + + +def changed_files_from_text(text: str) -> list[str]: + """Parse the newline-separated list used by CI systems that already + computed the diff. Blank lines, comments and surrounding quotes are + ignored; paths keep their original case for display.""" + paths = [] + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + paths.append(line.strip("\"'")) + return paths + + +def is_git_worktree(workdir: Path) -> bool: + try: + result = subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "-C", str(workdir), "rev-parse", "--is-inside-work-tree"], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.SubprocessError): + return False + return result.returncode == 0 and result.stdout.strip() == "true" + + +def _verify_ref(workdir: Path, ref: str) -> None: + if not ref or ref.startswith("-") or "\x00" in ref or "\n" in ref: + raise DiffScopeError(f"Invalid --changed-since ref: {ref!r}") + try: + result = subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "-C", str(workdir), "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}"], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise DiffScopeError(f"Could not check git ref {ref!r}: {exc}") from None + if result.returncode != 0: + raise DiffScopeError(f"Git ref {ref!r} does not exist in {workdir}") + + +def changed_paths_since(workdir: Path, ref: str) -> list[str]: + """Paths changed between ``ref`` and HEAD, using the merge base so a + long-lived feature branch does not pick up unrelated main-branch commits. + + The ``-z`` name-status format is used so paths with spaces or newlines + survive intact. Rename/copy records emit both paths, which is what keeps + findings in moved files alive in the structured findings lifecycle. + """ + if not is_git_worktree(workdir): + raise DiffScopeError(f"--changed-since needs a git repository: {workdir} is not a git worktree") + _verify_ref(workdir, ref) + try: + result = subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + [ + "git", "-C", str(workdir), "diff", "--name-status", "-z", + "--merge-base", "--find-renames", "--end-of-options", ref, + ], + capture_output=True, text=True, timeout=30, check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise DiffScopeError(f"Could not compute the diff against {ref!r}: {exc}") from None + if result.returncode != 0: + raise DiffScopeError(f"Could not compute the diff against {ref!r}: {result.stderr.strip()}") + + tokens = result.stdout.split("\x00") + paths: list[str] = [] + index = 0 + while index < len(tokens): + status = tokens[index].strip() + index += 1 + if not status: + continue + kind = status[0].upper() + if kind in {"R", "C"}: + # R100\0old\0new\0 -- both sides matter for finding identity. + if index + 1 < len(tokens): + paths.extend((tokens[index], tokens[index + 1])) + index += 2 + elif index < len(tokens): + paths.append(tokens[index]) + index += 1 + elif kind in {"A", "M", "D", "T", "U", "X", "B"} and index < len(tokens): + paths.append(tokens[index]) + index += 1 + if not paths: + return [] + return normalize_paths(paths) + + +def validate_diff_scope( + *, + target: str | None, + changed_since: str | None, + changed_files: str | None, + workdir: Path | None = None, +) -> None: + """Fail before any agent runs when a scope makes no sense. + + ``--changed-files`` needs no git metadata, but still needs a local git + target: the runner scopes the structured findings lifecycle by the + changed paths, which is meaningless for a downloaded URL target. + """ + if not changed_since and not changed_files: + return + if workdir is not None: + if not is_git_worktree(workdir): + raise DiffScopeError(f"--changed-since/--changed-files need a git repository: {workdir}") + if changed_since: + _verify_ref(workdir, changed_since) + return + # CLI-side pre-flight for local targets. Remote targets are validated by + # the runner once the temporary clone exists. + from secfoo.targets.resolver import TargetKind, resolve_target + + resolved = resolve_target(target) + if resolved.kind is not TargetKind.LOCAL or resolved.path is None: + if changed_since: + raise DiffScopeError("--changed-since needs a local git checkout or a CI-supplied --changed-files list") + return + if not is_git_worktree(resolved.path): + raise DiffScopeError(f"--changed-since/--changed-files need a git repository: {resolved.path}") + if changed_since: + _verify_ref(resolved.path, changed_since) + + +def resolved_changed_paths( + *, workdir: Path, changed_since: str | None, changed_files: str | None +) -> list[str] | None: + """Compute the scope inside the target workdir. ``None`` means a full + scan; an empty list means a diff scan whose diff was empty (nothing to + close, everything stays open).""" + if changed_files: + return normalize_paths(changed_files_from_text(changed_files)) + if changed_since: + return changed_paths_since(workdir, changed_since) + return None + + +def path_in_scope(path: str | None, changed_paths: list[str] | None) -> str: + """``changed`` for a path touched by the diff, ``context`` otherwise. + + A directory prefix counts: a finding in ``app/db/query.py`` is in scope + when the PR touched ``app/db``. A full scan has no context findings. + """ + if changed_paths is None or not path: + return SCOPE_CHANGED + normalized = _normalize(path) + for changed in changed_paths: + if normalized == changed or normalized.startswith(changed + "/"): + return SCOPE_CHANGED + return SCOPE_CONTEXT + + +def scope_markers(report_text: str) -> dict[str, str]: + """Explicit ``scope: context`` / ``scope: changed`` annotations in a + report, keyed by the finding's register id or title. The prompt asks the + agent to emit these; a human-written report can use them too.""" + markers: dict[str, str] = {} + for heading in headings(report_text): + if heading.level != 3 or not FINDING.match(heading.text): + continue + items = headings(report_text) + position = next((i for i, item in enumerate(items) if item.start == heading.start), None) + if position is None: + continue + end = next( + (item.start for item in items[position + 1:] if item.start >= heading.end), + len(report_text), + ) + body = report_text[heading.end:end] + match = _AUTHORIZED_SCOPE_MARKER.search(body) + if match is None: + continue + title = re.sub(r"^#{1,6}\s*", "", heading.text) + title = re.sub(r"^\[[A-Za-z]+\]\s*", "", title).strip().lower() + # "### [High] F1: SQL injection" -> match the register title ("SQL + # injection") as well as the full heading, whichever the skill used. + title_without_id = re.sub(r"^[a-z]\d+\s*:\s*", "", title) + markers[title] = match.group(1).lower() + markers[title_without_id] = match.group(1).lower() + id_match = re.match(r"^([a-z]\d+)\b", title) + if id_match: + markers[id_match.group(1)] = match.group(1).lower() + return markers diff --git a/src/secfoo/report/sarif.py b/src/secfoo/report/sarif.py index 0629c98..d4c4952 100644 --- a/src/secfoo/report/sarif.py +++ b/src/secfoo/report/sarif.py @@ -134,6 +134,11 @@ def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> } if runtime: result["properties"] = {"secfoo": {"runtime": runtime}} + # #109: only when an export was made against a baseline. SARIF 2.1.0 + # allows new/unchanged/updated/absent; secfoo emits the first two. + baseline_state = record.get("baselineState") + if baseline_state in {"new", "unchanged", "updated", "absent"}: + result["baselineState"] = baseline_state locations = _locations(record) if locations: result["locations"] = locations diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 93f3a32..60d52f3 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -9,6 +9,7 @@ from __future__ import annotations +import json import logging import re import time @@ -23,9 +24,17 @@ from secfoo import cloud, cvss, memory, osv from secfoo.agents.registry import get_adapter +from secfoo.baseline import Baseline from secfoo.config import ensure_store_dirs, run_dir from secfoo.context_brief import build_context_brief from secfoo.context_sources import ContextSource +from secfoo.diff_scope import ( + SCOPE_CHANGED, + path_in_scope, + resolved_changed_paths, + scope_markers, + validate_diff_scope, +) from secfoo.report import sca as sca_report from secfoo.report import secret_scanning as secret_report from secfoo.report.context_coverage import CoverageRecord, coverage_for_run @@ -109,6 +118,16 @@ def already_scanned_skills( repo.close() +@dataclass(frozen=True) +class GateFinding: + """One finding with the metadata the #109 CI gates need.""" + + severity: str + title: str = "" + fingerprint: str | None = None + scope: str = SCOPE_CHANGED + + @dataclass class RunOutcome: run_uuid: str @@ -134,6 +153,47 @@ class RunOutcome: failure_reason: str | None = None # Documentation sources provided or discovered, reconciled against the report (#125). context_sources: tuple[CoverageRecord, ...] = () + # #109: per-finding scope + fingerprint for --fail-scope / --baseline. + # Empty for full scans and for callers that construct an outcome directly; + # the CLI falls back to the aggregate counts in that case. + gate_findings: tuple[GateFinding, ...] = () + + +def _gate_findings_from_report(report_text, changed_paths: list[str] | None) -> tuple[GateFinding, ...]: + """Fallback for skills without a structured findings table: derive one + gate record per `### [SEVERITY]` finding heading, using an explicit + `Scope:` line when present and the changed-path list otherwise.""" + from secfoo.report.markdown import FINDING, MalformedReportError, headings + + try: + items = headings(report_text) + markers = scope_markers(report_text) + except MalformedReportError: + # The malformed report was already marked failed above; a gate built + # from a half-parsed report would be worse than no gate at all. + return () + findings = [] + for position, heading in enumerate(items): + if heading.level != 3 or FINDING.match(heading.text) is None: + continue + match = re.match(r"^###\s*\[([A-Za-z]+)\]", heading.text) + if match is None: + continue + end = next((item.start for item in items[position + 1:] if item.start >= heading.end), len(report_text)) + body = report_text[heading.end:end] + title = re.sub(r"^#{1,6}\s*", "", heading.text) + title = re.sub(r"^\[[A-Za-z]+\]\s*", "", title).strip() + lowered = title.lower() + marker = markers.get(lowered) or next( + (value for key, value in markers.items() if key in lowered), None + ) + scope = marker or ( + SCOPE_CHANGED + if any(path in body or path.rsplit("/", 1)[-1] in body for path in changed_paths or []) + else path_in_scope(None, changed_paths) + ) + findings.append(GateFinding(severity=match.group(1).lower(), title=title, scope=scope)) + return tuple(findings) def _project_display_name(resolved: ResolvedTarget) -> str: @@ -452,6 +512,8 @@ def _run_single_skill( stack: Stack | None = None, model: str | None = None, max_input_tokens: int | None = None, + changed_paths: list[str] | None = None, + baseline: Baseline | None = None, ) -> RunOutcome: skill = load_skill(skill_id) memory_enabled = memory.is_active_for_agent(agent_id) @@ -501,6 +563,17 @@ def _run_single_skill( # Memory Bank: capture HEAD SHA so future runs can diff against this baseline. target_commit = _git_head_commit(target_ctx.local_path) + # #109: a diff-aware run only closes findings in the paths it + # actually looked at. If the adapter also computed its own + # incremental scope, intersect the two instead of widening one. + effective_scope = changed_paths + if result.scan_scope is not None: + effective_scope = ( + sorted(set(changed_paths) & set(result.scan_scope)) + if changed_paths is not None + else result.scan_scope + ) + (report_dir / "stdout.log").write_text(result.stdout, encoding="utf-8") (report_dir / "stderr.log").write_text(result.stderr, encoding="utf-8") report_path = report_dir / "report.md" @@ -538,7 +611,7 @@ def _run_single_skill( cost_usd=result.cost_usd, target_commit=target_commit, # Memory Bank: persisted for incremental diff rescans. memory_enabled=memory_enabled, - scan_scope=result.scan_scope, + scan_scope=effective_scope, ) except BaseException: # BaseException so Ctrl+C mid-run is recorded too; re-raised @@ -557,6 +630,7 @@ def _run_single_skill( except Exception: logger.exception("Failed to record documentation coverage for run %s", run_uuid) + gate_findings: tuple[GateFinding, ...] = () if result.status == "success": _try_cloud_sync(repo, run_uuid) output_type = skill.output_type # #79: a custom skill may reuse a built-in's lifecycle @@ -573,11 +647,49 @@ def _run_single_skill( report_text=report_text, workdir=target_ctx.local_path, stack=stack, - scan_scope=result.scan_scope, + scan_scope=effective_scope, close_stale=skill.is_builtin, ) + markers = scope_markers(report_text) + scopes: dict[str, str] = {} + rows = [ + row for _skill_id, row in repo.list_structured_findings( + skill_ids=[output_type], project_id=project_id, status=None + ) + if row.get("last_seen_run_id") == completed_run.id + ] + for row in rows: + fingerprint = str(row["fingerprint"]) + title = str(row.get("title") or row.get("issue") or row.get("secret_type") or "").lower() + marker = markers.get(title) or markers.get(str(row.get("current_ref") or "").lower()) + scopes[fingerprint] = marker or path_in_scope(row.get("location_file"), changed_paths) + repo.set_finding_scopes( + skill_id=output_type, project_id=project_id, run_id=completed_run.id, scopes=scopes + ) + if baseline is not None: + accepted = {} + for fingerprint in scopes: + entry = baseline.matches(fingerprint) + if entry is not None: + accepted[fingerprint] = json.dumps( + {"reason": entry.reason, "expires": entry.expires} + ) + repo.set_finding_baselines( + skill_id=output_type, project_id=project_id, accepted=accepted + ) + gate_findings = tuple( + GateFinding( + severity=str(row.get("severity") or "").lower(), + title=str(row.get("title") or row.get("issue") or row.get("secret_type") or ""), + fingerprint=str(row["fingerprint"]), + scope=scopes[str(row["fingerprint"])], + ) + for row in rows + ) except Exception: logger.exception("Failed to update %s finding lifecycle for run %s", skill.id, run_uuid) + if not gate_findings: + gate_findings = _gate_findings_from_report(report_text, changed_paths) return RunOutcome( run_uuid=run_uuid, @@ -598,6 +710,7 @@ def _run_single_skill( info_count=severity.info, failure_reason=failure_reason, context_sources=context_records, + gate_findings=gate_findings, ) finally: repo.close() @@ -623,6 +736,9 @@ def execute_runs( project_id: int | None = None, project_display_name: str | None = None, assessment_application_id: str | None = None, + changed_since: str | None = None, + changed_files: str | None = None, + baseline: Baseline | None = None, ) -> list[RunOutcome]: """Run each skill in `skill_ids` concurrently against `agent_id`. @@ -675,6 +791,16 @@ def execute_runs( repo = repo or RunRepository() try: resolved = resolve_target(target) + # #109: fail before creating a project/assessment or calling any + # agent when a local diff scope can't be resolved. A remote target + # can only supply a CI-computed path list, not a ref. + if changed_since or changed_files: + validate_diff_scope( + target=target, + changed_since=changed_since, + changed_files=changed_files, + workdir=resolved.path if resolved.kind is TargetKind.LOCAL else None, + ) if project_id is None: project_id = repo.upsert_project( identifier=resolved.display_name, @@ -702,12 +828,17 @@ def execute_runs( context_brief = build_context_brief(context_sources, mcp_servers) if context_sources else None with _target_workdir(resolved) as workdir: + changed_paths = resolved_changed_paths( + workdir=workdir, changed_since=changed_since, changed_files=changed_files + ) target_ctx = TargetContext( kind=resolved.kind.value, # type: ignore[arg-type] local_path=workdir, display_source=resolved.display_name, confluence_urls=confluence_urls, context_brief=context_brief, + changed_paths=tuple(changed_paths) if changed_paths is not None else None, + diff_ref=changed_since, ) # Once per target, not per skill: every skill scans the same tree. stack = detect_stack(workdir) @@ -730,6 +861,8 @@ def execute_runs( assessment_id=assessment_id, exclude_paths=exclude_paths, stack=stack, + changed_paths=changed_paths, + baseline=baseline, ) for skill_id in skill_ids ] diff --git a/src/secfoo/skills/renderer.py b/src/secfoo/skills/renderer.py index 8ad13fa..0ebc406 100644 --- a/src/secfoo/skills/renderer.py +++ b/src/secfoo/skills/renderer.py @@ -815,6 +815,37 @@ class TargetContext: display_source: str confluence_urls: list[str] = field(default_factory=list) context_brief: ContextBrief | None = None + # #109: paths touched by this PR (None = full scan). Kept on the + # immutable context so every concurrent skill renders the same brief. + changed_paths: tuple[str, ...] | None = None + diff_ref: str | None = None + + +def _diff_section(target: TargetContext) -> str | None: + if target.changed_paths is None: + return None + if not target.changed_paths: + return ( + "## Changed files (diff scope)\n" + f"No files changed relative to `{target.diff_ref or 'the supplied list'}`. " + "Report anything you find, but do not invent changes." + ) + listed = "\n".join(f"- `{path}`" for path in target.changed_paths[:200]) + more = "" + if len(target.changed_paths) > 200: + more = f"\n... and {len(target.changed_paths) - 200} more changed paths." + return ( + "## Changed files (diff scope)\n" + f"Focus this review on the paths changed relative to `{target.diff_ref or 'the supplied list'}`, " + "and on the code that calls them. The rest of the repository is context: " + "read it to understand the change, but report issues in unchanged files only " + "when they are directly relevant to the change.\n" + f"{listed}{more}\n" + "In each Detailed Findings entry, add a line `Scope: changed` when the " + "finding is in one of these paths, or `Scope: context` when it is in an " + "unchanged path. This lets CI apply `--fail-scope changed` without " + "hiding the finding." + ) def _target_section(target: TargetContext) -> str: @@ -935,6 +966,9 @@ def render_prompt( _target_section(target), _exclude_section(exclude_paths), ] + diff_section = _diff_section(target) + if diff_section: + sections.append(diff_section) additional_context = _additional_context_section(target) if additional_context: sections.append(additional_context) diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index f9fb016..defd8d2 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -186,6 +186,8 @@ class SastFindingRecord: reviewed_by: str | None = None reviewed_at: str | None = None locations: str | None = None + scope: str = "changed" # #109: 'changed' or 'context' for a diff-aware run + baseline_accepted: str | None = None # #109: JSON {"reason", "expires"} project_display_name: str | None = None def sites(self) -> list[dict]: @@ -220,6 +222,8 @@ class ScaFindingRecord: last_seen_at: str closed_in_run_id: int | None closed_at: str | None + scope: str = "changed" # #109: SCA has no file path, so always 'changed' + baseline_accepted: str | None = None # #109: JSON {"reason", "expires"} project_display_name: str | None = None @@ -250,6 +254,8 @@ class SecretFindingRecord: closed_in_run_id: int | None closed_at: str | None locations: str | None = None + scope: str = "changed" # #109: 'changed' or 'context' for a diff-aware run + baseline_accepted: str | None = None # #109: JSON {"reason", "expires"} project_display_name: str | None = None diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index f7f5e88..ab8ce8d 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -100,6 +100,8 @@ def use_db_path(path: Path): } _SAST_FINDINGS_MIGRATIONS = { + "baseline_accepted": "ALTER TABLE sast_findings ADD COLUMN baseline_accepted TEXT", + "scope": "ALTER TABLE sast_findings ADD COLUMN scope TEXT NOT NULL DEFAULT 'changed'", "code_region_hash": "ALTER TABLE sast_findings ADD COLUMN code_region_hash TEXT", "language": "ALTER TABLE sast_findings ADD COLUMN language TEXT", "framework": "ALTER TABLE sast_findings ADD COLUMN framework TEXT", @@ -117,9 +119,18 @@ def use_db_path(path: Path): } _SECRET_FINDINGS_MIGRATIONS = { + "baseline_accepted": "ALTER TABLE secret_findings ADD COLUMN baseline_accepted TEXT", + "scope": "ALTER TABLE secret_findings ADD COLUMN scope TEXT NOT NULL DEFAULT 'changed'", "locations": "ALTER TABLE secret_findings ADD COLUMN locations TEXT", } +# SCA has no file path, so a diff scan can never mark one of its findings as +# context; the column still exists so exports share one shape across skills. +_SCA_FINDINGS_MIGRATIONS = { + "baseline_accepted": "ALTER TABLE sca_findings ADD COLUMN baseline_accepted TEXT", + "scope": "ALTER TABLE sca_findings ADD COLUMN scope TEXT NOT NULL DEFAULT 'changed'", +} + SAST_REVIEW_STATUSES = ("confirmed", "false_positive", "accepted_risk") # Skill id -> its per-finding lifecycle table. Every one of these tables @@ -224,6 +235,12 @@ def _migrate(self) -> None: for column, ddl in _SECRET_FINDINGS_MIGRATIONS.items(): if column not in existing_secret_cols: self._add_column(ddl) + existing_sca_cols = { + row["name"] for row in self._conn.execute("PRAGMA table_info(sca_findings)").fetchall() + } + for column, ddl in _SCA_FINDINGS_MIGRATIONS.items(): + if column not in existing_sca_cols: + self._add_column(ddl) self._conn.commit() self._backfill_locations() self._migrate_attachment_kind_check() @@ -1639,6 +1656,43 @@ def close_stale_findings( self._conn.execute(query, params) self._conn.commit() + def set_finding_scopes( + self, *, skill_id: str, project_id: int, run_id: int, scopes: dict[str, str] + ) -> None: + """#109: tag the findings seen by a diff-aware run as 'changed' or + 'context'. A fingerprint absent from `scopes` keeps its previous tag. + Matching on this run's id avoids restamping an older finding that + happens to share a fingerprint from a previous run.""" + if not scopes: + return + table = _FINDINGS_TABLES[skill_id] + for fingerprint, scope in scopes.items(): + self._conn.execute( + f"UPDATE {table} SET scope = ? " # nosec B608 -- table from a fixed dict + "WHERE project_id = ? AND fingerprint = ? AND last_seen_run_id = ?", + (scope, project_id, fingerprint, run_id), + ) + self._conn.commit() + + def set_finding_baselines( + self, *, skill_id: str, project_id: int, accepted: dict[str, str] + ) -> None: + """#109: record which findings an active baseline accepted in this + run, so the dashboard can show "Accepted in baseline" (rather than + hiding them). Values are pre-serialised JSON strings. Fingerprints + not in `accepted` are cleared: a baseline that was edited or removed + must not leave a stale badge behind.""" + table = _FINDINGS_TABLES[skill_id] + self._conn.execute( + f"UPDATE {table} SET baseline_accepted = NULL WHERE project_id = ?", # nosec B608 -- fixed table + (project_id,), + ) + self._conn.executemany( + f"UPDATE {table} SET baseline_accepted = ? WHERE project_id = ? AND fingerprint = ?", # nosec B608 -- fixed table + [(value, project_id, fingerprint) for fingerprint, value in accepted.items()], + ) + self._conn.commit() + def _upsert_finding( self, table: str, *, project_id: int, fingerprint: str, run_id: int, fields: dict[str, object] ) -> None: diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 0360a10..8a8ecaf 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -244,6 +244,13 @@ CREATE TABLE IF NOT EXISTS sast_findings ( description TEXT, -- the report's own Detailed Findings narrative, refreshed each run recommendation TEXT, status TEXT NOT NULL CHECK (status IN ('open','closed')), + -- #109: 'changed' (the PR touched this file) or 'context' (included for + -- context by a diff-aware run). Full scans mark every finding 'changed'. + scope TEXT NOT NULL DEFAULT 'changed', + -- #109: JSON {"reason", "expires"} when a run with --baseline saw this + -- finding as accepted; NULL otherwise. The dashboard shows a badge + -- rather than hiding it. Expired entries are not stored as accepted. + baseline_accepted TEXT, first_seen_run_id INTEGER NOT NULL REFERENCES runs(id), first_seen_at TEXT NOT NULL, last_seen_run_id INTEGER NOT NULL REFERENCES runs(id), @@ -282,6 +289,8 @@ CREATE TABLE IF NOT EXISTS sca_findings ( framework TEXT, construct TEXT, status TEXT NOT NULL CHECK (status IN ('open','closed')), + scope TEXT NOT NULL DEFAULT 'changed', -- #109; SCA has no file path, so always 'changed'. + baseline_accepted TEXT, -- #109; JSON {"reason", "expires"} when baselined first_seen_run_id INTEGER NOT NULL REFERENCES runs(id), first_seen_at TEXT NOT NULL, last_seen_run_id INTEGER NOT NULL REFERENCES runs(id), @@ -317,6 +326,13 @@ CREATE TABLE IF NOT EXISTS secret_findings ( framework TEXT, construct TEXT, status TEXT NOT NULL CHECK (status IN ('open','closed')), + -- #109: 'changed' (the PR touched this file) or 'context' (included for + -- context by a diff-aware run). Full scans mark every finding 'changed'. + scope TEXT NOT NULL DEFAULT 'changed', + -- #109: JSON {"reason", "expires"} when a run with --baseline saw this + -- finding as accepted; NULL otherwise. The dashboard shows a badge + -- rather than hiding it. Expired entries are not stored as accepted. + baseline_accepted TEXT, first_seen_run_id INTEGER NOT NULL REFERENCES runs(id), first_seen_at TEXT NOT NULL, last_seen_run_id INTEGER NOT NULL REFERENCES runs(id), diff --git a/src/secfoo/web/templates/activities/sast_finding_detail.html b/src/secfoo/web/templates/activities/sast_finding_detail.html index cfd1b2f..ecc4864 100644 --- a/src/secfoo/web/templates/activities/sast_finding_detail.html +++ b/src/secfoo/web/templates/activities/sast_finding_detail.html @@ -9,6 +9,7 @@ CVSS {{ "%.1f"|format(finding.cvss_score) }} ({{ finding.cvss_score | cvss_rating_label | capitalize }}) {% endif %} {% if finding.status == "closed" %}Closed{% else %}Open{% endif %} + {% if finding.baseline_accepted %}Accepted in baseline{% endif %}

{{ finding.title }}

diff --git a/src/secfoo/web/templates/activities/sast_findings_list.html b/src/secfoo/web/templates/activities/sast_findings_list.html index 69f1611..2e9a3bc 100644 --- a/src/secfoo/web/templates/activities/sast_findings_list.html +++ b/src/secfoo/web/templates/activities/sast_findings_list.html @@ -61,6 +61,7 @@

All findings

{% endif %} + {% if f.baseline_accepted %}Accepted in baseline {% endif %} {% if f.review_status == 'confirmed' %}Confirmed {% elif f.review_status == 'false_positive' %}False positive {% elif f.review_status == 'accepted_risk' %}Risk accepted diff --git a/tests/test_baseline.py b/tests/test_baseline.py new file mode 100644 index 0000000..07bc251 --- /dev/null +++ b/tests/test_baseline.py @@ -0,0 +1,93 @@ +"""#109: baseline file round-trip, expiry, and stale-entry checks.""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path + +import pytest + +from secfoo.baseline import ( + Baseline, + BaselineError, + BaselineEntry, + entries_from_rows, + stale_entries, + title_for_row, +) +from secfoo.storage.repository import RunRepository + + +def _finding_repo(tmp_path: Path) -> RunRepository: + db_path = tmp_path / "db.sqlite" + repo = RunRepository(db_path=db_path) + project_id = repo.upsert_project(identifier="/p", display_name="proj", kind="local") + run_id = repo.get_run(repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] + )).id + repo.upsert_sast_finding( + project_id=project_id, fingerprint="a", current_ref="F1", title="SQLi", severity="High", cwe="CWE-89", + owasp=None, verdict="Confirmed", location_file="app/db.py", location_line="4", cvss_vector=None, + cvss_score=None, run_id=run_id, + ) + return repo # caller owns closing it + + +def test_baseline_round_trip_preserves_reason_and_title(tmp_path: Path): + path = tmp_path / "nested" / "baseline.json" + baseline = Baseline(entries={"a": BaselineEntry("a", "sast", "high", "SQLi", reason="issue 12")}) + baseline.write(path) + loaded = Baseline.load(path) + assert loaded.entries["a"].reason == "issue 12" + assert loaded.matches("a") is not None + assert loaded.matches("unknown") is None + + +def test_expired_entries_count_again_and_are_reported(tmp_path: Path): + path = tmp_path / "baseline.json" + Baseline(entries={ + "a": BaselineEntry("a", "sast", "high", "SQLi", expires="2020-01-01"), + "b": BaselineEntry("b", "sast", "high", "XSS", expires="2999-01-01"), + }).write(path) + baseline = Baseline.load(path) + assert [entry.fingerprint for entry in baseline.expired(today=date(2026, 1, 1))] == ["a"] + assert set(baseline.active(today=date(2026, 1, 1))) == {"b"} + assert baseline.matches("a", today=date(2026, 1, 1)) is None + + +def test_invalid_baseline_is_rejected_not_silently_ignored(tmp_path: Path): + path = tmp_path / "baseline.json" + path.write_text('{"entries": [{"fingerprint": "a", "expires": "tomorrow"}]}', encoding="utf-8") + with pytest.raises(BaselineError, match="YYYY-MM-DD"): + Baseline.load(path) + + +def test_check_reports_closed_and_missing_entries(tmp_path: Path): + repo = _finding_repo(tmp_path) + baseline = Baseline(entries={ + "a": BaselineEntry("a", "sast", "high", "SQLi"), + "gone": BaselineEntry("gone", "sast", "high", "Deleted"), + }) + # An open finding is not stale; the entry with no stored finding is. + assert [(entry.fingerprint, state) for entry, state in stale_entries(repo, baseline)] == [ + ("gone", "missing") + ] + + project_id = repo.find_project_id("/p") + run_id = repo.list_sast_findings()[0].last_seen_run_id + repo.close_stale_sast_findings( + project_id=project_id, run_id=run_id, seen_fingerprints=[], closed_at="2026-01-01T00:00:00+00:00" + ) + stale = stale_entries(repo, baseline) + assert [(entry.fingerprint, state) for entry, state in stale] == [("a", "closed"), ("gone", "missing")] + repo.close() + + +def test_entries_from_rows_skips_closed_findings(): + entries = entries_from_rows([ + ("sast", {"fingerprint": "a", "status": "open", "severity": "High", "title": "SQLi"}), + ("sast", {"fingerprint": "b", "status": "closed", "severity": "Low", "title": "XSS"}), + ], reason="known", expires="2999-01-01") + assert [entry.fingerprint for entry in entries] == ["a"] + assert entries[0].reason == "known" + assert title_for_row("sca-reachability", {"package": "requests"}) == "requests" diff --git a/tests/test_cli_diff_baseline.py b/tests/test_cli_diff_baseline.py new file mode 100644 index 0000000..bf6979e --- /dev/null +++ b/tests/test_cli_diff_baseline.py @@ -0,0 +1,178 @@ +"""#109 CLI surface: diff flags, --fail-scope, baseline gates, baseline commands.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from typer.testing import CliRunner + +from secfoo.baseline import Baseline, BaselineEntry +from secfoo.cli import app +from secfoo.diff_scope import DiffScopeError +from secfoo.runner import GateFinding, RunOutcome +from secfoo.settings import Defaults, SecfooConfig +from secfoo.storage.repository import RunRepository + +runner = CliRunner() + + +def _no_config(monkeypatch): + monkeypatch.setattr("secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=[])) + + +def _outcome(findings=()) -> RunOutcome: + return RunOutcome( + run_uuid="u1", skill_id="sast", skill_name="SAST", agent_id="claude", status="success", + exit_code=0, duration_seconds=1.0, report_path="/tmp/r.md", gate_findings=tuple(findings), + critical_count=0, high_count=len(findings), + ) + + +def _seed_findings(monkeypatch, tmp_path: Path): + db_path = tmp_path / "db.sqlite" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + repo = RunRepository(db_path=db_path) + project_id = repo.upsert_project(identifier="/p", display_name="proj", kind="local") + run_id = repo.get_run(repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] + )).id + repo.upsert_sast_finding( + project_id=project_id, fingerprint="abc123", current_ref="F1", title="SQLi", severity="High", + cwe="CWE-89", owasp=None, verdict="Confirmed", location_file="app/db.py", location_line="4", + cvss_vector=None, cvss_score=None, run_id=run_id, + ) + repo.close() + + +def test_changed_flags_are_forwarded_to_the_runner(monkeypatch): + _no_config(monkeypatch) + captured = {} + + def fake_execute(**kwargs): + captured.update(kwargs) + return [_outcome()] + + monkeypatch.setattr("secfoo.cli.execute_runs", fake_execute) + result = runner.invoke(app, [ + "run", "--skill", "sast", "--agent", "claude", "--changed-files", "app/db.py\napp/views.py", + "--json", + ]) + assert result.exit_code == 0, result.output + assert captured["changed_files"] == "app/db.py\napp/views.py" + assert "changed_files" in json.loads(result.stdout)["diff_scope"] + + +def test_fail_scope_changed_ignores_context_findings(monkeypatch): + _no_config(monkeypatch) + findings = [ + GateFinding("high", "SQLi", "abc", "changed"), + GateFinding("high", "XSS in untouched file", "def", "context"), + ] + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kwargs: [_outcome(findings)]) + base = ["run", "--skill", "sast", "--agent", "claude", "--fail-on", "high"] + + all_result = runner.invoke(app, base + ["--json"]) + assert json.loads(all_result.stdout)["gates"]["findings"]["count"] == 2 + + changed_result = runner.invoke(app, base + ["--fail-scope", "changed", "--json"]) + document = json.loads(changed_result.stdout) + assert document["gates"]["findings"] == { + "threshold": "high", "count": 1, "passed": False, "scope": "changed", + } + + +def test_baseline_excludes_active_entries_but_expired_ones_count(monkeypatch, tmp_path: Path): + _no_config(monkeypatch) + path = tmp_path / "baseline.json" + Baseline(entries={ + "abc": BaselineEntry("abc", "sast", "high", "SQLi", reason="issue 42"), + "def": BaselineEntry("def", "sast", "high", "XSS", expires="2020-01-01"), + }).write(path) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kwargs: [_outcome([ + GateFinding("high", "SQLi", "abc"), GateFinding("high", "XSS", "def"), + ])]) + result = runner.invoke(app, [ + "run", "--skill", "sast", "--agent", "claude", "--fail-on", "high", + "--baseline", str(path), "--json", + ]) + document = json.loads(result.stdout) + assert document["gates"]["findings"]["count"] == 1 # only the expired entry + assert document["gates"]["findings"]["expired_entries"] == ["def"] + assert document["baseline"]["active_entries"] == 1 + assert "expired" in (result.stdout + result.stderr) + + +def test_usage_errors_are_reported_before_a_run(monkeypatch, tmp_path: Path): + _no_config(monkeypatch) + called = [] + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kwargs: called.append(1) or [_outcome()]) + result = runner.invoke(app, [ + "run", "--skill", "sast", "--changed-since", "main", "--changed-files", "app/db.py", + ]) + assert result.exit_code == 2 + assert "mutually exclusive" in result.output + + def reject(**kwargs): + raise DiffScopeError("bad ref") + + monkeypatch.setattr("secfoo.cli.validate_diff_scope", reject) + result = runner.invoke(app, ["run", "--skill", "sast", "--changed-since", "missing"]) + assert result.exit_code == 2 + assert "bad ref" in result.output + assert called == [] + + +def test_baseline_write_and_check_round_trip(monkeypatch, tmp_path: Path): + _seed_findings(monkeypatch, tmp_path) + path = tmp_path / ".secfoo" / "baseline.json" + written = runner.invoke(app, [ + "findings", "baseline", "write", str(path), "--reason", "triaged", "--expires", "2999-01-01", + ]) + assert written.exit_code == 0, written.output + baseline = Baseline.load(path) + assert baseline.entries["abc123"].reason == "triaged" + + checked = runner.invoke(app, ["findings", "baseline", "check", str(path)]) + assert checked.exit_code == 0, checked.output + assert "nothing to prune" in checked.output + + repo = RunRepository(db_path=tmp_path / "db.sqlite") + run_id = repo.list_sast_findings()[0].last_seen_run_id + repo.close_stale_sast_findings( + project_id=repo.find_project_id("/p"), run_id=run_id, seen_fingerprints=[], + closed_at="2026-01-01T00:00:00+00:00", + ) + repo.close() + checked = runner.invoke(app, ["findings", "baseline", "check", str(path)]) + assert "closed" in checked.output + + +def test_export_annotates_baseline_state_in_jsonl_and_sarif(monkeypatch, tmp_path: Path): + _seed_findings(monkeypatch, tmp_path) + path = tmp_path / "baseline.json" + Baseline(entries={"abc123": BaselineEntry("abc123", "sast", "high", "SQLi", reason="known")}).write(path) + + jsonl = runner.invoke(app, ["findings", "export", "--baseline", str(path)]) + assert jsonl.exit_code == 0, jsonl.output + record = json.loads(jsonl.stdout) + assert record["baselineState"] == "unchanged" + assert record["baseline"] == {"reason": "known", "expires": None} + + sarif = runner.invoke(app, ["findings", "export", "--format", "sarif", "--baseline", str(path)]) + assert sarif.exit_code == 0, sarif.output + assert json.loads(sarif.stdout)["runs"][0]["results"][0]["baselineState"] == "unchanged" + + no_baseline = runner.invoke(app, ["findings", "export", "--baseline", str(path), "--status", "closed"]) + assert no_baseline.stdout == "" + + +def test_run_rejects_a_bad_baseline_file(monkeypatch, tmp_path: Path): + _no_config(monkeypatch) + path = tmp_path / "bad.json" + path.write_text("{}", encoding="utf-8") + result = runner.invoke(app, ["run", "--skill", "sast", "--baseline", str(path)]) + assert result.exit_code == 2 + assert "entries" in result.output diff --git a/tests/test_diff_scope.py b/tests/test_diff_scope.py new file mode 100644 index 0000000..50ca192 --- /dev/null +++ b/tests/test_diff_scope.py @@ -0,0 +1,107 @@ +"""#109: changed-path computation, prompt brief, and scope tagging.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from secfoo.diff_scope import ( + DiffScopeError, + changed_files_from_text, + changed_paths_since, + normalize_paths, + path_in_scope, + scope_markers, + validate_diff_scope, +) +from secfoo.skills.renderer import TargetContext, render_prompt + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True) + + +@pytest.fixture +def git_repo(tmp_path: Path) -> Path: + repo = tmp_path / "repo" + repo.mkdir() + _git(repo, "init", "-q") + _git(repo, "config", "user.email", "test@example.com") + _git(repo, "config", "user.name", "Test") + (repo / "app").mkdir() + (repo / "app" / "db.py").write_text("old = 1\n", encoding="utf-8") + (repo / "app" / "views.py").write_text("view = 1\n", encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-qm", "base") + return repo + + +def test_changed_paths_since_uses_merge_base_and_committed_changes(git_repo: Path): + base = subprocess.run( + ["git", "-C", str(git_repo), "rev-parse", "HEAD"], check=True, capture_output=True, text=True + ).stdout.strip() + (git_repo / "app" / "db.py").write_text("old = 2\n", encoding="utf-8") + _git(git_repo, "add", ".") + _git(git_repo, "commit", "-qm", "change") + assert changed_paths_since(git_repo, base) == ["app/db.py"] + + +def test_changed_paths_since_includes_both_sides_of_a_rename(git_repo: Path): + base = subprocess.run( + ["git", "-C", str(git_repo), "rev-parse", "HEAD"], check=True, capture_output=True, text=True + ).stdout.strip() + _git(git_repo, "mv", "app/db.py", "app/storage.py") + _git(git_repo, "commit", "-qm", "rename") + assert changed_paths_since(git_repo, base) == ["app/db.py", "app/storage.py"] + + +def test_missing_ref_and_non_git_target_fail(git_repo: Path, tmp_path: Path): + with pytest.raises(DiffScopeError, match="does not exist"): + changed_paths_since(git_repo, "no-such-ref") + plain = tmp_path / "plain" + plain.mkdir() + with pytest.raises(DiffScopeError, match="need a git repository"): + validate_diff_scope(target=str(plain), changed_since="HEAD", changed_files=None) + with pytest.raises(DiffScopeError, match="need a git repository"): + validate_diff_scope(target=str(plain), changed_since=None, changed_files="app/db.py") + + +def test_changed_files_list_and_path_normalization(): + assert changed_files_from_text("# paths\n app/db.py \n\n\"app/views.py\"\n") == [ + "app/db.py", "app/views.py", + ] + assert normalize_paths(["./App/DB.py", "app/db.py", "", "app\\views.py"]) == [ + "app/db.py", "app/views.py", + ] + assert path_in_scope("app/db/query.py", ["app/db"]) == "changed" + assert path_in_scope("app/views.py", ["app/db"]) == "context" + assert path_in_scope("app/views.py", None) == "changed" + + +def test_explicit_scope_marker_in_report_wins(): + report = """# SAST Report + +## 3. Detailed Findings + +### [High] F1: Injection in db +Scope: context +""" + markers = scope_markers(report) + assert markers["f1"] == "context" + assert markers["injection in db"] == "context" + + +def test_prompt_names_changed_files_and_asks_for_scope_tag(tmp_path: Path): + from secfoo.skills.loader import load_skill + + target = TargetContext( + kind="local", local_path=tmp_path, display_source=str(tmp_path), + changed_paths=("app/db.py",), diff_ref="origin/main", + ) + prompt = render_prompt(load_skill("sast"), target, depth="quick") + assert "app/db.py" in prompt + assert "origin/main" in prompt + assert "Scope: context" in prompt + assert "code that calls them" in prompt diff --git a/tests/test_runner_diff_scope.py b/tests/test_runner_diff_scope.py new file mode 100644 index 0000000..50ad8b2 --- /dev/null +++ b/tests/test_runner_diff_scope.py @@ -0,0 +1,153 @@ +"""#109 runner behaviour: a diff-scoped run must not close findings it never +looked at, and must tag findings in unchanged files as context.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +from secfoo.agents.base import AgentAdapter, AgentResult +from secfoo.baseline import Baseline, BaselineEntry +from secfoo.runner import execute_runs +from secfoo.storage.repository import RunRepository +from test_runner import _patch_runner + +_VECTOR = "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N" + + +def _report(*rows: tuple[str, str, str, str]) -> str: + lines = [ + "# SAST Report", "", "## 3. Findings Register", + "| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict |", + "|----|---------|----------|-----|-------|-------------|----------|---------|", + ] + for finding_id, title, cwe, path in rows: + lines.append(f"| {finding_id} | {title} | High | {cwe} | A03:2021 | {_VECTOR} | `{path}` | Confirmed |") + return "\n".join(lines) + "\n" + + +_BOTH = _report( + ("F1", "SQL Injection in db", "CWE-89", "app/db.py:42"), + ("F2", "XSS in view", "CWE-79", "app/views.py:8"), +) +_ONLY_DB = _report(("F1", "SQL Injection in db", "CWE-89", "app/db.py:42")) + + +class _SequenceAdapter(AgentAdapter): + name = "fake" + binary = "fake-binary" + default_timeout_seconds = 30 + + def __init__(self, reports: list[str]) -> None: + self.reports = reports + + def build_command(self, prompt, *, workdir): + return ["fake-binary"] + + def is_available(self) -> bool: + return True + + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): + return AgentResult( + agent=self.name, exit_code=0, stdout="ok", stderr="", duration_seconds=0.1, + timed_out=False, status="success", raw_report=self.reports.pop(0), + ) + + +def _git_repo(tmp_path: Path) -> Path: + target = tmp_path / "target" + (target / "app").mkdir(parents=True) + (target / "app" / "db.py").write_text("x = 1\n", encoding="utf-8") + (target / "app" / "views.py").write_text("y = 1\n", encoding="utf-8") + for args in ( + ("init", "-q"), ("config", "user.email", "t@example.com"), ("config", "user.name", "T"), + ("add", "."), ("commit", "-qm", "base"), + ): + subprocess.run(["git", "-C", str(target), *args], check=True, capture_output=True, text=True) + return target + + +def test_diff_run_tags_context_findings_and_keeps_out_of_scope_findings_open(tmp_path, monkeypatch): + _patch_runner(monkeypatch, tmp_path) + target = _git_repo(tmp_path) + adapter = _SequenceAdapter([_BOTH, _BOTH, _ONLY_DB]) + monkeypatch.setattr("secfoo.runner.get_adapter", lambda agent_id: adapter) + + repo = RunRepository(db_path=tmp_path / "db.sqlite") + + def scan(changed_files: str | None = None): + return execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", + repo=repo, changed_files=changed_files, + )[0] + + scan() # a full audit: both findings open + diff = scan("app/db.py") + assert {f.scope for f in diff.gate_findings} == {"changed", "context"} + + rows = { + row["fingerprint"]: row + for _skill, row in repo.list_structured_findings(skill_ids=["sast"], status=None) + } + assert {row["scope"] for row in rows.values()} == {"changed", "context"} + assert all(row["status"] == "open" for row in rows.values()) + + # A third run that didn't look at app/views.py must not close its finding. + third = scan("app/db.py") + assert third.gate_findings and third.gate_findings[0].scope == "changed" + rows = { + row["fingerprint"]: row + for _skill, row in repo.list_structured_findings(skill_ids=["sast"], status=None) + } + assert len(rows) == 2 + assert all(row["status"] == "open" for row in rows.values()) + repo.close() + + +def test_baseline_run_marks_accepted_findings_for_the_dashboard(tmp_path, monkeypatch): + _patch_runner(monkeypatch, tmp_path) + target = _git_repo(tmp_path) + adapter = _SequenceAdapter([_BOTH]) + monkeypatch.setattr("secfoo.runner.get_adapter", lambda agent_id: adapter) + + repo = RunRepository(db_path=tmp_path / "db.sqlite") + execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", repo=repo, + ) + fingerprints = [row.fingerprint for row in repo.list_sast_findings()] + assert len(fingerprints) == 2 + + baseline = Baseline(entries={ + fingerprints[0]: BaselineEntry(fingerprints[0], "sast", "high", "SQLi", reason="issue 42"), + }) + adapter.reports = [_BOTH] + execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", repo=repo, + baseline=baseline, + ) + marked = {row.fingerprint: row.baseline_accepted for row in repo.list_sast_findings()} + assert "issue 42" in marked[fingerprints[0]] + assert marked[fingerprints[1]] is None + repo.close() + + +def test_diff_run_prompt_names_changed_files(tmp_path, monkeypatch): + _patch_runner(monkeypatch, tmp_path) + target = _git_repo(tmp_path) + captured = {} + + # Use a real adapter that records the rendered prompt. + class PromptAdapter(_SequenceAdapter): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): + captured["prompt"] = prompt + return super().run(prompt, workdir=workdir, timeout=timeout, prev_commit=prev_commit) + + monkeypatch.setattr("secfoo.runner.get_adapter", lambda agent_id: PromptAdapter([_ONLY_DB])) + repo = RunRepository(db_path=tmp_path / "db.sqlite") + execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", + repo=repo, changed_files="app/db.py", + ) + repo.close() + assert "app/db.py" in captured["prompt"] + assert "Scope: context" in captured["prompt"]