47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
"""Append-only audit log.
|
|
|
|
`approval_history` and `comments` were NOT created as separate tables (report §13.2).
|
|
Approval history is a filtered query over this table; every comment in this system
|
|
attaches to a state change, so it lives in `audit_log.comment`.
|
|
|
|
SEC-3: the application must never be granted UPDATE or DELETE on this table. See
|
|
`scripts/harden_audit.sql`.
|
|
"""
|
|
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy import DateTime, Enum, ForeignKey, String, Text, func
|
|
from sqlalchemy.dialects.postgresql import JSONB
|
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
|
|
|
from app.common.enums import AuditAction, EntityType
|
|
from app.database.base import Base, UUIDMixin
|
|
|
|
|
|
class AuditLog(Base, UUIDMixin):
|
|
__tablename__ = "audit_log"
|
|
|
|
actor_user_id: Mapped[uuid.UUID] = mapped_column(
|
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
|
)
|
|
entity_type: Mapped[EntityType] = mapped_column(
|
|
Enum(EntityType, name="entity_type_enum", native_enum=False, length=30),
|
|
nullable=False,
|
|
index=True,
|
|
)
|
|
entity_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False, index=True)
|
|
action: Mapped[AuditAction] = mapped_column(
|
|
Enum(AuditAction, name="audit_action_enum", native_enum=False, length=20), nullable=False
|
|
)
|
|
before_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
|
|
after_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
|
|
#: The manager's reason — business context no automatic row-versioner can capture.
|
|
comment: Mapped[str | None] = mapped_column(Text)
|
|
ip_address: Mapped[str | None] = mapped_column(String(45))
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
|
|
)
|