|
| 1 | +""" |
| 2 | +Domain whitelist management for email access control. |
| 3 | +
|
| 4 | +Loads domain whitelist definitions from domain-whitelist.json and provides |
| 5 | +validation for user email domains. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import logging |
| 10 | +from pathlib import Path |
| 11 | +from typing import Optional, Set |
| 12 | +from dataclasses import dataclass |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class DomainWhitelistConfig: |
| 19 | + """Configuration for domain whitelist.""" |
| 20 | + enabled: bool |
| 21 | + domains: Set[str] |
| 22 | + subdomain_matching: bool |
| 23 | + version: str |
| 24 | + description: str |
| 25 | + |
| 26 | + |
| 27 | +class DomainWhitelistManager: |
| 28 | + """Manages domain whitelist configuration and validation.""" |
| 29 | + |
| 30 | + def __init__(self, config_path: Optional[Path] = None): |
| 31 | + """Initialize the domain whitelist manager. |
| 32 | + |
| 33 | + Args: |
| 34 | + config_path: Path to domain-whitelist.json. If None, uses default location. |
| 35 | + """ |
| 36 | + self.config: Optional[DomainWhitelistConfig] = None |
| 37 | + |
| 38 | + if config_path is None: |
| 39 | + # Try to find config in standard locations |
| 40 | + backend_root = Path(__file__).parent.parent |
| 41 | + project_root = backend_root.parent |
| 42 | + |
| 43 | + search_paths = [ |
| 44 | + project_root / "config" / "overrides" / "domain-whitelist.json", |
| 45 | + project_root / "config" / "defaults" / "domain-whitelist.json", |
| 46 | + backend_root / "configfilesadmin" / "domain-whitelist.json", |
| 47 | + backend_root / "configfiles" / "domain-whitelist.json", |
| 48 | + ] |
| 49 | + |
| 50 | + for path in search_paths: |
| 51 | + if path.exists(): |
| 52 | + config_path = path |
| 53 | + break |
| 54 | + |
| 55 | + if config_path and config_path.exists(): |
| 56 | + self._load_config(config_path) |
| 57 | + else: |
| 58 | + logger.warning("No domain-whitelist.json found, domain whitelist disabled") |
| 59 | + self.config = DomainWhitelistConfig( |
| 60 | + enabled=False, |
| 61 | + domains=set(), |
| 62 | + subdomain_matching=True, |
| 63 | + version="1.0", |
| 64 | + description="No config loaded" |
| 65 | + ) |
| 66 | + |
| 67 | + def _load_config(self, config_path: Path): |
| 68 | + """Load domain whitelist configuration from JSON file.""" |
| 69 | + try: |
| 70 | + with open(config_path, 'r', encoding='utf-8') as f: |
| 71 | + config_data = json.load(f) |
| 72 | + |
| 73 | + # Extract domains from the list of domain objects |
| 74 | + domains = set() |
| 75 | + for domain_entry in config_data.get('domains', []): |
| 76 | + if isinstance(domain_entry, dict): |
| 77 | + domains.add(domain_entry.get('domain', '').lower()) |
| 78 | + elif isinstance(domain_entry, str): |
| 79 | + domains.add(domain_entry.lower()) |
| 80 | + |
| 81 | + self.config = DomainWhitelistConfig( |
| 82 | + enabled=config_data.get('enabled', False), |
| 83 | + domains=domains, |
| 84 | + subdomain_matching=config_data.get('subdomain_matching', True), |
| 85 | + version=config_data.get('version', '1.0'), |
| 86 | + description=config_data.get('description', '') |
| 87 | + ) |
| 88 | + |
| 89 | + logger.info(f"Loaded {len(self.config.domains)} domains from {config_path}") |
| 90 | + logger.debug(f"Domain whitelist enabled: {self.config.enabled}") |
| 91 | + |
| 92 | + except Exception as e: |
| 93 | + logger.error(f"Error loading domain-whitelist.json: {e}") |
| 94 | + # Use disabled config on error |
| 95 | + self.config = DomainWhitelistConfig( |
| 96 | + enabled=False, |
| 97 | + domains=set(), |
| 98 | + subdomain_matching=True, |
| 99 | + version="1.0", |
| 100 | + description="Error loading config" |
| 101 | + ) |
| 102 | + |
| 103 | + def is_enabled(self) -> bool: |
| 104 | + """Check if domain whitelist is enabled. |
| 105 | + |
| 106 | + Returns: |
| 107 | + True if enabled, False otherwise |
| 108 | + """ |
| 109 | + return self.config is not None and self.config.enabled |
| 110 | + |
| 111 | + def is_domain_allowed(self, email: str) -> bool: |
| 112 | + """Check if an email address is from an allowed domain. |
| 113 | + |
| 114 | + Args: |
| 115 | + email: Email address to validate |
| 116 | + |
| 117 | + Returns: |
| 118 | + True if domain is allowed, False otherwise |
| 119 | + """ |
| 120 | + if not self.config or not self.config.enabled: |
| 121 | + # If not enabled or no config, allow all |
| 122 | + return True |
| 123 | + |
| 124 | + if not email or "@" not in email: |
| 125 | + return False |
| 126 | + |
| 127 | + domain = email.split("@", 1)[1].lower() |
| 128 | + |
| 129 | + # Check if domain is in whitelist (O(1) lookup) |
| 130 | + if domain in self.config.domains: |
| 131 | + return True |
| 132 | + |
| 133 | + # Check subdomains if enabled - check each parent level |
| 134 | + if self.config.subdomain_matching: |
| 135 | + # Split domain and check each parent level |
| 136 | + # e.g., for "mail.dept.sandia.gov" check: "dept.sandia.gov", "sandia.gov" |
| 137 | + parts = domain.split(".") |
| 138 | + for i in range(1, len(parts)): |
| 139 | + parent_domain = ".".join(parts[i:]) |
| 140 | + if parent_domain in self.config.domains: |
| 141 | + return True |
| 142 | + |
| 143 | + return False |
| 144 | + |
| 145 | + def get_domains(self) -> Set[str]: |
| 146 | + """Get the set of whitelisted domains. |
| 147 | + |
| 148 | + Returns: |
| 149 | + Set of allowed domains |
| 150 | + """ |
| 151 | + return self.config.domains if self.config else set() |
0 commit comments