"""Author: Sandeep Belgavi. Explicit tenant boundary; synthetic trusted principals.""" from dataclasses import dataclass import json @dataclass(frozen=True) class Principal: subject: str tenants: frozenset[str] scopes: frozenset[str] class TenantStore: def __init__(self, limit=2): if limit < 1: raise ValueError('Positive per-tenant limit required') self.limit, self.rows, self.cache, self.counts = limit, {}, {}, {} def authorize(self, principal, tenant, scope): if not isinstance(principal, Principal) or not principal.subject: raise PermissionError('Trusted principal required') if tenant not in principal.tenants or scope not in principal.scopes: raise PermissionError('Tenant or scope denied') def write(self, principal, tenant, incident, text): self.authorize(principal, tenant, 'write') if not incident or not text: raise ValueError('Incident and text required') key = (tenant, incident) if key not in self.rows and self.counts.get(tenant, 0) >= self.limit: raise OverflowError('Tenant record limit reached') if key not in self.rows: self.counts[tenant] = self.counts.get(tenant, 0) + 1 self.rows[key] = text self.cache.pop(key, None) def read(self, principal, tenant, incident): self.authorize(principal, tenant, 'read') # Check before cache lookup. key = (tenant, incident) if key not in self.cache: self.cache[key] = self.rows[key] return self.cache[key] def main(): store = TenantStore() a = Principal('alice', frozenset({'a'}), frozenset({'read', 'write'})) b = Principal('bob', frozenset({'b'}), frozenset({'read', 'write'})) store.write(a, 'a', 'INC-1', 'tenant-a-evidence') store.write(b, 'b', 'INC-1', 'tenant-b-evidence') denied = False try: store.read(a, 'b', 'INC-1') except PermissionError: denied = True print(json.dumps({'a': store.read(a, 'a', 'INC-1'), 'b': store.read(b, 'b', 'INC-1'), 'cross_tenant_denied': denied}, sort_keys=True)) if __name__ == '__main__': main()