Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/secfoo/storage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ class SastFindingRecord:
language: str | None = None
framework: str | None = None
construct: str | None = None
review_status: str | None = None
review_note: str | None = None
reviewed_by: str | None = None
reviewed_at: str | None = None
project_display_name: str | None = None


Expand Down
54 changes: 54 additions & 0 deletions src/secfoo/storage/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,17 @@ def use_db_path(path: Path):
"language": "ALTER TABLE sast_findings ADD COLUMN language TEXT",
"framework": "ALTER TABLE sast_findings ADD COLUMN framework TEXT",
"construct": "ALTER TABLE sast_findings ADD COLUMN construct TEXT",
# Reviewer sign-off (dashboard Confirm / False positive / Accept risk).
# Stored on the finding row so a sign-off survives the finding being
# re-seen by later runs -- the upsert never touches these columns.
"review_status": "ALTER TABLE sast_findings ADD COLUMN review_status TEXT",
"review_note": "ALTER TABLE sast_findings ADD COLUMN review_note TEXT",
"reviewed_by": "ALTER TABLE sast_findings ADD COLUMN reviewed_by TEXT",
"reviewed_at": "ALTER TABLE sast_findings ADD COLUMN reviewed_at TEXT",
}

SAST_REVIEW_STATUSES = ("confirmed", "false_positive", "accepted_risk")

