oidc_env.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 pydantic import ValidationError
  12. from sqlalchemy import select, update
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. logger = logging.getLogger(__name__)
  15. # All four or nothing: a provider missing its secret would be written to the
  16. # database and then fail at authorize time, long after the operator could
  17. # connect the failure to a typo in their compose file.
  18. _REQUIRED = (
  19. "BAMBUDDY_OIDC_NAME",
  20. "BAMBUDDY_OIDC_ISSUER_URL",
  21. "BAMBUDDY_OIDC_CLIENT_ID",
  22. "BAMBUDDY_OIDC_CLIENT_SECRET",
  23. )
  24. _TRUTHY = {"true", "1", "yes"}
  25. def _env_bool(key: str, default: bool) -> bool:
  26. value = os.environ.get(key)
  27. return default if value is None else value.strip().lower() in _TRUTHY
  28. def read_env_oidc_config() -> dict | None:
  29. """The provider's fields from the environment, or None if it isn't configured.
  30. An empty required var counts as unset -- `BAMBUDDY_OIDC_CLIENT_SECRET=` in
  31. a compose file is a forgotten value, not an intentional empty secret.
  32. """
  33. if not all(os.environ.get(key) for key in _REQUIRED):
  34. return None
  35. return {
  36. "name": os.environ["BAMBUDDY_OIDC_NAME"],
  37. "issuer_url": os.environ["BAMBUDDY_OIDC_ISSUER_URL"],
  38. "client_id": os.environ["BAMBUDDY_OIDC_CLIENT_ID"],
  39. "client_secret": os.environ["BAMBUDDY_OIDC_CLIENT_SECRET"],
  40. "scopes": os.environ.get("BAMBUDDY_OIDC_SCOPES", "openid email profile"),
  41. "is_enabled": _env_bool("BAMBUDDY_OIDC_ENABLED", True),
  42. "auto_create_users": _env_bool("BAMBUDDY_OIDC_AUTO_CREATE_USERS", False),
  43. "auto_link_existing_accounts": _env_bool("BAMBUDDY_OIDC_AUTO_LINK_EXISTING", False),
  44. "email_claim": os.environ.get("BAMBUDDY_OIDC_EMAIL_CLAIM", "email"),
  45. "require_email_verified": _env_bool("BAMBUDDY_OIDC_REQUIRE_EMAIL_VERIFIED", True),
  46. "icon_url": os.environ.get("BAMBUDDY_OIDC_ICON_URL"),
  47. "is_autologin": _env_bool("BAMBUDDY_OIDC_AUTOLOGIN", False),
  48. }
  49. # Everything the schema validates and the model stores, except client_secret --
  50. # that one goes through the property so it is encrypted at rest.
  51. _APPLIED_FIELDS = (
  52. "name",
  53. "issuer_url",
  54. "client_id",
  55. "scopes",
  56. "is_enabled",
  57. "auto_create_users",
  58. "auto_link_existing_accounts",
  59. "email_claim",
  60. "require_email_verified",
  61. "icon_url",
  62. "is_autologin",
  63. )
  64. async def apply_env_oidc_provider(db: AsyncSession) -> None:
  65. """Upsert the env-managed provider, or release it when the config is gone.
  66. Never raises: this runs during startup, and a typo in one variable must not
  67. stop the app from booting. A rejected config is logged and skipped.
  68. """
  69. # Imported here rather than at module scope: app.core is imported by the
  70. # models themselves, so a top-level import would be a cycle.
  71. from backend.app.models.oidc_provider import OIDCProvider
  72. from backend.app.schemas.auth import OIDCProviderCreate
  73. config = read_env_oidc_config()
  74. if config is None:
  75. # Nothing to look up by name any more, so the previously managed rows are
  76. # found by the flag -- and then released. All of them: an install
  77. # upgraded from a version that did not sweep the flag on rename carries
  78. # two, and scalar_one_or_none() would raise MultipleResultsFound out of
  79. # the lifespan instead of booting.
  80. released_rows = (
  81. (await db.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))).scalars().all()
  82. )
  83. for released in released_rows:
  84. # Disabled, never deleted: user_oidc_links.provider_id is FK ON
  85. # DELETE CASCADE, so removing the row would unlink every bound
  86. # account and the links would not come back when the variables do.
  87. # The flag is cleared as well: with no config behind it, a provider
  88. # the API still refuses to edit or delete would be a dead end
  89. # reachable only through the database.
  90. released.is_enabled = False
  91. released.is_env_managed = False
  92. # Cleared too, or the released row keeps a latent autologin claim:
  93. # update_oidc_provider only re-runs the exclusivity sweep when a
  94. # request sets is_autologin=True, so re-enabling this row in the UI
  95. # would silently make it the autologin target again.
  96. released.is_autologin = False
  97. logger.info(
  98. "BAMBUDDY_OIDC_* is unset -- provider %r disabled and released to the UI.",
  99. released.name,
  100. )
  101. if released_rows:
  102. await db.commit()
  103. return
  104. # Identity is the name, which is unique on the table. Matching on the flag
  105. # instead meant an operator who named the env provider after one that
  106. # already existed hit that unique constraint during startup -- and this
  107. # function runs in the lifespan, so the app would not boot.
  108. existing = (await db.execute(select(OIDCProvider).where(OIDCProvider.name == config["name"]))).scalar_one_or_none()
  109. try:
  110. # The same schema the API uses, so env config cannot reach a state the
  111. # UI would have refused (notably the SEC-1 auto-link check).
  112. validated = OIDCProviderCreate(**config)
  113. except ValidationError as exc:
  114. # errors(include_input=False) strips the submitted values -- str(exc)
  115. # embeds input_value=... and would leak BAMBUDDY_OIDC_CLIENT_SECRET.
  116. logger.error(
  117. "BAMBUDDY_OIDC_* config rejected, provider not applied: %s",
  118. exc.errors(include_input=False),
  119. )
  120. return
  121. except Exception as exc: # noqa: BLE001 -- any rejection must be survivable
  122. # Log only the exception class, never str(exc): an unexpected error here
  123. # could carry a configured value in its message. Structural guarantee,
  124. # not one contingent on which exceptions the schema validators raise.
  125. logger.error("BAMBUDDY_OIDC_* config could not be applied: %s", type(exc).__name__)
  126. return
  127. if existing is None:
  128. existing = OIDCProvider(is_env_managed=True)
  129. db.add(existing)
  130. for field in _APPLIED_FIELDS:
  131. setattr(existing, field, getattr(validated, field))
  132. existing.client_secret = validated.client_secret
  133. existing.is_env_managed = True
  134. await db.flush() # the id is needed by the sweeps below
  135. # Renaming BAMBUDDY_OIDC_NAME matches nothing, so the row managed until now
  136. # stays behind. Left flagged it would keep a stale issuer and secret on the
  137. # login page while the API refuses every edit, disable and delete on it
  138. # (409) -- the dead end reachable only through the database that the release
  139. # path exists to prevent -- and the next release would find two rows and
  140. # take the boot down with MultipleResultsFound. Released, not deleted, for
  141. # the same cascade reason as everywhere else.
  142. await db.execute(
  143. update(OIDCProvider)
  144. .where(OIDCProvider.id != existing.id, OIDCProvider.is_env_managed.is_(True))
  145. .values(is_env_managed=False, is_enabled=False, is_autologin=False)
  146. )
  147. if existing.is_autologin:
  148. await db.execute(
  149. update(OIDCProvider)
  150. .where(OIDCProvider.id != existing.id, OIDCProvider.is_autologin.is_(True))
  151. .values(is_autologin=False)
  152. )
  153. await db.commit()
  154. logger.info("Env-managed OIDC provider %r applied.", existing.name)