/** * Tenant Isolation Utilities * * Provides comprehensive multi-tenant isolation mechanisms to ensure strict data segregation * across different tenants in the slide-show platform. This module implements security * controls, data filtering, and tenant context management. * * Features: * - Strict tenant data isolation * - Tenant context validation * - Cross-tenant access prevention * - Tenant lifecycle management * - Data filtering and scoping * - Security policy enforcement * - Audit logging for tenant operations */ import type { SupabaseClient } from '@supabase/supabase-js'; import type { CustomJWTClaims } from './auth-config'; // ============================================================================ // TENANT ISOLATION INTERFACES // ============================================================================ export interface TenantContext { tenantId: string; userId: string; roles: string[]; permissions: string[]; isAdmin: boolean; sessionId?: string; deviceId?: string; } export interface TenantValidationResult { isValid: boolean; tenantId: string; errors: string[]; warnings: string[]; } export interface TenantInfo { id: string; name: string; domain?: string; status: 'active' | 'suspended' | 'inactive'; plan: 'free' | 'professional' | 'enterprise'; maxUsers: number; currentUsers: number; maxPresentations: number; currentPresentations: number; features: string[]; settings: Record; createdAt: string; updatedAt: string; } export interface CrossTenantAccessAttempt { userId: string; sourceTenantId: string; targetTenantId: string; resourceType: string; resourceId: string; action: string; timestamp: string; blocked: boolean; reason?: string; } export interface TenantResourceQuota { tenantId: string; resourceType: string; maxAllowed: number; currentUsage: number; isAtLimit: boolean; nextResetAt?: string; } export interface TenantOperationContext { tenantId: string; userId: string; operation: string; resourceType: string; resourceId?: string; metadata?: Record; } // ============================================================================ // TENANT ISOLATION MANAGER // ============================================================================ /** * Comprehensive tenant isolation management system */ export class TenantIsolationManager { private client: SupabaseClient; private currentContext?: TenantContext; constructor(client: SupabaseClient) { this.client = client; } // ============================================================================ // CONTEXT MANAGEMENT // ============================================================================ /** * Set current tenant context from JWT claims */ setTenantContext(claims: CustomJWTClaims): void { this.currentContext = { tenantId: claims.tenant_id, userId: claims.sub, roles: claims.roles || [], permissions: claims.permissions || [], isAdmin: claims.is_admin || false, sessionId: claims.session_id, deviceId: claims.device_context?.device_id, }; } /** * Get current tenant context */ getTenantContext(): TenantContext | null { return this.currentContext || null; } /** * Clear tenant context */ clearTenantContext(): void { this.currentContext = undefined; } /** * Validate tenant context */ async validateTenantContext(tenantId?: string): Promise { const contextTenantId = tenantId || this.currentContext?.tenantId; const errors: string[] = []; const warnings: string[] = []; if (!contextTenantId) { errors.push('No tenant ID provided or available in context'); return { isValid: false, tenantId: '', errors, warnings }; } try { // Validate tenant exists and is active const { data: tenant, error } = await this.client .from('tenants') .select('id, status, name') .eq('id', contextTenantId) .single(); if (error || !tenant) { errors.push(`Tenant not found: ${contextTenantId}`); return { isValid: false, tenantId: contextTenantId, errors, warnings }; } if (tenant.status !== 'active') { errors.push(`Tenant is not active: ${tenant.status}`); return { isValid: false, tenantId: contextTenantId, errors, warnings }; } // Validate user access to tenant if (this.currentContext?.userId) { const hasAccess = await this.validateUserTenantAccess( this.currentContext.userId, contextTenantId ); if (!hasAccess) { errors.push('User does not have access to this tenant'); return { isValid: false, tenantId: contextTenantId, errors, warnings }; } } // Check for any warnings (resource limits, etc.) const quotaWarnings = await this.checkResourceQuotas(contextTenantId); warnings.push(...quotaWarnings); return { isValid: errors.length === 0, tenantId: contextTenantId, errors, warnings, }; } catch (error) { console.error('[TenantIsolationManager] Validation error:', error); errors.push(`Validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); return { isValid: false, tenantId: contextTenantId, errors, warnings }; } } // ============================================================================ // DATA ISOLATION METHODS // ============================================================================ /** * Create tenant-scoped query builder */ createTenantScopedQuery<_T>(tableName: string, tenantId?: string) { const scopedTenantId = tenantId || this.currentContext?.tenantId; if (!scopedTenantId) { throw new Error('No tenant context available for scoped query'); } return this.client .from(tableName) .select() .eq('tenant_id', scopedTenantId); } /** * Filter data by tenant context */ filterByTenant(data: T[], tenantId?: string): T[] { const filterTenantId = tenantId || this.currentContext?.tenantId; if (!filterTenantId) { console.warn('[TenantIsolationManager] No tenant context for filtering, returning empty array'); return []; } return data.filter(item => item.tenant_id === filterTenantId); } /** * Validate data belongs to current tenant */ validateTenantOwnership(data: T, tenantId?: string): boolean { const ownerTenantId = tenantId || this.currentContext?.tenantId; if (!ownerTenantId) { return false; } return data.tenant_id === ownerTenantId; } /** * Enforce tenant isolation in database operations */ async enforceTenantIsolation(operation: TenantOperationContext): Promise { try { // Log the operation for audit purposes await this.logTenantOperation(operation); // Validate tenant context const validation = await this.validateTenantContext(operation.tenantId); if (!validation.isValid) { throw new Error(`Tenant validation failed: ${validation.errors.join(', ')}`); } // Check resource quotas await this.enforceResourceQuotas(operation.tenantId, operation.resourceType); // Validate user permissions if (!this.hasPermissionForOperation(operation.operation, operation.resourceType)) { throw new Error(`Insufficient permissions for operation: ${operation.operation} on ${operation.resourceType}`); } } catch (error) { console.error('[TenantIsolationManager] Tenant isolation enforcement failed:', error); // Log security violation await this.logSecurityViolation({ userId: operation.userId, tenantId: operation.tenantId, operation: operation.operation, resourceType: operation.resourceType, resourceId: operation.resourceId, error: error instanceof Error ? error.message : 'Unknown error', timestamp: new Date().toISOString(), }); throw error; } } // ============================================================================ // CROSS-TENANT ACCESS PREVENTION // ============================================================================ /** * Prevent cross-tenant data access */ async preventCrossTenantAccess( targetTenantId: string, resourceType: string, resourceId: string, action: string ): Promise { const currentTenantId = this.currentContext?.tenantId; const userId = this.currentContext?.userId; if (!currentTenantId || !userId) { throw new Error('No valid tenant context for access validation'); } if (currentTenantId !== targetTenantId) { // Log cross-tenant access attempt const accessAttempt: CrossTenantAccessAttempt = { userId, sourceTenantId: currentTenantId, targetTenantId, resourceType, resourceId, action, timestamp: new Date().toISOString(), blocked: true, reason: 'Cross-tenant access violation', }; await this.logCrossTenantAccessAttempt(accessAttempt); throw new Error(`Cross-tenant access denied: ${action} on ${resourceType}:${resourceId}`); } } /** * Validate user has access to specific tenant */ async validateUserTenantAccess(userId: string, tenantId: string): Promise { try { const { data, error } = await this.client .from('users') .select('tenant_id, status') .eq('id', userId) .eq('tenant_id', tenantId) .eq('status', 'active') .single(); return !error && !!data; } catch (error) { console.error('[TenantIsolationManager] User tenant access validation failed:', error); return false; } } // ============================================================================ // TENANT MANAGEMENT // ============================================================================ /** * Get tenant information */ async getTenantInfo(tenantId?: string): Promise { const queryTenantId = tenantId || this.currentContext?.tenantId; if (!queryTenantId) { return null; } try { const { data, error } = await this.client .from('tenants') .select('*') .eq('id', queryTenantId) .single(); if (error || !data) { return null; } // Get current usage statistics const [userCount, presentationCount] = await Promise.all([ this.getCurrentUserCount(queryTenantId), this.getCurrentPresentationCount(queryTenantId), ]); return { id: data.id, name: data.name, domain: data.domain, status: data.status, plan: data.plan, maxUsers: data.max_users || 0, currentUsers: userCount, maxPresentations: data.max_presentations || 0, currentPresentations: presentationCount, features: data.features || [], settings: data.settings || {}, createdAt: data.created_at, updatedAt: data.updated_at, }; } catch (error) { console.error('[TenantIsolationManager] Failed to get tenant info:', error); return null; } } /** * Create new tenant (admin only) */ async createTenant(tenantData: Partial): Promise { if (!this.currentContext?.isAdmin) { throw new Error('Admin privileges required to create tenant'); } try { const { data, error } = await this.client .from('tenants') .insert({ name: tenantData.name, domain: tenantData.domain, status: 'active', plan: tenantData.plan || 'free', max_users: tenantData.maxUsers || 10, max_presentations: tenantData.maxPresentations || 50, features: tenantData.features || [], settings: tenantData.settings || {}, }) .select() .single(); if (error) { throw new Error(`Failed to create tenant: ${error.message}`); } await this.logTenantOperation({ tenantId: data.id, userId: this.currentContext.userId, operation: 'create_tenant', resourceType: 'tenant', resourceId: data.id, metadata: { tenantName: data.name }, }); return { id: data.id, name: data.name, domain: data.domain, status: data.status, plan: data.plan, maxUsers: data.max_users, currentUsers: 0, maxPresentations: data.max_presentations, currentPresentations: 0, features: data.features, settings: data.settings, createdAt: data.created_at, updatedAt: data.updated_at, }; } catch (error) { console.error('[TenantIsolationManager] Failed to create tenant:', error); throw error; } } // ============================================================================ // RESOURCE QUOTA MANAGEMENT // ============================================================================ /** * Check resource quotas for tenant */ async checkResourceQuotas(tenantId: string): Promise { const warnings: string[] = []; try { const quotas = await this.getTenantResourceQuotas(tenantId); for (const quota of quotas) { const usagePercentage = (quota.currentUsage / quota.maxAllowed) * 100; if (quota.isAtLimit) { warnings.push(`Resource limit reached for ${quota.resourceType}`); } else if (usagePercentage > 90) { warnings.push(`Resource usage high for ${quota.resourceType}: ${usagePercentage.toFixed(1)}%`); } } } catch (error) { console.error('[TenantIsolationManager] Failed to check resource quotas:', error); } return warnings; } /** * Enforce resource quotas */ async enforceResourceQuotas(tenantId: string, resourceType: string): Promise { try { const quotas = await this.getTenantResourceQuotas(tenantId); const quota = quotas.find(q => q.resourceType === resourceType); if (quota && quota.isAtLimit) { throw new Error(`Resource quota exceeded for ${resourceType}. Limit: ${quota.maxAllowed}, Current: ${quota.currentUsage}`); } } catch (error) { console.error('[TenantIsolationManager] Resource quota enforcement failed:', error); throw error; } } /** * Get tenant resource quotas */ async getTenantResourceQuotas(tenantId: string): Promise { try { // Get tenant info for limits const tenantInfo = await this.getTenantInfo(tenantId); if (!tenantInfo) { return []; } const [userCount, presentationCount] = await Promise.all([ this.getCurrentUserCount(tenantId), this.getCurrentPresentationCount(tenantId), ]); return [ { tenantId, resourceType: 'users', maxAllowed: tenantInfo.maxUsers, currentUsage: userCount, isAtLimit: userCount >= tenantInfo.maxUsers, }, { tenantId, resourceType: 'presentations', maxAllowed: tenantInfo.maxPresentations, currentUsage: presentationCount, isAtLimit: presentationCount >= tenantInfo.maxPresentations, }, ]; } catch (error) { console.error('[TenantIsolationManager] Failed to get resource quotas:', error); return []; } } // ============================================================================ // UTILITY METHODS // ============================================================================ /** * Get current user count for tenant */ private async getCurrentUserCount(tenantId: string): Promise { try { const { count, error } = await this.client .from('users') .select('*', { count: 'exact', head: true }) .eq('tenant_id', tenantId) .eq('status', 'active'); return error ? 0 : count || 0; } catch (_error) { return 0; } } /** * Get current presentation count for tenant */ private async getCurrentPresentationCount(tenantId: string): Promise { try { const { count, error } = await this.client .from('presentations') .select('*', { count: 'exact', head: true }) .eq('tenant_id', tenantId); return error ? 0 : count || 0; } catch (_error) { return 0; } } /** * Check if user has permission for operation */ private hasPermissionForOperation(operation: string, resourceType: string): boolean { if (!this.currentContext) { return false; } // Admin users have all permissions if (this.currentContext.isAdmin) { return true; } // Check specific permissions const requiredPermission = `${resourceType}:${operation}`; return this.currentContext.permissions.includes(requiredPermission) || this.currentContext.permissions.includes(`${resourceType}:*`) || this.currentContext.permissions.includes('*:*'); } /** * Log tenant operation for audit */ private async logTenantOperation(operation: TenantOperationContext): Promise { try { await this.client.rpc('log_tenant_operation', { tenant_id: operation.tenantId, user_id: operation.userId, operation_type: operation.operation, resource_type: operation.resourceType, resource_id: operation.resourceId, metadata: operation.metadata || {}, timestamp: new Date().toISOString(), }); } catch (error) { console.error('[TenantIsolationManager] Failed to log tenant operation:', error); } } /** * Log cross-tenant access attempt */ private async logCrossTenantAccessAttempt(attempt: CrossTenantAccessAttempt): Promise { try { await this.client.rpc('log_cross_tenant_access_attempt', attempt); } catch (error) { console.error('[TenantIsolationManager] Failed to log cross-tenant access attempt:', error); } } /** * Log security violation */ private async logSecurityViolation(violation: Record): Promise { try { await this.client.rpc('log_security_violation', violation); } catch (error) { console.error('[TenantIsolationManager] Failed to log security violation:', error); } } } // ============================================================================ // TENANT ISOLATION UTILITIES // ============================================================================ /** * Create tenant isolation manager instance */ export function createTenantIsolationManager(client: SupabaseClient): TenantIsolationManager { return new TenantIsolationManager(client); } /** * Validate tenant ID format */ export function isValidTenantId(tenantId: string): boolean { // UUID v4 format validation const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; return uuidRegex.test(tenantId); } /** * Extract tenant ID from various sources */ export function extractTenantId(source: { headers?: Record; query?: Record; claims?: CustomJWTClaims; context?: TenantContext; }): string | null { // Priority order: claims > context > headers > query if (source.claims?.tenant_id) { return source.claims.tenant_id; } if (source.context?.tenantId) { return source.context.tenantId; } if (source.headers?.['x-tenant-id']) { return source.headers['x-tenant-id']; } if (source.query?.tenant_id) { return source.query.tenant_id; } return null; } /** * Create tenant-scoped error */ export function createTenantError(message: string, tenantId?: string): Error { const errorMessage = tenantId ? `[Tenant: ${tenantId}] ${message}` : `[No Tenant Context] ${message}`; return new Error(errorMessage); } export default TenantIsolationManager;