From d96668701bee5b8ad8743d54049289ffc47db629 Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Sat, 7 Nov 2026 10:25:31 +0000 Subject: [PATCH] Sync private SECFOO-13 and SECFOO-22 work into public From the private repo, public-safe parts only (checked by the snapshot guard: no private paths, no references to private components): - SECFOO-13 incremental scans for the api agent: only files changed since the last scanned commit are sent; runs record scan_scope and the findings lifecycle only closes findings inside that scope; --rescan. The api agent never follows symlinks when collecting files. - SECFOO-22 dashboard work not yet in public: severity and first-found date filters on the findings lists, sorting and bulk status change on the assessments list, responsive layout, findings cells kept as real table cells, and every inline style moved to static/css/dashboard.css so the dashboard renders under a strict CSP (now enforced by tests). - The SECFOO-69 redesign and public's own SECFOO-22 ports are kept; where both repos fixed the same ticket, one implementation is kept (e.g. finding_filters.parse_project_id for the "All projects" 422). Co-Authored-By: Claude Opus 5.5 --- design-system/components/donut.css | 7 +- design-system/components/tables.css | 11 + src/secfoo/agents/antigravity.py | 2 +- src/secfoo/agents/api.py | 124 +++++- src/secfoo/agents/base.py | 6 +- src/secfoo/cli.py | 28 +- src/secfoo/cloud.py | 3 + src/secfoo/runner.py | 71 +++- src/secfoo/storage/models.py | 2 + src/secfoo/storage/repository.py | 96 ++++- src/secfoo/storage/schema.sql | 6 +- src/secfoo/web/finding_filters.py | 77 ++++ src/secfoo/web/routes/activities.py | 87 ++-- src/secfoo/web/routes/assessments.py | 68 +++ src/secfoo/web/static/css/dashboard.css | 192 +++++++++ .../static/design-system/components/donut.css | 7 +- .../design-system/components/tables.css | 11 + src/secfoo/web/static/js/interactive.js | 41 +- src/secfoo/web/templates/_macros.html | 18 +- .../activities/architecture_dashboard.html | 74 ++-- .../web/templates/activities/detail.html | 38 +- .../templates/activities/sast_dashboard.html | 52 +-- .../activities/sast_finding_detail.html | 30 +- .../activities/sast_findings_list.html | 33 +- .../templates/activities/sca_dashboard.html | 46 +- .../activities/sca_vulnerabilities_list.html | 17 +- .../activities/sca_vulnerability_detail.html | 28 +- .../activities/secret_scanning_dashboard.html | 40 +- .../secret_scanning_finding_detail.html | 14 +- .../secret_scanning_findings_list.html | 17 +- .../activities/threat_modeling_dashboard.html | 80 ++-- src/secfoo/web/templates/agents.html | 2 +- .../web/templates/assessments/detail.html | 30 +- .../web/templates/assessments/list.html | 48 ++- src/secfoo/web/templates/assessments/new.html | 6 +- src/secfoo/web/templates/assessments/run.html | 8 +- src/secfoo/web/templates/base.html | 15 +- src/secfoo/web/templates/overview.html | 44 +- src/secfoo/web/templates/project.html | 12 +- src/secfoo/web/templates/responsible_ai.html | 8 +- src/secfoo/web/templates/run_detail.html | 24 +- src/secfoo/web/templates/third_party.html | 16 +- tests/test_cloud.py | 3 +- tests/test_memory.py | 2 +- tests/test_memory_bank.py | 393 ++++++++++++++++++ tests/test_runner.py | 12 +- tests/test_web/test_architecture_dashboard.py | 4 +- tests/test_web/test_assessment_routes.py | 95 ++++- tests/test_web/test_finding_filters.py | 25 ++ tests/test_web/test_no_inline_scripts.py | 30 ++ tests/test_web/test_sast_finding_route.py | 67 ++- .../test_web/test_sca_vulnerability_route.py | 14 +- tests/test_web/test_secret_scanning_route.py | 14 +- tests/test_web/test_table_markup.py | 33 ++ .../test_threat_modeling_dashboard.py | 2 +- 55 files changed, 1818 insertions(+), 415 deletions(-) create mode 100644 src/secfoo/web/finding_filters.py create mode 100644 src/secfoo/web/static/css/dashboard.css create mode 100644 tests/test_memory_bank.py create mode 100644 tests/test_web/test_finding_filters.py create mode 100644 tests/test_web/test_table_markup.py 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 %} -
    +
      {% for url in run.confluence_urls %}
    • {{ url }}
    • {% endfor %}
    {% endif %} @@ -58,9 +58,9 @@

    Run receipt

    {% if blocked %} -
    +

    {{ blocked.title }}

    -

    {{ blocked.explanation }}

    +

    {{ blocked.explanation }}

    {% if blocked.fix %}
    How to fix @@ -69,12 +69,12 @@

    {{ blocked.title }}

    {% endif %} {% if run.stderr_excerpt %}
    - Error output from the agent -
    {{ run.stderr_excerpt }}
    + Error output from the agent +
    {{ run.stderr_excerpt }}
    {% endif %} {% if run.assessment_id %} - Try again + Try again {% endif %}
    {% endif %} @@ -85,7 +85,7 @@

    {{ blocked.title }}

    {% elif not blocked and not is_active %}
    -

    No report content available.

    +

    No report content available.

    {% endif %} diff --git a/src/secfoo/web/templates/third_party.html b/src/secfoo/web/templates/third_party.html index f62a1edb..5ff6b5aa 100644 --- a/src/secfoo/web/templates/third_party.html +++ b/src/secfoo/web/templates/third_party.html @@ -6,15 +6,15 @@ {{ page_head("third-party", "Third-Party", "Third-party assessments", counts.total ~ " third-party assessment(s) · AI-BOM: " ~ models_count ~ " model(s), " ~ tools_count ~ " tool(s) tracked.") }} {% if counts.total == 0 %} -{% call empty_state("No third-party assessments yet", "/assessments/new", "New Assessment") %} +{% call empty_state("No third-party assessments yet", "/assessments/new", "New Assessment", "u-mt-6") %} Create an assessment with type Third-Party and upload the vendor's documents (SOC 2 report, ISO certificate, pen test report or questionnaire). The conformance view below fills in from that evidence. {% endcall %} {% endif %} -
    +

    Vendor CCM v4 conformance

    -

    +

    Aggregated from {{ dash.assessed_vendor_count }} vendor(s)' most recent Third-Party Risk Assessment run -- evidence found in vendor-provided documents (SOC 2 reports, ISO certificates, pen test reports, questionnaires), never a guess. Hatched = no vendor has provided evidence for this domain yet, not a failing score. @@ -26,7 +26,7 @@

    Vendor CCM v4 conformance

    {% if row.hatched %}
    {% else %} -
    +
    {% endif %}
    {{ row.code }} — {% if row.hatched %}not assessed{% else %}{{ row.score }}%{% endif %} @@ -35,12 +35,12 @@

    Vendor CCM v4 conformance

    {% if assessments %} -
    +
    {% for a in assessments %} - + - + {% endfor %} @@ -56,7 +56,7 @@

    Vendor CCM v4 conformance

    ProjectStatusFindingsReviewed
    {{ a.project_display_name }} {% if a.application_id or a.sar_number %} @@ -48,7 +48,7 @@

    Vendor CCM v4 conformance

    {% endif %}
    {{ a.status | assessment_status_label }}{{ findings_badges(a) }}
    {{ findings_badges(a) }}
    {{ a.review_date or (a.updated_at | fmt_time) }}
    {% else %} -
    +
    No third-party assessments yet. Create one from the Assessments page with type "Third-Party".
    {% endif %} diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 609e8782..62a10f7d 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -137,7 +137,7 @@ def test_push_run_posts_expected_payload_shape(fake_urlopen): id=1, run_uuid="u1", project_id=1, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[], status="success", exit_code=0, started_at="t1", finished_at="t2", duration_seconds=1.0, report_path=None, prompt_path=None, stderr_excerpt=None, - project_display_name="acme/app", cost_usd=0.0123, + project_display_name="acme/app", cost_usd=0.0123, scan_scope=["app/views.py"], ) cloud.push_run( @@ -155,6 +155,7 @@ def test_push_run_posts_expected_payload_shape(fake_urlopen): assert body["project"]["kind"] == "github" assert body["run"]["skill_id"] == "sast" assert body["run"]["cost_usd"] == 0.0123 + assert body["run"]["scan_scope"] == ["app/views.py"] # Memory Bank: portal scopes its lifecycle by it assert body["report_markdown"] == "# Report\n" diff --git a/tests/test_memory.py b/tests/test_memory.py index a6338c15..cd5282f1 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 00000000..6c6dd17f --- /dev/null +++ b/tests/test_memory_bank.py @@ -0,0 +1,393 @@ +"""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) + + +def test_collect_files_never_follows_symlinks(tmp_path): + secret = tmp_path / "outside" / "id_rsa" + secret.parent.mkdir() + secret.write_text("PRIVATE KEY MATERIAL\n") + target = tmp_path / "target" + target.mkdir() + (target / "app.py").write_text("print(1)\n") + (target / "notes.txt").symlink_to(secret) # points outside the target + (target / "gone.py").symlink_to(target / "missing.py") # dangling + + text = api.collect_files(target) + + assert "===== FILE: app.py =====" in text + assert "PRIVATE KEY MATERIAL" not in text + assert "gone.py" not in text diff --git a/tests/test_runner.py b/tests/test_runner.py index 9d0d5d02..10da493f 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, diff --git a/tests/test_web/test_architecture_dashboard.py b/tests/test_web/test_architecture_dashboard.py index c518bfe9..ddd5c553 100644 --- a/tests/test_web/test_architecture_dashboard.py +++ b/tests/test_web/test_architecture_dashboard.py @@ -123,7 +123,7 @@ def test_dashboard_renders_with_real_data(client, tmp_path): "Most-deviated standards", "Uncovered CCM domains", 'class="donut"', - 'class="stacked-bar"', + 'class="stacked-bar u-mt-4"', 'class="conformance-bar"', ]: assert marker in text, f"missing: {marker}" @@ -162,7 +162,7 @@ def test_dashboard_shows_exceptions_past_expiry(client, tmp_path): assert resp.status_code == 200 assert "Exceptions past expiry" in resp.text # The stat-card value of 1 must appear with the error-colored styling. - assert "color:var(--color-error)" in resp.text + assert "u-color-error" in resp.text def test_dashboard_flags_never_reviewed_project(client, tmp_path): diff --git a/tests/test_web/test_assessment_routes.py b/tests/test_web/test_assessment_routes.py index 65e33dbf..1357514a 100644 --- a/tests/test_web/test_assessment_routes.py +++ b/tests/test_web/test_assessment_routes.py @@ -66,7 +66,7 @@ def test_assessments_list_row_is_clickable_anywhere_not_just_the_first_cell(clie """ _project_id, assessment_id = _create_assessment(application_id="APP-1") resp = client.get("/assessments") - assert f'' in resp.text + assert f'' in resp.text def test_assessments_list_filters_by_type(client): @@ -560,3 +560,96 @@ def test_responsible_ai_page_shows_derived_risk(client, tmp_path): assert resp.status_code == 200 assert "high-risk" in resp.text assert "provisional" in resp.text + + +def _row_order(html: str) -> list[str]: + import re + + return re.findall(r'' in resp.text + + +def test_bulk_status_updates_selected_assessments_only(client): + _, a1 = _create_assessment(status="ready") + _, a2 = _create_assessment(status="ready") + _, a3 = _create_assessment(status="ready") + + resp = client.post( + "/assessments/bulk-status", + data={"ids": [str(a1), str(a2)], "new_status": "completed"}, + follow_redirects=False, + ) + assert resp.status_code == 303 + assert resp.headers["location"].startswith("/assessments?") + + repo = RunRepository() + statuses = {a: repo.get_assessment(a).status for a in (a1, a2, a3)} + repo.close() + assert statuses == {a1: "completed", a2: "completed", a3: "ready"} + + page = client.get(resp.headers["location"]).text + assert "Updated 2 assessments to" in page + + +def test_bulk_status_keeps_the_list_filters_in_the_redirect(client): + _, a1 = _create_assessment(status="ready") + resp = client.post( + "/assessments/bulk-status", + data={"ids": [str(a1)], "new_status": "blocked", "type": "internal", "q": "a&b", "sort": "project"}, + follow_redirects=False, + ) + location = resp.headers["location"] + assert "type=internal" in location and "sort=project" in location and "q=a%26b" in location + + +def test_bulk_status_rejects_an_unknown_status(client): + _, a1 = _create_assessment(status="ready") + resp = client.post("/assessments/bulk-status", data={"ids": [str(a1)], "new_status": "deleted"}) + assert resp.status_code == 400 + repo = RunRepository() + assert repo.get_assessment(a1).status == "ready" + repo.close() + + +def test_bulk_status_skips_unknown_ids_and_handles_no_selection(client): + _, a1 = _create_assessment(status="ready") + resp = client.post( + "/assessments/bulk-status", data={"ids": [str(a1), "999999"], "new_status": "in_progress"} + ) + assert resp.status_code == 200 # followed the redirect + assert "Updated 1 assessment to" in resp.text + + resp = client.post("/assessments/bulk-status", data={"new_status": "in_progress"}) + assert resp.status_code == 200 + assert "No assessments were selected" in resp.text + + +def test_assessments_list_rows_have_selection_checkboxes(client): + _, a1 = _create_assessment() + html = client.get("/assessments").text + assert f'name="ids" value="{a1}" form="bulk-status-form"' in html + assert 'data-select-all="ids"' in html diff --git a/tests/test_web/test_finding_filters.py b/tests/test_web/test_finding_filters.py new file mode 100644 index 00000000..ecd07126 --- /dev/null +++ b/tests/test_web/test_finding_filters.py @@ -0,0 +1,25 @@ +from datetime import date + +from secfoo.web import finding_filters as ff + + +def test_normalize_severity(): + assert ff.normalize_severity("High") == "high" + assert ff.normalize_severity(" CRITICAL ") == "critical" + assert ff.normalize_severity("Informational") == "info" + assert ff.normalize_severity("bogus") == "" + assert ff.normalize_severity(None) == "" + + +def test_in_day_range_is_inclusive_and_open_ended(): + ts = "2026-10-09T22:24:40+00:00" + assert ff.in_day_range(ts, None, None) + assert ff.in_day_range(ts, date(2026, 10, 9), date(2026, 10, 9)) + assert ff.in_day_range(ts, date(2026, 10, 1), None) + assert not ff.in_day_range(ts, date(2026, 10, 10), None) + assert not ff.in_day_range(ts, None, date(2026, 10, 8)) + assert not ff.in_day_range(None, date(2026, 10, 1), None) + + +def test_query_string_drops_empty_values_and_encodes(): + assert ff.query_string(status="open", q="a&b", severity="", project_id=None) == "status=open&q=a%26b" diff --git a/tests/test_web/test_no_inline_scripts.py b/tests/test_web/test_no_inline_scripts.py index b0562369..84fb3910 100644 --- a/tests/test_web/test_no_inline_scripts.py +++ b/tests/test_web/test_no_inline_scripts.py @@ -58,3 +58,33 @@ def test_no_template_has_an_inline_script_block(): "Move the code into a file under src/secfoo/web/static/js/ and reference it " "with