- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json) - Multi-instance support: flere instanser af samme modultype med adskilte assets - Community/Enterprise licensing med admin enterprise-toggle - Capacity forecasting, trends, what-if simulator, alert policies - MCP server + LLM copilot integration - Dockerfile + rune.yaml til Yggdrasil
637 lines
24 KiB
Python
637 lines
24 KiB
Python
"""HTTP API."""
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
from fastapi import APIRouter, BackgroundTasks, Body, Depends, File, HTTPException, Request, Response, UploadFile
|
|
from pydantic import BaseModel, Field
|
|
|
|
from . import auth, capacity, config, copilot, db, licensing, mcp, metrics, registry, scheduler, seed
|
|
from .util import now_iso
|
|
|
|
router = APIRouter(prefix="/api")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Models
|
|
# ---------------------------------------------------------------------------
|
|
class LoginIn(BaseModel):
|
|
username: str
|
|
password: str
|
|
|
|
|
|
class PasswordIn(BaseModel):
|
|
current_password: str
|
|
new_password: str
|
|
|
|
|
|
class ModuleIn(BaseModel):
|
|
enabled: Optional[bool] = None
|
|
config: Optional[Dict[str, Any]] = None
|
|
|
|
|
|
class ModuleInstanceIn(BaseModel):
|
|
module_type: str = Field(min_length=1)
|
|
name: Optional[str] = None
|
|
config: Optional[Dict[str, Any]] = None
|
|
copy_from: Optional[str] = None
|
|
|
|
|
|
class EnterpriseModeIn(BaseModel):
|
|
enabled: bool = True
|
|
|
|
|
|
class PolicyIn(BaseModel):
|
|
name: str
|
|
metric: str
|
|
warn: float
|
|
crit: float
|
|
enabled: bool = True
|
|
|
|
|
|
class SettingsIn(BaseModel):
|
|
site_name: Optional[str] = None
|
|
retention_days: Optional[int] = None
|
|
alert_webhook: Optional[str] = None
|
|
|
|
|
|
class LicenseIn(BaseModel):
|
|
key: str
|
|
|
|
|
|
class DevLicenseIn(BaseModel):
|
|
customer: str = "Homelab"
|
|
days: int = 365
|
|
|
|
|
|
class ApiKeyIn(BaseModel):
|
|
name: str
|
|
role: str = "operator"
|
|
|
|
|
|
class AIConfigIn(BaseModel):
|
|
base_url: str = ""
|
|
model: str = ""
|
|
api_key: Optional[str] = None
|
|
|
|
|
|
class ChatIn(BaseModel):
|
|
messages: List[Dict[str, str]] = Field(default_factory=list)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public
|
|
# ---------------------------------------------------------------------------
|
|
@router.get("/health")
|
|
def health() -> Dict[str, Any]:
|
|
db_ok = True
|
|
try:
|
|
db.query_one("SELECT 1 AS ok")
|
|
except Exception:
|
|
db_ok = False
|
|
return {
|
|
"status": "ok" if db_ok else "degraded",
|
|
"version": config.APP_VERSION,
|
|
"database": db_ok,
|
|
"scheduler": scheduler.scheduler.stats(),
|
|
}
|
|
|
|
|
|
@router.post("/auth/login")
|
|
def login(payload: LoginIn, request: Request, response: Response) -> Dict[str, Any]:
|
|
user = auth.login(payload.username, payload.password, request, response)
|
|
return {
|
|
"user": user,
|
|
"edition": licensing.status(),
|
|
"site_name": db.get_setting("site_name", "Homelab HQ"),
|
|
}
|
|
|
|
|
|
@router.post("/auth/logout")
|
|
def logout(response: Response) -> Dict[str, bool]:
|
|
auth.logout(response)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/bootstrap")
|
|
def bootstrap(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return {
|
|
"user": user,
|
|
"edition": licensing.status(),
|
|
"site_name": db.get_setting("site_name", "Homelab HQ"),
|
|
"version": config.APP_VERSION,
|
|
"meta": metrics.meta(),
|
|
"feature_labels": licensing.FEATURE_LABELS,
|
|
"scheduler": scheduler.scheduler.stats(),
|
|
"features": {
|
|
"custom_modules": licensing.has_feature("custom_modules"),
|
|
"llm_copilot": licensing.has_feature("llm_copilot"),
|
|
"mcp_server": licensing.has_feature("mcp_server"),
|
|
"audit_export": licensing.has_feature("audit_export"),
|
|
},
|
|
"limits": licensing.status()["limits"],
|
|
"dev_license_enabled": config.ALLOW_DEV_LICENSE,
|
|
"asset_count": registry.asset_count(),
|
|
"open_alerts": db.query_one("SELECT COUNT(*) AS n FROM alerts WHERE state='open'")["n"],
|
|
}
|
|
|
|
|
|
@router.put("/auth/password")
|
|
def change_password(payload: PasswordIn, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, bool]:
|
|
auth.change_password(user, payload.current_password, payload.new_password)
|
|
return {"ok": True}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fleet
|
|
# ---------------------------------------------------------------------------
|
|
@router.get("/overview")
|
|
def overview(window: int = 7, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
window = max(1, min(365, window))
|
|
data = capacity.overview(window)
|
|
data["edition"] = licensing.status()
|
|
return data
|
|
|
|
|
|
@router.get("/assets")
|
|
def assets(
|
|
type: Optional[str] = None,
|
|
module: Optional[str] = None,
|
|
q: Optional[str] = None,
|
|
user: Dict[str, Any] = Depends(auth.current_user),
|
|
) -> Dict[str, Any]:
|
|
rows = capacity.list_assets(type_filter=type, module_id=module, search=q)
|
|
latest = capacity.latest_values()
|
|
analyses, _ = capacity._analyses(rows, latest)
|
|
items = [capacity.summary(row, latest.get(row["id"], {}), analyses[row["id"]]) for row in rows]
|
|
items.sort(key=lambda item: item.get("pressure") or 0, reverse=True)
|
|
return {"items": items, "count": len(items)}
|
|
|
|
|
|
@router.get("/assets/{asset_id:path}")
|
|
def asset_detail(
|
|
asset_id: str,
|
|
window: int = 30,
|
|
user: Dict[str, Any] = Depends(auth.current_user),
|
|
) -> Dict[str, Any]:
|
|
detail = capacity.asset_detail(asset_id, max(1, min(365, window)))
|
|
if not detail:
|
|
raise HTTPException(status_code=404, detail="Asset not found")
|
|
return detail
|
|
|
|
|
|
@router.get("/capacity")
|
|
def capacity_groups(window: int = 7, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
groups = capacity.groups(max(1, min(365, window)))
|
|
all_assets = capacity.list_assets()
|
|
latest = capacity.latest_values()
|
|
slopes: Dict[Any, float] = {}
|
|
totals = capacity.resource_totals(all_assets, latest, slopes)
|
|
return {"groups": groups, "totals": totals, "generated_at": now_iso()}
|
|
|
|
|
|
@router.post("/capacity/simulate")
|
|
def simulate(payload: Dict[str, Any] = Body(default={}), user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return capacity.simulate(payload)
|
|
|
|
|
|
@router.get("/alerts")
|
|
def alerts(include_resolved: bool = False, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
items = capacity.alerts(include_resolved=include_resolved, limit=500)
|
|
open_items = items if not include_resolved else capacity.alerts(include_resolved=False, limit=500)
|
|
return {
|
|
"items": items,
|
|
"open": len(open_items),
|
|
"critical": sum(1 for item in open_items if item["severity"] == "critical"),
|
|
"warning": sum(1 for item in open_items if item["severity"] == "warning"),
|
|
}
|
|
|
|
|
|
@router.post("/alerts/{alert_id}/resolve")
|
|
def resolve_alert(alert_id: int, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
row = db.query_one("SELECT * FROM alerts WHERE id=?", (alert_id,))
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Alert not found")
|
|
db.execute("UPDATE alerts SET state='resolved', resolved_at=? WHERE id=?", (now_iso(), alert_id))
|
|
db.audit(user["username"], "alert.resolve", str(alert_id))
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/policies")
|
|
def list_policies(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
rows = [dict(row) for row in db.query("SELECT * FROM policies ORDER BY id")]
|
|
return {"items": rows}
|
|
|
|
|
|
@router.post("/policies")
|
|
def create_policy(payload: PolicyIn, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
if payload.warn >= payload.crit:
|
|
raise HTTPException(status_code=400, detail="Warning threshold must be below the critical threshold")
|
|
policy_id = db.execute(
|
|
"INSERT INTO policies(name, metric, warn, crit, enabled, created_at) VALUES(?,?,?,?,?,?)",
|
|
(payload.name[:120], payload.metric[:60], payload.warn, payload.crit, 1 if payload.enabled else 0, now_iso()),
|
|
)
|
|
db.audit(user["username"], "policy.create", str(policy_id), payload.name)
|
|
capacity.evaluate_policies()
|
|
return {"id": policy_id}
|
|
|
|
|
|
@router.put("/policies/{policy_id}")
|
|
def update_policy(policy_id: int, payload: PolicyIn, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
if payload.warn >= payload.crit:
|
|
raise HTTPException(status_code=400, detail="Warning threshold must be below the critical threshold")
|
|
row = db.query_one("SELECT id FROM policies WHERE id=?", (policy_id,))
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Policy not found")
|
|
db.execute(
|
|
"UPDATE policies SET name=?, metric=?, warn=?, crit=?, enabled=? WHERE id=?",
|
|
(payload.name[:120], payload.metric[:60], payload.warn, payload.crit, 1 if payload.enabled else 0, policy_id),
|
|
)
|
|
db.audit(user["username"], "policy.update", str(policy_id), payload.name)
|
|
capacity.evaluate_policies()
|
|
return {"ok": True}
|
|
|
|
|
|
@router.delete("/policies/{policy_id}")
|
|
def delete_policy(policy_id: int, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
row = db.query_one("SELECT id FROM policies WHERE id=?", (policy_id,))
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Policy not found")
|
|
db.execute("DELETE FROM policies WHERE id=?", (policy_id,))
|
|
db.execute("UPDATE alerts SET state='resolved', resolved_at=? WHERE policy_id=? AND state='open'", (now_iso(), policy_id))
|
|
db.audit(user["username"], "policy.delete", str(policy_id))
|
|
return {"ok": True}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Modules
|
|
# ---------------------------------------------------------------------------
|
|
def _module_or_404(module_id: str) -> Dict[str, Any]:
|
|
for module in registry.list_modules():
|
|
if module["id"] == module_id:
|
|
return module
|
|
raise HTTPException(status_code=404, detail="Module not found")
|
|
|
|
|
|
@router.get("/modules")
|
|
def modules(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return {
|
|
"items": registry.list_modules(),
|
|
"asset_limit": licensing.asset_limit(),
|
|
"custom_modules": licensing.has_feature("custom_modules"),
|
|
"multi_instance": True,
|
|
}
|
|
|
|
|
|
@router.post("/modules/instances")
|
|
def create_module_instance(
|
|
payload: ModuleInstanceIn,
|
|
background: BackgroundTasks,
|
|
user: Dict[str, Any] = Depends(auth.require_admin),
|
|
) -> Dict[str, Any]:
|
|
try:
|
|
result = registry.add_instance(
|
|
module_type=payload.module_type,
|
|
name=payload.name,
|
|
config=payload.config,
|
|
copy_from=payload.copy_from,
|
|
)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
instance_id = result.get("id")
|
|
if instance_id:
|
|
background.add_task(_run_module_bg, instance_id)
|
|
db.audit(user["username"], "module.instance.create", instance_id or payload.module_type, result)
|
|
return result
|
|
|
|
|
|
@router.put("/modules/{module_id}")
|
|
def update_module(
|
|
module_id: str,
|
|
payload: ModuleIn,
|
|
background: BackgroundTasks,
|
|
user: Dict[str, Any] = Depends(auth.require_admin),
|
|
) -> Dict[str, Any]:
|
|
current = _module_or_404(module_id)
|
|
was_enabled = current["enabled"]
|
|
try:
|
|
if payload.config is not None:
|
|
registry.update_config(module_id, payload.config, enabled=payload.enabled)
|
|
elif payload.enabled is not None:
|
|
registry.set_enabled(module_id, payload.enabled)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
updated = _module_or_404(module_id)
|
|
if payload.enabled and not was_enabled:
|
|
background.add_task(_run_module_bg, module_id)
|
|
db.audit(
|
|
user["username"],
|
|
"module.update",
|
|
module_id,
|
|
{"enabled": payload.enabled, "config_keys": sorted((payload.config or {}).keys())},
|
|
)
|
|
return updated
|
|
|
|
|
|
def _run_module_bg(module_id: str) -> None:
|
|
try:
|
|
registry.run_module(module_id, trigger="enable")
|
|
capacity.evaluate_policies()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
@router.post("/modules/{module_id}/run")
|
|
def run_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
_module_or_404(module_id)
|
|
try:
|
|
result = registry.run_module(module_id, trigger="manual")
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
capacity.evaluate_policies()
|
|
db.audit(user["username"], "module.run", module_id)
|
|
return result
|
|
|
|
|
|
@router.post("/modules/{module_id}/test")
|
|
def test_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_operator)) -> Dict[str, Any]:
|
|
_module_or_404(module_id)
|
|
try:
|
|
result = registry.test_module(module_id)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
return result
|
|
|
|
|
|
@router.get("/modules/{module_id}/logs")
|
|
def module_logs(module_id: str, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
_module_or_404(module_id)
|
|
try:
|
|
logs = registry.logs_for(module_id)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=404, detail=str(exc))
|
|
return {"module_id": module_id, "logs": logs}
|
|
|
|
|
|
@router.post("/modules/upload")
|
|
async def upload_module(
|
|
file: UploadFile = File(...),
|
|
user: Dict[str, Any] = Depends(auth.require_feature("custom_modules", "admin")),
|
|
) -> Dict[str, Any]:
|
|
payload = await file.read(config.MAX_UPLOAD_BYTES + 1)
|
|
try:
|
|
result = registry.upload_module(payload, filename=file.filename or "module.zip")
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
db.audit(user["username"], "module.upload", result["id"], result)
|
|
return result
|
|
|
|
|
|
@router.delete("/modules/{module_id}")
|
|
def delete_module(module_id: str, user: Dict[str, Any] = Depends(auth.require_feature("custom_modules", "admin"))) -> Dict[str, Any]:
|
|
try:
|
|
registry.delete_module(module_id)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
db.audit(user["username"], "module.delete", module_id)
|
|
return {"ok": True}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Licensing & settings
|
|
# ---------------------------------------------------------------------------
|
|
@router.get("/license")
|
|
def license_status(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
status = licensing.status()
|
|
status["trial_available"] = not bool(db.get_setting("trial_started_at"))
|
|
status["matrix"] = licensing.edition_matrix()
|
|
return status
|
|
|
|
|
|
@router.post("/license/activate")
|
|
def activate_license(payload: LicenseIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
try:
|
|
payload_data = licensing.activate(payload.key)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
db.audit(user["username"], "license.activate", payload_data.get("customer", ""))
|
|
return licensing.status()
|
|
|
|
|
|
@router.post("/license/trial")
|
|
def start_trial(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
try:
|
|
status = licensing.start_trial()
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
db.audit(user["username"], "license.trial", "")
|
|
return status
|
|
|
|
|
|
@router.delete("/license")
|
|
def deactivate_license(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
licensing.deactivate()
|
|
db.audit(user["username"], "license.deactivate", "")
|
|
return licensing.status()
|
|
|
|
|
|
@router.post("/license/enterprise")
|
|
def set_enterprise_mode(payload: EnterpriseModeIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
db.set_setting("enterprise_mode", "1" if payload.enabled else "0")
|
|
db.audit(user["username"], "license.enterprise_mode", "enabled" if payload.enabled else "disabled")
|
|
return licensing.status()
|
|
|
|
|
|
@router.post("/license/dev-issue")
|
|
def issue_dev_license(payload: DevLicenseIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
if not config.ALLOW_DEV_LICENSE:
|
|
raise HTTPException(status_code=403, detail="Development license issuing is disabled")
|
|
key = licensing.issue_key(payload.customer, days=max(1, min(3650, payload.days)))
|
|
db.audit(user["username"], "license.dev_issue", payload.customer)
|
|
return {"key": key, "customer": payload.customer, "days": payload.days}
|
|
|
|
|
|
@router.get("/editions")
|
|
def editions(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return {
|
|
"status": licensing.status(),
|
|
"matrix": licensing.edition_matrix(),
|
|
"community_limits": licensing.COMMUNITY_LIMITS,
|
|
"enterprise_limits": licensing.ENTERPRISE_LIMITS,
|
|
"trial_days": licensing.TRIAL_DAYS,
|
|
"trial_available": not bool(db.get_setting("trial_started_at")),
|
|
"contact": "[email protected]",
|
|
}
|
|
|
|
|
|
@router.get("/settings")
|
|
def get_settings(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return {
|
|
"site_name": db.get_setting("site_name", "Homelab HQ"),
|
|
"retention_days": int(db.get_setting("retention_days", "30") or 30),
|
|
"effective_retention_days": licensing.retention_days(),
|
|
"alert_webhook": db.get_setting("alert_webhook", ""),
|
|
"scheduler": scheduler.scheduler.stats(),
|
|
"db_path": str(config.DB_PATH),
|
|
"modules_dir": str(config.MODULES_DIR),
|
|
"admin_user": config.ADMIN_USER,
|
|
}
|
|
|
|
|
|
@router.put("/settings")
|
|
def update_settings(payload: SettingsIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
if payload.site_name is not None:
|
|
name = payload.site_name.strip()[:80]
|
|
if not name:
|
|
raise HTTPException(status_code=400, detail="Site name cannot be empty")
|
|
db.set_setting("site_name", name)
|
|
if payload.retention_days is not None:
|
|
if not 7 <= payload.retention_days <= 400:
|
|
raise HTTPException(status_code=400, detail="Retention must be between 7 and 400 days")
|
|
db.set_setting("retention_days", payload.retention_days)
|
|
if payload.alert_webhook is not None:
|
|
url = payload.alert_webhook.strip()
|
|
if url and not (url.startswith("http://") or url.startswith("https://")):
|
|
raise HTTPException(status_code=400, detail="Webhook must be an http(s) URL")
|
|
db.set_setting("alert_webhook", url[:500])
|
|
db.audit(user["username"], "settings.update", "", payload.model_dump(exclude_none=True))
|
|
return get_settings(user)
|
|
|
|
|
|
@router.get("/audit")
|
|
def audit_log(limit: int = 100, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
limit = max(1, min(1000, limit))
|
|
rows = [dict(row) for row in db.query("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (limit,))]
|
|
return {"items": rows}
|
|
|
|
|
|
@router.get("/export/audit.csv")
|
|
def export_audit(user: Dict[str, Any] = Depends(auth.require_feature("audit_export", "admin"))) -> Response:
|
|
buffer = io.StringIO()
|
|
writer = csv.writer(buffer)
|
|
writer.writerow(["id", "ts", "actor", "action", "target", "detail"])
|
|
for row in db.query("SELECT * FROM audit ORDER BY id"):
|
|
writer.writerow([row["id"], row["ts"], row["actor"], row["action"], row["target"], row["detail"]])
|
|
return Response(
|
|
content=buffer.getvalue(),
|
|
media_type="text/csv; charset=utf-8",
|
|
headers={"Content-Disposition": 'attachment; filename="headroom-audit.csv"'},
|
|
)
|
|
|
|
|
|
@router.post("/admin/reseed")
|
|
def reseed(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
seed.clear_all_data()
|
|
seed.seed()
|
|
capacity.evaluate_policies()
|
|
db.audit(user["username"], "demo.reseed", "")
|
|
return {"ok": True, "assets": len(capacity.list_assets()), "seeded_at": now_iso()}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# API keys, AI, MCP, ingestion
|
|
# ---------------------------------------------------------------------------
|
|
@router.get("/keys")
|
|
def list_keys(user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
rows = db.query("SELECT id, name, prefix, role, created_at, last_used FROM api_keys ORDER BY id DESC")
|
|
return {"items": [dict(row) for row in rows]}
|
|
|
|
|
|
@router.post("/keys")
|
|
def create_key(payload: ApiKeyIn, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
if payload.role not in ("admin", "operator", "viewer"):
|
|
raise HTTPException(status_code=400, detail="Role must be admin, operator or viewer")
|
|
name = payload.name.strip()[:80] or "API key"
|
|
from .security import api_key_prefix, hash_api_key, new_api_key
|
|
|
|
key = new_api_key()
|
|
key_id = db.execute(
|
|
"INSERT INTO api_keys(name, prefix, key_hash, role, created_at) VALUES(?,?,?,?,?)",
|
|
(name, api_key_prefix(key), hash_api_key(key), payload.role, now_iso()),
|
|
)
|
|
db.audit(user["username"], "apikey.create", name, payload.role)
|
|
return {"id": key_id, "name": name, "role": payload.role, "key": key, "prefix": api_key_prefix(key)}
|
|
|
|
|
|
@router.delete("/keys/{key_id}")
|
|
def delete_key(key_id: int, user: Dict[str, Any] = Depends(auth.require_admin)) -> Dict[str, Any]:
|
|
row = db.query_one("SELECT name FROM api_keys WHERE id=?", (key_id,))
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="API key not found")
|
|
db.execute("DELETE FROM api_keys WHERE id=?", (key_id,))
|
|
db.audit(user["username"], "apikey.delete", row["name"])
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/ai/config")
|
|
def ai_config(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return {"config": copilot.config(), "suggested_questions": copilot.suggested_questions()}
|
|
|
|
|
|
@router.put("/ai/config")
|
|
def update_ai_config(payload: AIConfigIn, user: Dict[str, Any] = Depends(auth.require_feature("llm_copilot", "admin"))) -> Dict[str, Any]:
|
|
data = copilot.update_config(payload.model_dump())
|
|
db.audit(user["username"], "ai.config", payload.base_url)
|
|
return data
|
|
|
|
|
|
@router.post("/ai/chat")
|
|
def ai_chat(payload: ChatIn, user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
try:
|
|
return copilot.chat(payload.messages)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
|
|
|
|
@router.get("/mcp")
|
|
def mcp_catalog(user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return mcp.catalog()
|
|
|
|
|
|
@router.post("/mcp")
|
|
def mcp_endpoint(payload: Dict[str, Any] = Body(...), user: Dict[str, Any] = Depends(auth.current_user)) -> Dict[str, Any]:
|
|
return mcp.handle(payload, user)
|
|
|
|
|
|
@router.post("/ingest/{module_id}")
|
|
def ingest(
|
|
module_id: str,
|
|
payload: Dict[str, Any] = Body(...),
|
|
user: Dict[str, Any] = Depends(auth.require_operator),
|
|
) -> Dict[str, Any]:
|
|
module = _module_or_404(module_id)
|
|
if not module["enabled"]:
|
|
raise HTTPException(status_code=400, detail="Enable the module before pushing data to it")
|
|
assets = payload.get("assets")
|
|
if not isinstance(assets, list):
|
|
raise HTTPException(status_code=400, detail="Payload must contain an 'assets' list")
|
|
if len(assets) > config.MAX_PUSH_ASSETS:
|
|
raise HTTPException(status_code=400, detail=f"Maximum {config.MAX_PUSH_ASSETS} assets per push")
|
|
try:
|
|
registry.persist_result(module_id, {"assets": assets, "notes": f"Push ingestion from {user['username']}"}, 0)
|
|
except registry.ModuleError as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
evaluation = capacity.evaluate_policies()
|
|
db.audit(user["username"], "ingest.push", module_id, {"assets": len(assets)})
|
|
return {"ok": True, "assets": len(assets), "policy_evaluation": evaluation}
|
|
|
|
|
|
@router.get("/export/assets.csv")
|
|
def export_assets(user: Dict[str, Any] = Depends(auth.current_user)) -> Response:
|
|
return Response(
|
|
content=capacity.export_assets_csv(),
|
|
media_type="text/csv; charset=utf-8",
|
|
headers={"Content-Disposition": 'attachment; filename="headroom-assets.csv"'},
|
|
)
|
|
|
|
|
|
@router.get("/export/alerts.csv")
|
|
def export_alerts(user: Dict[str, Any] = Depends(auth.current_user)) -> Response:
|
|
return Response(
|
|
content=capacity.export_alerts_csv(),
|
|
media_type="text/csv; charset=utf-8",
|
|
headers={"Content-Disposition": 'attachment; filename="headroom-alerts.csv"'},
|
|
)
|