186 lines
6.6 KiB
Python
186 lines
6.6 KiB
Python
"""Tenant Context Resolution and Governance Interceptors.
|
|
|
|
Fulfills FR-TENANTMEMBERSHIPCONTEXT-002 (UC-019), FR-TENANTSECURITYAUDIT-001/003 (UC-017).
|
|
Standardized per UP-AI v1.5 / LLD-002 (§1, §3).
|
|
Resolves verified server-side tenant memberships and injects immutable TenantContext.
|
|
"""
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import logging
|
|
from typing import Any, Dict, List, Optional
|
|
import uuid
|
|
|
|
from backend.app.db.session import storage, InMemoryTenantStorage
|
|
from backend.app.models.tenant import TransactionAuditLog
|
|
|
|
logger = logging.getLogger("atb.auth.tenant_context")
|
|
|
|
SENSITIVE_KEYS = {"password", "secret", "token", "access_token", "refresh_token", "private_key", "credentials"}
|
|
|
|
|
|
def redact_sensitive_payload(data: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
|
"""Recursively redacts sensitive security keys from audit diff payloads."""
|
|
if not data:
|
|
return {}
|
|
clean = {}
|
|
for k, v in data.items():
|
|
if k.lower() in SENSITIVE_KEYS:
|
|
clean[k] = "[REDACTED]"
|
|
elif isinstance(v, dict):
|
|
clean[k] = redact_sensitive_payload(v)
|
|
else:
|
|
clean[k] = v
|
|
return clean
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TenantContext:
|
|
"""Immutable verified tenant context (LLD-002 §1)."""
|
|
tenant_id: str
|
|
subject_id: str
|
|
email: str
|
|
roles: List[str]
|
|
correlation_id: str
|
|
business_name: Optional[str] = None
|
|
|
|
|
|
class TenantContextResolutionError(Exception):
|
|
"""Raised when tenant context derivation or verification fails."""
|
|
def __init__(self, message: str, code: str = "INVALID_TENANT_CONTEXT", status_code: int = 403):
|
|
super().__init__(message)
|
|
self.message = message
|
|
self.code = code
|
|
self.status_code = status_code
|
|
|
|
|
|
class TenantContextResolver:
|
|
"""Derives and verifies active tenant context from server-side membership records."""
|
|
|
|
def __init__(self, store: InMemoryTenantStorage = storage):
|
|
self.store = store
|
|
|
|
def resolve_context(
|
|
self,
|
|
subject_id: str,
|
|
email: str,
|
|
user_roles: List[str],
|
|
requested_tenant_id: Optional[str] = None,
|
|
correlation_id: Optional[str] = None,
|
|
is_platform_route: bool = False
|
|
) -> TenantContext:
|
|
"""Derives effective tenant context.
|
|
|
|
Validates:
|
|
1. Platform admin routes allow platform context for System Administrators.
|
|
2. Client-supplied tenant ID is validated against server-side active memberships.
|
|
3. Target tenant is verified to be in ACTIVE status.
|
|
4. Fails closed (403 Forbidden) on missing, forged, suspended, or closed tenant context.
|
|
"""
|
|
corr_id = correlation_id or f"corr_{uuid.uuid4().hex[:12]}"
|
|
|
|
# Platform Admin bypass for platform control plane routes only
|
|
if is_platform_route and "System Administrator" in user_roles:
|
|
return TenantContext(
|
|
tenant_id="platform",
|
|
subject_id=subject_id,
|
|
email=email,
|
|
roles=["System Administrator"],
|
|
correlation_id=corr_id,
|
|
business_name="Platform Administration Control Plane"
|
|
)
|
|
|
|
if not requested_tenant_id:
|
|
raise TenantContextResolutionError(
|
|
"Missing tenant identifier in request context.",
|
|
code="MISSING_TENANT_CONTEXT",
|
|
status_code=400
|
|
)
|
|
|
|
# 1. Verify tenant existence and lifecycle status
|
|
tenant = self.store.get_tenant(requested_tenant_id)
|
|
if not tenant:
|
|
raise TenantContextResolutionError(
|
|
f"Tenant '{requested_tenant_id}' does not exist or is unrecognized.",
|
|
code="INVALID_TENANT_CONTEXT",
|
|
status_code=403
|
|
)
|
|
|
|
if tenant.status != "ACTIVE":
|
|
raise TenantContextResolutionError(
|
|
f"Tenant '{requested_tenant_id}' is currently {tenant.status}. Access is denied.",
|
|
code="TENANT_NOT_ACTIVE",
|
|
status_code=403
|
|
)
|
|
|
|
# 2. Verify active membership for the authenticated subject
|
|
# Query memberships matching user subject / email
|
|
eligible_memberships = [
|
|
m for m in self.store.memberships.values()
|
|
if (m.user_id == subject_id or m.email.lower() == email.lower())
|
|
and m.tenant_id == requested_tenant_id
|
|
and m.status == "ACTIVE"
|
|
]
|
|
|
|
if not eligible_memberships:
|
|
raise TenantContextResolutionError(
|
|
f"User has no active membership in tenant '{requested_tenant_id}'.",
|
|
code="INVALID_TENANT_CONTEXT",
|
|
status_code=403
|
|
)
|
|
|
|
effective_roles = list(dict.fromkeys(m.role for m in eligible_memberships))
|
|
|
|
return TenantContext(
|
|
tenant_id=requested_tenant_id,
|
|
subject_id=subject_id,
|
|
email=email,
|
|
roles=effective_roles,
|
|
correlation_id=corr_id,
|
|
business_name=tenant.business_name
|
|
)
|
|
|
|
|
|
def record_audit_event(
|
|
store: Optional[InMemoryTenantStorage] = None,
|
|
tenant_id: str = "",
|
|
actor_id: Optional[str] = None,
|
|
entity_type: Optional[str] = None,
|
|
entity_id: Optional[str] = None,
|
|
action: Optional[str] = None,
|
|
field_diff: Optional[Dict[str, Any]] = None,
|
|
correlation_id: Optional[str] = None,
|
|
**kwargs: Any
|
|
) -> TransactionAuditLog:
|
|
"""Appends an immutable transaction audit log record.
|
|
|
|
Automatically redacts sensitive payload fields and enforces append-only immutability.
|
|
Supports backward-compatible keyword aliases (actor_user_id, resource_type, etc.).
|
|
"""
|
|
target_store = store or storage
|
|
effective_actor = actor_id or kwargs.get("actor_user_id", "system")
|
|
effective_entity_type = entity_type or kwargs.get("resource_type", "Unknown")
|
|
effective_entity_id = entity_id or kwargs.get("resource_id", "")
|
|
effective_action = action or kwargs.get("action_type", "UNKNOWN")
|
|
effective_diff = field_diff if field_diff is not None else (kwargs.get("after_state") or kwargs.get("diff"))
|
|
|
|
clean_diff = redact_sensitive_payload(effective_diff)
|
|
diff_json = json.dumps(clean_diff) if clean_diff else None
|
|
|
|
log = TransactionAuditLog(
|
|
tenant_id=tenant_id,
|
|
actor_id=effective_actor,
|
|
entity_type=effective_entity_type,
|
|
entity_id=effective_entity_id,
|
|
action=effective_action,
|
|
correlation_id=correlation_id,
|
|
field_diff_json=diff_json,
|
|
timestamp=datetime.now(timezone.utc)
|
|
)
|
|
target_store.record_audit_log(log)
|
|
return log
|
|
|
|
|
|
context_resolver = TenantContextResolver()
|
|
|