"""Privileged Support Access & Tenant Resource Isolation Security Models. Fulfills: - FR-TENANTSUPPORTSECURITY-001 (End-to-End Tenant Resource Isolation) - FR-TENANTSUPPORTSECURITY-002 (Controlled Privileged Support Access) Adheres to LLD-001, LLD-002, and UP-AI v1.5 standards. """ from datetime import datetime, timezone, timedelta from typing import Optional, Dict, Any, Callable import uuid try: from sqlalchemy import Column, String, DateTime, Integer, Boolean from backend.app.models.user import Base except ImportError: class Base: pass Column = String = DateTime = Integer = Boolean = lambda *args, **kwargs: None # Constants & Status Sets SUPPORT_GRANT_STATUSES = { "PENDING", "ACTIVE", "REJECTED", "REVOKED", "EXPIRED", "BREAK_GLASS_ACTIVE" } SUPPORT_ACCESS_SCOPES = {"FULL_SUPPORT", "READ_ONLY_SUPPORT"} MIN_GRANT_MINUTES = 15 MAX_GRANT_MINUTES = 120 class MissingTenantContextException(Exception): """Raised when an asynchronous worker or thread executes without an explicit tenant context.""" pass class PrivilegedSupportGrant(Base): """Privileged support impersonation grant with dual-authorization and ephemeral lifecycle.""" __tablename__ = "privileged_support_grants" id = Column(String(36), primary_key=True) tenant_id = Column(String(36), nullable=False, index=True) engineer_user_id = Column(String(100), nullable=False) requested_by = Column(String(100), nullable=False) approved_by = Column(String(100), nullable=True) reason = Column(String(500), nullable=False) duration_minutes = Column(Integer, nullable=False, default=60) access_scope = Column(String(50), nullable=False, default="FULL_SUPPORT") status = Column(String(30), nullable=False, default="PENDING") token_jti = Column(String(64), nullable=True) requested_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc)) approved_at = Column(DateTime, nullable=True) expires_at = Column(DateTime, nullable=True) revoked_at = Column(DateTime, nullable=True) is_break_glass = Column(Boolean, nullable=False, default=False) break_glass_justification = Column(String(1000), nullable=True) def __init__( self, tenant_id: str, engineer_user_id: str, requested_by: str, reason: str, duration_minutes: int = 60, access_scope: str = "FULL_SUPPORT", is_break_glass: bool = False, break_glass_justification: Optional[str] = None, id: Optional[str] = None, ): if not tenant_id or not tenant_id.strip(): raise ValueError("Tenant ID cannot be empty") if not engineer_user_id or not engineer_user_id.strip(): raise ValueError("Engineer user ID cannot be empty") if not reason or len(reason.strip()) < 5: raise ValueError("Reason must be at least 5 characters citing incident or ticket ID") if not (MIN_GRANT_MINUTES <= duration_minutes <= MAX_GRANT_MINUTES): raise ValueError(f"Duration must be between {MIN_GRANT_MINUTES} and {MAX_GRANT_MINUTES} minutes") scope = access_scope.strip().upper() if scope not in SUPPORT_ACCESS_SCOPES: raise ValueError(f"Invalid access scope '{scope}'. Allowed: {sorted(SUPPORT_ACCESS_SCOPES)}") self.id = id or str(uuid.uuid4()) self.tenant_id = tenant_id.strip() self.engineer_user_id = engineer_user_id.strip() self.requested_by = requested_by.strip() self.reason = reason.strip() self.duration_minutes = duration_minutes self.access_scope = scope self.is_break_glass = is_break_glass self.break_glass_justification = break_glass_justification.strip() if break_glass_justification else None now = datetime.now(timezone.utc) self.requested_at = now if is_break_glass: if not self.break_glass_justification or len(self.break_glass_justification) < 10: raise ValueError("Break-glass justification must be at least 10 characters") self.status = "BREAK_GLASS_ACTIVE" self.approved_by = "BREAK_GLASS_EMERGENCY" self.approved_at = now self.expires_at = now + timedelta(minutes=duration_minutes) self.token_jti = str(uuid.uuid4()) else: self.status = "PENDING" self.approved_by = None self.approved_at = None self.expires_at = None self.token_jti = None def approve(self, approver_email: str, duration_minutes: Optional[int] = None) -> str: """Approves the grant, setting status to ACTIVE and issuing a fresh ephemeral token JTI.""" if self.status != "PENDING": raise ValueError(f"Cannot approve grant with status '{self.status}'. Must be 'PENDING'.") if not approver_email or not approver_email.strip(): raise ValueError("Approver email cannot be empty") if approver_email.strip().lower() == self.requested_by.strip().lower(): raise ValueError("Dual authorization required: requester cannot self-approve support grant.") if duration_minutes is not None: if not (MIN_GRANT_MINUTES <= duration_minutes <= MAX_GRANT_MINUTES): raise ValueError(f"Duration must be between {MIN_GRANT_MINUTES} and {MAX_GRANT_MINUTES} minutes") self.duration_minutes = duration_minutes now = datetime.now(timezone.utc) self.approved_by = approver_email.strip() self.approved_at = now self.expires_at = now + timedelta(minutes=self.duration_minutes) self.status = "ACTIVE" self.token_jti = str(uuid.uuid4()) return self.token_jti def reject(self, rejector_email: str, reason: Optional[str] = None) -> None: """Rejects the grant request.""" if self.status != "PENDING": raise ValueError(f"Cannot reject grant with status '{self.status}'. Must be 'PENDING'.") self.status = "REJECTED" self.approved_by = rejector_email.strip() self.revoked_at = datetime.now(timezone.utc) def revoke(self, revoker_email: str) -> None: """Revokes an active or break-glass grant immediately.""" if self.status not in {"ACTIVE", "BREAK_GLASS_ACTIVE"}: raise ValueError(f"Cannot revoke grant with status '{self.status}'. Must be 'ACTIVE' or 'BREAK_GLASS_ACTIVE'.") self.status = "REVOKED" self.revoked_at = datetime.now(timezone.utc) def is_valid(self, as_of: Optional[datetime] = None) -> bool: """Checks whether the grant is currently active and within its expiration window.""" ref_time = as_of or datetime.now(timezone.utc) if self.status not in {"ACTIVE", "BREAK_GLASS_ACTIVE"}: return False if not self.expires_at: return False exp = self.expires_at if exp.tzinfo is None: exp = exp.replace(tzinfo=timezone.utc) if ref_time.tzinfo is None: ref_time = ref_time.replace(tzinfo=timezone.utc) if ref_time >= exp: self.status = "EXPIRED" return False return True def to_dict(self) -> Dict[str, Any]: return { "id": self.id, "tenant_id": self.tenant_id, "engineer_user_id": self.engineer_user_id, "requested_by": self.requested_by, "approved_by": self.approved_by, "reason": self.reason, "duration_minutes": self.duration_minutes, "access_scope": self.access_scope, "status": self.status, "token_jti": self.token_jti, "requested_at": self.requested_at.isoformat() if hasattr(self.requested_at, "isoformat") else str(self.requested_at), "approved_at": self.approved_at.isoformat() if hasattr(self.approved_at, "isoformat") and self.approved_at else None, "expires_at": self.expires_at.isoformat() if hasattr(self.expires_at, "isoformat") and self.expires_at else None, "revoked_at": self.revoked_at.isoformat() if hasattr(self.revoked_at, "isoformat") and self.revoked_at else None, "is_break_glass": self.is_break_glass, "break_glass_justification": self.break_glass_justification, } def run_with_tenant_context(tenant_id: Optional[str], fn: Callable, *args, **kwargs) -> Any: """Fail-closed execution wrapper enforcing explicit tenant context for background tasks. Fulfills FR-TENANTSUPPORTSECURITY-001: prevents worker execution without tenant scope. """ if not tenant_id or not tenant_id.strip(): raise MissingTenantContextException("Fail-closed security check: Background task executed without tenant context.") return fn(*args, **kwargs)