250 lines
11 KiB
Python
250 lines
11 KiB
Python
"""HTTP-Schnittstelle für Netzwerk-Discovery, Assets, Docker-Status und Zugangsdaten."""
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import uuid
|
|
from typing import Any, Optional
|
|
|
|
from fastapi import APIRouter, HTTPException, Query, Request
|
|
|
|
from . import auth
|
|
from .audit import AuditLog
|
|
from .credentials_store import decrypt_secrets, encrypt_secrets
|
|
from .models import CredentialKind, CredentialProfile, NetworkSubnet, utcnow
|
|
from .net_discovery import detect_local_subnets
|
|
from .scanner.docker_scanner import check_docker_connection
|
|
from .scanner.endpoint_scanner import test_endpoint_connection
|
|
from .scanner.infra_scanner import test_infra_connection
|
|
|
|
|
|
def build_router(db: Any, settings: Any, scope: Any, audit: AuditLog) -> APIRouter:
|
|
"""Baut den Infrastruktur-Router (Subnetze, Assets, Zugangsdaten, Docker-Status)."""
|
|
router = APIRouter()
|
|
|
|
def protokoll(request: Request, action: str, category: str,
|
|
detail: str = "", target: str = "") -> None:
|
|
zugriff = getattr(request.state, "pingognito_zugriff", None)
|
|
audit.schreibe(
|
|
action, category, zugriff=zugriff, detail=detail, target=target,
|
|
ip=auth.client_ip(request),
|
|
user_agent=request.headers.get("user-agent", "") or "",
|
|
request=request,
|
|
)
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Subnetze / VLANs
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/infra/subnets")
|
|
def list_subnets() -> dict[str, Any]:
|
|
return {"subnets": [s.model_dump(mode="json") for s in db.list_subnets()]}
|
|
|
|
@router.post("/api/infra/subnets/discover")
|
|
def discover_subnets(request: Request) -> dict[str, Any]:
|
|
found = detect_local_subnets()
|
|
for sub in found:
|
|
db.upsert_subnet(sub)
|
|
protokoll(request, "infra.subnets.discover", "scan",
|
|
detail=f"{len(found)} Subnetze erkannt")
|
|
return {
|
|
"discovered": len(found),
|
|
"subnets": [s.model_dump(mode="json") for s in db.list_subnets()],
|
|
}
|
|
|
|
@router.post("/api/infra/subnets", status_code=201)
|
|
def add_subnet(payload: dict[str, Any], request: Request) -> dict[str, Any]:
|
|
raw_cidr = str((payload or {}).get("cidr", "") or "").strip()
|
|
try:
|
|
net = ipaddress.ip_network(raw_cidr, strict=False)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=f"Ungültiges Subnetz '{raw_cidr}': {exc}")
|
|
sub = NetworkSubnet(
|
|
cidr=str(net),
|
|
interface=str(payload.get("interface", "") or "").strip(),
|
|
gateway=str(payload.get("gateway", "") or "").strip(),
|
|
label=str(payload.get("label", "") or str(net)).strip(),
|
|
approved=bool(payload.get("approved", False)),
|
|
auto_detected=False,
|
|
)
|
|
db.upsert_subnet(sub)
|
|
if sub.approved:
|
|
db.set_subnet_approved(sub.cidr, True, sub.label)
|
|
protokoll(request, "infra.subnet.added", "settings",
|
|
detail=f"Subnetz {sub.cidr} angelegt (freigegeben={sub.approved})",
|
|
target=sub.cidr)
|
|
return {"subnets": [s.model_dump(mode="json") for s in db.list_subnets()]}
|
|
|
|
@router.put("/api/infra/subnets/approve")
|
|
def approve_subnet(payload: dict[str, Any], request: Request) -> dict[str, Any]:
|
|
raw_cidr = str((payload or {}).get("cidr", "") or "").strip()
|
|
try:
|
|
net = ipaddress.ip_network(raw_cidr, strict=False)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=f"Ungültiges Subnetz: {exc}")
|
|
cidr = str(net)
|
|
approved = bool(payload.get("approved", True))
|
|
label = str(payload.get("label", "") or "").strip()
|
|
if not db.set_subnet_approved(cidr, approved, label=label):
|
|
raise HTTPException(status_code=404, detail=f"Subnetz '{cidr}' nicht gefunden")
|
|
protokoll(request, "infra.subnet.approved", "settings",
|
|
detail=f"Subnetz {cidr} {'freigegeben' if approved else 'gesperrt'}",
|
|
target=cidr)
|
|
return {"cidr": cidr, "approved": approved,
|
|
"subnets": [s.model_dump(mode="json") for s in db.list_subnets()]}
|
|
|
|
@router.delete("/api/infra/subnets")
|
|
def delete_subnet(cidr: str = Query(...), request: Request = None) -> dict[str, Any]: # type: ignore[assignment]
|
|
if not db.delete_subnet(cidr):
|
|
raise HTTPException(status_code=404, detail="Subnetz nicht gefunden")
|
|
if request is not None:
|
|
protokoll(request, "infra.subnet.deleted", "settings",
|
|
detail=f"Subnetz {cidr} entfernt", target=cidr)
|
|
return {"deleted": cidr}
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Docker-Status
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/infra/docker/status")
|
|
def docker_status() -> dict[str, Any]:
|
|
ok, info = check_docker_connection(settings.docker_host)
|
|
return {"available": ok, "docker_host": settings.docker_host, "detail": info}
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Assets / Geräte-Inventar
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/infra/assets")
|
|
def list_assets(
|
|
device_type: str = Query(default=""),
|
|
search: str = Query(default=""),
|
|
limit: int = Query(default=500, ge=1, le=2000),
|
|
) -> dict[str, Any]:
|
|
assets = db.list_assets(device_type=device_type, search=search, limit=limit)
|
|
type_counts: dict[str, int] = {}
|
|
for a in db.list_assets(limit=2000):
|
|
type_counts[a.device_type] = type_counts.get(a.device_type, 0) + 1
|
|
return {
|
|
"assets": [a.model_dump(mode="json") for a in assets],
|
|
"type_counts": type_counts,
|
|
}
|
|
|
|
@router.get("/api/infra/assets/{asset_id}")
|
|
def get_asset(asset_id: str) -> dict[str, Any]:
|
|
asset = db.get_asset(asset_id)
|
|
if not asset:
|
|
raise HTTPException(status_code=404, detail="Asset nicht gefunden")
|
|
return {"asset": asset.model_dump(mode="json")}
|
|
|
|
@router.delete("/api/infra/assets/{asset_id}")
|
|
def delete_asset(asset_id: str, request: Request) -> dict[str, Any]:
|
|
if not db.delete_asset(asset_id):
|
|
raise HTTPException(status_code=404, detail="Asset nicht gefunden")
|
|
protokoll(request, "infra.asset.deleted", "settings",
|
|
detail=f"Asset {asset_id} gelöscht", target=asset_id)
|
|
return {"deleted": asset_id}
|
|
|
|
# ------------------------------------------------------------------ #
|
|
# Zugangsdaten (SSH, WinRM, SNMP, Proxmox, Firewalls)
|
|
# ------------------------------------------------------------------ #
|
|
@router.get("/api/infra/credentials")
|
|
def list_credentials(kind: str = Query(default="")) -> dict[str, Any]:
|
|
creds = db.list_credentials(kind=kind)
|
|
return {"credentials": [c.model_dump(mode="json") for c in creds]}
|
|
|
|
@router.post("/api/infra/credentials", status_code=201)
|
|
def create_credential(payload: dict[str, Any], request: Request) -> dict[str, Any]:
|
|
profile, secret_enc = _build_credential(payload, settings.cred_key_path)
|
|
db.upsert_credential(profile, secret_enc=secret_enc)
|
|
protokoll(request, "infra.credential.created", "admin",
|
|
detail=f"Zugang '{profile.name}' ({profile.kind.value}) für {profile.host_pattern}",
|
|
target=profile.id)
|
|
saved = db.get_credential(profile.id)
|
|
return {"credential": (saved[0] if saved else profile).model_dump(mode="json")}
|
|
|
|
@router.put("/api/infra/credentials/{cred_id}")
|
|
def update_credential(cred_id: str, payload: dict[str, Any], request: Request) -> dict[str, Any]:
|
|
existing = db.get_credential(cred_id)
|
|
if not existing:
|
|
raise HTTPException(status_code=404, detail="Zugangsprofil nicht gefunden")
|
|
profile, secret_enc = _build_credential(payload, settings.cred_key_path, cred_id=cred_id)
|
|
db.upsert_credential(profile, secret_enc=secret_enc if secret_enc is not None else None)
|
|
protokoll(request, "infra.credential.updated", "admin",
|
|
detail=f"Zugang '{profile.name}' ({profile.kind.value}) geändert",
|
|
target=cred_id)
|
|
saved = db.get_credential(cred_id)
|
|
return {"credential": (saved[0] if saved else profile).model_dump(mode="json")}
|
|
|
|
@router.delete("/api/infra/credentials/{cred_id}")
|
|
def delete_credential(cred_id: str, request: Request) -> dict[str, Any]:
|
|
if not db.delete_credential(cred_id):
|
|
raise HTTPException(status_code=404, detail="Zugangsprofil nicht gefunden")
|
|
protokoll(request, "infra.credential.deleted", "admin",
|
|
detail="Zugangsprofil gelöscht", target=cred_id)
|
|
return {"deleted": cred_id}
|
|
|
|
@router.post("/api/infra/credentials/{cred_id}/test")
|
|
def test_credential(cred_id: str, request: Request) -> dict[str, Any]:
|
|
pair = db.get_credential(cred_id)
|
|
if not pair:
|
|
raise HTTPException(status_code=404, detail="Zugangsprofil nicht gefunden")
|
|
prof, enc = pair
|
|
secrets = decrypt_secrets(enc, settings.cred_key_path)
|
|
if prof.kind.value == "ssh":
|
|
ok, msg = test_endpoint_connection(prof, secrets)
|
|
elif prof.kind.value == "winrm":
|
|
ok, msg = test_endpoint_connection(prof, secrets)
|
|
else:
|
|
ok, msg = test_infra_connection(prof, secrets, verify_tls=settings.verify_infra_tls)
|
|
protokoll(request, "infra.credential.test", "admin",
|
|
detail=f"{prof.name}: {'OK' if ok else msg}", target=cred_id)
|
|
return {"ok": ok, "message": msg}
|
|
|
|
return router
|
|
|
|
|
|
def _build_credential(
|
|
payload: dict[str, Any],
|
|
key_path: Any,
|
|
cred_id: str = "",
|
|
) -> tuple[CredentialProfile, Optional[str]]:
|
|
name = str((payload or {}).get("name", "") or "").strip()
|
|
if not name:
|
|
raise HTTPException(status_code=400, detail="Name des Zugangsprofils fehlt.")
|
|
try:
|
|
kind = CredentialKind(str(payload.get("kind", "ssh")).strip().lower())
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=f"Unbekannter Zugangstyp: {exc}")
|
|
|
|
host_pattern = str(payload.get("host_pattern", "") or "").strip()
|
|
if not host_pattern:
|
|
raise HTTPException(status_code=400, detail="Host / IP fehlt.")
|
|
|
|
extra = payload.get("extra") if isinstance(payload.get("extra"), dict) else {}
|
|
raw_port = payload.get("port") or 0
|
|
try:
|
|
port = int(raw_port)
|
|
except (TypeError, ValueError):
|
|
port = 0
|
|
|
|
secrets = payload.get("secrets") if isinstance(payload.get("secrets"), dict) else {}
|
|
# Komfort-Felder flach ebenfalls annehmen
|
|
for k in ("password", "token", "private_key", "passphrase", "community", "auth_pass", "priv_pass"):
|
|
if payload.get(k):
|
|
secrets[k] = payload[k]
|
|
|
|
secret_enc: Optional[str] = None
|
|
if secrets:
|
|
secret_enc = encrypt_secrets(secrets, key_path)
|
|
|
|
profile = CredentialProfile(
|
|
id=cred_id or uuid.uuid4().hex,
|
|
name=name,
|
|
kind=kind,
|
|
host_pattern=host_pattern,
|
|
username=str(payload.get("username", "") or "").strip(),
|
|
port=port,
|
|
extra=extra,
|
|
secret_set=bool(secret_enc),
|
|
enabled=bool(payload.get("enabled", True)),
|
|
updated_at=utcnow(),
|
|
)
|
|
return profile, secret_enc
|