diff --git a/src/secfoo/agents/api.py b/src/secfoo/agents/api.py index 8c60e32..01b34b7 100644 --- a/src/secfoo/agents/api.py +++ b/src/secfoo/agents/api.py @@ -18,6 +18,7 @@ import fnmatch import os +import subprocess # nosec B404 -- fixed git argv, no shell import time from pathlib import Path from typing import TypedDict @@ -50,6 +51,10 @@ class _State(TypedDict): workdir: str model: str timeout: int + prev_commit: str | None # Memory Bank: SHA of the last scanned commit; None = full scan. + # Memory Bank: paths an incremental scan covered (files sent + files + # deleted); None = full scan. The runner only closes findings in these. + scan_scope: list[str] | None messages: list[dict] report: str attempts: int @@ -63,21 +68,75 @@ def _matches(name: str, patterns: list[str]) -> bool: return any(fnmatch.fnmatch(name, p) for p in patterns) -def collect_files(workdir: Path) -> str: - """Return every readable text file under `workdir` as one labelled string.""" +def _git(workdir: Path, *args: str, timeout: int = 30) -> subprocess.CompletedProcess[str]: + return subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "-C", str(workdir), *args], capture_output=True, text=True, timeout=timeout, check=False + ) + + +def _ensure_commit_available(workdir: Path, commit: str) -> bool: + """GitHub targets are depth-1 clones, so the previous scan's commit is + usually missing. Fetch only that commit (all a diff against it needs) + rather than unshallowing the whole history on every rescan.""" + if _git(workdir, "cat-file", "-e", f"{commit}^{{commit}}").returncode == 0: + return True + _git(workdir, "fetch", "--depth=1", "origin", commit, timeout=60) + return _git(workdir, "cat-file", "-e", f"{commit}^{{commit}}").returncode == 0 + + +def _git_changed_files(workdir: Path, prev_commit: str) -> tuple[list[str], list[str]] | None: + """Return (changed_paths, deleted_paths), relative to `workdir`, for + everything that differs between prev_commit and the files on disk now: + commits since prev_commit, uncommitted edits, and untracked files. + + Renames come back as a delete of the old path plus a new path + (--no-renames), so findings recorded against the old path are covered. + + None means the diff couldn't be computed (git missing, commit not + reachable); the caller then falls back to a full scan. + """ + try: + if not _ensure_commit_available(workdir, prev_commit): + return None + # `git diff ` (no `..HEAD`) compares against the working + # tree, so staged and unstaged edits are included, not just commits. + diff = _git(workdir, "diff", "--name-status", "--no-renames", "--relative", "-z", prev_commit) + untracked = _git(workdir, "ls-files", "--others", "--exclude-standard", "-z") + except (OSError, subprocess.SubprocessError): + return None + if diff.returncode != 0 or untracked.returncode != 0: + return None + changed: set[str] = set() + deleted: set[str] = set() + tokens = diff.stdout.split("\0") + for status, path in zip(tokens[0::2], tokens[1::2]): + if path: + (deleted if status.startswith("D") else changed).add(path) + changed.update(path for path in untracked.stdout.split("\0") if path) + return sorted(changed), sorted(deleted) + + +def _read_files(workdir: Path, *, changed_only: list[str] | None = None) -> tuple[str, list[str]]: + """collect_files, plus the relative paths that actually made it into the + text (after exclusions, size limits and binary detection).""" + allowed = set(changed_only) if changed_only is not None else None chunks: list[str] = [] + included: list[str] = [] total = 0 for root, dirs, files in os.walk(workdir): dirs[:] = sorted(d for d in dirs if not _matches(d, DIR_PATTERNS)) for name in sorted(files): path = Path(root) / name + rel = path.relative_to(workdir).as_posix() + if allowed is not None and rel not in allowed: + continue # incremental scan: unchanged file if _matches(name, FILE_PATTERNS) or path.stat().st_size > MAX_FILE_BYTES: continue try: text = path.read_text(encoding="utf-8") except (UnicodeDecodeError, OSError): continue # binary file (image, font, ...) - chunk = f"\n===== FILE: {path.relative_to(workdir).as_posix()} =====\n{text}\n" + chunk = f"\n===== FILE: {rel} =====\n{text}\n" total += len(chunk) if total > MAX_TOTAL_CHARS: raise ValueError( @@ -85,7 +144,14 @@ def collect_files(workdir: Path) -> str: "Use --exclude to narrow it, or use a CLI agent." ) chunks.append(chunk) - return "".join(chunks) + included.append(rel) + return "".join(chunks), included + + +def collect_files(workdir: Path, *, changed_only: list[str] | None = None) -> str: + """Return readable text files under `workdir` as one labelled string. + If `changed_only` is given, only those paths are included (incremental scan).""" + return _read_files(workdir, changed_only=changed_only)[0] def build_graph(litellm, StateGraph, START, END): @@ -93,12 +159,41 @@ def build_graph(litellm, StateGraph, START, END): run the real graph against a fake LiteLLM.""" def collect(state: _State) -> dict: - code = collect_files(Path(state["workdir"])) + workdir = Path(state["workdir"]) + prev_commit = state["prev_commit"] + scan_scope: list[str] | None = None + scope_note = "" + code = "" + if prev_commit: + diff = _git_changed_files(workdir, prev_commit) + if diff is not None: + changed, deleted = diff + code, included = _read_files(workdir, changed_only=changed) + # Go incremental only if at least one changed file is actually + # scannable. A commit touching only images, lock files or + # excluded directories would otherwise send the model no + # source at all -- and an empty report would read as "every + # open finding is fixed". + if included: + scan_scope = sorted(set(included) | set(deleted)) + scope_note = ( + f"Note: this is an incremental scan. Only files changed since " + f"commit {prev_commit[:8]} are included below.\n\n" + ) + if deleted: + scope_note += ( + "## Deleted files\nThe following files were deleted since the last scan " + "and are no longer present:\n" + "\n".join(f"- {f}" for f in deleted) + "\n\n" + ) + if scan_scope is None: + # First scan, nothing scannable changed, or git couldn't diff: full scan. + code = collect_files(workdir) content = ( - f"{state['prompt']}\n\n## Source files\nYou cannot open files. " + f"{state['prompt']}\n\n{scope_note}" + f"## Source files\nYou cannot open files. " f"The complete target source is included below.\n{code}" ) - return {"messages": [{"role": "user", "content": content}]} + return {"messages": [{"role": "user", "content": content}], "scan_scope": scan_scope} def assess(state: _State) -> dict: response = litellm.completion( @@ -149,7 +244,7 @@ def is_available(self) -> bool: def build_command(self, prompt: str, *, workdir: Path) -> list[str]: return [] # required by the base class; there is no program to launch - def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None, prev_commit: str | None = None) -> AgentResult: # Memory Bank: prev_commit triggers incremental diff scan. started = time.monotonic() _strip_key_whitespace() if not self.is_available(): @@ -170,6 +265,8 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen "workdir": str(workdir), "model": os.environ.get("SECFOO_API_MODEL", DEFAULT_MODEL), "timeout": timeout or self.default_timeout_seconds, + "prev_commit": prev_commit, # Memory Bank: None = full scan, SHA = incremental diff. + "scan_scope": None, "messages": [], "report": "", "attempts": 0, @@ -186,7 +283,9 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen cost_usd=None if final["unpriced"] else final["cost_usd"], ) report = final["report"] - return self._result("success", started, stdout=report, report=report, usage=usage) + return self._result( + "success", started, stdout=report, report=report, usage=usage, scan_scope=final.get("scan_scope") + ) def _result( self, @@ -197,6 +296,7 @@ def _result( stderr: str = "", report: str = "", usage: Usage | None = None, + scan_scope: list[str] | None = None, ) -> AgentResult: usage = usage or Usage() return AgentResult( @@ -211,6 +311,7 @@ def _result( input_tokens=usage.input_tokens, output_tokens=usage.output_tokens, cost_usd=usage.cost_usd, + scan_scope=scan_scope, ) diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 00bd3ba..91b6bf0 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -70,6 +70,10 @@ class AgentResult: input_tokens: int | None = None output_tokens: int | None = None cost_usd: float | None = None + # Memory Bank: for an incremental scan, the paths it covered (files sent + # to the model plus files deleted since the last scan). None means a + # full scan. The runner only closes findings located in these paths. + scan_scope: list[str] | None = None @dataclass(frozen=True) @@ -112,6 +116,7 @@ def detect_failure(self, stdout: str, stderr: str) -> str | None: its "no findings" report would read as a clean bill of health). Default: trust the exit code.""" return None + def extract_usage_from_stderr(self, stderr: str) -> Usage: """Pull token counts / cost out of raw stderr. Default: unknown. @@ -135,7 +140,7 @@ def _collect_usage(self, stdout: str, stderr: str) -> Usage: usage = self.extract_usage_from_stderr(stderr) return usage - def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None, prev_commit: str | None = None) -> AgentResult: # Memory Bank: prev_commit passed through; CLI adapters ignore it. if not self.is_available(): return AgentResult( agent=self.name, diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 1a483f7..4c0fff6 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -11,7 +11,7 @@ import typer from rich.console import Console from rich.progress import Progress, SpinnerColumn, TextColumn -from rich.prompt import Prompt +from rich.prompt import Confirm, Prompt from rich.table import Table from secfoo import cloud as cloud_module @@ -23,7 +23,7 @@ from secfoo.cloud import CloudConfig, CloudError from secfoo.config import CLOUD_CONFIG_PATH, attachment_dir from secfoo.cost import format_cost, format_tokens, sum_optional -from secfoo.runner import _project_display_name, execute_runs +from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs from secfoo.settings import CONFIG_PATH, ConfigError, load_config from secfoo.skills.loader import load_all_skills from secfoo.skills.renderer import merge_excludes as _merge_excludes @@ -271,6 +271,12 @@ def run( help="Don't give the agent the secfoo-memory pattern tools for this run, " "even if `secfoo memory signup/login` has configured a key.", ), + rescan: bool = typer.Option( + False, + "--rescan", + 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.", + ), ) -> None: """Run one or more security skills against a target using the chosen agent. @@ -322,6 +328,24 @@ def run( # config's list, so naming one path can't silently drop the others. exclude_paths = _merge_excludes(file_defaults.exclude, exclude) + # Memory Bank: on a terminal, ask before repeating a scan of a commit that + # was already scanned. Only here, never in execute_runs(), which the + # dashboard and CI also call with no terminal to answer. + if not rescan and _is_interactive() and not json_output: + try: + head, repeats = already_scanned_skills(skill_ids=[s.value for s in skill], target=target) + except TargetResolutionError: + head, repeats = None, [] # execute_runs reports the bad target below + if head and repeats and not Confirm.ask( + f"Commit {head[:8]} was already scanned for {', '.join(repeats)}. Scan again?", + default=False, + console=console, + ): + skill = [s for s in skill if s.value not in repeats] + if not skill: + console.print("Nothing new to scan. Use --rescan to scan this commit again.") + raise typer.Exit(code=0) + task_ids: dict[str, int] = {} # In --json mode nothing but the final document may reach stdout, so # the spinner is disabled and human-facing notes go to stderr. diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 9a63a4c..a7e194b 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -59,6 +59,50 @@ def _git_head_commit(path: Path) -> str | None: return None +def _git_tree_dirty(path: Path) -> bool: + """True if `path` has uncommitted or untracked changes (or git fails, + so a caller never treats an unknown state as "nothing changed").""" + import subprocess + + try: + result = subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "-C", str(path), "status", "--porcelain", "--", "."], + capture_output=True, text=True, timeout=10, check=False, + ) + except (OSError, subprocess.SubprocessError): + return True + return result.returncode != 0 or bool(result.stdout.strip()) + + +def already_scanned_skills( + *, skill_ids: list[str], target: str | None, repo: RunRepository | None = None +) -> tuple[str | None, list[str]]: + """Memory Bank: (HEAD SHA, skills whose last successful run already + scanned exactly this commit with a clean working tree). The CLI uses + this to ask before repeating a scan; execute_runs never prompts, since + it also runs under the dashboard and CI with no terminal. + + Local targets only: a GitHub target's HEAD isn't known without cloning + it, so it always reports nothing to skip. + """ + resolved = resolve_target(target) + if resolved.kind is not TargetKind.LOCAL or resolved.path is None: + return None, [] + head = _git_head_commit(resolved.path) + if head is None or _git_tree_dirty(resolved.path): + return head, [] + owns_repo = repo is None + repo = repo or RunRepository() + try: + project_id = repo.find_project_id(resolved.display_name) + if project_id is None: + return head, [] + return head, [s for s in skill_ids if repo.get_last_commit(project_id=project_id, skill_id=s) == head] + finally: + if owns_repo: + repo.close() + + @dataclass class RunOutcome: run_uuid: str @@ -143,6 +187,7 @@ def update_sast_findings( report_text: str, workdir: Path | None = None, stack: Stack | None = None, + scan_scope: list[str] | None = None, ) -> None: """Matches this run's Findings Register against the project's currently-open sast_findings rows by fingerprint (report/sast.py), @@ -204,11 +249,14 @@ def update_sast_findings( ) seen_fingerprints.append(row["fingerprint"]) + # scan_scope (Memory Bank incremental scan): only findings in files this + # run actually looked at can be closed; everything else stays as it was. repo.close_stale_sast_findings( project_id=project_id, run_id=run_id, seen_fingerprints=seen_fingerprints, closed_at=_closed_now(), + only_files=scan_scope, ) @@ -219,6 +267,7 @@ def update_sca_findings( run_id: int, report_text: str, stack: Stack | None = None, + scan_scope: list[str] | None = None, ) -> None: """update_sast_findings' lifecycle for the SCA Risk Register.""" seen_fingerprints = [] @@ -244,7 +293,7 @@ def update_sca_findings( seen_fingerprints.append(row["fingerprint"]) repo.close_stale_findings( SCA_SKILL_ID, project_id=project_id, run_id=run_id, seen_fingerprints=seen_fingerprints, - closed_at=_closed_now(), + closed_at=_closed_now(), only_files=scan_scope, ) @@ -256,6 +305,7 @@ def update_secret_findings( report_text: str, workdir: Path | None = None, stack: Stack | None = None, + scan_scope: list[str] | None = None, ) -> None: """update_sast_findings' lifecycle for the Secret Scanning register.""" seen_fingerprints = [] @@ -281,7 +331,7 @@ def update_secret_findings( seen_fingerprints.append(row["fingerprint"]) repo.close_stale_findings( SECRET_SKILL_ID, project_id=project_id, run_id=run_id, seen_fingerprints=seen_fingerprints, - closed_at=_closed_now(), + closed_at=_closed_now(), only_files=scan_scope, ) @@ -315,6 +365,7 @@ def update_structured_findings( report_text: str, workdir: Path | None = None, stack: Stack | None = None, + scan_scope: list[str] | None = None, ) -> None: """Dispatches one successful run's report to its skill's findings lifecycle (a no-op for skills without one). The single entry point both @@ -323,13 +374,17 @@ def update_structured_findings( region hashes or framework detection).""" if skill_id == SAST_SKILL_ID: update_sast_findings( - repo, project_id=project_id, run_id=run_id, report_text=report_text, workdir=workdir, stack=stack + repo, project_id=project_id, run_id=run_id, report_text=report_text, workdir=workdir, stack=stack, + scan_scope=scan_scope, ) elif skill_id == SCA_SKILL_ID: - update_sca_findings(repo, project_id=project_id, run_id=run_id, report_text=report_text, stack=stack) + update_sca_findings( + repo, project_id=project_id, run_id=run_id, report_text=report_text, stack=stack, scan_scope=scan_scope + ) elif skill_id == SECRET_SKILL_ID: update_secret_findings( - repo, project_id=project_id, run_id=run_id, report_text=report_text, workdir=workdir, stack=stack + repo, project_id=project_id, run_id=run_id, report_text=report_text, workdir=workdir, stack=stack, + scan_scope=scan_scope, ) @@ -393,7 +448,9 @@ def _run_single_skill( on_skill_start(skill.name) adapter = get_adapter(agent_id) - result = adapter.run(prompt, workdir=target_ctx.local_path, timeout=timeout) + # Memory Bank: look up the last successful commit so the adapter can diff and send only changed files. + prev_commit = repo.get_last_commit(project_id=project_id, skill_id=skill.id) + result = adapter.run(prompt, workdir=target_ctx.local_path, timeout=timeout, prev_commit=prev_commit) # Memory Bank: capture HEAD SHA so future runs can diff against this baseline. target_commit = _git_head_commit(target_ctx.local_path) @@ -425,6 +482,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, ) except BaseException: # BaseException so Ctrl+C mid-run is recorded too; re-raised @@ -447,6 +505,7 @@ def _run_single_skill( report_text=report_text, workdir=target_ctx.local_path, stack=stack, + scan_scope=result.scan_scope, ) except Exception: logger.exception("Failed to update %s finding lifecycle for run %s", skill.id, run_uuid) diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 77273d9..d23c568 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -43,6 +43,8 @@ class RunRecord: project_display_name: str | None = None target_commit: str | None = None # Memory Bank: git HEAD SHA at scan time. memory_enabled: int | None = None # 1/0: secfoo-memory tools wired in; NULL = unknown (older run). + # Memory Bank: paths an incremental scan covered; None = full scan. + scan_scope: list[str] | None = None @dataclass(frozen=True) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index e2fa673..92f0658 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -77,6 +77,8 @@ def use_db_path(path: Path): # Memory Bank: git HEAD SHA at scan time; foundation for incremental diff-based rescans. "target_commit": "ALTER TABLE runs ADD COLUMN target_commit TEXT", "memory_enabled": "ALTER TABLE runs ADD COLUMN memory_enabled INTEGER", + # Memory Bank: JSON list of paths an incremental scan covered; NULL = full scan. + "scan_scope": "ALTER TABLE runs ADD COLUMN scan_scope TEXT", } _ASSESSMENTS_MIGRATIONS = { @@ -94,6 +96,9 @@ def use_db_path(path: Path): # shares the open/closed + first/last-seen columns, which is what lets # close_stale_findings and list_structured_findings serve all three. _FINDINGS_TABLES = {"sast": "sast_findings", "sca-reachability": "sca_findings", "secret-scanning": "secret_findings"} +# Findings tables with a location_file column, i.e. ones an incremental +# scan's file scope can be applied to (see close_stale_findings). +_FILE_SCOPED_TABLES = frozenset({"sast_findings", "secret_findings"}) _ASSESSMENT_UPDATE_FIELDS = { "assessment_type", "status", "application_id", "sar_number", "reviewer", "review_date", "notes", @@ -315,12 +320,13 @@ def complete_run( cost_usd: float | None = None, target_commit: str | None = None, # Memory Bank: HEAD SHA of the scanned repo. memory_enabled: bool | None = None, + scan_scope: list[str] | None = None, # Memory Bank: None = full scan. ) -> None: self._conn.execute( "UPDATE runs SET status = ?, exit_code = ?, finished_at = ?, duration_seconds = ?, " "report_path = ?, prompt_path = ?, stderr_excerpt = ?, critical_count = ?, high_count = ?, " "medium_count = ?, low_count = ?, info_count = ?, input_tokens = ?, output_tokens = ?, " - "cost_usd = ?, target_commit = ?, memory_enabled = ? WHERE run_uuid = ?", + "cost_usd = ?, target_commit = ?, memory_enabled = ?, scan_scope = ? WHERE run_uuid = ?", ( status, exit_code, @@ -339,11 +345,30 @@ def complete_run( cost_usd, target_commit, None if memory_enabled is None else int(memory_enabled), + None if scan_scope is None else json.dumps(scan_scope), run_uuid, ), ) self._conn.commit() + def find_project_id(self, identifier: str) -> int | None: + """The id of an existing project, without creating one (unlike + upsert_project). Used to check for a repeat scan before running.""" + row = self._conn.execute("SELECT id FROM projects WHERE identifier = ?", (identifier,)).fetchone() + return row["id"] if row else None + + def get_last_commit(self, *, project_id: int, skill_id: str) -> str | None: + """Return the HEAD SHA from the most recent successful run for this + project+skill, or None if no prior run exists. + Used by Memory Bank to compute incremental diffs on rescans.""" + row = self._conn.execute( + "SELECT target_commit FROM runs WHERE project_id = ? AND skill_id = ? " + "AND status = 'success' AND target_commit IS NOT NULL " + "ORDER BY rowid DESC LIMIT 1", + (project_id, skill_id), + ).fetchone() + return row["target_commit"] if row else None + def mark_run_synced(self, run_uuid: str) -> None: """Records that this run has been pushed to the enterprise portal. Called by `secfoo cloud` after a successful `push_run()` -- see @@ -373,6 +398,8 @@ def _row_to_run(self, row: sqlite3.Row) -> RunRecord: data = dict(row) confluence_urls = json.loads(data.pop("confluence_urls") or "[]") project_display_name = data.pop("display_name", None) + if data.get("scan_scope") is not None: + data["scan_scope"] = json.loads(data["scan_scope"]) return RunRecord(confluence_urls=confluence_urls, project_display_name=project_display_name, **data) def total_cost_usd(self, *, project_id: int | None = None) -> float: @@ -1274,7 +1301,13 @@ def rekey_open_sast_fingerprint( self._conn.commit() def close_stale_sast_findings( - self, *, project_id: int, run_id: int, seen_fingerprints: list[str], closed_at: str + self, + *, + project_id: int, + run_id: int, + seen_fingerprints: list[str], + closed_at: str, + only_files: list[str] | None = None, ) -> None: """Closes every currently-open finding for this project NOT among `seen_fingerprints` -- i.e. whatever this run's Findings Register @@ -1282,27 +1315,49 @@ def close_stale_sast_findings( row from that run has been upserted via upsert_sast_finding. """ self.close_stale_findings( - "sast", project_id=project_id, run_id=run_id, seen_fingerprints=seen_fingerprints, closed_at=closed_at + "sast", + project_id=project_id, + run_id=run_id, + seen_fingerprints=seen_fingerprints, + closed_at=closed_at, + only_files=only_files, ) def close_stale_findings( - self, skill_id: str, *, project_id: int, run_id: int, seen_fingerprints: list[str], closed_at: str + self, + skill_id: str, + *, + project_id: int, + run_id: int, + seen_fingerprints: list[str], + closed_at: str, + only_files: list[str] | None = None, ) -> None: - """close_stale_sast_findings for any of the _FINDINGS_TABLES.""" + """close_stale_sast_findings for any of the _FINDINGS_TABLES. + + `only_files` is the scope of an incremental scan (Memory Bank): only + findings located in those files can be closed, since the run never + looked at the rest. A table with no file column (SCA) closes nothing + for an incremental run, because its findings can't be placed in or + out of the scope. + """ table = _FINDINGS_TABLES[skill_id] + if only_files is not None and (table not in _FILE_SCOPED_TABLES or not only_files): + return + query = ( + f"UPDATE {table} SET status = 'closed', closed_in_run_id = ?, closed_at = ? " # nosec B608 -- table from a fixed dict, placeholders are ? binds + "WHERE project_id = ? AND status = 'open'" + ) + params: list[object] = [run_id, closed_at, project_id] if seen_fingerprints: - placeholders = ",".join("?" * len(seen_fingerprints)) - query = ( - f"UPDATE {table} SET status = 'closed', closed_in_run_id = ?, closed_at = ? " # nosec B608 -- table from a fixed dict, placeholders are ? binds - f"WHERE project_id = ? AND status = 'open' AND fingerprint NOT IN ({placeholders})" - ) - params: list[object] = [run_id, closed_at, project_id, *seen_fingerprints] - else: - query = ( - f"UPDATE {table} SET status = 'closed', closed_in_run_id = ?, closed_at = ? " # nosec B608 -- table from a fixed dict - "WHERE project_id = ? AND status = 'open'" - ) - params = [run_id, closed_at, project_id] + query += f" AND fingerprint NOT IN ({','.join('?' * len(seen_fingerprints))})" + params.extend(seen_fingerprints) + if only_files is not None: + # Same normalisation as report.sast._normalize_path, which is + # what the stored location_file values are matched by elsewhere. + scope = sorted({path.strip().lstrip("./").lower() for path in only_files}) + query += f" AND LOWER(LTRIM(TRIM(location_file), './')) IN ({','.join('?' * len(scope))})" + params.extend(scope) self._conn.execute(query, params) self._conn.commit() diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 8357599..0d64994 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -76,7 +76,11 @@ CREATE TABLE IF NOT EXISTS runs ( -- 1 if the agent had the secfoo-memory pattern tools wired in for this -- run, 0 if not, NULL for runs from before this column existed. Lets -- evaluation compare memory-on vs memory-off runs of the same target. - memory_enabled INTEGER + memory_enabled INTEGER, + -- Memory Bank: JSON list of the paths an incremental scan covered (files + -- sent plus files deleted). NULL means a full scan. Findings lifecycle + -- only closes findings inside this set for an incremental run. + scan_scope TEXT ); -- Files manually uploaded to an assessment (AI-BOM inventories, or other diff --git a/tests/test_memory.py b/tests/test_memory.py index a6338c1..cd5282f 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -173,7 +173,7 @@ def build_command(self, prompt, *, workdir): def is_available(self) -> bool: return True - def run(self, prompt, *, workdir, timeout=None): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): _CapturingAdapter.prompts.append(prompt) return AgentResult( agent=self.name, exit_code=0, stdout="ok", stderr="", duration_seconds=0.1, diff --git a/tests/test_memory_bank.py b/tests/test_memory_bank.py new file mode 100644 index 0000000..2fc0b6a --- /dev/null +++ b/tests/test_memory_bank.py @@ -0,0 +1,376 @@ +"""Memory Bank incremental scanning (PR #22 review cases). + +The end-to-end tests use a real git repository, the real api adapter and +LangGraph graph, and a fake LiteLLM that reports a finding only for a file +it was actually shown -- so they exercise exactly what an incremental scan +sends the model and what the findings lifecycle does with the result. +""" + +from __future__ import annotations + +import subprocess +import sys +import types + +import pytest +from typer.testing import CliRunner + +from secfoo.agents import api +from secfoo.agents.api import ApiAdapter, _git_changed_files +from secfoo.cli import app +from secfoo.runner import RunOutcome, already_scanned_skills, execute_runs +from secfoo.storage.repository import RunRepository + +_HEADER = """\ +# SAST Report + +## 3. Findings Register +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +""" +_ROWS = { + "app/db.py": "| F1 | SQL Injection | High | CWE-89 | A03:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | `app/db.py:2` | Confirmed |\n", + "app/views.py": "| F2 | Reflected XSS | Medium | CWE-79 | A03:2021 | AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N | `app/views.py:2` | Confirmed |\n", +} + + +def _git(repo, *args): + subprocess.run( + ["git", "-C", str(repo), "-c", "user.email=t@example.com", "-c", "user.name=t", *args], + check=True, capture_output=True, text=True, + ) + + +def _commit_all(repo, message): + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", message) + + +@pytest.fixture +def target(tmp_path): + repo = tmp_path / "target" + (repo / "app").mkdir(parents=True) + (repo / "app" / "db.py").write_text("import sqlite3\ncur.execute('SELECT * FROM u WHERE id=' + uid)\n") + (repo / "app" / "views.py").write_text("from flask import request\nreturn '

