config.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. DATABASE_URL: str = "sqlite:///./dev.db"
  16. AUTH_PROXY_HEADER: str = "X-Remote-User"
  17. TRUSTED_PROXY_IPS: CsvList = Field(default_factory=lambda: ["127.0.0.1", "::1"])
  18. JWT_SECRET: str = DEVELOPMENT_JWT_SECRET
  19. JWT_ISSUER: str = "gcepic"
  20. JWT_AUDIENCE: str = "gcepic-web"
  21. JWT_IDLE_MINUTES: int = 30
  22. JWT_ABSOLUTE_HOURS: int = 8
  23. JWT_RENEW_BEFORE_MINUTES: int = 5
  24. COOKIE_SECURE: bool = False
  25. SESSION_COOKIE_NAME: str = "gcepic_session"
  26. LOGIN_CSRF_COOKIE_NAME: str = "gcepic_login_csrf"
  27. LDAP_URL: str | None = None
  28. LDAP_BASE_DN: str | None = None
  29. LDAP_BIND_DN: str | None = Field(
  30. default=None,
  31. validation_alias=AliasChoices("LDAP_BIND_DN", "LDAP_USER_DN"),
  32. )
  33. LDAP_BIND_PASSWORD: str | None = None
  34. LDAP_UPN_SUFFIX: str | None = None
  35. LDAP_START_TLS: bool = False
  36. LOCAL_STORAGE: str | None = None
  37. @model_validator(mode="after")
  38. def validate_security_settings(self) -> "Settings":
  39. if self.ENVIRONMENT.lower() == "production":
  40. if len(self.JWT_SECRET.encode("utf-8")) < 32 or self.JWT_SECRET == DEVELOPMENT_JWT_SECRET:
  41. raise ValueError("A unique JWT_SECRET with at least 32 bytes is required in production")
  42. if not self.COOKIE_SECURE:
  43. raise ValueError("COOKIE_SECURE must be enabled in production")
  44. if self.JWT_IDLE_MINUTES <= 0 or self.JWT_ABSOLUTE_HOURS <= 0:
  45. raise ValueError("JWT session lifetimes must be positive")
  46. return self
  47. def is_trusted_proxy(self, host: str | None) -> bool:
  48. if not host:
  49. return False
  50. try:
  51. address = ip_address(host)
  52. except ValueError:
  53. return host in self.TRUSTED_PROXY_IPS and self.ENVIRONMENT.lower() != "production"
  54. for entry in self.TRUSTED_PROXY_IPS:
  55. try:
  56. if address in ip_network(entry, strict=False):
  57. return True
  58. except ValueError:
  59. continue
  60. return False
  61. @lru_cache
  62. def get_settings() -> Settings:
  63. return Settings()
  64. settings = get_settings()