Files

148 lines
5.0 KiB
Python

"""HTTP-Schnittstelle für Healthcheck, Cache, Einstellungen und Scope."""
from __future__ import annotations
import ipaddress
import logging
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from . import i18n
from .access import normalize_allowed
from .api_common import make_protokoll
from .api_i18n import req_lang
from .audit import AuditLog
from .cache import ExpiringCache
from .models import ScopeConfig
log = logging.getLogger("pingognito")
def build_router(
db: Any,
settings: Any,
scope: Any,
jobs: Any,
scheduler: Any,
audit: AuditLog,
app_version: str,
) -> APIRouter:
"""Baut den Router für Healthcheck, CVE-Cache, Einstellungen und Scope."""
router = APIRouter()
protokoll = make_protokoll(audit)
def _cache() -> ExpiringCache:
return ExpiringCache(settings.osv_cache_path, ttl_seconds=settings.osv_cache_ttl)
def _access_state() -> dict[str, Any]:
return {
"token_required": bool(settings.access_token),
"allowed_hosts": normalize_allowed(settings.access_allowed_hosts),
"host_check": bool(settings.access_allowed_hosts),
}
@router.get("/health")
def health_kurz() -> dict[str, Any]:
"""Schlanker Healthcheck für Probes von außen."""
return {"status": "ok", "version": app_version}
@router.get("/api/health")
def health() -> dict[str, Any]:
return {
"status": "ok",
"version": app_version,
"data_dir": settings.data_dir,
"scope_file": settings.scope_file,
"active_scans": jobs.active_ids(),
"scheduler": scheduler.status(),
"cache": _cache().stats(),
"access": _access_state(),
}
@router.get("/api/cache")
def cache_status() -> dict[str, Any]:
"""Zustand des CVE-Caches."""
return {"cache": _cache().stats()}
@router.post("/api/cache/clear")
def cache_clear(http_request: Request) -> dict[str, Any]:
"""Leert den CVE-Cache."""
entfernt = _cache().clear()
log.info("CVE-Cache geleert (%d Einträge).", entfernt)
protokoll(
http_request, "cache.cleared", "settings",
detail=f"{entfernt} Cache-Einträge entfernt",
)
return {"removed": entfernt, "cache": _cache().stats()}
@router.get("/api/settings")
def read_settings() -> dict[str, Any]:
return {"settings": settings.public_dict()}
@router.post("/api/settings")
def update_settings(payload: dict[str, Any], http_request: Request) -> dict[str, Any]:
changed = settings.apply_overrides(payload)
settings.save_overrides()
protokoll(
http_request, "settings.updated", "settings",
detail="Einstellungen geändert: " + ", ".join(changed),
)
return {"changed": changed, "settings": settings.public_dict()}
@router.get("/api/scope")
def read_scope() -> dict[str, Any]:
return {"scope": scope.config.model_dump(mode="json")}
@router.put("/api/scope")
def write_scope(payload: ScopeConfig, http_request: Request) -> dict[str, Any]:
cleaned_cidrs: list[str] = []
invalid_cidrs: list[str] = []
for raw in payload.allowed_cidrs:
item = str(raw or "").strip()
if not item:
continue
try:
net = ipaddress.ip_network(item, strict=False)
except ValueError:
invalid_cidrs.append(item)
else:
cleaned_cidrs.append(str(net))
if invalid_cidrs:
raise HTTPException(
status_code=400,
detail=f"Ungültige CIDR-Angabe: {', '.join(invalid_cidrs)}",
)
cleaned = payload.model_copy(update={
"allowed_hosts": [str(h).strip() for h in payload.allowed_hosts if str(h or "").strip()],
"allowed_cidrs": cleaned_cidrs,
"denied_hosts": [str(h).strip() for h in payload.denied_hosts if str(h or "").strip()],
})
scope.update(cleaned)
scope.save(settings.scope_file)
erlaubt = ", ".join(cleaned.allowed_hosts) or "keine"
gesperrt = ", ".join(cleaned.denied_hosts) or "keine"
protokoll(
http_request, "scope.updated", "settings",
detail=f"Allowlist: {erlaubt} | Deny-List: {gesperrt}",
target="scope",
)
return {"scope": scope.config.model_dump(mode="json")}
@router.post("/api/scope/check")
def check_scope(payload: dict[str, str], http_request: Request) -> dict[str, Any]:
url = (payload or {}).get("url", "")
decision = scope.check_url(url)
lang = req_lang(http_request)
reason = decision.reason
if reason and lang != "de":
reason = i18n.translate_text(reason, lang, source_lang="de", db=db)
return {
"url": url,
"allowed": decision.allowed,
"reason": reason,
"host": decision.host,
"ip": decision.ip,
}
return router