Files
microfish/backend/app/services/audit_service.py
Kunthawat Greethong 8b84378fe1 feat: SaaS foundation for CrowdSight
Elevate MiroFish/CrowdSight from single-container dev to a SaaS foundation:

- Local memory backend (Zep-compatible): memory services/models, local graph
  builder + updater, AgentActivity seam, import-boundary isolation; Zep stays
  default, local is opt-in behind MEMORY_BACKEND. Semantic parity not yet proven.
- Durable product persistence: projects/simulations/reports schema (migration
  0007) + tenant/owner-scoped ProductRepository + dual-write + scoped_project
  read-first + ArtifactStore abstraction; durable JobQueue + worker.py.
- SaaS hardening: durable RateLimiter (wired to login), UsageService (LLM
  accounting), redacted AuditService, idempotency, CORS allowlist, safe API
  errors, single-use PasswordResetService + endpoints (covers invite-pending).
- Exactly 3 roles (super_admin/admin/user) with tenant authz policy.
- Admin UI: GET/POST/PATCH /api/admin/users + GET/PUT /api/admin/settings
  (super-admin only, encrypted/masked); AdminView.vue + SettingsView.vue with
  admin/super-admin route guards, th/en i18n.
- Production deploy topology: multi-stage Dockerfile (frontend build + gunicorn
  wsgi + nginx SPA-proxy + supervisord worker), backend/wsgi.py, gunicorn dep.

Backend 197 passed; frontend 10 tests + build green. ruff unavailable (gap).
No commit of credentials; secrets handled via env/.env.example.
Deferred: Zep semantic A/B parity, object storage cutover, mobile QA, EasyPanel
container build of deploy topology.
2026-08-31 13:05:21 +07:00

64 lines
1.8 KiB
Python

"""Durable, redacted audit event recording.
Audit details never store secrets, tokens, password hashes, API keys, or raw
prompts — such keys are stripped before persisting. Events are tenant-scoped.
"""
from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Session
from ..models.operations import AuditLog
_SENSITIVE_KEYS = {"password", "token", "api_key", "secret", "authorization", "prompt"}
class AuditService:
def __init__(self, session: Session):
self.session = session
@staticmethod
def _redact(details) -> Optional[dict]:
if not isinstance(details, dict):
return None
return {
key: value
for key, value in details.items()
if key.lower() not in _SENSITIVE_KEYS
}
def record(
self,
*,
organization_id: str,
actor_user_id: Optional[str] = None,
action: str,
target_type: str,
target_id: Optional[str] = None,
details: Optional[dict] = None,
) -> str:
if not isinstance(organization_id, str) or not organization_id:
raise ValueError("organization_id_required")
entry = AuditLog(
organization_id=organization_id,
actor_user_id=actor_user_id,
action=action,
target_type=target_type,
target_id=target_id,
details=self._redact(details),
)
self.session.add(entry)
self.session.flush()
return entry.id
def list_for_organization(self, *, organization_id: str, limit: int = 100) -> list[AuditLog]:
return (
self.session.query(AuditLog)
.filter(AuditLog.organization_id == organization_id)
.order_by(AuditLog.created_at.desc())
.limit(min(max(int(limit), 1), 1000))
.all()
)