# Skill id -> its per-finding lifecycle table. Every one of these tables
# shares the open/closed + first/last-seen columns, which is what lets
# close_stale_findings and list_structured_findings serve all three.
Expand Down Expand Up @@ -415,6 +424,22 @@ def list_runs(
rows = self._conn.execute(query, params).fetchall()
return [self._row_to_run(row) for row in rows]

def agent_run_stats(self) -> dict[str, dict]:
"""Per-agent run count, last run, last success and last status --
backs the dashboard's agent health cards."""
rows = self._conn.execute(
"SELECT agent_id, COUNT(*) runs, MAX(started_at) last_run_at, "
"MAX(CASE WHEN status = 'success' THEN started_at END) last_success_at "
"FROM runs GROUP BY agent_id"
).fetchall()
stats = {row["agent_id"]: dict(row) for row in rows}
for row in self._conn.execute(
"SELECT agent_id, status FROM runs r WHERE started_at = "
"(SELECT MAX(started_at) FROM runs WHERE agent_id = r.agent_id)"
).fetchall():
stats[row["agent_id"]]["last_status"] = row["status"]
return stats

def get_run(self, run_uuid: str) -> RunRecord | None:
row = self._conn.execute(
"SELECT runs.*, projects.display_name FROM runs "
Expand Down Expand Up @@ -1453,6 +1478,35 @@ def list_structured_findings(
result.append((skill_id, dict(row)))
return result

def review_sast_finding(
self,
finding_id: int,
*,
review_status: str | None,
note: str | None = None,
reviewed_by: str | None = None,
) -> None:
"""Records (or, with review_status=None, clears) a reviewer's
sign-off on one finding. Accepting a risk needs a reason -- a bare
"accepted" with nothing behind it is exactly what an auditor flags.
"""
if review_status is not None and review_status not in SAST_REVIEW_STATUSES:
raise ValueError(f"unknown review status {review_status!r}")
if review_status == "accepted_risk" and not (note or "").strip():
raise ValueError("accepting a risk needs a reason")
self._conn.execute(
"UPDATE sast_findings SET review_status = ?, review_note = ?, reviewed_by = ?, reviewed_at = ? "
"WHERE id = ?",
(
review_status,
(note or "").strip() or None if review_status else None,
(reviewed_by or "").strip() or None if review_status else None,
_now() if review_status else None,
finding_id,
),
)
self._conn.commit()

def list_sast_findings(
self,
*,
Expand Down
4 changes: 4 additions & 0 deletions src/secfoo/storage/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ CREATE TABLE IF NOT EXISTS sast_findings (
last_seen_at TEXT NOT NULL,
closed_in_run_id INTEGER REFERENCES runs(id),
closed_at TEXT,
review_status TEXT, -- reviewer sign-off: confirmed / false_positive / accepted_risk, NULL = awaiting
review_note TEXT,
reviewed_by TEXT,
reviewed_at TEXT,
UNIQUE (project_id, fingerprint)
);

Expand Down
13 changes: 13 additions & 0 deletions src/secfoo/web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from secfoo.config import STORE_DIR
from secfoo.web.routes import (
activities,
agents,
assessments,
overview,
projects,
Expand All @@ -34,13 +35,25 @@ def mermaid_bundle_available() -> bool:

def create_app() -> FastAPI:
app = FastAPI(title="secfoo dashboard")

@app.middleware("http")
async def revalidate_static(request, call_next):
# Make the browser re-check stylesheets/scripts on each load (a cheap
# 304 via ETag when unchanged). Without this, heuristic caching can
# keep serving an old design-system.css -- and its @import-ed
# component files -- after an upgrade, so a new UI looks broken.
response = await call_next(request)
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
return response
# Mounted BEFORE /static: Starlette matches mounts in registration
# order, so the broader /static would otherwise swallow /static/vendor.
VENDOR_DIR.mkdir(parents=True, exist_ok=True)
app.mount("/static/vendor", StaticFiles(directory=str(VENDOR_DIR)), name="vendor")
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
app.include_router(overview.router)
app.include_router(activities.router)
app.include_router(agents.router)
app.include_router(assessments.router)
app.include_router(third_party.router)
app.include_router(responsible_ai.router)
Expand Down
29 changes: 28 additions & 1 deletion src/secfoo/web/routes/activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

from pathlib import Path

from fastapi import APIRouter, HTTPException, Request
from fastapi import APIRouter, Form, HTTPException, Request
from fastapi.responses import RedirectResponse

from secfoo.report.architecture import count_trust_boundaries, extract_design_verdict, extract_mermaid_diagram
from secfoo.skills.loader import SkillLoadError, load_skill
Expand Down Expand Up @@ -218,6 +219,32 @@ def sast_finding_detail(request: Request, fingerprint: str):
)


@router.post("/activities/sast/findings/{fingerprint}/review")
def sast_finding_review(
fingerprint: str,
finding_id: int = Form(...),
review_status: str = Form(...),
note: str = Form(""),
reviewer: str = Form(""),
):
"""Reviewer sign-off: Confirm, False positive, Accept risk (needs a
reason), or "clear" to put the finding back to awaiting review."""
with RunRepository() as repo:
finding = next((f for f in repo.list_sast_findings() if f.id == finding_id), None)
if finding is None or finding.fingerprint != fingerprint:
raise HTTPException(status_code=404, detail="Finding not found")
try:
repo.review_sast_finding(
finding_id,
review_status=None if review_status == "clear" else review_status,
note=note,
reviewed_by=reviewer,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RedirectResponse(url=f"/activities/sast/findings/{fingerprint}", status_code=303)


@router.get("/activities/{skill_id}/vulnerabilities")
def sca_vulnerabilities_list(request: Request, skill_id: str, project_id: int | None = None):
"""The full SCA vulnerability register, filterable by project -- what
Expand Down
16 changes: 16 additions & 0 deletions src/secfoo/web/routes/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from __future__ import annotations

from fastapi import APIRouter, Request

from secfoo.storage.repository import RunRepository
from secfoo.web.run_status import agent_health
from secfoo.web.templating import templates

router = APIRouter()


@router.get("/agents")
def agents_page(request: Request):
with RunRepository() as repo:
stats = repo.agent_run_stats()
return templates.TemplateResponse(request, "agents.html", {"agents": agent_health(stats)})
35 changes: 33 additions & 2 deletions src/secfoo/web/routes/assessments.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
from secfoo.skills.renderer import merge_excludes
from secfoo.storage.repository import RunRepository
from secfoo.targets.resolver import TargetResolutionError, resolve_target
from secfoo.web.templating import severity_rows, templates
from secfoo.web.run_status import assessment_pipeline
from secfoo.web.templating import SIDEBAR_ACTIVITY_IDS, ordered_skills, severity_rows, templates
from secfoo.web.third_party_dashboard import SKILL_ID as THIRD_PARTY_RISK_SKILL_ID

router = APIRouter()
Expand Down Expand Up @@ -91,9 +92,38 @@ def _run_third_party_risk_assessment(assessment_id: int, project_id: int) -> Non
shutil.rmtree(tmp_dir, ignore_errors=True)


# One-click presets on the Run Assessment form (static/js/run-form.js ticks
# the matching skill boxes and sets depth). Skills missing from this
# install are dropped rather than breaking the card.
RUN_STARTERS = [
{"title": "Quick code triage", "skills": ["sast", "secret-scanning"], "depth": "quick",
"meta": "SAST + secrets · quick"},
{"title": "Full design review", "skills": ["security-architecture-review", "threat-modeling"],
"depth": "standard", "meta": "architecture + threat model · standard"},
{"title": "Dependency check", "skills": ["sca-reachability"], "depth": "quick",
"meta": "SCA reachability · quick"},
{"title": "AI system review", "skills": ["prompt-review", "responsible-ai-compliance"], "depth": "standard",
"meta": "prompts + responsible AI · standard"},
]


def _pipeline_skills(runs) -> list:
"""The five core review activities always, plus any other skill that
actually ran on this assessment (e.g. responsible-ai-compliance)."""
ran = {r.skill_id for r in runs}
return [s for s in ordered_skills() if s.id in SIDEBAR_ACTIVITY_IDS or s.id in ran]


def _run_form_context() -> dict:
skills = load_all_skills()
starters = []
for starter in RUN_STARTERS:
present = [skill_id for skill_id in starter["skills"] if skill_id in skills]
if present:
starters.append({**starter, "skills": present})
return {
"skills": sorted(load_all_skills().values(), key=lambda s: s.name),
"starters": starters,
"skills": [skill for skill in ordered_skills() if skill.id in skills],
"agent_options": [
{"id": agent_id, "available": get_adapter(agent_id).is_available()} for agent_id in ADAPTERS
],
Expand Down Expand Up @@ -195,6 +225,7 @@ def assessment_detail(request: Request, assessment_id: int):
"models_count": models_count,
"tools_count": tools_count,
"has_running_run": has_running_run,
"pipeline": assessment_pipeline(runs, _pipeline_skills(runs)),
"severity_rows": severity_rows(
assessment.critical_count,
assessment.high_count,
Expand Down
15 changes: 15 additions & 0 deletions src/secfoo/web/routes/overview.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from secfoo.cost import sum_optional
from secfoo.storage.repository import RunRepository
from secfoo.web.run_status import COST_REPORTING_AGENTS, agent_health, setup_steps
from secfoo.web.templating import ordered_skills, severity_rows, templates
from secfoo.web.top_findings import build_top_findings

Expand All @@ -22,6 +23,10 @@ def overview(request: Request):
models_count, tools_count = repo.ai_bom_counts_total()
top_findings = build_top_findings(repo)
cost_by_agent = repo.cost_summary(group_by="agent")
agent_stats = repo.agent_run_stats()
recent_runs = repo.list_runs(limit=6)
assessment_count = repo.count_assessments()
reviewed_count = sum(1 for f in repo.list_sast_findings() if f.review_status)

# Coverage is "projects that have had this activity run", so the
# denominator is the project count -- see RunRepository.skill_coverage.
Expand Down Expand Up @@ -51,6 +56,16 @@ def overview(request: Request):
"tools_count": tools_count,
"top_findings": top_findings,
"cost_by_agent": cost_by_agent,
"cost_reporting_agents": COST_REPORTING_AGENTS,
"agents": agent_health(agent_stats),
"recent_runs": recent_runs,
"setup": setup_steps(
agents=agent_health(agent_stats),
assessment_count=assessment_count,
run_count=sum(stats["runs"] for stats in agent_stats.values()),
reviewed_count=reviewed_count,
),
"run_count": sum(stats["runs"] for stats in agent_stats.values()),
# None (rendered "-") until at least one run has a known cost,
# so runs that predate tracking don't read as free. An agent
# whose runs are all unpriced has cost_usd=None; skip it rather
Expand Down
36 changes: 35 additions & 1 deletion src/secfoo/web/routes/runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
from pathlib import Path

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse
from fastapi.responses import FileResponse, JSONResponse

from secfoo.report.markdown import render_report_html
from secfoo.storage.repository import RunRepository
from secfoo.web.run_status import ACTIVE_STATUSES, blocked_hint, elapsed_seconds, run_steps
from secfoo.web.templating import templates

router = APIRouter()
Expand All @@ -32,6 +33,10 @@ def run_detail(request: Request, run_uuid: str):
"run_detail.html",
{
"run": record,
"steps": run_steps(record),
"blocked": blocked_hint(record),
"elapsed": elapsed_seconds(record),
"is_active": record.status in ACTIVE_STATUSES,
"report_html": report_html,
"mermaid_available": mermaid_bundle_available(),
},
Expand All @@ -45,3 +50,32 @@ def run_report_download(run_uuid: str):
if record is None or not record.report_path or not Path(record.report_path).exists():
raise HTTPException(status_code=404, detail="Report not found")
return FileResponse(record.report_path, media_type="text/markdown", filename=f"{run_uuid}.md")


@router.get("/runs/{run_uuid}/status.json")
def run_status_json(run_uuid: str):
"""Polled by static/js/live-run.js while a run is in flight, so the run
page can tick its step list without reloading the whole report view."""
with RunRepository() as repo:
record = repo.get_run(run_uuid)
if record is None:
raise HTTPException(status_code=404, detail="Run not found")
return JSONResponse(
{
"status": record.status,
"active": record.status in ACTIVE_STATUSES,
"elapsed_seconds": elapsed_seconds(record),
"steps": [{"label": s.label, "state": s.state, "detail": s.detail} for s in run_steps(record)],
}
)


@router.get("/runs/{run_uuid}/prompt.md")
def run_prompt_download(run_uuid: str):
"""The exact prompt the agent was given -- part of the run receipt, so a
reviewer can see what was asked, not just what came back."""
with RunRepository() as repo:
record = repo.get_run(run_uuid)
if record is None or not record.prompt_path or not Path(record.prompt_path).exists():
raise HTTPException(status_code=404, detail="Prompt not found")
return FileResponse(record.prompt_path, media_type="text/markdown", filename=f"{run_uuid}-prompt.md")
Loading
Loading