' + request.args['q']\n") + _git(repo, "init", "-q") + _commit_all(repo, "initial") + return repo + + +@pytest.fixture +def model(monkeypatch, tmp_path): + """Fake LiteLLM: records every prompt, and reports a finding for a file + only if that file's source was in the prompt.""" + module = types.SimpleNamespace(prompts=[]) + + def _completion(**kwargs): + content = kwargs["messages"][-1]["content"] + module.prompts.append(content) + rows = "".join(row for path, row in _ROWS.items() if f"===== FILE: {path} =====" in content) + report = _HEADER + rows + "\n**Overall risk rating:** High.\n" + return types.SimpleNamespace( + choices=[types.SimpleNamespace(message=types.SimpleNamespace(content=report))], + usage=types.SimpleNamespace(prompt_tokens=len(content), completion_tokens=10), + ) + + module.completion = _completion + module.completion_cost = lambda completion_response: 0.0 + monkeypatch.setitem(sys.modules, "litellm", module) + monkeypatch.setenv("OPENAI_API_KEY", "test-key") + monkeypatch.setattr("secfoo.runner.run_dir", lambda run_uuid: tmp_path / "reports" / run_uuid) + monkeypatch.setattr("secfoo.runner.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.runner.get_adapter", lambda agent_id: ApiAdapter()) + return module + + +@pytest.fixture +def repo(tmp_path): + repo = RunRepository(db_path=tmp_path / "db.sqlite") + yield repo + repo.close() + + +def _scan(repo, target): + return execute_runs(skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="api", repo=repo) + + +def _status(repo): + """Per file: "open" if the file has an open finding, else "closed". (Editing + a file can re-key its finding -- the fingerprint includes a hash of the + surrounding code -- so one file may have a closed row and an open one.)""" + status: dict[str, str] = {} + for f in repo.list_sast_findings(): + if f.status == "open" or f.location_file not in status: + status[f.location_file] = f.status + return status + + +# -- Review item 1 ----------------------------------------------------------- + + +def test_incremental_scan_keeps_findings_in_unchanged_files_open(repo, target, model): + _scan(repo, target) + assert _status(repo) == {"app/db.py": "open", "app/views.py": "open"} + + (target / "app" / "views.py").write_text( + "from flask import request\nreturn '

' + request.args['q']\n# touched\n" + ) + _commit_all(target, "touch views only") + _scan(repo, target) + + assert "===== FILE: app/views.py" in model.prompts[-1] + assert "===== FILE: app/db.py" not in model.prompts[-1] # really incremental + # db.py was neither changed nor scanned, so its finding must stay open. + assert _status(repo) == {"app/db.py": "open", "app/views.py": "open"} + last_run = repo.list_runs()[0] + assert last_run.scan_scope == ["app/views.py"] + + +def test_incremental_scan_still_closes_a_finding_fixed_in_a_changed_file(repo, target, model): + _scan(repo, target) + (target / "app" / "views.py").write_text("from flask import request\nfrom markupsafe import escape\n") + _commit_all(target, "fix xss") + # The model no longer reports the XSS for the fixed file. + original = model.completion + + def _completion(**kwargs): + response = original(**kwargs) + message = response.choices[0].message + message.content = message.content.replace(_ROWS["app/views.py"], "") + return response + + model.completion = _completion + _scan(repo, target) + + assert _status(repo) == {"app/db.py": "open", "app/views.py": "closed"} + + +def test_findings_in_a_deleted_file_are_closed(repo, target, model): + (target / "app" / "util.py").write_text("x = 1\n") + _commit_all(target, "add util") + _scan(repo, target) + + _git(target, "rm", "-q", "app/views.py") + (target / "app" / "util.py").write_text("x = 2\n") + _commit_all(target, "delete views, touch util") + _scan(repo, target) + + assert _status(repo) == {"app/db.py": "open", "app/views.py": "closed"} + + +# -- Review item 2 ----------------------------------------------------------- + + +def test_commit_with_no_scannable_files_falls_back_to_a_full_scan(repo, target, model): + _scan(repo, target) + + (target / "logo.png").write_bytes(b"\x89PNG\r\n\x1a\n\x00\xff\xfe") + _commit_all(target, "add logo") + _scan(repo, target) + + assert "incremental scan" not in model.prompts[-1] + assert "===== FILE: app/db.py" in model.prompts[-1] + assert _status(repo) == {"app/db.py": "open", "app/views.py": "open"} + assert repo.list_runs()[0].scan_scope is None + + +# -- Review item 3 ----------------------------------------------------------- + + +def test_uncommitted_and_untracked_changes_are_sent(repo, target, model): + _scan(repo, target) + + (target / "app" / "views.py").write_text("changed but not committed\n") + (target / "app" / "new.py").write_text("untracked\n") + _scan(repo, target) + + prompt = model.prompts[-1] + assert "===== FILE: app/views.py" in prompt + assert "===== FILE: app/new.py" in prompt + assert "===== FILE: app/db.py" not in prompt + + +def test_git_changed_files_covers_commits_working_tree_and_untracked(target): + head = subprocess.run( + ["git", "-C", str(target), "rev-parse", "HEAD"], capture_output=True, text=True, check=True + ).stdout.strip() + (target / "app" / "db.py").write_text("committed change\n") + _commit_all(target, "change db") + (target / "app" / "views.py").write_text("unstaged change\n") + (target / "notes.txt").write_text("untracked\n") + + changed, deleted = _git_changed_files(target, head) + + assert changed == ["app/db.py", "app/views.py", "notes.txt"] + assert deleted == [] + + +# -- Review item 6: renames and missing commits ------------------------------- + + +def test_a_rename_reports_the_old_path_as_deleted(target): + head = subprocess.run( + ["git", "-C", str(target), "rev-parse", "HEAD"], capture_output=True, text=True, check=True + ).stdout.strip() + _git(target, "mv", "app/views.py", "app/pages.py") + _commit_all(target, "rename") + + changed, deleted = _git_changed_files(target, head) + + assert changed == ["app/pages.py"] + assert deleted == ["app/views.py"] + + +def test_an_unreachable_previous_commit_means_a_full_scan(target): + assert _git_changed_files(target, "0" * 40) is None + + +def test_diff_paths_are_relative_to_a_subdirectory_target(target): + head = subprocess.run( + ["git", "-C", str(target), "rev-parse", "HEAD"], capture_output=True, text=True, check=True + ).stdout.strip() + (target / "app" / "db.py").write_text("changed\n") + (target / "README.md").write_text("outside the target\n") + + changed, _deleted = _git_changed_files(target / "app", head) + + assert changed == ["db.py"] # what collect_files calls it, relative to the target + + +# -- Review item 4: no prompt in execute_runs ---------------------------------- + + +def test_execute_runs_never_reads_stdin_even_for_an_already_scanned_commit(repo, target, model, monkeypatch): + def _no_stdin(*args, **kwargs): + raise AssertionError("execute_runs must not prompt: it also runs under the dashboard and CI") + + monkeypatch.setattr("builtins.input", _no_stdin) + _scan(repo, target) + outcomes = _scan(repo, target) # same commit again + + assert [o.status for o in outcomes] == ["success"] + + +def test_already_scanned_skills_reports_only_repeats_of_a_clean_head(repo, target, model): + _scan(repo, target) + + head, repeats = already_scanned_skills(skill_ids=["sast", "secret-scanning"], target=str(target), repo=repo) + assert head is not None + assert repeats == ["sast"] + + (target / "app" / "db.py").write_text("dirty\n") + assert already_scanned_skills(skill_ids=["sast"], target=str(target), repo=repo)[1] == [] + + +def _outcome() -> RunOutcome: + return RunOutcome( + run_uuid="u1", skill_id="sast", skill_name="SAST", agent_id="api", status="success", + exit_code=0, duration_seconds=1.0, report_path="/tmp/r.md", + ) + + +def test_cli_asks_on_a_terminal_and_skips_only_the_repeated_skills(monkeypatch): + captured: dict = {} + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: captured.update(kw) or [_outcome()]) + monkeypatch.setattr("secfoo.cli._is_interactive", lambda: True) + monkeypatch.setattr("secfoo.cli.Prompt.ask", lambda *a, **k: "") + monkeypatch.setattr("secfoo.cli.already_scanned_skills", lambda **kw: ("abcdef1234", ["sast"])) + monkeypatch.setattr("secfoo.cli.Confirm.ask", lambda *a, **k: False) + + result = CliRunner().invoke(app, ["run", "-s", "sast", "-s", "secret-scanning", "-a", "api"]) + + assert result.exit_code == 0, result.output + assert captured["skill_ids"] == ["secret-scanning"] + + +def test_cli_rescan_flag_and_non_terminal_runs_never_ask(monkeypatch): + captured: dict = {} + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: captured.update(kw) or [_outcome()]) + monkeypatch.setattr("secfoo.cli.already_scanned_skills", lambda **kw: ("abcdef1234", ["sast"])) + + def _no_prompt(*a, **k): + raise AssertionError("must not ask") + + monkeypatch.setattr("secfoo.cli.Confirm.ask", _no_prompt) + monkeypatch.setattr("secfoo.cli.Prompt.ask", lambda *a, **k: "") + + monkeypatch.setattr("secfoo.cli._is_interactive", lambda: True) + assert CliRunner().invoke(app, ["run", "-s", "sast", "-a", "api", "--rescan"]).exit_code == 0 + assert captured["skill_ids"] == ["sast"] + + monkeypatch.setattr("secfoo.cli._is_interactive", lambda: False) + assert CliRunner().invoke(app, ["run", "-s", "sast", "-a", "api"]).exit_code == 0 + assert captured["skill_ids"] == ["sast"] + + +def test_cli_exits_cleanly_when_every_skill_was_already_scanned(monkeypatch): + def _no_run(**kw): + raise AssertionError("nothing should run") + + monkeypatch.setattr("secfoo.cli.execute_runs", _no_run) + monkeypatch.setattr("secfoo.cli._is_interactive", lambda: True) + monkeypatch.setattr("secfoo.cli.Prompt.ask", lambda *a, **k: "") + monkeypatch.setattr("secfoo.cli.already_scanned_skills", lambda **kw: ("abcdef1234", ["sast"])) + monkeypatch.setattr("secfoo.cli.Confirm.ask", lambda *a, **k: False) + + result = CliRunner().invoke(app, ["run", "-s", "sast", "-a", "api"]) + + assert result.exit_code == 0 + assert "--rescan" in result.output + + +# -- Storage ------------------------------------------------------------------- + + +def _finding_run(repo, project_id): + run_uuid = repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="api", confluence_urls=[] + ) + repo.complete_run( + run_uuid, status="success", exit_code=0, duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt=None, target_commit="abc", scan_scope=["app/db.py"], + ) + return repo.get_run(run_uuid) + + +def test_scan_scope_round_trips_and_get_last_commit_reads_it(repo): + project_id = repo.upsert_project("p", "P", "local") + run = _finding_run(repo, project_id) + + assert run.scan_scope == ["app/db.py"] + assert repo.get_last_commit(project_id=project_id, skill_id="sast") == "abc" + assert repo.find_project_id("p") == project_id + assert repo.find_project_id("missing") is None + + +def test_close_stale_findings_with_a_scope_only_closes_inside_it(repo): + project_id = repo.upsert_project("p", "P", "local") + run_id = _finding_run(repo, project_id).id + for fingerprint, path in [("in-scope", "./App/DB.py"), ("out-of-scope", "app/views.py")]: + repo.upsert_sast_finding( + project_id=project_id, fingerprint=fingerprint, run_id=run_id, current_ref="F1", title="t", + severity="High", cwe="CWE-89", owasp=None, verdict=None, location_file=path, + location_line="1", cvss_vector=None, cvss_score=None, + ) + + repo.close_stale_sast_findings( + project_id=project_id, run_id=run_id, seen_fingerprints=[], closed_at="now", only_files=["app/db.py"] + ) + + status = {f.fingerprint: f.status for f in repo.list_sast_findings(project_id=project_id)} + assert status == {"in-scope": "closed", "out-of-scope": "open"} + + +def test_an_incremental_run_never_closes_sca_findings(repo): + project_id = repo.upsert_project("p", "P", "local") + before = repo._conn.total_changes + repo.close_stale_findings( + "sca-reachability", project_id=project_id, run_id=1, seen_fingerprints=[], closed_at="now", + only_files=["requirements.txt"], + ) + assert repo._conn.total_changes == before + + +def test_collect_files_is_unchanged_for_callers(tmp_path): + (tmp_path / "a.py").write_text("print(1)\n") + assert "===== FILE: a.py =====" in api.collect_files(tmp_path) diff --git a/tests/test_runner.py b/tests/test_runner.py index 9d0d5d0..10da493 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -24,7 +24,7 @@ def build_command(self, prompt, *, workdir): def is_available(self) -> bool: return True - def run(self, prompt, *, workdir, timeout=None): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): time.sleep(0.15) return AgentResult( agent=self.name, @@ -69,7 +69,7 @@ def build_command(self, prompt, *, workdir): def is_available(self) -> bool: return True - def run(self, prompt, *, workdir, timeout=None): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): barrier.wait() return AgentResult( agent=self.name, @@ -108,7 +108,7 @@ def test_a_run_that_crashes_is_marked_failed_not_left_running(tmp_path, monkeypa target_dir.mkdir() class _CrashingAdapter(_SleepyAdapter): - def run(self, prompt, *, workdir, timeout=None): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): raise FileNotFoundError(2, "The system cannot find the file specified") monkeypatch.setattr("secfoo.runner.get_adapter", lambda agent_id: _CrashingAdapter()) @@ -416,7 +416,7 @@ def test_execute_runs_persists_report_files(tmp_path, monkeypatch): def test_execute_runs_strips_preamble_from_persisted_report(tmp_path, monkeypatch): class _ChattyAdapter(_SleepyAdapter): - def run(self, prompt, *, workdir, timeout=None): + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): result = super().run(prompt, workdir=workdir, timeout=timeout) result.raw_report = "Sounds good, here's the report:\n\n" + result.raw_report return result @@ -589,7 +589,7 @@ def build_command(self, prompt, *, workdir): def is_available(self) -> bool: return True - def run(self, prompt, *, workdir, timeout=None): + 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=_SCA_REPORT, @@ -730,7 +730,7 @@ def build_command(self, prompt, *, workdir): def is_available(self) -> bool: return True - def run(self, prompt, *, workdir, timeout=None): + 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._report,