| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- from functools import lru_cache
- from ipaddress import ip_address, ip_network
- from typing import Annotated
- 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"
- 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
- LOCAL_STORAGE: str | None = None
- @model_validator(mode="after")
- def validate_security_settings(self) -> "Settings":
- 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
- 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()
|