feat: enforce role-aware audit event queries

This commit is contained in:
beubax
2026-06-15 13:43:24 +05:30
parent 3a1a564673
commit 08446d1e28
+27 -5
View File
@@ -1,8 +1,9 @@
"""Audit event routes."""
from typing import Any
from datetime import datetime
from typing import Annotated, Any, Literal
from fastapi import APIRouter, Depends, Request
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from authsome import audit
from authsome.identity.principal import PrincipalRole
@@ -16,13 +17,34 @@ router = APIRouter(prefix="/audit", tags=["audit"])
@router.get("/events")
async def list_audit_events(
async def list_audit_events( # noqa: PLR0913
request: Request,
limit: int = 50,
cursor: str | None = None,
event: str | None = None,
provider: str | None = None,
identity: str | None = None,
principal_id: str | None = None,
from_: Annotated[datetime | None, Query(alias="from")] = None,
to: datetime | None = None,
auth: CredentialService = Depends(get_daemon_or_browser_auth_service),
) -> dict[str, Any]:
principal_id = None if auth.principal_role == PrincipalRole.ADMIN else auth.principal_id
return {"entries": await request.app.state.audit_log.list_events(limit=limit, principal_id=principal_id)}
effective_principal_id = principal_id if auth.principal_role == PrincipalRole.ADMIN else auth.principal_id
scope: Literal["global", "principal"] = "global" if effective_principal_id is None else "principal"
try:
page = await request.app.state.audit_log.query_events(
limit=limit,
principal_id=effective_principal_id,
event=event,
provider=provider,
identity=identity,
since=from_,
until=to,
cursor=cursor,
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
return {"entries": page.entries, "next_cursor": page.next_cursor, "scope": scope}
@router.post("/events")