371 lines
15 KiB
Python
371 lines
15 KiB
Python
"""HTTP-Schnittstelle für Scans, Reports, Logs, Trends und Dashboard-Übersicht."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any, Optional
|
|
import unicodedata
|
|
|
|
from fastapi import APIRouter, HTTPException, Query, Request
|
|
from fastapi.responses import Response
|
|
|
|
from . import i18n
|
|
from .api_common import make_protokoll
|
|
from .api_i18n import req_lang
|
|
from .audit import AuditLog
|
|
from .diff import compare_scans
|
|
from .log_bundle import build_log_bundle
|
|
from .models import ScanRecord, ScanRequest
|
|
from .reports import build_report
|
|
from .scanner import detect_providers
|
|
from .scope import normalize_base_url
|
|
|
|
|
|
def build_router(
|
|
db: Any,
|
|
settings: Any,
|
|
scope: Any,
|
|
jobs: Any,
|
|
audit: AuditLog,
|
|
) -> APIRouter:
|
|
"""Baut den Router für Scans, Reports, Trends und Übersicht."""
|
|
router = APIRouter()
|
|
protokoll = make_protokoll(audit)
|
|
|
|
def _scan_dict_i18n(
|
|
scan: ScanRecord,
|
|
all_i18n: dict[str, dict[str, dict[str, str]]],
|
|
lang: str,
|
|
) -> dict[str, Any]:
|
|
d = scan.model_dump(mode="json")
|
|
ent = all_i18n.get(scan.id)
|
|
needs_sync = (not ent and scan.name)
|
|
if ent and scan.name:
|
|
cat_en = i18n._lookup_catalog_phrase(scan.name, "en")
|
|
cur_en = (ent.get("name") or {}).get("en", "")
|
|
if cat_en and cur_en != cat_en:
|
|
needs_sync = True
|
|
if needs_sync:
|
|
ent = i18n.sync_entry_translations(
|
|
db, "scan", scan.id, {"name": scan.name}, source_lang="auto"
|
|
)
|
|
d["i18n"] = ent or {}
|
|
if lang != "de":
|
|
if d.get("current_step"):
|
|
d["current_step"] = i18n.translate_text(
|
|
d["current_step"], lang, source_lang="auto", db=db
|
|
)
|
|
if d.get("error"):
|
|
d["error"] = i18n.translate_text(
|
|
d["error"], lang, source_lang="auto", db=db
|
|
)
|
|
return d
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Übersicht & Statistiken
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/providers")
|
|
def providers() -> dict[str, Any]:
|
|
return {"providers": detect_providers()}
|
|
|
|
@router.get("/api/stats")
|
|
def stats() -> dict[str, Any]:
|
|
return db.stats()
|
|
|
|
@router.get("/api/overview")
|
|
def overview(http_request: Request) -> dict[str, Any]:
|
|
scans = db.list_scans(20)
|
|
lang = req_lang(http_request)
|
|
all_i18n = db.get_all_entry_i18n("scan")
|
|
return {
|
|
"stats": db.stats(),
|
|
"scans": [_scan_dict_i18n(s, all_i18n, lang) for s in scans],
|
|
"providers": detect_providers(),
|
|
"scope": scope.config.model_dump(mode="json"),
|
|
"settings": settings.public_dict(),
|
|
}
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Trend-Auswertung
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/trend")
|
|
def trend(
|
|
mode: str = Query("", description="Nur Scans dieses Modus"),
|
|
limit: int = Query(30, ge=1, le=200),
|
|
) -> dict[str, Any]:
|
|
"""Befundentwicklung über die letzten Scans."""
|
|
scan_ids = db.scan_series(mode=mode, limit=limit)
|
|
daten = db.trend(scan_ids)
|
|
all_i18n = db.get_all_entry_i18n("scan")
|
|
for p in daten.get("punkte") or []:
|
|
sid = str(p.get("scan_id") or "")
|
|
sname = str(p.get("name") or "")
|
|
ent = all_i18n.get(sid) if sid else None
|
|
needs_sync = (not ent and sid and sname)
|
|
if ent and sid and sname:
|
|
cat_en = i18n._lookup_catalog_phrase(sname, "en")
|
|
cur_en = (ent.get("name") or {}).get("en", "")
|
|
if cat_en and cur_en != cat_en:
|
|
needs_sync = True
|
|
if needs_sync:
|
|
ent = i18n.sync_entry_translations(
|
|
db, "scan", sid, {"name": sname}, source_lang="auto"
|
|
)
|
|
p["i18n"] = ent or {}
|
|
return {
|
|
"punkte": daten["punkte"],
|
|
"schweregrade": daten["schweregrade"],
|
|
"modus": mode,
|
|
"anzahl_scans": len(daten["punkte"]),
|
|
}
|
|
|
|
@router.get("/api/trend/histogramm")
|
|
def trend_histogramm(
|
|
mode: str = Query("", description="Nur Scans dieses Modus"),
|
|
limit: int = Query(30, ge=1, le=200),
|
|
buckets: str = Query("auto", description="tag, woche, monat oder auto"),
|
|
) -> dict[str, Any]:
|
|
"""Befunde nach Zeitabschnitt statt je Scan."""
|
|
scan_ids = db.scan_series(mode=mode, limit=limit)
|
|
daten = db.trend_histogramm(scan_ids, buckets=buckets)
|
|
return {
|
|
"abschnitte": daten["abschnitte"],
|
|
"schweregrade": daten["schweregrade"],
|
|
"buckets": daten["buckets"],
|
|
"modus": mode,
|
|
"anzahl_scans": sum(a.get("scans", 0) for a in daten["abschnitte"]),
|
|
}
|
|
|
|
@router.get("/api/trend/{fingerprint}")
|
|
def finding_trend(
|
|
fingerprint: str, limit: int = Query(30, ge=1, le=200)
|
|
) -> dict[str, Any]:
|
|
"""Verlauf eines einzelnen Befunds (gleicher Fingerabdruck)."""
|
|
scan_ids = db.scan_series(limit=limit)
|
|
punkte = db.finding_trend(fingerprint, scan_ids)
|
|
return {"fingerprint": fingerprint, "punkte": punkte}
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Scans & Reports
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/scans")
|
|
def list_scans(
|
|
http_request: Request,
|
|
limit: int = Query(default=100, ge=1, le=1000),
|
|
) -> dict[str, Any]:
|
|
lang = req_lang(http_request)
|
|
all_i18n = db.get_all_entry_i18n("scan")
|
|
scans = db.list_scans(limit)
|
|
return {"scans": [_scan_dict_i18n(s, all_i18n, lang) for s in scans]}
|
|
|
|
@router.post("/api/scans", status_code=202)
|
|
def create_scan(request: ScanRequest, http_request: Request) -> dict[str, Any]:
|
|
for raw_target in request.cleaned_targets():
|
|
url = normalize_base_url(raw_target)
|
|
if not url:
|
|
continue
|
|
decision = scope.check_url(url)
|
|
if not decision.allowed:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=f"Ziel {raw_target} steht nicht in der Allowlist: {decision.reason}",
|
|
)
|
|
scan = jobs.start(request)
|
|
ent_i18n = i18n.sync_entry_translations(
|
|
db, "scan", scan.id, {"name": scan.name},
|
|
source_lang=req_lang(http_request),
|
|
)
|
|
protokoll(
|
|
http_request, "scan.started", "scan",
|
|
detail=f"Scan '{scan.name}' im Modus {scan.mode.value} gestartet",
|
|
target=scan.id,
|
|
)
|
|
d = scan.model_dump(mode="json")
|
|
d["i18n"] = ent_i18n
|
|
return {"scan": d}
|
|
|
|
@router.get("/api/scans/{scan_id}")
|
|
def get_scan(scan_id: str, http_request: Request) -> dict[str, Any]:
|
|
scan = db.get_scan(scan_id)
|
|
if not scan:
|
|
raise HTTPException(status_code=404, detail="Scan nicht gefunden")
|
|
all_i18n = {scan.id: db.get_entry_i18n("scan", scan.id)}
|
|
return {"scan": _scan_dict_i18n(scan, all_i18n, req_lang(http_request))}
|
|
|
|
@router.get("/api/scans/{scan_id}/diff")
|
|
def diff_scan(
|
|
scan_id: str, http_request: Request, baseline: str = ""
|
|
) -> dict[str, Any]:
|
|
"""Vergleicht einen Scan mit einem früheren."""
|
|
scan = db.get_scan(scan_id)
|
|
if not scan:
|
|
raise HTTPException(status_code=404, detail="Scan nicht gefunden")
|
|
|
|
base_scan: Optional[ScanRecord] = None
|
|
if baseline:
|
|
base_scan = db.get_scan(baseline)
|
|
if not base_scan:
|
|
raise HTTPException(status_code=404, detail="Vergleichs-Scan nicht gefunden")
|
|
else:
|
|
kandidaten = [
|
|
s for s in db.list_scans(200)
|
|
if s.id != scan.id and s.mode == scan.mode and s.created_at < scan.created_at
|
|
]
|
|
if kandidaten:
|
|
base_scan = kandidaten[0]
|
|
|
|
base_findings = db.get_findings(scan_id=base_scan.id) if base_scan else []
|
|
head_findings = db.get_findings(scan_id=scan.id)
|
|
ergebnis = compare_scans(base_findings, head_findings)
|
|
lang = req_lang(http_request)
|
|
custom_i18n = db.get_all_entry_i18n("rule")
|
|
for key in ("new", "fixed", "unchanged", "severity_changed"):
|
|
if isinstance(ergebnis.get(key), list):
|
|
ergebnis[key] = [
|
|
i18n.localize_finding_dict(item, lang, db=db, custom_rules_i18n=custom_i18n)
|
|
if isinstance(item, dict) else item
|
|
for item in ergebnis[key]
|
|
]
|
|
ergebnis["scan"] = scan.model_dump(mode="json")
|
|
ergebnis["baseline"] = base_scan.model_dump(mode="json") if base_scan else None
|
|
return ergebnis
|
|
|
|
@router.delete("/api/scans/{scan_id}")
|
|
def delete_scan(scan_id: str, http_request: Request) -> dict[str, Any]:
|
|
scan = db.get_scan(scan_id)
|
|
if not scan:
|
|
raise HTTPException(status_code=404, detail="Scan nicht gefunden")
|
|
if scan.status.value in ("running", "queued"):
|
|
jobs.cancel(scan_id)
|
|
db.delete_scan(scan_id)
|
|
db.delete_entry_i18n("scan", scan_id)
|
|
protokoll(
|
|
http_request, "scan.deleted", "scan",
|
|
detail=f"Scan '{scan.name}' gelöscht", target=scan_id,
|
|
)
|
|
return {"deleted": scan_id}
|
|
|
|
@router.post("/api/scans/{scan_id}/cancel")
|
|
def cancel_scan(scan_id: str, http_request: Request) -> dict[str, Any]:
|
|
scan = db.get_scan(scan_id)
|
|
if not scan:
|
|
raise HTTPException(status_code=404, detail="Scan nicht gefunden")
|
|
cancelled = jobs.cancel(scan_id)
|
|
protokoll(
|
|
http_request, "scan.cancelled", "scan",
|
|
detail=f"Scan '{scan.name}' abgebrochen", target=scan_id,
|
|
)
|
|
return {"cancelled": cancelled, "scan_id": scan_id}
|
|
|
|
@router.get("/api/scans/{scan_id}/findings")
|
|
def scan_findings(
|
|
scan_id: str,
|
|
http_request: Request,
|
|
severity: str = "",
|
|
category: str = "",
|
|
tool: str = "",
|
|
origin: str = "",
|
|
search: str = "",
|
|
include_fp: bool = True,
|
|
include_covered: bool = True,
|
|
ack_filter: str = "",
|
|
) -> dict[str, Any]:
|
|
severities = [s for s in severity.split(",") if s] or None
|
|
categories = [c for c in category.split(",") if c] or None
|
|
tools = [t for t in tool.split(",") if t] or None
|
|
origins = [o for o in origin.split(",") if o] or None
|
|
target_scan_id = None if scan_id in ("all", "__all__", "*") else scan_id
|
|
findings = db.get_findings(
|
|
scan_id=target_scan_id, severities=severities, categories=categories, tools=tools,
|
|
origins=origins, search=search, include_fp=include_fp,
|
|
include_covered=include_covered, ack_filter=ack_filter,
|
|
)
|
|
lang = req_lang(http_request)
|
|
custom_i18n = db.get_all_entry_i18n("rule")
|
|
return {
|
|
"findings": [
|
|
i18n.localize_finding_dict(
|
|
f.model_dump(mode="json"), lang, db=db, custom_rules_i18n=custom_i18n
|
|
)
|
|
for f in findings
|
|
]
|
|
}
|
|
|
|
@router.get("/api/scans/{scan_id}/logs")
|
|
def scan_logs(scan_id: str, http_request: Request) -> dict[str, Any]:
|
|
lang = req_lang(http_request)
|
|
logs = db.get_logs(scan_id)
|
|
if lang != "de":
|
|
for entry in logs:
|
|
if entry.get("message"):
|
|
entry["message"] = i18n.translate_text(
|
|
entry["message"], lang, source_lang="auto", db=db
|
|
)
|
|
return {"logs": logs}
|
|
|
|
@router.get("/api/logs/export")
|
|
def export_all_logs(
|
|
http_request: Request,
|
|
fmt: str = Query(default="txt", pattern="^(txt|json)$"),
|
|
) -> Response:
|
|
"""Exportiert alle Laufzeit-, Scan-, System- und Asset-Logs als eine Datei."""
|
|
data, mimetype, ext = build_log_bundle(db, settings, scope, fmt=fmt)
|
|
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
filename = f"pingognito-logs-{stamp}.{ext}"
|
|
protokoll(
|
|
http_request, "logs.exported", "admin",
|
|
detail=f"Komplettes Log-Paket als {ext} heruntergeladen",
|
|
)
|
|
return Response(
|
|
content=data,
|
|
media_type=mimetype,
|
|
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
|
)
|
|
|
|
@router.get("/api/scans/{scan_id}/report/{fmt}")
|
|
def scan_report(scan_id: str, fmt: str, http_request: Request) -> Response:
|
|
scan = db.get_scan(scan_id)
|
|
if not scan:
|
|
raise HTTPException(status_code=404, detail="Scan nicht gefunden")
|
|
findings = db.get_findings(scan_id=scan_id)
|
|
lang = req_lang(http_request)
|
|
scan_for_report = scan
|
|
if lang != "de":
|
|
all_scan_i18n = db.get_all_entry_i18n("scan")
|
|
scan_ent = all_scan_i18n.get(scan.id) or {}
|
|
loc_name = (scan_ent.get("name") or {}).get(lang) or (
|
|
i18n.translate_text(scan.name, lang, source_lang="auto", db=db)
|
|
if scan.name else scan.name
|
|
)
|
|
scan_for_report = scan.model_copy(update={"name": loc_name or scan.name})
|
|
custom_i18n = db.get_all_entry_i18n("rule")
|
|
localized_findings = []
|
|
for f in findings:
|
|
ld = i18n.localize_finding_dict(
|
|
f.model_dump(mode="json"), lang, db=db, custom_rules_i18n=custom_i18n
|
|
)
|
|
localized_findings.append(f.model_copy(update={
|
|
"title": ld.get("title", f.title),
|
|
"description": ld.get("description", f.description),
|
|
"remediation": ld.get("remediation", f.remediation),
|
|
}))
|
|
findings = localized_findings
|
|
deps = db.get_dependencies(scan_id) if fmt.lower() == "sbom" else None
|
|
try:
|
|
data, mimetype, ext = build_report(fmt, scan_for_report, findings, deps, lang=lang)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
safe_name = (
|
|
unicodedata.normalize("NFKD", scan_for_report.name or "scan")
|
|
.encode("ascii", "ignore")
|
|
.decode("ascii")
|
|
)
|
|
raw_filename = f"pingognito-{safe_name[:40].replace(' ', '_')}-{scan_id[:8]}.{ext}"
|
|
filename = "".join(ch for ch in raw_filename if ch.isascii() and (ch.isalnum() or ch in "-_."))
|
|
return Response(
|
|
content=data,
|
|
media_type=mimetype,
|
|
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
|
)
|
|
|
|
return router
|