diff --git a/design-system/components/donut.css b/design-system/components/donut.css index 610c20d9..1abe89e6 100644 --- a/design-system/components/donut.css +++ b/design-system/components/donut.css @@ -3,9 +3,10 @@ ----------- Pure-CSS conic-gradient donut for a small category mix (e.g. gate decisions). The gradient itself is set per-instance via the - --donut-gradient custom property in an inline style, since CSS alone - can't express data-driven percentages -- same pattern already used for - severity-bar's proportional widths. + --donut-gradient custom property, since CSS alone can't express + data-driven percentages. Templates pass it as data-donut-gradient and + static/js/interactive.js applies it (inline style="" is CSP-blocked on + the portal) -- same pattern as severity-bar widths (data-bar-width). */ .donut { diff --git a/design-system/components/tables.css b/design-system/components/tables.css index ddc5a59f..39fc719f 100644 --- a/design-system/components/tables.css +++ b/design-system/components/tables.css @@ -47,3 +47,14 @@ tr.run-row:focus-visible { .table tbody tr:hover { background-color: var(--color-teal-100); } + +/* Clickable rows (, opened by + static/js/interactive.js). A visible outline when reached with the + keyboard; the global :focus-visible box-shadow doesn't render reliably + on table rows, so use an inset outline instead. */ +tr.run-row:focus-visible { + outline: 2px solid var(--color-primary-500); + outline-offset: -2px; + box-shadow: none; + border-radius: 0; +} diff --git a/src/secfoo/agents/antigravity.py b/src/secfoo/agents/antigravity.py index 51b8e847..02da1461 100644 --- a/src/secfoo/agents/antigravity.py +++ b/src/secfoo/agents/antigravity.py @@ -42,6 +42,6 @@ def build_command(self, prompt: str, *, workdir: Path) -> list[str]: effective_timeout = getattr(self, "_effective_timeout", self.default_timeout_seconds) return [self.binary, "--print", prompt, "--print-timeout", f"{effective_timeout}s"] - 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 is only used by the api agent. self._effective_timeout = timeout or self.default_timeout_seconds return super().run(prompt, workdir=workdir, timeout=timeout) diff --git a/src/secfoo/agents/api.py b/src/secfoo/agents/api.py index 8c60e323..19b5ba69 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,80 @@ 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 + # Never follow symlinks: a target repo could point one at a file + # outside itself (~/.ssh/id_rsa) and have it sent to the model, + # and a dangling one would crash the whole scan on stat(). + if path.is_symlink(): + continue 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 +149,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 +164,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 +249,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 +270,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 +288,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 +301,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 +316,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 00bd3ba1..44bb0334 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) @@ -135,7 +139,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 1a483f77..4c0fff68 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/cloud.py b/src/secfoo/cloud.py index 804432a1..c0fa7484 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -150,6 +150,9 @@ def push_run( "output_tokens": run.output_tokens, "cost_usd": run.cost_usd, "confluence_urls": run.confluence_urls, + # Memory Bank: an incremental run's file scope, so the portal's + # findings lifecycle closes only what this run actually scanned. + "scan_scope": run.scan_scope, }, "report_markdown": report_markdown, "cli_version": _cli_version(), diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 9a63a4cd..a7e194b0 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 e4c4ca58..a2e29d67 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 117b3e41..77c38169 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 = { @@ -103,7 +105,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", } @@ -287,19 +291,21 @@ def create_completed_run( input_tokens: int | None = None, output_tokens: int | None = None, cost_usd: float | None = None, + scan_scope: list[str] | None = None, ) -> None: """Insert a run that already completed in another process.""" self._conn.execute( "INSERT INTO runs (run_uuid, project_id, skill_id, skill_name, agent_id, confluence_urls, " "status, exit_code, started_at, finished_at, duration_seconds, report_path, " "critical_count, high_count, medium_count, low_count, info_count, assessment_id, " - "input_tokens, output_tokens, cost_usd) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "input_tokens, output_tokens, cost_usd, scan_scope) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_uuid, project_id, skill_id, skill_name, agent_id, json.dumps(confluence_urls), status, exit_code, started_at, finished_at, duration_seconds, report_path, critical_count, high_count, medium_count, low_count, info_count, assessment_id, input_tokens, output_tokens, cost_usd, + None if scan_scope is None else json.dumps(scan_scope), ), ) self._conn.commit() @@ -324,12 +330,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, @@ -348,11 +355,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 @@ -382,6 +408,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: @@ -1299,7 +1327,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 @@ -1307,27 +1341,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 164a70c9..4063277b 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/src/secfoo/web/finding_filters.py b/src/secfoo/web/finding_filters.py new file mode 100644 index 00000000..c154f033 --- /dev/null +++ b/src/secfoo/web/finding_filters.py @@ -0,0 +1,77 @@ +"""Shared filters for the findings-list pages (SAST findings, SCA +vulnerabilities, secret findings): severity, and -- for SAST, the only +register that records when a finding first appeared -- a first-found +date range. + +Filtering happens in Python over the already-built rows, the same way the +SCA and secret lists already filter by project: the registers are small +(one row per distinct finding), and it keeps all three pages behaving the +same regardless of how each one builds its rows. +""" + +from __future__ import annotations + +from datetime import date +from urllib.parse import urlencode + +# (value used in the URL, label shown in the dropdown) +SEVERITY_OPTIONS = [ + ("critical", "Critical"), + ("high", "High"), + ("medium", "Medium"), + ("low", "Low"), + ("info", "Informational"), +] +_VALID_SEVERITIES = {value for value, _ in SEVERITY_OPTIONS} + + +def normalize_severity(value: str | None) -> str: + """'High' / 'high' -> 'high'; 'Informational' -> 'info'; anything + unrecognised (including an empty or hand-edited query param) -> '' + meaning "no severity filter".""" + v = (value or "").strip().lower() + if v == "informational": + v = "info" + return v if v in _VALID_SEVERITIES else "" + + +def parse_day(value: str | None) -> date | None: + """A YYYY-MM-DD query param (what submits) -> date. + Malformed values are ignored rather than erroring, like a filter that + wasn't set.""" + try: + return date.fromisoformat((value or "").strip()) + except ValueError: + return None + + +def matches_severity(finding_severity: str | None, selected: str) -> bool: + return not selected or normalize_severity(finding_severity) == selected + + +def in_day_range(timestamp: str | None, start: date | None, end: date | None) -> bool: + """Inclusive on both ends, compared by calendar day (the stored value is + an ISO timestamp such as 2026-10-09T22:24:40+00:00).""" + if start is None and end is None: + return True + day = parse_day((timestamp or "")[:10]) + if day is None: + return False + return (start is None or day >= start) and (end is None or day <= end) + + +def query_string(**params: object) -> str: + """Builds a properly encoded query string from the non-empty params -- + for links that carry the current filters (e.g. the Open/Closed tabs).""" + return urlencode({k: v for k, v in params.items() if v not in (None, "")}) + + +def parse_project_id(value: str | None) -> int | None: + """The "All projects" option submits project_id= (empty). Declaring the + route param as `int | None` made FastAPI reject that with a 422, so + choosing "All projects" -- or pressing Search with it selected, the + default -- errored. Accept the raw string; empty/invalid means "all".""" + try: + return int((value or "").strip()) + except ValueError: + return None diff --git a/src/secfoo/web/routes/activities.py b/src/secfoo/web/routes/activities.py index 97de7983..e1c5ea93 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -25,6 +25,7 @@ from secfoo.skills.loader import SkillLoadError, load_skill from secfoo.storage.repository import RunRepository from secfoo.web import architecture_dashboard as arch_dashboard +from secfoo.web import finding_filters from secfoo.web import sast_dashboard from secfoo.web import sca_dashboard from secfoo.web import secret_scanning_dashboard @@ -34,17 +35,6 @@ router = APIRouter() -def _project_id(value: str | None) -> int | None: - """The findings lists' "All projects" option submits project_id= - (empty). Declared as `int | None`, FastAPI rejected that with a 422, so - picking "All projects" -- or pressing Search with it selected, the - default -- showed a JSON error. Take the raw string instead; empty or - non-numeric means "all projects".""" - try: - return int((value or "").strip()) - except ValueError: - return None - _GATE_MIX_COLORS = { "approve": "var(--color-success)", "conditions": "var(--color-warning)", @@ -190,20 +180,46 @@ def sast_findings_list( status: str = "open", q: str | None = None, project_id: str | None = None, + severity: str | None = None, + found_from: str | None = None, + found_to: str | None = None, ): """The full, filterable SAST findings register -- the program dashboard itself only ever shows a short "Top findings" preview (see sast_dashboard.html); this is where "View all findings" lands, with a project filter the dashboard preview deliberately doesn't have (it's - already cross-project by design). + already cross-project by design). Also filterable by severity and by + the day a finding was first found (first_seen_at); the Open/Closed tab + counts reflect every filter except the status itself, so a tab's count + is what clicking it shows. """ - project_id = _project_id(project_id) + project_id = finding_filters.parse_project_id(project_id) + selected_severity = finding_filters.normalize_severity(severity) + start = finding_filters.parse_day(found_from) + end = finding_filters.parse_day(found_to) + + def keep(f) -> bool: + return finding_filters.matches_severity(f.severity, selected_severity) and finding_filters.in_day_range( + f.first_seen_at, start, end + ) + with RunRepository() as repo: projects = repo.activity_summary_by_project(sast_dashboard.SKILL_ID) - findings = repo.list_sast_findings(project_id=project_id, status=status, search=q or None) - open_count = len(repo.list_sast_findings(project_id=project_id, status="open")) - closed_count = len(repo.list_sast_findings(project_id=project_id, status="closed")) - + by_status = { + s: [f for f in repo.list_sast_findings(project_id=project_id, status=s, search=q or None) if keep(f)] + for s in ("open", "closed") + } + 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)] + + filters = { + "project_id": project_id, + "q": q or "", + "severity": selected_severity, + "found_from": start.isoformat() if start else "", + "found_to": end.isoformat() if end else "", + } return templates.TemplateResponse( request, "activities/sast_findings_list.html", @@ -213,8 +229,15 @@ def sast_findings_list( "selected_status": status, "selected_project_id": project_id, "search": q or "", - "open_count": open_count, - "closed_count": closed_count, + "open_count": len(by_status["open"]), + "closed_count": len(by_status["closed"]), + "severity_options": finding_filters.SEVERITY_OPTIONS, + "selected_severity": selected_severity, + "found_from": filters["found_from"], + "found_to": filters["found_to"], + "open_query": finding_filters.query_string(status="open", **filters), + "closed_query": finding_filters.query_string(status="closed", **filters), + "filters_active": any(v for v in filters.values()), }, ) @@ -259,7 +282,9 @@ def sast_finding_review( @router.get("/activities/{skill_id}/vulnerabilities") -def sca_vulnerabilities_list(request: Request, skill_id: str, project_id: str | None = None): +def sca_vulnerabilities_list( + request: Request, skill_id: str, project_id: str | None = None, severity: str | None = None +): """The full SCA vulnerability register, filterable by project -- what the program dashboard's "Top vulnerabilities" preview links out to. Filtering happens post-aggregation, over sca_dashboard.build()'s @@ -270,7 +295,7 @@ def sca_vulnerabilities_list(request: Request, skill_id: str, project_id: str | """ if skill_id != sca_dashboard.SKILL_ID: raise HTTPException(status_code=404, detail="Not found") - project_id = _project_id(project_id) + project_id = finding_filters.parse_project_id(project_id) with RunRepository() as repo: projects = repo.activity_summary_by_project(sca_dashboard.SKILL_ID) @@ -281,6 +306,8 @@ def sca_vulnerabilities_list(request: Request, skill_id: str, project_id: str | vulnerabilities = [ v for v in vulnerabilities if any(p["project_id"] == project_id for p in v.affected_projects) ] + selected_severity = finding_filters.normalize_severity(severity) + vulnerabilities = [v for v in vulnerabilities if finding_filters.matches_severity(v.severity, selected_severity)] return templates.TemplateResponse( request, @@ -290,6 +317,9 @@ def sca_vulnerabilities_list(request: Request, skill_id: str, project_id: str | "projects": projects, "vulnerabilities": vulnerabilities, "selected_project_id": project_id, + "severity_options": finding_filters.SEVERITY_OPTIONS, + "selected_severity": selected_severity, + "filters_active": bool(project_id is not None or selected_severity), }, ) @@ -314,12 +344,12 @@ def sca_vulnerability_detail(request: Request, skill_id: str, key: str): @router.get("/activities/secret-scanning/findings") -def secret_scanning_findings_list(request: Request, project_id: str | None = None): +def secret_scanning_findings_list(request: Request, project_id: str | None = None, severity: str | None = None): """The full secret findings register, filterable by project -- what the program dashboard's "Top findings" preview links out to, same pattern as SAST's and SCA's findings-list pages. """ - project_id = _project_id(project_id) + project_id = finding_filters.parse_project_id(project_id) with RunRepository() as repo: projects = repo.activity_summary_by_project(secret_scanning_dashboard.SKILL_ID) dash = secret_scanning_dashboard.build(repo) @@ -327,11 +357,20 @@ def secret_scanning_findings_list(request: Request, project_id: str | None = Non findings = dash.findings if project_id is not None: findings = [f for f in findings if f.project_id == project_id] + selected_severity = finding_filters.normalize_severity(severity) + findings = [f for f in findings if finding_filters.matches_severity(f.severity, selected_severity)] return templates.TemplateResponse( request, "activities/secret_scanning_findings_list.html", - {"projects": projects, "findings": findings, "selected_project_id": project_id}, + { + "projects": projects, + "findings": findings, + "selected_project_id": project_id, + "severity_options": finding_filters.SEVERITY_OPTIONS, + "selected_severity": selected_severity, + "filters_active": bool(project_id is not None or selected_severity), + }, ) diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py index e85f3e54..d6e84c7c 100644 --- a/src/secfoo/web/routes/assessments.py +++ b/src/secfoo/web/routes/assessments.py @@ -5,6 +5,7 @@ import threading from pathlib import Path from typing import Optional +from urllib.parse import urlencode from fastapi import APIRouter, Form, HTTPException, Request, UploadFile from fastapi.responses import RedirectResponse @@ -130,13 +131,46 @@ def _run_form_context() -> dict: } +# Must match the CHECK constraint on assessments.status in schema.sql. +ASSESSMENT_STATUSES = ["ready", "in_progress", "completed", "blocked"] + +# (value, label) for the Sort dropdown; "recent" is the original order. +ASSESSMENT_SORTS = [ + ("recent", "Recently updated"), + ("project", "Project (A–Z)"), + ("status", "Status"), + ("findings", "Most severe findings"), + ("review_oldest", "Oldest review first"), +] +_SORT_KEYS = { + "project": lambda a: (a.project_display_name or "").lower(), + "status": lambda a: ASSESSMENT_STATUSES.index(a.status) if a.status in ASSESSMENT_STATUSES else len(ASSESSMENT_STATUSES), + # Most severe first: compare critical, then high, ... (descending). + "findings": lambda a: (-a.critical_count, -a.high_count, -a.medium_count, -a.low_count, -a.info_count), + # The "Reviewed" column shows review_date, falling back to updated_at. + "review_oldest": lambda a: a.review_date or a.updated_at or "", +} + + +def _list_query(**params: object) -> str: + return urlencode({k: v for k, v in params.items() if v not in (None, "")}) + + @router.get("/assessments") def assessments_list( request: Request, type: Optional[str] = None, # noqa: A002 -- matches the query param name status: Optional[str] = None, q: Optional[str] = None, + sort: Optional[str] = None, + updated: Optional[int] = None, + updated_to: Optional[str] = None, ): + """Sorting happens in Python over the rows the page already shows + (list_assessments' most-recently-updated cap), which keeps the + findings-severity sort -- computed per row, not stored -- consistent + with the simple column sorts.""" + selected_sort = sort if sort in _SORT_KEYS else "recent" with RunRepository() as repo: assessments = repo.list_assessments(assessment_type=type or None, status=status or None, search=q) counts = { @@ -144,6 +178,8 @@ def assessments_list( "internal": repo.count_assessments(assessment_type="internal"), "third_party": repo.count_assessments(assessment_type="third_party"), } + if selected_sort != "recent": + assessments = sorted(assessments, key=_SORT_KEYS[selected_sort]) return templates.TemplateResponse( request, "assessments/list.html", @@ -153,10 +189,42 @@ def assessments_list( "active_type": type or "all", "active_status": status or "", "search": q or "", + "sort_options": ASSESSMENT_SORTS, + "selected_sort": selected_sort, + "status_options": ASSESSMENT_STATUSES, + # Confirmation after a bulk status change (see below). + "bulk_updated": updated, + "bulk_updated_to": updated_to if updated_to in ASSESSMENT_STATUSES else None, }, ) +@router.post("/assessments/bulk-status") +def assessments_bulk_status( + ids: list[int] = Form(default_factory=list), + new_status: str = Form(...), + type: str = Form(""), # noqa: A002 -- the list's current filters, to return to the same view + status: str = Form(""), + q: str = Form(""), + sort: str = Form(""), +): + """Set the status of several assessments at once (status only -- bulk + delete is deliberately not offered). Unknown ids are skipped. Redirects + back to the list with the same filters; the redirect target is built + here from those fields, never taken from the request, so it can't be + pointed elsewhere.""" + if new_status not in ASSESSMENT_STATUSES: + raise HTTPException(status_code=400, detail=f"Unknown status {new_status!r}") + changed = 0 + with RunRepository() as repo: + for assessment_id in dict.fromkeys(ids): # de-duplicated, order kept + if repo.get_assessment(assessment_id) is not None: + repo.update_assessment(assessment_id, status=new_status) + changed += 1 + query = _list_query(type=type, status=status, q=q, sort=sort, updated=changed, updated_to=new_status) + return RedirectResponse(url=f"/assessments?{query}", status_code=303) + + @router.get("/assessments/new") def assessment_new_form(request: Request): return templates.TemplateResponse(request, "assessments/new.html", {}) diff --git a/src/secfoo/web/static/css/dashboard.css b/src/secfoo/web/static/css/dashboard.css new file mode 100644 index 00000000..65b37185 --- /dev/null +++ b/src/secfoo/web/static/css/dashboard.css @@ -0,0 +1,192 @@ +/* + Dashboard styles that aren't part of the design system. + + Lives in a stylesheet (not inline style="..." attributes or {% block head_extra %}{% endblock %} @@ -25,7 +14,7 @@ {% set path = request.url.path %}
{% if run.confluence_urls %} -