from functools import lru_cache from ipaddress import ip_address, ip_network from typing import Annotated, Literal from pydantic import AliasChoices, BeforeValidator, Field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict DEVELOPMENT_JWT_SECRET = "development-only-change-me-32-bytes" def _split_csv(value: object) -> list[str]: if isinstance(value, str): return [item.strip() for item in value.split(",") if item.strip()] return list(value or []) CsvList = Annotated[list[str], BeforeValidator(_split_csv)] class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", extra="ignore", case_sensitive=False) ENVIRONMENT: str = "development" DEBUG_AUTH: bool = False DATABASE_URL: str = "sqlite:///./dev.db" AUTH_PROXY_HEADER: str = "X-Remote-User" TRUSTED_PROXY_IPS: CsvList = Field(default_factory=lambda: ["127.0.0.1", "::1"]) JWT_SECRET: str = DEVELOPMENT_JWT_SECRET JWT_ISSUER: str = "gcepic" JWT_AUDIENCE: str = "gcepic-web" JWT_IDLE_MINUTES: int = 30 JWT_ABSOLUTE_HOURS: int = 8 JWT_RENEW_BEFORE_MINUTES: int = 5 COOKIE_SECURE: bool = False SESSION_COOKIE_NAME: str = "gcepic_session" LOGIN_CSRF_COOKIE_NAME: str = "gcepic_login_csrf" LDAP_URL: str | None = None LDAP_BASE_DN: str | None = None LDAP_BIND_DN: str | None = Field( default=None, validation_alias=AliasChoices("LDAP_BIND_DN", "LDAP_USER_DN"), ) LDAP_BIND_PASSWORD: str | None = None LDAP_UPN_SUFFIX: str | None = None LDAP_START_TLS: bool = False DOCUWARE_MODE: Literal["live", "mock"] = "live" DOCUWARE_MOCK_PATH: str = "data/docuware-sample" LOCAL_STORAGE: str | None = None UPLOAD_MAX_FILE_SIZE_MB: int = Field(default=50, gt=0) LOG_LEVEL: Annotated[ Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], BeforeValidator(lambda value: str(value).upper()) ] = "INFO" LOG_DIR: str = "logs" LOG_TO_FILE: bool = True LOG_TO_CONSOLE: bool = True LOG_RETENTION_DAYS: int = Field(default=30, ge=1) LOG_SQL_STATEMENT: bool = True @model_validator(mode="after") def validate_security_settings(self) -> "Settings": if self.DEBUG_AUTH and self.ENVIRONMENT.lower() not in {"development", "debug", "test"}: raise ValueError("DEBUG_AUTH is only allowed in development, debug or test") if self.ENVIRONMENT.lower() == "production": if len(self.JWT_SECRET.encode("utf-8")) < 32 or self.JWT_SECRET == DEVELOPMENT_JWT_SECRET: raise ValueError("A unique JWT_SECRET with at least 32 bytes is required in production") if not self.COOKIE_SECURE: raise ValueError("COOKIE_SECURE must be enabled in production") if self.JWT_IDLE_MINUTES <= 0 or self.JWT_ABSOLUTE_HOURS <= 0: raise ValueError("JWT session lifetimes must be positive") return self @property def debug_auth_enabled(self) -> bool: return self.DEBUG_AUTH and self.ENVIRONMENT.lower() in {"development", "debug", "test"} def is_trusted_proxy(self, host: str | None) -> bool: if not host: return False try: address = ip_address(host) except ValueError: return host in self.TRUSTED_PROXY_IPS and self.ENVIRONMENT.lower() != "production" for entry in self.TRUSTED_PROXY_IPS: try: if address in ip_network(entry, strict=False): return True except ValueError: continue return False @lru_cache def get_settings() -> Settings: return Settings() settings = get_settings()