# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/at-what-boot-time-schema-and-secret-precondition-gates-must-an-instance-validate-runtime-configuration-to-prevent-late-bound-production-crashes.md # Remnant Warrant: https://corpusfetch.com/c/at-what-boot-time-schema-and-secret-precondition-gates-must-an-instance-validate-runtime-configuration-to-prevent-late-bound-production-crashes.warrant.json # Markdown SHA-256: 5dc63d2b696db2733af77895ad765302216bf932b288c4c1f003741f448e06ea # Code AST SHA-256: 197554523b4c273457d6039536b5efe6440f0ffeedf9fc5513607a175a7470e7 # Verified Classes: StartupConfigError, AppRuntimeConfig # Defensive Guards: 4 fail-closed invariants (zero external deps) import os from dataclasses import dataclass, field from typing import Mapping from urllib.parse import urlsplit _TRUE_STRINGS = frozenset({"1", "true", "yes", "on"}) _FALSE_STRINGS = frozenset({"0", "false", "no", "off"}) class StartupConfigError(RuntimeError): '''Raised at process boot when one or more configuration invariants fail.''' pass def parse_strict_env_bool(raw: str, key_name: str) -> bool: ''' Parses a boolean environment string strictly without falling into Python's `bool("false") == True` trap. ''' normalized = raw.strip().lower() if normalized in _TRUE_STRINGS: return True if normalized in _FALSE_STRINGS: return False raise ValueError( f"{key_name}: invalid boolean string {raw!r}; " f"expected one of {sorted(_TRUE_STRINGS | _FALSE_STRINGS)}" ) def parse_bounded_env_int( raw: str, key_name: str, *, min_val: int, max_val: int, ) -> int: try: val = int(raw.strip(), 10) except ValueError as exc: raise ValueError(f"{key_name}: expected base-10 integer, got {raw!r}") from exc if not (min_val <= val <= max_val): raise ValueError( f"{key_name}: value {val} out of allowed bounds [{min_val}, {max_val}]" ) return val @dataclass(frozen=True) class AppRuntimeConfig: ''' Immutable, boot-verified runtime configuration. Secret fields use `repr=False` so logging `config` never leaks credentials. ''' environment: str listen_port: int db_pool_size: int enable_metrics: bool database_url: str = field(repr=False) hmac_signing_key: bytes = field(repr=False) @classmethod def load_and_verify_at_boot( cls, env_map: Mapping[str, str] | None = None, ) -> "AppRuntimeConfig": ''' Validates all required environment variables in a single pass at startup. Aggregates all errors so operators see every misconfiguration at once. ''' source = os.environ if env_map is None else env_map errors: list[str] = [] # 1. Environment tier validation raw_env = source.get("APP_ENV", "production").strip().lower() if raw_env not in ("development", "staging", "production", "test"): errors.append( f"APP_ENV: invalid environment {raw_env!r}; expected development|staging|production|test" ) # 2. Bounded integer port & pool size listen_port = 8080 if "PORT" in source: try: listen_port = parse_bounded_env_int( source["PORT"], "PORT", min_val=1, max_val=65535 ) except ValueError as exc: errors.append(str(exc)) db_pool_size = 10 if "DB_POOL_SIZE" in source: try: db_pool_size = parse_bounded_env_int( source["DB_POOL_SIZE"], "DB_POOL_SIZE", min_val=1, max_val=200 ) except ValueError as exc: errors.append(str(exc)) # 3. Strict boolean parsing (blocks `bool("false") == True`) enable_metrics = True if "ENABLE_METRICS" in source: try: enable_metrics = parse_strict_env_bool( source["ENABLE_METRICS"], "ENABLE_METRICS" ) except ValueError as exc: errors.append(str(exc)) # 4. Required Database URL (no insecure localhost fallback in prod!) raw_db_url = source.get("DATABASE_URL", "").strip() if not raw_db_url: errors.append("DATABASE_URL: required variable is missing or empty") else: parsed_url = urlsplit(raw_db_url) if parsed_url.scheme not in ("postgresql", "postgres", "sqlite"): errors.append( f"DATABASE_URL: unsupported scheme {parsed_url.scheme!r} (redacted host/credentials)" ) # 5. Required Cryptographic Secret with minimum entropy length check raw_secret = source.get("HMAC_SIGNING_KEY", "") hmac_bytes = raw_secret.encode("utf-8") if not raw_secret: errors.append("HMAC_SIGNING_KEY: required secret variable is missing") elif len(hmac_bytes) < 32: errors.append( f"HMAC_SIGNING_KEY: must be at least 32 bytes long (got {len(hmac_bytes)} bytes)" ) elif raw_secret.lower() in ("changeme", "secret", "default", "dev-secret"): errors.append("HMAC_SIGNING_KEY: insecure placeholder value is forbidden") # Gate: Fail fast with aggregated report BEFORE binding sockets or starting workers if errors: bullet_list = "\n - ".join(errors) raise StartupConfigError( f"Boot-time configuration validation failed with {len(errors)} error(s):\n - {bullet_list}" ) return cls( environment=raw_env, listen_port=listen_port, db_pool_size=db_pool_size, enable_metrics=enable_metrics, database_url=raw_db_url, hmac_signing_key=hmac_bytes, )