Spaces:
Running
Running
Download core/gateway/audit.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/gateway/audit.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/gateway/audit.py
-
curl -L -o audit.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/gateway/audit.py
3.92 kB
| """Hash-chained, append-only audit log (one chain per tenant).""" | |
| from __future__ import annotations | |
| import uuid | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from typing import Any | |
| from sqlalchemy import select, text | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from core.gateway.models import AuditLog | |
| from core.privacy.redact import redact_value | |
| from core.tools.preview import canonical_json, sha256_hex | |
| GENESIS = "0" * 64 | |
| _HASHED_FIELDS = ( | |
| "id", | |
| "tenant_id", | |
| "at", | |
| "run_id", | |
| "actor", | |
| "model", | |
| "prompt_hash", | |
| "tool", | |
| "args_redacted", | |
| "args_hash", | |
| "taint", | |
| "decision", | |
| "reason", | |
| "policy_version", | |
| "approval_id", | |
| "idempotency_key", | |
| "result_status", | |
| "latency_ms", | |
| "cost_usd", | |
| ) | |
| def _row_payload(row: AuditLog) -> dict[str, Any]: | |
| out: dict[str, Any] = {} | |
| for f in _HASHED_FIELDS: | |
| v = getattr(row, f) | |
| if isinstance(v, datetime): | |
| v = v.astimezone(UTC).isoformat() | |
| elif isinstance(v, uuid.UUID): | |
| v = str(v) | |
| out[f] = v | |
| return out | |
| def compute_hash(prev_hash: str, row: AuditLog) -> str: | |
| return sha256_hex(prev_hash + canonical_json(_row_payload(row))) | |
| class AuditEntry: | |
| tenant_id: uuid.UUID | |
| actor: str | |
| tool: str | |
| args: dict[str, Any] | |
| taint: dict[str, bool] | |
| decision: str | |
| policy_version: str | |
| reason: str | None = None | |
| run_id: uuid.UUID | None = None | |
| model: str | None = None | |
| prompt_hash: str | None = None | |
| approval_id: uuid.UUID | None = None | |
| idempotency_key: uuid.UUID | None = None | |
| result_status: str | None = None | |
| latency_ms: int = 0 | |
| cost_usd: float = 0.0 | |
| async def append(session: AsyncSession, entry: AuditEntry) -> AuditLog: | |
| # Serialize writers per tenant so the chain has no forks. | |
| await session.execute( | |
| text("SELECT pg_advisory_xact_lock(hashtext(:k))"), {"k": f"audit:{entry.tenant_id}"} | |
| ) | |
| prev = ( | |
| await session.execute( | |
| select(AuditLog.row_hash) | |
| .where(AuditLog.tenant_id == entry.tenant_id) | |
| .order_by(AuditLog.seq.desc()) | |
| .limit(1) | |
| ) | |
| ).scalar_one_or_none() or GENESIS | |
| now = (await session.execute(text("SELECT now()"))).scalar_one() | |
| row = AuditLog( | |
| id=uuid.uuid4(), | |
| tenant_id=entry.tenant_id, | |
| at=now, | |
| run_id=entry.run_id, | |
| actor=entry.actor, | |
| model=entry.model, | |
| prompt_hash=entry.prompt_hash, | |
| tool=entry.tool, | |
| args_redacted=redact_value(entry.args), | |
| args_hash=sha256_hex(canonical_json(entry.args)), | |
| taint=entry.taint, | |
| decision=entry.decision, | |
| reason=entry.reason, | |
| policy_version=entry.policy_version, | |
| approval_id=entry.approval_id, | |
| idempotency_key=entry.idempotency_key, | |
| result_status=entry.result_status, | |
| latency_ms=entry.latency_ms, | |
| cost_usd=entry.cost_usd, | |
| prev_hash=prev, | |
| ) | |
| row.row_hash = compute_hash(prev, row) | |
| session.add(row) | |
| await session.flush() | |
| return row | |
| class ChainReport: | |
| ok: bool | |
| checked: int | |
| broken_at_seq: int | None = None | |
| async def verify_chain(session: AsyncSession, tenant_id: uuid.UUID) -> ChainReport: | |
| rows = ( | |
| await session.execute( | |
| select(AuditLog).where(AuditLog.tenant_id == tenant_id).order_by(AuditLog.seq) | |
| ) | |
| ).scalars() | |
| prev = GENESIS | |
| n = 0 | |
| for row in rows: | |
| n += 1 | |
| if row.prev_hash != prev or compute_hash(prev, row) != row.row_hash: | |
| return ChainReport(ok=False, checked=n, broken_at_seq=row.seq) | |
| prev = row.row_hash | |
| return ChainReport(ok=True, checked=n) | |