oidc_env.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Read the single OIDC provider defined by BAMBUDDY_OIDC_* env vars (#2593).
  2. A declarative deployment (compose, Helm, GitOps) has no way to click through
  3. the settings UI, so one provider can be configured entirely from the
  4. environment. This module only reads and defaults; validity is decided by the
  5. same OIDCProviderCreate schema the API uses, so env config cannot bypass a
  6. check the UI enforces.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import os
  11. from sqlalchemy import select, update
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. logger = logging.getLogger(__name__)
  14. # All four or nothing: a provider missing its secret would be written to the
  15. # database and then fail at authorize time, long after the operator could
  16. # connect the failure to a typo in their compose file.
  17. _REQUIRED = (
  18. "BAMBUDDY_OIDC_NAME",
  19. "BAMBUDDY_OIDC_ISSUER_URL",
  20. "BAMBUDDY_OIDC_CLIENT_ID",
  21. "BAMBUDDY_OIDC_CLIENT_SECRET",
  22. )
  23. _TRUTHY = {"true", "1", "yes"}
  24. def _env_bool(key: str, default: bool) -> bool:
  25. value = os.environ.get(key)
  26. return default if value is None else value.strip().lower() in _TRUTHY
  27. def read_env_oidc_config() -> dict | None:
  28. """The provider's fields from the environment, or None if it isn't configured.
  29. An empty required var counts as unset -- `BAMBUDDY_OIDC_CLIENT_SECRET=` in
  30. a compose file is a forgotten value, not an intentional empty secret.
  31. """
  32. if not all(os.environ.get(key) for key in _REQUIRED):
  33. return None
  34. return {
  35. "name": os.environ["BAMBUDDY_OIDC_NAME"],
  36. "issuer_url": os.environ["BAMBUDDY_OIDC_ISSUER_URL"],
  37. "client_id": os.environ["BAMBUDDY_OIDC_CLIENT_ID"],
  38. "client_secret": os.environ["BAMBUDDY_OIDC_CLIENT_SECRET"],
  39. "scopes": os.environ.get("BAMBUDDY_OIDC_SCOPES", "openid email profile"),
  40. "is_enabled": _env_bool("BAMBUDDY_OIDC_ENABLED", True),
  41. "auto_create_users": _env_bool("BAMBUDDY_OIDC_AUTO_CREATE_USERS", False),
  42. "auto_link_existing_accounts": _env_bool("BAMBUDDY_OIDC_AUTO_LINK_EXISTING", False),
  43. "email_claim": os.environ.get("BAMBUDDY_OIDC_EMAIL_CLAIM", "email"),
  44. "require_email_verified": _env_bool("BAMBUDDY_OIDC_REQUIRE_EMAIL_VERIFIED", True),
  45. "icon_url": os.environ.get("BAMBUDDY_OIDC_ICON_URL"),
  46. "is_autologin": _env_bool("BAMBUDDY_OIDC_AUTOLOGIN", False),
  47. }
  48. # Everything the schema validates and the model stores, except client_secret --
  49. # that one goes through the property so it is encrypted at rest.
  50. _APPLIED_FIELDS = (
  51. "name",
  52. "issuer_url",
  53. "client_id",
  54. "scopes",
  55. "is_enabled",
  56. "auto_create_users",
  57. "auto_link_existing_accounts",
  58. "email_claim",
  59. "require_email_verified",
  60. "icon_url",
  61. "is_autologin",
  62. )
  63. async def apply_env_oidc_provider(db: AsyncSession) -> None:
  64. """Upsert the env-managed provider, or disable it when the config is gone.
  65. Never raises: this runs during startup, and a typo in one variable must not
  66. stop the app from booting. A rejected config is logged and skipped.
  67. """
  68. # Imported here rather than at module scope: app.core is imported by the
  69. # models themselves, so a top-level import would be a cycle.
  70. from backend.app.models.oidc_provider import OIDCProvider
  71. from backend.app.schemas.auth import OIDCProviderCreate
  72. config = read_env_oidc_config()
  73. existing = (
  74. await db.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  75. ).scalar_one_or_none()
  76. if config is None:
  77. # Disabled, never deleted: user_oidc_links.provider_id is FK ON DELETE
  78. # CASCADE, so removing the row would unlink every bound account and the
  79. # links would not come back when the variables do.
  80. if existing is not None and existing.is_enabled:
  81. existing.is_enabled = False
  82. await db.commit()
  83. logger.info("BAMBUDDY_OIDC_* is unset -- env-managed provider disabled.")
  84. return
  85. try:
  86. # The same schema the API uses, so env config cannot reach a state the
  87. # UI would have refused (notably the SEC-1 auto-link check).
  88. validated = OIDCProviderCreate(**config)
  89. except Exception as exc: # noqa: BLE001 -- any rejection must be survivable
  90. logger.error("BAMBUDDY_OIDC_* config rejected, provider not applied: %s", exc)
  91. return
  92. if existing is None:
  93. existing = OIDCProvider(is_env_managed=True)
  94. db.add(existing)
  95. for field in _APPLIED_FIELDS:
  96. setattr(existing, field, getattr(validated, field))
  97. existing.client_secret = validated.client_secret
  98. existing.is_env_managed = True
  99. await db.flush() # the id is needed by the autologin sweep below
  100. if existing.is_autologin:
  101. await db.execute(
  102. update(OIDCProvider)
  103. .where(OIDCProvider.id != existing.id, OIDCProvider.is_autologin.is_(True))
  104. .values(is_autologin=False)
  105. )
  106. await db.commit()
  107. logger.info("Env-managed OIDC provider %r applied.", existing.name)