Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
+46
View File
@@ -0,0 +1,46 @@
"""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
)
+68
View File
@@ -0,0 +1,68 @@
import uuid
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.schemas import ApprovalHistoryItem, AuditLogRead
from app.audit.service import AuditService
from app.auth.dependencies import assert_can_view_dcr, get_current_user
from app.common.enums import EntityType, Role
from app.common.exceptions import NotFoundError
from app.database.session import get_db
from app.reports.repository import DCRRepository
from app.users.models import User
router = APIRouter(prefix="/audit", tags=["audit"])
@router.get("", response_model=list[AuditLogRead])
async def get_audit_history(
entity_type: EntityType = Query(...),
entity_id: uuid.UUID = Query(...),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Scoped audit history.
For a report, the caller must be able to view the report itself — the audit log is
not a side door around the data-scope rules.
"""
if entity_type == EntityType.DCR:
dcr = await DCRRepository(db).get(entity_id)
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
elif current_user.role not in (Role.ADMIN, Role.GM):
from app.common.exceptions import ForbiddenError
raise ForbiddenError("Only ADMIN or GM may read non-report audit history")
return await AuditService(db).history_for(entity_type, entity_id)
@router.get("/dcr/{dcr_id}/approval-history", response_model=list[ApprovalHistoryItem])
async def approval_history(
dcr_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[ApprovalHistoryItem]:
""""Approval history" is a filtered view over audit_log, not a second table."""
dcr = await DCRRepository(db).get(dcr_id)
if dcr is None:
raise NotFoundError("Report not found")
await assert_can_view_dcr(db, current_user, dcr)
entries = await AuditService(db).approval_history_for(dcr_id)
items: list[ApprovalHistoryItem] = []
for entry in entries:
actor = await db.get(User, entry.actor_user_id)
items.append(
ApprovalHistoryItem(
action=entry.action,
actor_name=actor.full_name if actor else "Unknown",
actor_role=actor.role.value if actor else "-",
comment=entry.comment,
at=entry.created_at,
)
)
return items
+32
View File
@@ -0,0 +1,32 @@
import uuid
from datetime import datetime
from typing import Any
from pydantic import BaseModel, ConfigDict
from app.common.enums import AuditAction, EntityType
class AuditLogRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
actor_user_id: uuid.UUID
entity_type: EntityType
entity_id: uuid.UUID
action: AuditAction
comment: str | None
before_data: dict[str, Any] | None
after_data: dict[str, Any] | None
ip_address: str | None
created_at: datetime
class ApprovalHistoryItem(BaseModel):
"""The approval trail as shown on S7 and printed in the PDF."""
action: AuditAction
actor_name: str
actor_role: str
comment: str | None
at: datetime
+80
View File
@@ -0,0 +1,80 @@
"""Explicit, application-level audit logging.
Deliberately NOT automatic row-versioning (report §14.3 C4): an automatic versioner
records *what* changed but cannot record *why* — and the manager's return reason is
the single most important thing in this audit trail.
Every `log()` call happens inside the caller's transaction, so a state change and its
audit row commit together or not at all (V12).
"""
import uuid
from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.models import AuditLog
from app.common.enums import AuditAction, EntityType
class AuditService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
async def log(
self,
*,
actor_user_id: uuid.UUID,
entity_type: EntityType,
entity_id: uuid.UUID,
action: AuditAction,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
comment: str | None = None,
ip_address: str | None = None,
) -> AuditLog:
entry = AuditLog(
actor_user_id=actor_user_id,
entity_type=entity_type,
entity_id=entity_id,
action=action,
before_data=before,
after_data=after,
comment=comment,
ip_address=ip_address,
)
self.db.add(entry)
# Flush, not commit — the caller owns the transaction boundary.
await self.db.flush()
return entry
async def history_for(
self, entity_type: EntityType, entity_id: uuid.UUID
) -> list[AuditLog]:
stmt = (
select(AuditLog)
.where(AuditLog.entity_type == entity_type, AuditLog.entity_id == entity_id)
.order_by(AuditLog.created_at.asc())
)
return list((await self.db.execute(stmt)).scalars().all())
async def approval_history_for(self, dcr_id: uuid.UUID) -> list[AuditLog]:
""""Approval history" is a FILTERED QUERY, not a second table (report §13.2)."""
workflow_actions = [
AuditAction.CREATE,
AuditAction.SUBMIT,
AuditAction.FORWARD,
AuditAction.RETURN,
AuditAction.APPROVE,
]
stmt = (
select(AuditLog)
.where(
AuditLog.entity_type == EntityType.DCR,
AuditLog.entity_id == dcr_id,
AuditLog.action.in_(workflow_actions),
)
.order_by(AuditLog.created_at.asc())
)
return list((await self.db.execute(stmt)).scalars().all())