config.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from functools import lru_cache
  2. from ipaddress import ip_address, ip_network
  3. from typing import Annotated
  4. from pydantic import AliasChoices, BeforeValidator, Field, model_validator
  5. from pydantic_settings import BaseSettings, SettingsConfigDict
  6. DEVELOPMENT_JWT_SECRET = "development-only-change-me-32-bytes"
  7. def _split_csv(value: object) -> list[str]:
  8. if isinstance(value, str):
  9. return [item.strip() for item in value.split(",") if item.strip()]
  10. return list(value or [])
  11. CsvList = Annotated[list[str], BeforeValidator(_split_csv)]
  12. class Settings(BaseSettings):
  13. model_config = SettingsConfigDict(env_file=".env", extra="ignore", case_sensitive=False)
  14. ENVIRONMENT: str = "development"
  15. DEBUG_AUTH: bool = False
  16. DATABASE_URL: str = "sqlite:///./dev.db"
  17. AUTH_PROXY_HEADER: str = "X-Remote-User"
  18. TRUSTED_PROXY_IPS: CsvList = Field(default_factory=lambda: ["127.0.0.1", "::1"])
  19. JWT_SECRET: str = DEVELOPMENT_JWT_SECRET
  20. JWT_ISSUER: str = "gcepic"
  21. JWT_AUDIENCE: str = "gcepic-web"
  22. JWT_IDLE_MINUTES: int = 30
  23. JWT_ABSOLUTE_HOURS: int = 8
  24. JWT_RENEW_BEFORE_MINUTES: int = 5
  25. COOKIE_SECURE: bool = False
  26. SESSION_COOKIE_NAME: str = "gcepic_session"
  27. LOGIN_CSRF_COOKIE_NAME: str = "gcepic_login_csrf"
  28. LDAP_URL: str | None = None
  29. LDAP_BASE_DN: str | None = None
  30. LDAP_BIND_DN: str | None = Field(
  31. default=None,
  32. validation_alias=AliasChoices("LDAP_BIND_DN", "LDAP_USER_DN"),
  33. )
  34. LDAP_BIND_PASSWORD: str | None = None
  35. LDAP_UPN_SUFFIX: str | None = None
  36. LDAP_START_TLS: bool = False
  37. LOCAL_STORAGE: str | None = None
  38. @model_validator(mode="after")
  39. def validate_security_settings(self) -> "Settings":
  40. if self.DEBUG_AUTH and self.ENVIRONMENT.lower() not in {"development", "debug", "test"}:
  41. raise ValueError("DEBUG_AUTH is only allowed in development, debug or test")
  42. if self.ENVIRONMENT.lower() == "production":
  43. if len(self.JWT_SECRET.encode("utf-8")) < 32 or self.JWT_SECRET == DEVELOPMENT_JWT_SECRET:
  44. raise ValueError("A unique JWT_SECRET with at least 32 bytes is required in production")
  45. if not self.COOKIE_SECURE:
  46. raise ValueError("COOKIE_SECURE must be enabled in production")
  47. if self.JWT_IDLE_MINUTES <= 0 or self.JWT_ABSOLUTE_HOURS <= 0:
  48. raise ValueError("JWT session lifetimes must be positive")
  49. return self
  50. @property
  51. def debug_auth_enabled(self) -> bool:
  52. return self.DEBUG_AUTH and self.ENVIRONMENT.lower() in {"development", "debug", "test"}
  53. def is_trusted_proxy(self, host: str | None) -> bool:
  54. if not host:
  55. return False
  56. try:
  57. address = ip_address(host)
  58. except ValueError:
  59. return host in self.TRUSTED_PROXY_IPS and self.ENVIRONMENT.lower() != "production"
  60. for entry in self.TRUSTED_PROXY_IPS:
  61. try:
  62. if address in ip_network(entry, strict=False):
  63. return True
  64. except ValueError:
  65. continue
  66. return False
  67. @lru_cache
  68. def get_settings() -> Settings:
  69. return Settings()
  70. settings = get_settings()