Spaces:
Running

File size: 3,699 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"""Tools catalog, audit log and kill switches."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import select

from core.api.routes.runs import services
from core.api.schemas import KillSwitchIn
from core.auth.deps import Principal, current_principal, require_role
from core.gateway import killswitch
from core.gateway.models import AuditLog
from core.services import Services
from core.tenancy.models import Role

router = APIRouter(tags=["admin"])


@router.get("/tools")
async def list_tools(

    _: Principal = Depends(current_principal), svc: Services = Depends(services)

) -> list[dict]:
    return [
        {
            "name": t.name,
            "description": t.description,
            "risk_tier": int(t.risk_tier),
            "pack": t.pack,
            "sensitive_args": list(t.sensitive_args),
        }
        for t in svc.registry.specs()
    ]


@router.get("/tools/search")
async def search_tools(

    q: str = Query(min_length=2, max_length=200),

    k: int = Query(default=5, ge=1, le=20),

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> list[str]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        return await svc.search.search(s, q, k)


@router.get("/admin/audit")
async def list_audit(

    limit: int = Query(default=50, ge=1, le=500),

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> list[dict]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        rows = (
            await s.execute(select(AuditLog).order_by(AuditLog.seq.desc()).limit(limit))
        ).scalars()
        return [
            {
                "seq": r.seq,
                "at": r.at,
                "actor": r.actor,
                "tool": r.tool,
                "args": r.args_redacted,
                "taint": r.taint,
                "decision": r.decision,
                "reason": r.reason,
                "policy_version": r.policy_version,
                "approval_id": r.approval_id,
                "row_hash": r.row_hash,
            }
            for r in rows
        ]


@router.get("/admin/audit/verify")
async def verify_audit(

    p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services)

) -> dict:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        # Anchored check: also verifies chains whose oldest rows were purged by retention.
        from core.ops.retention import verify_chain_anchored

        report = await verify_chain_anchored(s, p.tenant_id)
    return {"ok": report.ok, "checked": report.checked, "broken_at_seq": report.broken_at_seq}


@router.post("/admin/killswitch")
async def set_killswitch(

    body: KillSwitchIn,

    p: Principal = Depends(require_role(Role.OWNER)),

    svc: Services = Depends(services),

) -> dict:
    """Tenant-level and per-tool switches. The global switch is ops-only (owner DB role)."""
    if body.scope == "tool" and not body.target:
        raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "tool scope needs a target")
    target = str(p.tenant_id) if body.scope == "tenant" else str(body.target)
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        await killswitch.set_switch(
            s,
            scope=body.scope,
            target=target,
            enabled=body.enabled,
            reason=body.reason,
            tenant_id=p.tenant_id,
        )
    return {"scope": body.scope, "target": target, "enabled": body.enabled}