Spaces:
Paused

yaz / src /core /database /audit.py
anaselamr's picture
[PLATFORM] fix(endpoints+templates): Sprint 52 — zero-error operational pass
579285c
Raw History Blame Contribute Delete
7.82 kB
"""
YAZ Care Platform — Append-Only Audit Trail (DB-backed)
=========================================================
MEDICO-LEGAL requirement: once written, audit events MUST NOT be
modified or deleted. The table deliberately has NO UPDATE/DELETE
permissions granted at the DB level.
DB Constraints enforcing immutability:
CREATE RULE no_update_audit AS ON UPDATE TO audit_events DO INSTEAD NOTHING;
CREATE RULE no_delete_audit AS ON DELETE TO audit_events DO INSTEAD NOTHING;
(Applied in the accompanying Alembic migration)
ORM Protection:
- AuditEvent has no update/delete service methods
- SQLAlchemy never calls UPDATE on this model
Fields per spec:
event_id, timestamp, user_id, role, action, entity_type, entity_id,
before_snapshot (JSONB), after_snapshot (JSONB), diff,
correlation_id, ip_address, user_agent, org_id
"""
from __future__ import annotations
import asyncio
import structlog
from datetime import datetime, timezone
from typing import Any, Dict, Optional
from uuid import UUID, uuid4
from sqlalchemy import Column, Index, String, Text, DateTime
from sqlalchemy.dialects.postgresql import JSONB, UUID as SQLUUID
from sqlmodel import SQLModel, Field
logger = structlog.get_logger(__name__)
# ---------------------------------------------------------------------------
# Model
# ---------------------------------------------------------------------------
class AuditLog(SQLModel, table=True):
"""
Append-only audit event row.
Standards: HIPAA §164.312(b), FDA 21 CFR Part 11, ISO 27001
Constraint: NO UPDATE / NO DELETE at database level
"""
__tablename__ = "audit_logs"
__table_args__ = (
Index("ix_audit_logs_org_ts", "org_id", "timestamp"),
Index("ix_audit_logs_entity", "entity_type", "entity_id"),
Index("ix_audit_logs_user", "user_id"),
Index("ix_audit_logs_correlation", "correlation_id"),
{"schema": "core"},
)
event_id: UUID = Field(
default_factory=uuid4,
sa_column=Column(SQLUUID(as_uuid=True), primary_key=True),
)
timestamp: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
nullable=False,
index=True,
)
# Who
user_id: Optional[str] = Field(default=None, max_length=100, index=True)
user_role: Optional[str] = Field(default=None, max_length=50)
# What
action: str = Field(max_length=100, nullable=False, index=True)
entity_type: Optional[str] = Field(default=None, max_length=100, index=True)
entity_id: Optional[str] = Field(default=None, max_length=200)
# Snapshots (PostgreSQL JSONB; TEXT fallback for SQLite in tests)
before_snapshot: Optional[Dict[str, Any]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
)
after_snapshot: Optional[Dict[str, Any]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
)
diff: Optional[Dict[str, Any]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
)
# Context
correlation_id: Optional[str] = Field(default=None, max_length=100, index=True)
ip_address: Optional[str] = Field(default=None, max_length=45) # IPv6 max 45
user_agent: Optional[str] = Field(default=None, max_length=512)
org_id: Optional[str] = Field(default=None, max_length=100, index=True)
# Extra metadata
extra: Optional[Dict[str, Any]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
)
# ---------------------------------------------------------------------------
# Audit Event Constants
# ---------------------------------------------------------------------------
class AuditAction:
"""Canonical action strings. Prefer these over raw strings."""
# Auth
USER_LOGIN = "USER_LOGIN"
USER_LOGOUT = "USER_LOGOUT"
USER_LOGIN_FAILED = "USER_LOGIN_FAILED"
USER_CREATED = "USER_CREATED"
USER_UPDATED = "USER_UPDATED"
USER_DELETED = "USER_DELETED"
USER_MFA_ENROLLED = "USER_MFA_ENROLLED"
USER_MFA_BYPASSED = "USER_MFA_BYPASSED"
PASSWORD_CHANGED = "PASSWORD_CHANGED"
TOKEN_REVOKED = "TOKEN_REVOKED"
# Cases
CASE_CREATED = "CASE_CREATED"
CASE_SUBMITTED = "CASE_SUBMITTED"
CASE_VALIDATED = "CASE_VALIDATED"
CASE_SCHEDULED = "CASE_SCHEDULED"
CASE_OPERATED = "CASE_OPERATED"
CASE_POST_OP = "CASE_POST_OP"
CASE_CLOSED = "CASE_CLOSED"
CASE_ARCHIVED = "CASE_ARCHIVED"
CASE_TRANSITION_REJECTED = "CASE_TRANSITION_REJECTED"
# Surgery
SURGERY_CHECKLIST_COMPLETED = "SURGERY_CHECKLIST_COMPLETED"
SURGERY_COMPLICATION_RECORDED = "SURGERY_COMPLICATION_RECORDED"
SURGERY_NOTE_CREATED = "SURGERY_NOTE_CREATED"
# Documents
DOCUMENT_UPLOADED = "DOCUMENT_UPLOADED"
DOCUMENT_DOWNLOADED = "DOCUMENT_DOWNLOADED"
DOCUMENT_DELETED = "DOCUMENT_DELETED"
# Payments
PAYMENT_CREATED = "PAYMENT_CREATED"
PAYMENT_RECORDED = "PAYMENT_RECORDED"
PAYMENT_REFUNDED = "PAYMENT_REFUNDED"
# Patient data
PATIENT_DATA_ACCESSED = "PATIENT_DATA_ACCESSED"
PATIENT_PII_DECRYPTED = "PATIENT_PII_DECRYPTED"
# Protocol
PROTOCOL_GENERATED = "PROTOCOL_GENERATED"
# Feature flags
FLAG_STATE_CHANGED = "FLAG_STATE_CHANGED"
# ---------------------------------------------------------------------------
# Async write helpers
# ---------------------------------------------------------------------------
async def _write_audit_event(event: AuditLog) -> None:
"""
Persist one audit event in its own isolated transaction.
Failures are logged but NEVER re-raised — audit writing must never
block or crash the business request.
"""
try:
from core.database.connection import AsyncSessionLocal
if AsyncSessionLocal is None:
logger.warning(
"AsyncSessionLocal not available — audit event dropped: %s", event.action
)
return
async with AsyncSessionLocal() as session:
async with session.begin():
session.add(event)
except Exception as exc:
logger.error(
"audit_write_failed action=%s entity=%s error=%s",
event.action,
event.entity_id,
exc,
)
def emit_audit_event(
action: str,
*,
user_id: Optional[str] = None,
user_role: Optional[str] = None,
entity_type: Optional[str] = None,
entity_id: Optional[str] = None,
before: Optional[Dict[str, Any]] = None,
after: Optional[Dict[str, Any]] = None,
diff: Optional[Dict[str, Any]] = None,
correlation_id: Optional[str] = None,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None,
org_id: Optional[str] = None,
extra: Optional[Dict[str, Any]] = None,
) -> None:
"""
Fire-and-forget audit event writer.
Schedules an async write as a background task (non-blocking).
Safe to call from sync or async code.
"""
event = AuditLog(
action=action,
user_id=user_id,
user_role=user_role,
entity_type=entity_type,
entity_id=entity_id,
before_snapshot=before,
after_snapshot=after,
diff=diff,
correlation_id=correlation_id,
ip_address=ip_address,
user_agent=user_agent,
org_id=org_id,
extra=extra,
)
try:
loop = asyncio.get_event_loop()
if loop.is_running():
loop.create_task(_write_audit_event(event))
else:
loop.run_until_complete(_write_audit_event(event))
except RuntimeError:
# No event loop — schedule for when one is available
asyncio.ensure_future(_write_audit_event(event))
except Exception as exc:
logger.error("emit_audit_event scheduling failed: %s", exc)