From 9e5d0cd01425d1e14207b163c734a276c9fd2885 Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Sun, 29 Nov 2026 08:17:24 +0530 Subject: [PATCH 1/2] feat(ci): add diff-aware PR scans (--changed-since/--changed-files) and findings baseline (--baseline) --- action.yml | 23 +- docs/CI.md | 37 +- docs/REFERENCE.md | 7 + examples/ci/github-actions-manual.yml | 18 +- examples/ci/gitlab-ci.yml | 14 +- src/secfoo/cli.py | 233 ++++++++++- src/secfoo/report/baseline.py | 195 +++++++++ src/secfoo/report/sarif.py | 9 +- src/secfoo/runner.py | 136 ++++++- src/secfoo/skills/renderer.py | 22 ++ src/secfoo/storage/repository.py | 111 +++++- src/secfoo/storage/schema.sql | 14 + src/secfoo/targets/diff.py | 151 +++++++ src/secfoo/web/routes/activities.py | 13 +- .../activities/sast_finding_detail.html | 6 + .../activities/sast_findings_list.html | 1 + tests/test_diff_and_baseline.py | 370 ++++++++++++++++++ 17 files changed, 1331 insertions(+), 29 deletions(-) create mode 100644 src/secfoo/report/baseline.py create mode 100644 src/secfoo/targets/diff.py create mode 100644 tests/test_diff_and_baseline.py diff --git a/action.yml b/action.yml index bbef553..09c2314 100644 --- a/action.yml +++ b/action.yml @@ -86,6 +86,17 @@ inputs: result-file: description: "Where to write the machine-readable run summary (the `--json` document)." default: "secfoo-result.json" + changed-only: + description: >- + On pull_request events, review only files changed since the PR base SHA + (--changed-since) and scope the fail gate to changed files (--fail-scope changed). + Requires checking out full history (fetch-depth: 0). + default: "false" + baseline: + description: >- + Path to a JSON baseline file (e.g. .secfoo/baseline.json). Active entries + are excluded from --fail-on and tagged baselineState: unchanged in SARIF. + default: "" outputs: exit-code: @@ -160,6 +171,9 @@ runs: IN_EXCLUDE: ${{ inputs.exclude }} IN_EXTRA_ARGS: ${{ inputs.extra-args }} IN_RESULT_FILE: ${{ inputs.result-file }} + IN_CHANGED_ONLY: ${{ inputs.changed-only }} + IN_BASELINE: ${{ inputs.baseline }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} # Non-interactive: no project-name prompt, no "scan again?" prompt. SECFOO_PROJECT_NAME: ${{ github.repository }} run: | @@ -172,6 +186,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" --fail-scope changed) + 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 +258,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=(findings export --format sarif --output "$SARIF_FILE") + [ -n "$IN_BASELINE" ] && export_args+=(--baseline "$IN_BASELINE") + secfoo "${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..fbb3863 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -112,6 +112,8 @@ and, without the Action, [examples/ci/github-actions-manual.yml](../examples/ci/ | `upload-sarif` | `true` | Upload to code scanning. | | `sarif-category` | `secfoo` | Code scanning category, so other tools' results are kept. | | `result-file` | `secfoo-result.json` | Where the `--json` document is written. | +| `changed-only` | `false` | On `pull_request` events, review only files changed since `github.event.pull_request.base.sha` (`--changed-since` + `--fail-scope changed`). Requires `fetch-depth: 0` on checkout. | +| `baseline` | | Baseline JSON file (e.g. `.secfoo/baseline.json`) to exclude known findings from `--fail-on` and set SARIF `baselineState`. | **Outputs**: `exit-code`, `critical`, `high`, `medium`, `low`, `cost-usd`, `result-file`, `sarif-file`. For example, to comment on a PR only when @@ -143,6 +145,29 @@ GitHub Advanced Security on private ones). Without it, set fail-on: high ``` +## Adopting secfoo in an existing repo + +Two features keep CI green without turning off the gate on legacy codebases: + +1. **Record a baseline once** after an initial full scan, commit it, and tighten later: + +```bash +secfoo run --skill sast --skill secret-scanning --target . +secfoo findings baseline write .secfoo/baseline.json \ + --reason "Pre-adoption backlog" --expires 2026-12-31 +``` + +On later runs, pass `--baseline .secfoo/baseline.json` (or `baseline: .secfoo/baseline.json` in the Action). Active entries are excluded from `--fail-on`, expired entries start counting again and are listed in the run summary, SARIF exports mark baselined results `baselineState: "unchanged"` (and new findings `"new"`), JSONL exports include `"baseline": {reason, expires}`, and the dashboard marks them **Accepted in baseline**. Periodically run `secfoo findings baseline check .secfoo/baseline.json` to spot closed findings that can be pruned. + +2. **Focus PRs on the diff** with `--changed-since ` (or `--changed-files ` for precomputed lists) and `--fail-scope changed`: + +```bash +secfoo run --agent api --target . --changed-since origin/main \ + --fail-on high --fail-scope changed --baseline .secfoo/baseline.json +``` + +Only changed paths (via `git diff --name-only --merge-base`) are targeted for review, out-of-scope findings keep their open/closed state, and any context finding in an unchanged file (`scope: context`) is ignored by `--fail-scope changed`. On GitHub Actions, set `changed-only: "true"` with `fetch-depth: 0`; on GitLab merge requests, use `CI_MERGE_REQUEST_DIFF_BASE_SHA`. + ## Pre-commit secfoo ships [`.pre-commit-hooks.yaml`](../.pre-commit-hooks.yaml) with two hooks: @@ -182,13 +207,21 @@ secfoo: - pip install --quiet secfoo script: - | + diff_args="" + if [ -n "${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}" ]; then + diff_args="--changed-since $CI_MERGE_REQUEST_DIFF_BASE_SHA --fail-scope changed" + fi + baseline_args="" + if [ -f .secfoo/baseline.json ]; then + baseline_args="--baseline .secfoo/baseline.json" + 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=$? + --fail-on high --max-cost 2.00 $diff_args $baseline_args > 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 --format sarif ${baseline_args:-} -o secfoo.sarif - exit ${code:-0} artifacts: when: always diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index b303ac4..fb274fb 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -324,6 +324,9 @@ 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 --format sarif --baseline .secfoo/baseline.json -o findings.sarif +secfoo findings baseline write .secfoo/baseline.json --reason "Pre-adoption" --expires 2026-12-31 +secfoo findings baseline check .secfoo/baseline.json # report closed/expired entries to prune ``` @@ -800,6 +803,10 @@ 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-scope all\|changed` | Controls `--fail-on` filtering for diff-scoped runs: `all` (default) or `changed` (excludes context findings tagged `scope: context`). | +| `--changed-since ` | Scope review to paths changed since git merge-base with ``, leaving out-of-scope findings open. Errors before runs if `` is missing or target is not a git repo. | +| `--changed-files ` | Newline-separated list of changed paths (alternative to `--changed-since`). | +| `--baseline ` | Baseline JSON file (`secfoo findings baseline write`); active matches do not trip `--fail-on`, expired entries are listed and counted again, and dashboard rows show **Accepted in baseline**. | | `--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..0c6cf37 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 - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" @@ -28,12 +30,24 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} # Keep going on exit 2 (gate tripped) so the SARIF still uploads. run: | + diff_args=() + if [ -n "${{ github.event.pull_request.base.sha }}" ]; then + diff_args+=(--changed-since "${{ github.event.pull_request.base.sha }}" --fail-scope changed) + fi + baseline_args=() + if [ -f .secfoo/baseline.json ]; then + baseline_args+=(--baseline .secfoo/baseline.json) + fi 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 \ + "${diff_args[@]}" "${baseline_args[@]}" > secfoo-result.json || echo "code=$?" >> "$GITHUB_OUTPUT" - name: Export SARIF - run: secfoo findings export --format sarif -o secfoo.sarif + run: | + export_args=(findings export --format sarif -o secfoo.sarif) + [ -f .secfoo/baseline.json ] && export_args+=(--baseline .secfoo/baseline.json) + secfoo "${export_args[@]}" - uses: github/codeql-action/upload-sarif@5895b2c9be147bc7f1c75ce72c5cb577febb1907 # v4 with: diff --git a/examples/ci/gitlab-ci.yml b/examples/ci/gitlab-ci.yml index 5c7a8d8..a1902db 100644 --- a/examples/ci/gitlab-ci.yml +++ b/examples/ci/gitlab-ci.yml @@ -20,14 +20,22 @@ secfoo: script: # Exit codes: 0 clean, 1 a run failed, 2 the --fail-on gate tripped, 3 the --max-cost gate tripped. - | + diff_args="" + if [ -n "${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}" ]; then + diff_args="--changed-since $CI_MERGE_REQUEST_DIFF_BASE_SHA --fail-scope changed" + fi + baseline_args="" + if [ -f .secfoo/baseline.json ]; then + baseline_args="--baseline .secfoo/baseline.json" + 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=$? + --fail-on high --max-cost 2.00 $diff_args $baseline_args > 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 + - secfoo findings export --format sarif ${baseline_args:-} -o secfoo.sarif + - secfoo findings export ${baseline_args:-} -o secfoo-findings.jsonl - exit ${code:-0} artifacts: when: always diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 6e49f2c..6d4cd41 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -29,6 +29,12 @@ 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.report.baseline import ( + BaselineError, + check_baseline, + load_baseline, + write_baseline, +) 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 @@ -43,6 +49,7 @@ ) from secfoo.skills.renderer import merge_excludes as _merge_excludes from secfoo.storage.repository import RunRepository +from secfoo.targets.diff import ChangedScopeError, load_changed_files from secfoo.targets.resolver import TargetResolutionError, resolve_target app = typer.Typer(name="secfoo", help="AI security review CLI: SAST, secret scanning, SCA, threat modeling and architecture review.") @@ -56,8 +63,10 @@ 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="Manage accepted findings baselines for CI gates and exports.") app.add_typer(mcp_app, name="mcp") app.add_typer(memory_app, name="memory") +findings_app.add_typer(baseline_app, name="baseline") app.add_typer(findings_app, name="findings") runtime_app = typer.Typer(name="runtime", help="Runtime evidence for SCA findings (opt-in; see docs/REFERENCE.md).") app.add_typer(runtime_app, name="runtime") @@ -183,14 +192,37 @@ 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.""" - total = 0 - for level in _SEVERITY_ORDER: - total += getattr(outcome, f"{level}_count", 0) - if level == threshold: - break - return total +class FailScope(str, Enum): + ALL = "all" + CHANGED = "changed" + + +def _findings_at_or_above( + outcome, + threshold: str, + *, + fail_scope: str = "all", + baselined_fingerprints: set[str] | None = None, +) -> tuple[int, int]: + """Return `(counted, excluded_by_baseline)` for findings at `threshold` or worse.""" + levels = _SEVERITY_ORDER[: _SEVERITY_ORDER.index(threshold) + 1] + run_findings = getattr(outcome, "findings", ()) or () + if run_findings and (fail_scope != "all" or baselined_fingerprints is not None): + counted = 0 + excluded = 0 + for item in run_findings: + if item.get("severity") not in levels: + continue + if fail_scope == "changed" and item.get("scope") == "context": + continue + fp = item.get("fingerprint") or "" + if baselined_fingerprints and fp and fp in baselined_fingerprints: + excluded += 1 + continue + counted += 1 + return counted, excluded + total = sum(getattr(outcome, f"{level}_count", 0) for level in levels) + return total, 0 class AssessmentTypeId(str, Enum): @@ -366,6 +398,25 @@ def run( "(critical|high|medium|low). Falls back to [defaults].fail_on in " "~/.secfoo/config.toml; unset means findings never fail the command.", ), + fail_scope: FailScope = typer.Option( + FailScope.ALL, + "--fail-scope", + help="Which findings count toward --fail-on when scanning a diff: " + "all (default) or changed (ignore findings tagged scope: context).", + ), + changed_since: Annotated[str | None, typer.Option( + "--changed-since", + help="Focus review on paths changed since git ref (via git diff --merge-base), " + "leaving out-of-scope findings open.", + )] = None, + changed_files: Annotated[Path | None, typer.Option( + "--changed-files", + help="File containing newline-separated changed paths (for CI runners with precomputed diffs).", + )] = None, + baseline: Annotated[Path | None, typer.Option( + "--baseline", + help="JSON baseline file (.secfoo/baseline.json); matching active fingerprints do not trip --fail-on.", + )] = None, max_cost: float | None = typer.Option( None, "--max-cost", @@ -428,6 +479,27 @@ def run( err_console.print("[red]Error:[/] pass at least one --skill or --skill-file.") raise typer.Exit(code=2) + if changed_since is not None and changed_files is not None: + err_console.print("[red]Error:[/] pass either --changed-since or --changed-files, not both.") + raise typer.Exit(code=2) + + changed_file_list: list[str] | None = None + if changed_files is not None: + try: + changed_file_list = load_changed_files(changed_files) + except ChangedScopeError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + + active_baseline: dict = {} + expired_baseline: list = [] + if baseline is not None: + try: + _, active_baseline, expired_baseline = load_baseline(baseline) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + _confirm_untrusted_skills(skill_ids, yes=yes, json_output=json_output) # No --assessment means execute_runs() will auto-create one for this run. @@ -583,6 +655,8 @@ def handle_complete(skill_name: str, result_status: str) -> None: on_skill_complete=handle_complete, assessment_id=assessment, exclude_paths=exclude_paths, + changed_since=changed_since, + changed_files=changed_file_list, project_display_name=project_name, assessment_application_id=app_id, ) @@ -595,16 +669,40 @@ def handle_complete(skill_name: str, result_status: str) -> None: total_cost = sum(priced) if priced else None unpriced_runs = len(outcomes) - len(priced) + baselined_fps = set(active_baseline) if baseline is not None else None + if baseline is not None: + project_ids = {getattr(o, "project_id", None) for o in outcomes if getattr(o, "project_id", None) is not None} + if project_ids: + with RunRepository() as repo: + serialized = [entry.as_dict() for entry in active_baseline.values()] + for pid in project_ids: + repo.replace_project_baseline(project_id=pid, entries=serialized) + # Policy gates. Both are evaluated even when a run failed, so the JSON # document is complete, but a failed run always wins on exit code (1): # a gate verdict computed from a partial scan isn't trustworthy. gate_findings = None if fail_on is not None: + counts_and_excluded = [ + _findings_at_or_above( + o, + fail_on.value, + fail_scope=fail_scope.value, + baselined_fingerprints=baselined_fps, + ) + for o in outcomes + ] + gate_count = sum(c for c, _ in counts_and_excluded) + excluded_count = sum(ex for _, ex in counts_and_excluded) gate_findings = { "threshold": fail_on.value, - "count": sum(_findings_at_or_above(o, fail_on.value) for o in outcomes), + "count": gate_count, + "passed": gate_count == 0, } - gate_findings["passed"] = gate_findings["count"] == 0 + if fail_scope is not FailScope.ALL: + gate_findings["scope"] = fail_scope.value + if baseline is not None: + gate_findings["baselined_excluded"] = excluded_count gate_cost = None if max_cost is not None: gate_cost = { @@ -658,6 +756,15 @@ 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}, + "baseline": ( + { + "path": str(baseline), + "active_entries": len(active_baseline), + "expired_entries": [e.as_dict() for e in expired_baseline], + } + if baseline is not None + else None + ), "any_run_failed": any_failed, "exit_code": exit_code, } @@ -692,10 +799,25 @@ 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[/]" + extra = ( + f" ({gate_findings['baselined_excluded']} excluded by baseline)" + if gate_findings.get("baselined_excluded") + else "" + ) + scope_note = f", scope={gate_findings['scope']}" if "scope" in gate_findings else "" + console.print( + f"Findings gate (--fail-on {gate_findings['threshold']}{scope_note}): " + f"{verdict} -- {gate_findings['count']} finding(s) at or above threshold{extra}" + ) + if expired_baseline: console.print( - f"Findings gate (--fail-on {gate_findings['threshold']}): {verdict} " - f"-- {gate_findings['count']} finding(s) at or above threshold" + f"[yellow]Expired baseline entries ({len(expired_baseline)}, counted again):[/]" ) + for entry in expired_baseline: + console.print( + f" {entry.fingerprint[:12]} {entry.skill} {entry.severity} " + f"{entry.title} (expired {entry.expires})" + ) if gate_cost is not None: verdict = "[green]passed[/]" if gate_cost["passed"] else "[red]FAILED[/]" console.print( @@ -1910,6 +2032,10 @@ def findings_export( runtime_priority: Annotated[bool, typer.Option( "--runtime-priority", help="SARIF: raise findings reached in production to level 'error'.", )] = False, + baseline: Annotated[Path | None, typer.Option( + "--baseline", + help="Optional baseline JSON file; matching active findings get SARIF baselineState='unchanged' and JSONL baseline metadata.", + )] = None, ) -> None: """Export structured findings (SAST, SCA, secret scanning) as JSONL, SARIF or a GitLab report. @@ -1920,6 +2046,14 @@ def findings_export( """ from secfoo.runtime.developer import RuntimeLookup + active_baseline: dict = {} + if baseline is not None: + try: + _, active_baseline, _ = load_baseline(baseline) + 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,12 +2073,27 @@ def findings_export( record[column] = value if skill_id == "sca-reachability" and not no_runtime: record["runtime"] = runtime.as_sarif() + fp = str(record.get("fingerprint") or "") + if baseline is not None and fp in active_baseline: + b_entry = active_baseline[fp] + record["baseline"] = {"reason": b_entry.reason or "", "expires": b_entry.expires} records.append(record) for note in lookup.notes: err_console.print(f"[yellow]Note:[/] {note}") written = len(records) if format is FindingsFormat.SARIF: - text = json.dumps(findings_to_sarif(records, runtime_priority=runtime_priority), indent=2, sort_keys=True) + "\n" + text = ( + json.dumps( + findings_to_sarif( + records, + runtime_priority=runtime_priority, + baseline_active=baseline is not None, + ), + indent=2, + sort_keys=True, + ) + + "\n" + ) elif format in _GITLAB_REPORT_TYPES: report = findings_to_gitlab( records, report_type=_GITLAB_REPORT_TYPES[format], start_time=datetime.now(timezone.utc), @@ -2082,6 +2231,64 @@ 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="Destination baseline JSON path (e.g. .secfoo/baseline.json).")], + reason: Annotated[str | None, typer.Option("--reason", help="Optional reason applied to recorded entries.")] = None, + expires: Annotated[str | None, typer.Option("--expires", help="Optional expiry date (YYYY-MM-DD).")] = 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: + """Write every currently open finding to a JSON baseline file.""" + with RunRepository() as repo: + open_items = repo.list_findings_for_baseline( + skill_ids=[s.value for s in skill] or None if skill else None, + project_id=project, + status="open", + ) + try: + baseline = write_baseline(path, open_items, reason=reason, expires=expires) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + console.print(f"Wrote {len(baseline.entries)} open finding(s) to {path}.") + + +@baseline_app.command(name="check") +def findings_baseline_check( + path: Annotated[Path, typer.Argument(help="Baseline JSON file to check against current finding status.")], + json_output: Annotated[bool, typer.Option("--json", help="Print JSON report.")] = False, +) -> None: + """Report baseline entries whose finding is now closed or expired so the file can be pruned.""" + try: + baseline, _, _ = load_baseline(path) + except BaselineError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=2) from None + + with RunRepository() as repo: + all_items = repo.list_findings_for_baseline(status=None) + summary = check_baseline(baseline, all_items) + if json_output: + print(json.dumps(summary, indent=2)) + return + console.print( + f"Baseline {path}: {summary['total']} total, {summary['active']} active, " + f"{len(summary['stale_closed'])} closed/missing (prunable), {len(summary['expired'])} expired." + ) + if summary["stale_closed"]: + console.print("[yellow]Prunable (closed/missing findings):[/]") + for item in summary["stale_closed"]: + console.print(f" {item['fingerprint'][:12]} {item['skill']} {item['severity']} {item['title']}") + if summary["expired"]: + console.print("[yellow]Expired entries:[/]") + for item in summary["expired"]: + console.print( + f" {item['fingerprint'][:12]} {item['skill']} {item['severity']} " + f"{item['title']} (expired {item['expires']})" + ) + + @runtime_app.command(name="ingest") def runtime_ingest( events: Annotated[ diff --git a/src/secfoo/report/baseline.py b/src/secfoo/report/baseline.py new file mode 100644 index 0000000..3b72483 --- /dev/null +++ b/src/secfoo/report/baseline.py @@ -0,0 +1,195 @@ +"""Findings baseline read/write/expiry/pruning helpers (#109).""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from datetime import date, datetime, timezone +from pathlib import Path + + +class BaselineError(ValueError): + """Raised when a baseline file or expiry argument is missing or invalid.""" + + +@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 + ref_day = today or datetime.now(timezone.utc).date() + return date.fromisoformat(self.expires) < ref_day + + def as_dict(self) -> dict[str, object]: + data: dict[str, object] = { + "fingerprint": self.fingerprint, + "skill": self.skill, + "severity": self.severity, + "title": self.title, + } + if self.reason: + data["reason"] = self.reason + if self.expires: + data["expires"] = self.expires + return data + + +@dataclass(frozen=True) +class BaselineFile: + version: int + generated_at: str + entries: list[BaselineEntry] + + def as_dict(self) -> dict[str, object]: + return { + "version": self.version, + "generated_at": self.generated_at, + "entries": [entry.as_dict() for entry in self.entries], + } + + +def validate_expires(expires: str | None) -> str | None: + if expires is None: + return None + cleaned = expires.strip() + if not cleaned: + return None + try: + parsed = date.fromisoformat(cleaned) + except ValueError as exc: + raise BaselineError(f"Invalid --expires date {expires!r}: expected YYYY-MM-DD.") from exc + return parsed.isoformat() + + +def write_baseline( + path: Path, + open_findings: list[dict], + *, + reason: str | None = None, + expires: str | None = None, +) -> BaselineFile: + """Write every open finding's identity to `path` as JSON.""" + norm_expires = validate_expires(expires) + clean_reason = (reason or "").strip() or None + entries: list[BaselineEntry] = [] + seen_fps: set[str] = set() + for item in open_findings: + fp = str(item.get("fingerprint") or "").strip() + if not fp or fp in seen_fps: + continue + seen_fps.add(fp) + entries.append( + BaselineEntry( + fingerprint=fp, + skill=str(item.get("skill") or item.get("skill_id") or ""), + severity=str(item.get("severity") or "").lower(), + title=str(item.get("title") or ""), + reason=clean_reason, + expires=norm_expires, + ) + ) + entries.sort(key=lambda e: (e.skill, e.severity, e.fingerprint)) + baseline = BaselineFile( + version=1, + generated_at=datetime.now(timezone.utc).isoformat(), + entries=entries, + ) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(baseline.as_dict(), indent=2) + "\n", encoding="utf-8") + except OSError as exc: + raise BaselineError(f"Unable to write baseline file {path}: {exc}") from exc + return baseline + + +def load_baseline( + path: Path, *, today: date | None = None +) -> tuple[BaselineFile, dict[str, BaselineEntry], list[BaselineEntry]]: + """Load `path` and partition entries into active (by fingerprint) and expired.""" + if not path.exists() or not path.is_file(): + raise BaselineError(f"Baseline file does not exist: {path}") + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, ValueError) as exc: + raise BaselineError(f"Invalid baseline file {path}: {exc}") from exc + if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list): + raise BaselineError(f"Invalid baseline file {path}: expected object with 'entries' list.") + + entries: list[BaselineEntry] = [] + active: dict[str, BaselineEntry] = {} + expired: list[BaselineEntry] = [] + for raw in payload["entries"]: + if not isinstance(raw, dict): + raise BaselineError(f"Invalid baseline entry in {path}: expected object.") + fp = str(raw.get("fingerprint") or "").strip() + if not fp: + raise BaselineError(f"Invalid baseline entry in {path}: missing 'fingerprint'.") + exp_raw = raw.get("expires") + exp = validate_expires(str(exp_raw)) if exp_raw is not None else None + entry = BaselineEntry( + fingerprint=fp, + skill=str(raw.get("skill") or raw.get("skill_id") or ""), + severity=str(raw.get("severity") or ""), + title=str(raw.get("title") or ""), + reason=str(raw.get("reason")).strip() if raw.get("reason") else None, + expires=exp, + ) + entries.append(entry) + if entry.is_expired(today=today): + expired.append(entry) + else: + active[fp] = entry + + baseline = BaselineFile( + version=int(payload.get("version") or 1), + generated_at=str(payload.get("generated_at") or ""), + entries=entries, + ) + return baseline, active, expired + + +def check_baseline( + baseline: BaselineFile, all_findings: list[dict], *, today: date | None = None +) -> dict[str, object]: + """Compare baseline entries against stored findings to surface stale/closed/expired entries.""" + by_fp: dict[str, dict] = {} + for row in all_findings: + fp = str(row.get("fingerprint") or "").strip() + if not fp: + continue + # Prefer 'open' if multiple projects carry the same fingerprint + if fp not in by_fp or row.get("status") == "open": + by_fp[fp] = row + + stale_closed: list[dict[str, object]] = [] + expired_entries: list[dict[str, object]] = [] + active_count = 0 + for entry in baseline.entries: + rec = by_fp.get(entry.fingerprint) + is_closed = rec is None or rec.get("status") != "open" + is_exp = entry.is_expired(today=today) + if is_closed: + stale_closed.append( + { + **entry.as_dict(), + "reason_stale": "closed" if rec is not None else "missing", + } + ) + if is_exp: + expired_entries.append(entry.as_dict()) + if not is_closed and not is_exp: + active_count += 1 + + return { + "total": len(baseline.entries), + "active": active_count, + "stale_closed": stale_closed, + "expired": expired_entries, + } diff --git a/src/secfoo/report/sarif.py b/src/secfoo/report/sarif.py index 0629c98..564f868 100644 --- a/src/secfoo/report/sarif.py +++ b/src/secfoo/report/sarif.py @@ -84,7 +84,12 @@ def _locations(record: dict) -> list[dict]: return locations -def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> dict: +def findings_to_sarif( + records: list[dict], + *, + runtime_priority: bool = False, + baseline_active: bool = False, +) -> dict: """Build one run; group rules by skill, CWE and severity. Severity is part of the rule identity because GitHub reads security-severity @@ -134,6 +139,8 @@ def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> } if runtime: result["properties"] = {"secfoo": {"runtime": runtime}} + if baseline_active or "baseline" in record: + result["baselineState"] = "unchanged" if record.get("baseline") else "new" locations = _locations(record) if locations: result["locations"] = locations diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 93f3a32..b2f5ebc 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -29,7 +29,12 @@ 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 -from secfoo.report.markdown import MalformedReportError, parse_report, strip_preamble +from secfoo.report.markdown import ( + MalformedReportError, + detail_blocks, + parse_report, + strip_preamble, +) from secfoo.report.sast import SKILL_ID as SAST_SKILL_ID from secfoo.report.sast import findings_with_fingerprints from secfoo.report.sca import SKILL_ID as SCA_SKILL_ID @@ -41,6 +46,13 @@ from secfoo.skills.renderer import TargetContext, render_prompt from secfoo.stack import Stack, detect_stack, language_for_ecosystem, language_for_path from secfoo.storage.repository import RunRepository +from secfoo.targets.diff import ( + classify_finding_scope, + extract_scope_by_id, + extract_scope_from_block, + normalize_scope_path, + resolve_changed_since, +) from secfoo.targets.forge import clone_forge from secfoo.targets.github import clone_shallow from secfoo.targets.resolver import ResolvedTarget, TargetKind, resolve_target @@ -134,6 +146,9 @@ class RunOutcome: failure_reason: str | None = None # Documentation sources provided or discovered, reconciled against the report (#125). context_sources: tuple[CoverageRecord, ...] = () + project_id: int | None = None + findings: tuple[dict[str, str], ...] = () + changed_files: tuple[str, ...] | None = None def _project_display_name(resolved: ResolvedTarget) -> str: @@ -435,6 +450,91 @@ def _target_workdir(resolved: ResolvedTarget) -> Iterator[Path]: yield resolved.path +_DETAIL_SEV_HEADING_RE = re.compile( + r"^###\s*\[(?P[^\]]+)\]\s*(?:(?P[A-Za-z]+\d+)\s*:\s*)?(?P.+?)\s*$" +) +_LOCATION_FIELD_RE = re.compile(r"\*\*Location:\*\*\s*`?([^`\n:]+)") + + +def _normalize_sev_word(value: str | None) -> str: + v = (value or "").strip().lower() + return "info" if v == "informational" else v + + +def _extract_run_findings( + *, + output_type: str, + skill_id: str, + report_text: str, + workdir: Path | None, + changed_files: list[str] | None, +) -> list[dict[str, str]]: + """Extract per-finding identity + diff scope for `--baseline` and `--fail-scope` (#109).""" + scope_by_id = extract_scope_by_id(report_text) + extracted: list[dict[str, str]] = [] + if output_type == SAST_SKILL_ID: + for row in findings_with_fingerprints(report_text, workdir=workdir): + paths = [row["location_file"]] if row.get("location_file") else [] + scope = classify_finding_scope(paths, changed_files, explicit_scope=scope_by_id.get(row["id"])) + extracted.append( + { + "fingerprint": row["fingerprint"], + "skill_id": skill_id, + "severity": _normalize_sev_word(row.get("severity")), + "title": row.get("title") or row["id"], + "scope": scope, + } + ) + elif output_type == SECRET_SKILL_ID: + for row in secret_report.findings_with_fingerprints(report_text, workdir=workdir): + paths = [row["location_file"]] if row.get("location_file") else [] + scope = classify_finding_scope(paths, changed_files, explicit_scope=scope_by_id.get(row["id"])) + extracted.append( + { + "fingerprint": row["fingerprint"], + "skill_id": skill_id, + "severity": _normalize_sev_word(row.get("severity")), + "title": row.get("secret_type") or row["id"], + "scope": scope, + } + ) + elif output_type == SCA_SKILL_ID: + for row in sca_report.findings_with_fingerprints(report_text): + scope = classify_finding_scope([], changed_files, explicit_scope=scope_by_id.get(row["id"])) + extracted.append( + { + "fingerprint": row["fingerprint"], + "skill_id": skill_id, + "severity": _normalize_sev_word(row.get("severity")), + "title": f"{row.get('package')}@{row.get('version') or '?'}: {row.get('issue') or ''}".strip(), + "scope": scope, + } + ) + + if extracted: + return extracted + + for heading, body in detail_blocks(report_text): + m = _DETAIL_SEV_HEADING_RE.match(heading) + if not m: + continue + loc_m = _LOCATION_FIELD_RE.search(body) + paths = [loc_m.group(1).strip()] if loc_m else [] + fid = (m.group("id") or "").strip() + explicit = extract_scope_from_block(body) or (scope_by_id.get(fid) if fid else None) + scope = classify_finding_scope(paths, changed_files, explicit_scope=explicit) + extracted.append( + { + "fingerprint": "", + "skill_id": skill_id, + "severity": _normalize_sev_word(m.group("severity")), + "title": m.group("title").strip(), + "scope": scope, + } + ) + return extracted + + def _run_single_skill( *, skill_id: str, @@ -449,6 +549,7 @@ def _run_single_skill( on_skill_complete: Callable[[str, str], None] | None, assessment_id: int | None = None, exclude_paths: list[str] | None = None, + changed_files: list[str] | None = None, stack: Stack | None = None, model: str | None = None, max_input_tokens: int | None = None, @@ -456,7 +557,13 @@ def _run_single_skill( skill = load_skill(skill_id) memory_enabled = memory.is_active_for_agent(agent_id) prompt = render_prompt( - skill, target_ctx, depth=depth, exclude_paths=exclude_paths, memory_enabled=memory_enabled, stack=stack + skill, + target_ctx, + depth=depth, + exclude_paths=exclude_paths, + changed_files=changed_files, + memory_enabled=memory_enabled, + stack=stack, ) # A fresh connection per worker thread: sqlite3 connections may not be @@ -520,6 +627,7 @@ def _run_single_skill( if on_skill_complete: on_skill_complete(skill.name, result.status) + effective_scan_scope = changed_files if changed_files is not None else result.scan_scope repo.complete_run( run_uuid, status=result.status, @@ -538,7 +646,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_scan_scope, ) except BaseException: # BaseException so Ctrl+C mid-run is recorded too; re-raised @@ -557,6 +665,7 @@ def _run_single_skill( except Exception: logger.exception("Failed to record documentation coverage for run %s", run_uuid) + run_findings: list[dict[str, str]] = [] 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 +682,18 @@ def _run_single_skill( report_text=report_text, workdir=target_ctx.local_path, stack=stack, - scan_scope=result.scan_scope, + scan_scope=effective_scan_scope, close_stale=skill.is_builtin, ) except Exception: logger.exception("Failed to update %s finding lifecycle for run %s", skill.id, run_uuid) + run_findings = _extract_run_findings( + output_type=output_type, + skill_id=skill.id, + report_text=report_text, + workdir=target_ctx.local_path, + changed_files=changed_files, + ) return RunOutcome( run_uuid=run_uuid, @@ -598,6 +714,9 @@ def _run_single_skill( info_count=severity.info, failure_reason=failure_reason, context_sources=context_records, + project_id=project_id, + findings=tuple(run_findings), + changed_files=tuple(changed_files) if changed_files is not None else None, ) finally: repo.close() @@ -620,6 +739,8 @@ def execute_runs( on_skill_complete: Callable[[str, str], None] | None = None, assessment_id: int | None = None, exclude_paths: list[str] | None = None, + changed_since: str | None = None, + changed_files: list[str] | None = None, project_id: int | None = None, project_display_name: str | None = None, assessment_application_id: str | None = None, @@ -702,6 +823,12 @@ def execute_runs( context_brief = build_context_brief(context_sources, mcp_servers) if context_sources else None with _target_workdir(resolved) as workdir: + scoped_files: list[str] | None = None + if changed_since is not None: + scoped_files = resolve_changed_since(workdir, changed_since) + elif changed_files is not None: + scoped_files = [normalize_scope_path(p) for p in changed_files if normalize_scope_path(p)] + target_ctx = TargetContext( kind=resolved.kind.value, # type: ignore[arg-type] local_path=workdir, @@ -729,6 +856,7 @@ def execute_runs( on_skill_complete=on_skill_complete, assessment_id=assessment_id, exclude_paths=exclude_paths, + changed_files=scoped_files, stack=stack, ) for skill_id in skill_ids diff --git a/src/secfoo/skills/renderer.py b/src/secfoo/skills/renderer.py index 8ad13fa..feb8f91 100644 --- a/src/secfoo/skills/renderer.py +++ b/src/secfoo/skills/renderer.py @@ -919,12 +919,32 @@ def _memory_section(stack: Stack | None, depth: Literal["quick", "standard"]) -> return section + "\n".join(lines) +def _diff_scope_section(changed_files: list[str]) -> str: + if not changed_files: + return ( + "## Changed files (PR / diff scope)\n" + "No changed files were detected in the requested diff scope. Focus only on verifying whether any\n" + "changes affect security; tag findings outside changed files with `- **Scope:** context`." + ) + listed = "\n".join(f"- `{p}`" for p in changed_files) + return ( + "## Changed files (PR / diff scope)\n" + "Review these changed files and the code that calls or interacts with them, using the rest of the\n" + "repository as context:\n" + f"{listed}\n\n" + "Findings rooted in unchanged files outside this list are allowed when relevant, but MUST include\n" + "`- **Scope:** context` (so `scope: context`) in the finding details so CI gates can filter on changed code.\n" + "Findings in the changed files above should be tagged `- **Scope:** changed`." + ) + + def render_prompt( skill: Skill, target: TargetContext, *, depth: Literal["quick", "standard"] = "quick", exclude_paths: list[str] | None = None, + changed_files: list[str] | None = None, memory_enabled: bool = False, stack: Stack | None = None, ) -> str: @@ -935,6 +955,8 @@ def render_prompt( _target_section(target), _exclude_section(exclude_paths), ] + if changed_files is not None: + sections.append(_diff_scope_section(changed_files)) additional_context = _additional_context_section(target) if additional_context: sections.append(additional_context) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index f7f5e88..b47b044 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -7,7 +7,7 @@ import uuid from contextlib import contextmanager from contextvars import ContextVar -from datetime import datetime, timedelta, timezone +from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import TYPE_CHECKING @@ -1853,3 +1853,112 @@ def list_sast_findings( params.append(limit) rows = self._conn.execute(query, params).fetchall() return [self._row_to_sast_finding(row) for row in rows] + + # ---------- Findings baseline (#109) ---------- + + def replace_project_baseline(self, *, project_id: int, entries: list[dict]) -> None: + """Persist active baseline acknowledgments for `project_id` so dashboards + mark matching findings as Accepted in baseline.""" + now = _now() + self._conn.execute("DELETE FROM finding_baselines WHERE project_id = ?", (project_id,)) + for entry in entries: + fp = str(entry.get("fingerprint") or "").strip() + if not fp: + continue + self._conn.execute( + "INSERT INTO finding_baselines (project_id, fingerprint, skill_id, reason, expires, updated_at) " + "VALUES (?, ?, ?, ?, ?, ?) " + "ON CONFLICT(project_id, fingerprint) DO UPDATE SET skill_id = excluded.skill_id, " + "reason = excluded.reason, expires = excluded.expires, updated_at = excluded.updated_at", + ( + project_id, + fp, + str(entry.get("skill") or entry.get("skill_id") or ""), + entry.get("reason"), + entry.get("expires"), + now, + ), + ) + self._conn.commit() + + def baseline_map( + self, *, project_id: int | None = None, today: date | None = None + ) -> dict[tuple[int, str], dict]: + """Map `(project_id, fingerprint)` -> active (unexpired) baseline metadata.""" + ref_day = today or datetime.now(timezone.utc).date() + query = "SELECT project_id, fingerprint, skill_id, reason, expires FROM finding_baselines" + params: list[object] = [] + if project_id is not None: + query += " WHERE project_id = ?" + params.append(project_id) + rows = self._conn.execute(query, params).fetchall() + result: dict[tuple[int, str], dict] = {} + for row in rows: + exp = row["expires"] + if exp: + try: + if date.fromisoformat(exp) < ref_day: + continue + except ValueError: + continue + result[(row["project_id"], row["fingerprint"])] = { + "skill_id": row["skill_id"], + "reason": row["reason"], + "expires": exp, + } + return result + + def list_findings_for_baseline( + self, + *, + skill_ids: list[str] | None = None, + project_id: int | None = None, + status: str | None = None, + ) -> list[dict]: + """Collect normalized finding dicts across structured findings tables (plus + generic_findings when present) for `baseline write/check`.""" + items: list[dict] = [] + for skill_id, row in self.list_structured_findings( + skill_ids=skill_ids, project_id=project_id, status=status + ): + if skill_id == "sca-reachability": + title = f"{row.get('package')}@{row.get('version') or '?'}: {row.get('issue') or row.get('cve') or ''}".strip() + else: + title = row.get("title") or row.get("secret_type") or skill_id + items.append( + { + "fingerprint": row["fingerprint"], + "skill": skill_id, + "severity": str(row.get("severity") or "").lower(), + "title": str(title), + "status": row.get("status", "open"), + "project_id": row.get("project_id"), + } + ) + has_generic = self._conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'generic_findings'" + ).fetchone() + if has_generic is not None: + query = "SELECT project_id, skill_id, fingerprint, title, severity, status FROM generic_findings WHERE 1=1" + params: list[object] = [] + if project_id is not None: + query += " AND project_id = ?" + params.append(project_id) + if status is not None: + query += " AND status = ?" + params.append(status) + if skill_ids: + query += f" AND skill_id IN ({','.join('?' * len(skill_ids))})" # nosec B608 -- fixed placeholders + params.extend(skill_ids) + for row in self._conn.execute(query, params).fetchall(): + items.append( + { + "fingerprint": row["fingerprint"], + "skill": row["skill_id"], + "severity": str(row["severity"] or "").lower(), + "title": str(row["title"] or ""), + "status": row["status"], + "project_id": row["project_id"], + } + ) + return items diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 0360a10..fd466b8 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -260,6 +260,20 @@ CREATE TABLE IF NOT EXISTS sast_findings ( CREATE INDEX IF NOT EXISTS idx_sast_findings_project_status ON sast_findings(project_id, status); +-- #109: baseline acceptance state recorded when `secfoo run --baseline` runs, +-- allowing the dashboard to label acknowledged findings "Accepted in baseline" +-- while keeping them open and visible. +CREATE TABLE IF NOT EXISTS finding_baselines ( + project_id INTEGER NOT NULL REFERENCES projects(id), + fingerprint TEXT NOT NULL, + skill_id TEXT NOT NULL DEFAULT '', + reason TEXT, + expires TEXT, + updated_at TEXT NOT NULL, + PRIMARY KEY (project_id, fingerprint) +); + + -- SCA (sca-reachability) per-finding lifecycle -- same open/closed model -- as sast_findings, keyed by report/sca.py:fingerprint_for_row (ecosystem -- + package [+ advisory ID]), never by the model's issue prose. diff --git a/src/secfoo/targets/diff.py b/src/secfoo/targets/diff.py new file mode 100644 index 0000000..b3ade79 --- /dev/null +++ b/src/secfoo/targets/diff.py @@ -0,0 +1,151 @@ +"""Diff-aware PR/branch file scoping for `--changed-since` and `--changed-files` (#109).""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +from secfoo.report.markdown import MalformedReportError, detail_blocks, parse_report +from secfoo.targets.resolver import TargetResolutionError + +_SCOPE_LINE_RE = re.compile(r"\*\*Scope:\*\*\s*`?(changed|context)\b", re.IGNORECASE) +_PLAIN_SCOPE_RE = re.compile(r"(?:^|\n)\s*(?:-\s*)?scope\s*:\s*`?(changed|context)\b", re.IGNORECASE) + + +class ChangedScopeError(TargetResolutionError): + """Raised when `--changed-since` or `--changed-files` cannot be resolved.""" + + +def normalize_scope_path(path: str | None) -> str: + """Normalize repo-relative POSIX paths for cross-platform diff matching.""" + cleaned = (path or "").strip().replace("\\", "/") + while cleaned.startswith("./"): + cleaned = cleaned[2:] + return cleaned.lstrip("/") + + +def _run_git(workdir: Path, *args: str) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "-C", str(workdir), *args], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise ChangedScopeError(f"git command failed in {workdir}: {exc}") from exc + + +def resolve_changed_since(workdir: Path, ref: str) -> list[str]: + """Return sorted relative changed paths in `workdir` against merge-base with `ref`. + + Uses `--no-renames` so renamed files report both the old path (allowing + stale findings on that path to close cleanly) and the new path. Raises + `ChangedScopeError` before any skill runs if `workdir` is not a git repo + or `ref` does not resolve. + """ + ref = (ref or "").strip() + if not ref or ref.startswith("-"): + raise ChangedScopeError(f"Invalid --changed-since git ref: {ref!r}") + + inside = _run_git(workdir, "rev-parse", "--is-inside-work-tree") + if inside.returncode != 0 or inside.stdout.strip().lower() != "true": + raise ChangedScopeError(f"--changed-since requires a git repository target; {workdir} is not a git repo.") + + verify = _run_git(workdir, "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}") + if verify.returncode != 0: + raise ChangedScopeError(f"Git ref {ref!r} does not exist in {workdir}.") + + diff = _run_git(workdir, "diff", "--name-only", "--no-renames", "-z", "--merge-base", ref) + if diff.returncode != 0: + mb = _run_git(workdir, "merge-base", "HEAD", ref) + if mb.returncode != 0 or not mb.stdout.strip(): + raise ChangedScopeError(f"Could not compute merge-base between HEAD and {ref!r} in {workdir}.") + base_sha = mb.stdout.strip().splitlines()[0] + diff = _run_git(workdir, "diff", "--name-only", "--no-renames", "-z", base_sha) + if diff.returncode != 0: + raise ChangedScopeError(f"git diff failed for ref {ref!r}: {diff.stderr.strip()}") + + untracked = _run_git(workdir, "ls-files", "--others", "--exclude-standard", "-z") + changed: set[str] = set() + for token in diff.stdout.split("\0"): + norm = normalize_scope_path(token) + if norm: + changed.add(norm) + if untracked.returncode == 0: + for token in untracked.stdout.split("\0"): + norm = normalize_scope_path(token) + if norm: + changed.add(norm) + return sorted(changed) + + +def load_changed_files(path: Path) -> list[str]: + """Read newline-separated changed paths from `path`, preserving uniqueness.""" + if not path.exists() or not path.is_file(): + raise ChangedScopeError(f"--changed-files path does not exist or is not a file: {path}") + try: + raw = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + raise ChangedScopeError(f"Unable to read --changed-files {path}: {exc}") from exc + + seen: set[str] = set() + result: list[str] = [] + for line in raw.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + norm = normalize_scope_path(stripped) + if norm and norm not in seen: + seen.add(norm) + result.append(norm) + return result + + +def extract_scope_from_block(body: str) -> str | None: + """Parse an explicit `- **Scope:** context|changed` tag from a finding body.""" + match = _SCOPE_LINE_RE.search(body or "") + if match: + return match.group(1).lower() + plain = _PLAIN_SCOPE_RE.search(body or "") + if plain: + return plain.group(1).lower() + return None + + +def extract_scope_by_id(report_markdown: str) -> dict[str, str]: + """Map finding ID (e.g. `F1`, `S2`) -> explicit `changed` or `context` scope.""" + try: + parsed = parse_report(report_markdown) + except MalformedReportError: + return {} + scopes: dict[str, str] = {} + id_re = re.compile(r"^###\s*\[[^\]]+\]\s*([A-Za-z]+\d+)\s*:", re.IGNORECASE) + for heading, body in detail_blocks(parsed): + m = id_re.match(heading) + if not m: + continue + scope = extract_scope_from_block(body) + if scope: + scopes[m.group(1)] = scope + return scopes + + +def classify_finding_scope( + paths: list[str], + changed_files: list[str] | None, + *, + explicit_scope: str | None = None, +) -> str: + """Return `'changed'` or `'context'` for one finding under a scoped run.""" + if explicit_scope in {"changed", "context"}: + return explicit_scope + if changed_files is None: + return "changed" + normalized_paths = [normalize_scope_path(p) for p in paths if normalize_scope_path(p)] + if not normalized_paths: + return "changed" + changed_set = {normalize_scope_path(p) for p in changed_files if normalize_scope_path(p)} + return "changed" if any(p in changed_set for p in normalized_paths) else "context" diff --git a/src/secfoo/web/routes/activities.py b/src/secfoo/web/routes/activities.py index 34f0ea4..020f390 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -304,6 +304,7 @@ def keep(f) -> bool: findings = by_status.get(status) if findings is None: findings = [f for f in repo.list_sast_findings(project_id=project_id, status=status, search=q or None) if keep(f)] + baseline_map = repo.baseline_map(project_id=project_id) filters = { "project_id": project_id, @@ -318,6 +319,7 @@ def keep(f) -> bool: { "projects": projects, "findings": findings, + "baseline_map": baseline_map, "selected_status": status, "selected_project_id": project_id, "search": q or "", @@ -338,12 +340,19 @@ def keep(f) -> bool: def sast_finding_detail(request: Request, fingerprint: str): with RunRepository() as repo: findings = repo.list_sast_findings() - finding = next((f for f in findings if f.fingerprint == fingerprint), None) + finding = next((f for f in findings if f.fingerprint == fingerprint), None) + baseline_entry = ( + repo.baseline_map(project_id=finding.project_id).get((finding.project_id, finding.fingerprint)) + if finding is not None + else None + ) if finding is None: raise HTTPException(status_code=404, detail="Finding not found") return templates.TemplateResponse( - request, "activities/sast_finding_detail.html", {"finding": finding} + request, + "activities/sast_finding_detail.html", + {"finding": finding, "baseline_entry": baseline_entry}, ) diff --git a/src/secfoo/web/templates/activities/sast_finding_detail.html b/src/secfoo/web/templates/activities/sast_finding_detail.html index cfd1b2f..6371426 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 @@ <span class="badge {{ finding.cvss_score | cvss_rating_label | cvss_badge }}">CVSS {{ "%.1f"|format(finding.cvss_score) }} ({{ finding.cvss_score | cvss_rating_label | capitalize }})</span> {% endif %} {% if finding.status == "closed" %}<span class="badge badge--success">Closed</span>{% else %}<span class="badge badge--error">Open</span>{% endif %} + {% if baseline_entry %}<span class="badge badge--neutral">Accepted in baseline</span>{% endif %} <h1 class="u-m-0">{{ finding.title }}</h1> </div> <p class="ds-body u-color-text-muted"> @@ -95,6 +96,11 @@ <h4 class="card__title">Lifecycle</h4> {% if finding.status == "closed" %} <p class="ds-body">Closed: {{ finding.closed_at | fmt_time }}</p> {% endif %} + {% if baseline_entry %} + <p class="ds-caption u-color-text-muted u-mt-2"> + Accepted in baseline{% if baseline_entry.reason %}: {{ baseline_entry.reason }}{% endif %}{% if baseline_entry.expires %} (expires {{ baseline_entry.expires }}){% endif %} + </p> + {% endif %} </div> </div> </div> diff --git a/src/secfoo/web/templates/activities/sast_findings_list.html b/src/secfoo/web/templates/activities/sast_findings_list.html index 69f1611..6eef286 100644 --- a/src/secfoo/web/templates/activities/sast_findings_list.html +++ b/src/secfoo/web/templates/activities/sast_findings_list.html @@ -65,6 +65,7 @@ <h1>All findings</h1> {% elif f.review_status == 'false_positive' %}<span class="badge badge--neutral">False positive</span> {% elif f.review_status == 'accepted_risk' %}<span class="badge badge--warning">Risk accepted</span> {% else %}<span class="ds-caption">Awaiting</span>{% endif %} + {% if baseline_map is defined and (f.project_id, f.fingerprint) in baseline_map %}<span class="badge badge--neutral">Accepted in baseline</span>{% endif %} </td> </tr> {% endfor %} diff --git a/tests/test_diff_and_baseline.py b/tests/test_diff_and_baseline.py new file mode 100644 index 0000000..f3c08a6 --- /dev/null +++ b/tests/test_diff_and_baseline.py @@ -0,0 +1,370 @@ +"""Tests for diff-aware PR scans (--changed-since / --changed-files / --fail-scope) +and findings baselines (--baseline, baseline write/check, SARIF, JSONL, dashboard) (#109). +""" +from __future__ import annotations + +import json +import subprocess +from datetime import date, timedelta +from pathlib import Path + +import pytest +import yaml +from fastapi.testclient import TestClient +from jsonschema import Draft7Validator, FormatChecker +from typer.testing import CliRunner + +from secfoo.agents.base import AgentResult +from secfoo.cli import EXIT_GATE_FAILED, app +from secfoo.report.baseline import check_baseline, load_baseline, write_baseline +from secfoo.report.sarif import findings_to_sarif +from secfoo.runner import execute_runs +from secfoo.skills.loader import load_skill +from secfoo.skills.renderer import TargetContext, render_prompt +from secfoo.storage.repository import RunRepository +from secfoo.targets.diff import ( + ChangedScopeError, + load_changed_files, + resolve_changed_since, +) +from secfoo.web.app import create_app + +cli = CliRunner(env={"COLUMNS": "300"}) + +SARIF_SCHEMA = json.loads((Path(__file__).parent / "fixtures" / "sarif-schema-2.1.0.json").read_text()) +SARIF_VALIDATOR = Draft7Validator(SARIF_SCHEMA, format_checker=FormatChecker()) + +_SAST_TWO_FILES = """# Static Application Security Testing Report + +## Executive Summary +Findings. + +## 3. Findings Register +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | SQLi in alpha | High | CWE-89 | A03:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | `app/a.py:4` | Confirmed | +| F2 | XSS in beta | High | CWE-79 | A03:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N | `app/b.py:4` | Confirmed | + +## 4. Detailed Findings + +### [HIGH] F1: SQLi in alpha +- **Severity:** High | **CWE:** CWE-89 | **OWASP:** A03:2021 | **Location:** `app/a.py:4` +- **CVSS Vector:** `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N` +- **Description:** Raw SQL in a.py. +- **Recommendation:** Parameterize query. + +### [HIGH] F2: XSS in beta +- **Severity:** High | **CWE:** CWE-79 | **OWASP:** A03:2021 | **Location:** `app/b.py:4` +- **CVSS Vector:** `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N` +- **Description:** Reflected output in b.py. +- **Recommendation:** Escape output. +""" + +_SAST_CONTEXT_AND_CHANGED = """# Static Application Security Testing Report + +## Executive Summary +Diff scan report. + +## 3. Findings Register +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | Unchecked helper in context | High | CWE-89 | A03:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | `app/b.py:4` | Confirmed | + +## 4. Detailed Findings + +### [HIGH] F1: Unchecked helper in context +- **Severity:** High | **CWE:** CWE-89 | **OWASP:** A03:2021 | **Location:** `app/b.py:4` +- **Scope:** context +- **CVSS Vector:** `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N` +- **Description:** Legacy bug in unchanged file. +- **Recommendation:** Fix caller. +""" + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True) + + +def _init_git_repo(repo: Path) -> None: + repo.mkdir(parents=True, exist_ok=True) + _git(repo, "init", "-b", "main") + _git(repo, "config", "user.name", "Tester") + _git(repo, "config", "user.email", "tester@example.com") + (repo / "app").mkdir() + (repo / "app" / "a.py").write_text("line1\nline2\nline3\nquery = 'SELECT ' + x\n", encoding="utf-8") + (repo / "app" / "b.py").write_text("line1\nline2\nline3\nhtml = f'<p>{x}</p>'\n", encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-m", "initial") + + +def test_resolve_changed_since_merge_base_renames_and_errors(tmp_path): + non_git = tmp_path / "plain" + non_git.mkdir() + with pytest.raises(ChangedScopeError): + resolve_changed_since(non_git, "main") + + repo = tmp_path / "repo" + _init_git_repo(repo) + with pytest.raises(ChangedScopeError): + resolve_changed_since(repo, "refs/heads/does-not-exist") + with pytest.raises(ChangedScopeError): + resolve_changed_since(repo, "--all") + + # Branch off initial commit, advance main separately, then rename + edit on feature branch + _git(repo, "checkout", "-b", "feat") + _git(repo, "mv", "app/a.py", "app/a_renamed.py") + (repo / "app" / "c.py").write_text("x = 1\n", encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-m", "rename and add c") + + _git(repo, "checkout", "main") + (repo / "unrelated_on_main.txt").write_text("main advance\n", encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-m", "main moved forward") + + _git(repo, "checkout", "feat") + changed = resolve_changed_since(repo, "main") + # Merge-base ignores unrelated_on_main.txt; --no-renames reports both old & new path + assert changed == ["app/a.py", "app/a_renamed.py", "app/c.py"] + + +def test_load_changed_files_and_render_prompt(tmp_path): + files_list = tmp_path / "changed.txt" + files_list.write_text("# comment\n./app/a.py\n\napp\\sub\\b.py\napp/a.py\n", encoding="utf-8") + assert load_changed_files(files_list) == ["app/a.py", "app/sub/b.py"] + with pytest.raises(ChangedScopeError): + load_changed_files(tmp_path / "missing.txt") + + prompt = render_prompt( + load_skill("sast"), + TargetContext(kind="local", local_path=tmp_path, display_source="repo"), + changed_files=["app/a.py", "app/c.py"], + ) + assert "Changed files (PR / diff scope)" in prompt + assert "- `app/a.py`" in prompt + assert "Scope:** context" in prompt + + +def test_diff_scan_leaves_out_of_scope_findings_open_and_honors_fail_scope(tmp_path, monkeypatch): + repo_dir = tmp_path / "repo" + _init_git_repo(repo_dir) + _git(repo_dir, "checkout", "-b", "pr-branch") + (repo_dir / "app" / "c.py").write_text("new_file = True\n", encoding="utf-8") + _git(repo_dir, "add", ".") + _git(repo_dir, "commit", "-m", "add c.py") + + 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) + monkeypatch.setattr("secfoo.runner._try_cloud_sync", lambda *a, **kw: None) + + reports = iter([_SAST_TWO_FILES, _SAST_CONTEXT_AND_CHANGED]) + prompts_seen: list[str] = [] + + class FakeAdapter: + name = "claude" + model_flag = None + supports_model = False + + def configure_model(self, model): + pass + + def configure_max_input_tokens(self, limit): + pass + + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): + prompts_seen.append(prompt) + return AgentResult( + agent="claude", + exit_code=0, + stdout="", + stderr="", + duration_seconds=0.5, + timed_out=False, + status="success", + raw_report=next(reports), + ) + + monkeypatch.setattr("secfoo.runner.get_adapter", lambda _aid: FakeAdapter()) + + # 1. Full scan opens F1 (app/a.py) and F2 (app/b.py) + full_outcomes = execute_runs( + skill_ids=["sast"], target=str(repo_dir), confluence_urls=[], agent_id="claude", depth="quick" + ) + assert len(full_outcomes) == 1 + with RunRepository() as repo: + open_before = repo.list_sast_findings(status="open") + assert len(open_before) == 2 + + # 2. Diff-scoped run against main (changed: app/c.py only): reports a context finding in app/b.py + # F1 in untouched app/a.py MUST remain open! + diff_outcomes = execute_runs( + skill_ids=["sast"], + target=str(repo_dir), + confluence_urls=[], + agent_id="claude", + depth="quick", + changed_since="main", + ) + assert "app/c.py" in prompts_seen[-1] + assert diff_outcomes[0].findings[0]["scope"] == "context" + + with RunRepository() as repo: + open_after = {f.location_file: f.status for f in repo.list_sast_findings()} + assert open_after["app/a.py"] == "open" + assert open_after["app/b.py"] == "open" + + # CLI fail-scope behavior over the diff outcome + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **_kw: diff_outcomes) + r_all = cli.invoke(app, ["run", "--skill", "sast", "--target", str(repo_dir), "--fail-on", "high", "--fail-scope", "all"]) + assert r_all.exit_code == EXIT_GATE_FAILED + + r_changed = cli.invoke(app, ["run", "--skill", "sast", "--target", str(repo_dir), "--fail-on", "high", "--fail-scope", "changed"]) + assert r_changed.exit_code == 0 + + +def test_changed_since_bad_ref_errors_before_running_agent(tmp_path, monkeypatch): + repo_dir = tmp_path / "repo" + _init_git_repo(repo_dir) + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + called = [] + monkeypatch.setattr("secfoo.runner.get_adapter", lambda _aid: called.append(True)) + + res = cli.invoke(app, ["run", "--skill", "sast", "--target", str(repo_dir), "--changed-since", "no-such-ref"]) + assert res.exit_code != 0 + assert "does not exist" in res.output + assert called == [] + + +def test_baseline_lifecycle_write_gate_expiry_check_sarif_jsonl_and_dashboard(tmp_path, monkeypatch): + 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) + + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/repo", "acme/repo", "github") + ru1 = repo.create_run(project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]) + repo.complete_run( + ru1, status="success", exit_code=0, duration_seconds=1.0, + report_path=None, prompt_path=None, stderr_excerpt=None, high_count=2, + ) + r1 = repo.get_run(ru1) + repo.upsert_sast_finding( + project_id=pid, fingerprint="fp-open-1", run_id=r1.id, current_ref="F1", + title="SQLi in alpha", severity="High", cwe="CWE-89", owasp="A03:2021", + verdict="Confirmed", location_file="app/a.py", location_line="4", + cvss_vector="AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", cvss_score=9.1, + ) + repo.upsert_sast_finding( + project_id=pid, fingerprint="fp-new-2", run_id=r1.id, current_ref="F2", + title="New High Bug", severity="High", cwe="CWE-79", owasp="A03:2021", + verdict="Confirmed", location_file="app/b.py", location_line="9", + cvss_vector="AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N", cvss_score=8.2, + ) + + baseline_path = tmp_path / ".secfoo" / "baseline.json" + future_day = (date.today() + timedelta(days=30)).isoformat() + past_day = (date.today() - timedelta(days=2)).isoformat() + + # Write baseline from DB with 1 finding (simulate filtering or write all then keep fp-open-1) + with RunRepository() as repo: + items = [x for x in repo.list_findings_for_baseline(status="open") if x["fingerprint"] == "fp-open-1"] + write_baseline(baseline_path, items, reason="Accepted legacy risk", expires=future_day) + _, active, expired = load_baseline(baseline_path) + assert "fp-open-1" in active and not expired + + # CLI baseline write + check roundtrip + cli_baseline = tmp_path / ".secfoo" / "all.json" + res_write = cli.invoke(app, ["findings", "baseline", "write", str(cli_baseline), "--reason", "Legacy", "--expires", future_day]) + assert res_write.exit_code == 0 + assert "2 open finding(s)" in res_write.output + + # Close fp-open-1 and verify `baseline check` flags it as prunable + with RunRepository() as repo: + ru2 = repo.create_run(project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]) + repo.complete_run(ru2, status="success", exit_code=0, duration_seconds=0.5, report_path=None, prompt_path=None, stderr_excerpt=None) + r2 = repo.get_run(ru2) + repo.close_stale_sast_findings(project_id=pid, run_id=r2.id, seen_fingerprints=["fp-new-2"], closed_at="2026-11-29T00:00:00Z") + res_check = cli.invoke(app, ["findings", "baseline", "check", str(cli_baseline), "--json"]) + assert res_check.exit_code == 0 + check_doc = json.loads(res_check.output) + assert any(entry["fingerprint"] == "fp-open-1" for entry in check_doc["stale_closed"]) + + # Reopen fp-open-1 for SARIF/JSONL export & --fail-on gate testing + with RunRepository() as repo: + repo.upsert_sast_finding( + project_id=pid, fingerprint="fp-open-1", run_id=r2.id, current_ref="F1", + title="SQLi in alpha", severity="High", cwe="CWE-89", owasp="A03:2021", + verdict="Confirmed", location_file="app/a.py", location_line="4", + cvss_vector="AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", cvss_score=9.1, + ) + + # Export SARIF with baseline -> fp-open-1 unchanged, fp-new-2 new, valid against schema + sarif_res = cli.invoke(app, ["findings", "export", "--format", "sarif", "--baseline", str(baseline_path)]) + assert sarif_res.exit_code == 0 + sarif_doc = json.loads(sarif_res.output) + SARIF_VALIDATOR.validate(sarif_doc) + states = {r["message"]["text"].splitlines()[0]: r.get("baselineState") for r in sarif_doc["runs"][0]["results"]} + assert states == {"SQLi in alpha": "unchanged", "New High Bug": "new"} + + # Export JSONL with baseline -> baseline object attached cleanly + jsonl_res = cli.invoke(app, ["findings", "export", "--format", "jsonl", "--baseline", str(baseline_path)]) + assert jsonl_res.exit_code == 0 + jsonl_rows = {json.loads(line)["fingerprint"]: json.loads(line) for line in jsonl_res.output.strip().splitlines()} + assert jsonl_rows["fp-open-1"]["baseline"] == {"expires": future_day, "reason": "Accepted legacy risk"} + assert "baseline" not in jsonl_rows["fp-new-2"] + + # CLI run --baseline gate test (active baseline excludes fp-open-1; expired baseline counts it again) + from secfoo.runner import RunOutcome + + outcome = RunOutcome( + run_uuid="u1", + skill_id="sast", + skill_name="SAST", + agent_id="claude", + status="success", + exit_code=0, + duration_seconds=1.0, + report_path=None, + high_count=1, + project_id=pid, + findings=( + {"fingerprint": "fp-open-1", "skill_id": "sast", "severity": "high", "title": "SQLi in alpha", "scope": "changed"}, + ), + ) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **_kw: [outcome]) + monkeypatch.setattr("secfoo.cli._detect_agent", lambda: "claude") + + run_ok = cli.invoke(app, ["run", "--skill", "sast", "--agent", "claude", "--target", ".", "--fail-on", "high", "--baseline", str(baseline_path)]) + assert run_ok.exit_code == 0 + + # Dashboard shows "Accepted in baseline" after run applied baseline + client = TestClient(create_app()) + assert "Accepted in baseline" in client.get("/activities/sast/findings").text + assert "Accepted in baseline" in client.get("/activities/sast/findings/fp-open-1").text + + # Expired baseline entry counts again and is listed + write_baseline(baseline_path, items, reason="Expired", expires=past_day) + run_exp = cli.invoke(app, ["run", "--skill", "sast", "--agent", "claude", "--target", ".", "--fail-on", "high", "--baseline", str(baseline_path)]) + assert run_exp.exit_code == EXIT_GATE_FAILED + assert "Expired baseline entries" in run_exp.output + assert "fp-open-1" in run_exp.output + + # Verify check_baseline reports expired entry + b_obj, _, _ = load_baseline(baseline_path) + with RunRepository() as repo: + chk = check_baseline(b_obj, repo.list_findings_for_baseline(status=None)) + assert len(chk["expired"]) == 1 + + # Verify sarif helper pure baseline_active option + pure = findings_to_sarif([{"skill_id": "sast", "title": "T"}], baseline_active=True) + SARIF_VALIDATOR.validate(pure) + assert pure["runs"][0]["results"][0]["baselineState"] == "new" + + +def test_action_yml_exposes_changed_only_and_baseline_inputs(): + action = yaml.safe_load((Path(__file__).parents[1] / "action.yml").read_text(encoding="utf-8")) + inputs = action["inputs"] + assert "changed-only" in inputs + assert "baseline" in inputs From 5e596c46c53ceeeee50b6f004f81ad9fd4f754ff Mon Sep 17 00:00:00 2001 From: aitechnology <40792067+vsn411@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:46:14 +0000 Subject: [PATCH 2/2] fix(diff): a finding's path decides its scope, not the model's tag classify_finding_scope let the report's Scope: tag override the finding's location. The tag is model output, so text in a scanned PR could get a finding in a changed file tagged context and past --fail-scope changed. Use the tag only for findings without a location. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/secfoo/targets/diff.py | 13 +++++++++---- tests/test_diff_and_baseline.py | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/secfoo/targets/diff.py b/src/secfoo/targets/diff.py index b3ade79..776c017 100644 --- a/src/secfoo/targets/diff.py +++ b/src/secfoo/targets/diff.py @@ -139,13 +139,18 @@ def classify_finding_scope( *, explicit_scope: str | None = None, ) -> str: - """Return `'changed'` or `'context'` for one finding under a scoped run.""" - if explicit_scope in {"changed", "context"}: - return explicit_scope + """Return `'changed'` or `'context'` for one finding under a scoped run. + + The finding's own paths decide whenever it has any. The model's + `Scope:` tag is used only for a finding without a location: the tag is + model output, and text in the scanned PR could otherwise talk it into + marking a finding in a changed file as `context`, taking it out of + `--fail-scope changed`. + """ if changed_files is None: return "changed" normalized_paths = [normalize_scope_path(p) for p in paths if normalize_scope_path(p)] if not normalized_paths: - return "changed" + return explicit_scope if explicit_scope in {"changed", "context"} else "changed" changed_set = {normalize_scope_path(p) for p in changed_files if normalize_scope_path(p)} return "changed" if any(p in changed_set for p in normalized_paths) else "context" diff --git a/tests/test_diff_and_baseline.py b/tests/test_diff_and_baseline.py index f3c08a6..d9432cd 100644 --- a/tests/test_diff_and_baseline.py +++ b/tests/test_diff_and_baseline.py @@ -368,3 +368,17 @@ def test_action_yml_exposes_changed_only_and_baseline_inputs(): inputs = action["inputs"] assert "changed-only" in inputs assert "baseline" in inputs + + +def test_model_scope_tag_cannot_downgrade_a_finding_in_a_changed_file(): + from secfoo.targets.diff import classify_finding_scope + + changed = ["app/a.py"] + # The path decides: a `Scope: context` tag on a changed file is ignored. + assert classify_finding_scope(["app/a.py"], changed, explicit_scope="context") == "changed" + assert classify_finding_scope(["app/b.py"], changed, explicit_scope="changed") == "context" + # Without a location the tag is all there is. + assert classify_finding_scope([], changed, explicit_scope="context") == "context" + assert classify_finding_scope([], changed) == "changed" + # A full scan has no context findings. + assert classify_finding_scope(["app/b.py"], None, explicit_scope="context") == "changed"