# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/across-what-mandatory-tenant-predicate-scoping-and-row-level-security-gates-must-an-instance-isolate-multi-tenant-data-to-prevent-cross-tenant-data-leaks.md # Remnant Warrant: https://corpusfetch.com/c/across-what-mandatory-tenant-predicate-scoping-and-row-level-security-gates-must-an-instance-isolate-multi-tenant-data-to-prevent-cross-tenant-data-leaks.warrant.json # Markdown SHA-256: 302f0b0e91945e861dda9b0171747dc9b52ee8409a83e552ba96ec748606c88b # Code AST SHA-256: bfa66a6153df07018b88c89a97d76e98e04c55d8a66b3e3ef7e3076ea1c81fb3 # Verified Classes: TenantContextViolationError, CrossTenantAccessError, MultiTenantSecureDatabase # Defensive Guards: 3 fail-closed invariants (zero external deps) import sqlite3 import contextvars from contextlib import contextmanager from typing import Any, Iterator # Request-scoped async/thread-safe context variable for tenant isolation _CURRENT_TENANT_VAR: contextvars.ContextVar[str | None] = contextvars.ContextVar( "current_tenant_id", default=None ) class TenantContextViolationError(PermissionError): '''Raised when a multi-tenant query is attempted without an active tenant context.''' pass class CrossTenantAccessError(PermissionError): '''Raised when a query or record access violates the active tenant boundary.''' pass class MultiTenantSecureDatabase: ''' Enforces absolute multi-tenant data isolation: 1. Binds tenant ID strictly to request-scoped `contextvars.ContextVar`. 2. Automatically injects `WHERE tenant_id = ?` into all SQL queries (AST scoping). 3. Simulates database Row-Level Security (RLS) by validating tenant predicates. 4. Guarantees context teardown on connection return (no session bleeding). ''' def __init__(self, conn: sqlite3.Connection) -> None: self.conn = conn self._init_schema() def _init_schema(self) -> None: with self.conn: self.conn.execute( "CREATE TABLE IF NOT EXISTS tenant_documents (" " id INTEGER PRIMARY KEY AUTOINCREMENT," " tenant_id TEXT NOT NULL," " title TEXT NOT NULL," " content TEXT NOT NULL" ")" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS idx_tenant_docs_scope " "ON tenant_documents (tenant_id, id)" ) @contextmanager def tenant_scope(self, tenant_id: str) -> Iterator[None]: ''' Gate 1: Establishes a strict request-scoped tenant boundary. Automatically resets the context token upon exiting the `with` block. ''' clean_tenant = tenant_id.strip() if not clean_tenant: raise ValueError("Tenant ID cannot be empty") token = _CURRENT_TENANT_VAR.set(clean_tenant) try: yield finally: _CURRENT_TENANT_VAR.reset(token) @staticmethod def get_current_tenant() -> str: tenant = _CURRENT_TENANT_VAR.get() if tenant is None: raise TenantContextViolationError( "Security violation: Multi-tenant query executed outside an active `tenant_scope` context" ) return tenant def execute_scoped_insert(self, title: str, content: str) -> int: ''' Gate 3: Automatically injects the active tenant ID into the insert statement, guaranteeing records can never be created without a valid tenant association. ''' tenant_id = self.get_current_tenant() with self.conn: cur = self.conn.execute( "INSERT INTO tenant_documents (tenant_id, title, content) VALUES (?, ?, ?)", (tenant_id, title, content), ) return int(cur.lastrowid) def execute_scoped_select(self, doc_id: int) -> dict[str, Any] | None: ''' Gate 3 & 4: Enforces mandatory tenant-predicate scoping on all lookups. Even if `doc_id` exists, if it belongs to another tenant, returns None (zero leak). ''' tenant_id = self.get_current_tenant() row = self.conn.execute( "SELECT id, tenant_id, title, content FROM tenant_documents " "WHERE id = ? AND tenant_id = ?", (doc_id, tenant_id), ).fetchone() if row is None: return None # Gate 4: Post-check verification if row[1] != tenant_id: raise CrossTenantAccessError("Fatal: Cross-tenant data access violation detected!") return { "id": int(row[0]), "tenant_id": row[1], "title": row[2], "content": row[3], }