"""Database Session Management and PostgreSQL RLS Isolation Engine. Fulfills FR-TENANTSECURITYAUDIT-001 (UC-017) and LLD-002 (§2). Enforces transaction-local context (`set_config('app.current_tenant_id', :tenant_id, true)`), prohibits cross-tenant data leakage across connection pool lifecycles, and provides deterministic isolation emulation for test environments. """ from contextlib import contextmanager from datetime import datetime, timezone import json import logging from typing import Any, Dict, Generator, List, Optional import uuid from backend.app.core.config import settings from backend.app.models.tenant import Tenant, TenantMembership, TransactionAuditLog logger = logging.getLogger("atb.db.session") class TenantIsolationError(Exception): """Raised when tenant context is missing, invalid, or cross-tenant leakage is detected.""" pass class ImmutableAuditViolationError(Exception): """Raised when an attempt is made to update or delete immutable transaction audit records.""" pass class InMemoryTenantStorage: """Deterministic Multi-Tenant In-Memory Storage Engine. Provides strict PostgreSQL Row-Level Security (RLS) simulation for test environments and offline execution without external database dependencies. """ def __init__(self): self.tenants: Dict[str, Tenant] = {} self.memberships: Dict[str, TenantMembership] = {} self.audit_logs: Dict[str, TransactionAuditLog] = {} self._collections: Dict[str, Dict[str, Dict[str, Any]]] = {} self.active_tenant_id: Optional[str] = None self._pool_connection_id: str = "conn_pool_01" self._seed_fixtures() def _seed_fixtures(self) -> None: """Seeds baseline fixtures so mock auth and tenants work out of the box.""" try: from sandbox.identity_mock import TEST_TENANTS, TEST_MEMBERSHIPS for t_id, data in TEST_TENANTS.items(): self.tenants[t_id] = Tenant( tenant_id=t_id, business_name=data["business_name"], legal_identifier=data.get("legal_identifier", f"GSTIN_{t_id}"), contact_email=data.get("contact_email", f"admin@{t_id}.com"), primary_mandi=data.get("primary_mandi", "APMC-PUN-01"), status=data.get("status", "ACTIVE"), created_at=data.get("created_at") ) for m in TEST_MEMBERSHIPS: mem_id = m["membership_id"] self.memberships[mem_id] = TenantMembership( membership_id=mem_id, tenant_id=m["tenant_id"], user_id=m["user_id"], email=m["email"], role=m["role"], status=m.get("status", "ACTIVE") ) except Exception as exc: logger.warning("Could not auto-seed baseline fixtures: %s", exc) try: from backend.app.db.demo_seed import seed_demo_dataset seed_demo_dataset(self, "demo-malwa-agri") except Exception as exc: logger.warning("Could not auto-seed demo dataset: %s", exc) def set_tenant_context(self, tenant_id: Optional[str]) -> None: """Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id).""" self.active_tenant_id = tenant_id def clear_tenant_context(self) -> None: """Clears transaction-local tenant isolation context upon transaction exit/pool return.""" self.active_tenant_id = None def query_tenants(self, platform_admin: bool = False) -> List[Tenant]: """Queries tenants. Platform admins see all tenants; ordinary callers see active only.""" if platform_admin: return list(self.tenants.values()) if not self.active_tenant_id: return [] tenant = self.tenants.get(self.active_tenant_id) return [tenant] if tenant else [] def save_tenant(self, tenant: Tenant) -> None: self.tenants[tenant.tenant_id] = tenant def get_tenant(self, tenant_id: str) -> Optional[Tenant]: return self.tenants.get(tenant_id) def query_memberships(self, tenant_id: Optional[str] = None) -> List[TenantMembership]: """Queries memberships enforced by RLS. If tenant context is active, caller can ONLY see memberships matching active_tenant_id. Queries without tenant context return 0 rows (fail-closed RLS invariant). """ effective_tenant = tenant_id or self.active_tenant_id if not effective_tenant or effective_tenant != self.active_tenant_id: # RLS blocks cross-tenant or unauthenticated queries return [] return [m for m in self.memberships.values() if m.tenant_id == effective_tenant and m.status == "ACTIVE"] def save_membership(self, membership: TenantMembership) -> None: # Enforce WITH CHECK RLS policy if self.active_tenant_id and membership.tenant_id != self.active_tenant_id: raise TenantIsolationError( f"RLS WITH CHECK Violation: Cannot write record for tenant '{membership.tenant_id}' " f"under active context '{self.active_tenant_id}'." ) self.memberships[membership.membership_id] = membership def get_membership(self, membership_id: str) -> Optional[TenantMembership]: membership = self.memberships.get(membership_id) if not membership: return None # Enforce USING RLS policy if self.active_tenant_id and membership.tenant_id != self.active_tenant_id: return None return membership def query_audit_logs(self, limit: int = 100) -> List[TransactionAuditLog]: """Queries audit logs scoped strictly to active tenant context.""" if not self.active_tenant_id: return [] logs = [log for log in self.audit_logs.values() if log.tenant_id == self.active_tenant_id] logs.sort(key=lambda l: l.timestamp, reverse=True) return logs[:limit] def record_audit_log(self, audit_log: TransactionAuditLog) -> None: """Records an append-only transaction audit entry.""" if self.active_tenant_id and audit_log.tenant_id != self.active_tenant_id: raise TenantIsolationError( f"RLS WITH CHECK Violation: Cannot record audit for tenant '{audit_log.tenant_id}' " f"under active context '{self.active_tenant_id}'." ) self.audit_logs[audit_log.audit_id] = audit_log def update_audit_log(self, audit_id: str, updates: Dict[str, Any]) -> None: """Enforces append-only immutability invariant (FR-TENANTSECURITYAUDIT-003).""" raise ImmutableAuditViolationError("Mutation prohibited: transaction_audit_logs is append-only.") def delete_audit_log(self, audit_id: str) -> None: """Enforces append-only immutability invariant (FR-TENANTSECURITYAUDIT-003).""" raise ImmutableAuditViolationError("Deletion prohibited: transaction_audit_logs is append-only.") def insert(self, collection: str, tenant_id: str, data: Dict[str, Any]) -> None: """Inserts a record into a tenant-scoped generic collection.""" if collection not in self._collections: self._collections[collection] = {} if tenant_id not in self._collections[collection]: self._collections[collection][tenant_id] = {} row_id = data.get("id") or str(uuid.uuid4()) self._collections[collection][tenant_id][row_id] = data def get(self, collection: str, tenant_id: str, row_id: str) -> Optional[Dict[str, Any]]: """Retrieves a record by ID scoped to tenant.""" return self._collections.get(collection, {}).get(tenant_id, {}).get(row_id) def list(self, collection: str, tenant_id: str) -> List[Dict[str, Any]]: """Lists all records in collection for tenant.""" return list(self._collections.get(collection, {}).get(tenant_id, {}).values()) def query(self, collection: str, tenant_id: str, predicate) -> List[Dict[str, Any]]: """Queries records in collection matching predicate.""" rows = self.list(collection, tenant_id) return [r for r in rows if predicate(r)] def update(self, collection: str, tenant_id: str, row_id: str, data: Dict[str, Any]) -> None: """Updates a record in collection for tenant.""" if collection in self._collections and tenant_id in self._collections[collection]: self._collections[collection][tenant_id][row_id] = data def delete(self, collection: str, tenant_id: str, row_id: str) -> None: """Deletes a record from collection for tenant.""" if collection in self._collections and tenant_id in self._collections[collection]: self._collections[collection][tenant_id].pop(row_id, None) def reset_for_tests(self) -> None: self.tenants.clear() self.memberships.clear() self.audit_logs.clear() self._collections.clear() self.active_tenant_id = None # Global in-memory storage instance storage = InMemoryTenantStorage() InMemoryStorage = InMemoryTenantStorage class DatabaseManager: """Manages transactional database sessions and PostgreSQL RLS context.""" def __init__(self, in_memory_store: InMemoryTenantStorage = storage): self.store = in_memory_store @contextmanager def transaction(self, tenant_id: Optional[str] = None): """Begins a transaction with transaction-local tenant context. Guarantees that context is cleared upon transaction commit or rollback, preventing connection pool leakage (LLD-002 §2). """ self.store.set_tenant_context(tenant_id) try: yield self.store finally: self.store.clear_tenant_context() db_manager = DatabaseManager()