Files
audit-core/audit_core/mock_file_backend.py
2026-07-04 00:39:03 +02:00

86 lines
2.8 KiB
Python

"""Development-only file backend for Audit Core.
Writes hourly JSONL files under ``/tmp/audit-core`` by default. See
``docs/audit-backend-contract.md`` for retention guarantees and the migration
path to durable archive backends.
"""
from __future__ import annotations
import json
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
from audit_core.interface import AuditEvent, EventValidationError, RetentionPolicy, validate_event
class MockFileAuditBackend:
"""Append audit events to hourly JSONL files and clean up old files.
Implements :class:`~audit_core.interface.AuditBackend` with
``custody_class=development``. Not suitable for production audit custody.
"""
def __init__(
self,
base_dir: str | Path | None = None,
retention_days: int | None = None,
now: datetime | None = None,
) -> None:
self.base_dir = Path(base_dir or os.environ.get("AUDIT_CORE_MOCK_DIR", "/tmp/audit-core"))
self.retention_days = int(
retention_days
if retention_days is not None
else os.environ.get("AUDIT_CORE_MOCK_RETENTION_DAYS", "7")
)
self._now = now
@property
def retention_policy(self) -> RetentionPolicy:
days = self.retention_days if self.retention_days >= 0 else None
return RetentionPolicy(
custody_class="development",
retention_days=days,
immutable=False,
tamper_evidence=False,
durable=False,
)
def emit(self, event: AuditEvent) -> str:
try:
validate_event(event)
except EventValidationError as exc:
raise ValueError(str(exc)) from exc
self.base_dir.mkdir(parents=True, exist_ok=True)
self.cleanup_old_files()
path = self.current_path()
record = event.as_record()
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n")
return str(path)
def cleanup_old_files(self) -> list[str]:
if self.retention_days < 0 or not self.base_dir.exists():
return []
cutoff = self.now() - timedelta(days=self.retention_days)
removed: list[str] = []
for path in self.base_dir.glob("audit-*.jsonl"):
try:
modified = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
except FileNotFoundError:
continue
if modified < cutoff:
path.unlink(missing_ok=True)
removed.append(str(path))
return removed
def current_path(self) -> Path:
stamp = self.now().strftime("%Y%m%dT%H")
return self.base_dir / f"audit-{stamp}.jsonl"
def now(self) -> datetime:
return self._now or datetime.now(timezone.utc)