oidc_env.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 release 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. if config is None:
  74. # Nothing to look up by name any more, so the previously managed row is
  75. # found by the flag -- and then released.
  76. released = (
  77. await db.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  78. ).scalar_one_or_none()
  79. if released is not None:
  80. # Disabled, never deleted: user_oidc_links.provider_id is FK ON
  81. # DELETE CASCADE, so removing the row would unlink every bound
  82. # account and the links would not come back when the variables do.
  83. # The flag is cleared as well: with no config behind it, a provider
  84. # the API still refuses to edit or delete would be a dead end
  85. # reachable only through the database.
  86. released.is_enabled = False
  87. released.is_env_managed = False
  88. await db.commit()
  89. logger.info(
  90. "BAMBUDDY_OIDC_* is unset -- provider %r disabled and released to the UI.",
  91. released.name,
  92. )
  93. return
  94. # Identity is the name, which is unique on the table. Matching on the flag
  95. # instead meant an operator who named the env provider after one that
  96. # already existed hit that unique constraint during startup -- and this
  97. # function runs in the lifespan, so the app would not boot.
  98. existing = (await db.execute(select(OIDCProvider).where(OIDCProvider.name == config["name"]))).scalar_one_or_none()
  99. try:
  100. # The same schema the API uses, so env config cannot reach a state the
  101. # UI would have refused (notably the SEC-1 auto-link check).
  102. validated = OIDCProviderCreate(**config)
  103. except Exception as exc: # noqa: BLE001 -- any rejection must be survivable
  104. logger.error("BAMBUDDY_OIDC_* config rejected, provider not applied: %s", exc)
  105. return
  106. if existing is None:
  107. existing = OIDCProvider(is_env_managed=True)
  108. db.add(existing)
  109. for field in _APPLIED_FIELDS:
  110. setattr(existing, field, getattr(validated, field))
  111. existing.client_secret = validated.client_secret
  112. existing.is_env_managed = True
  113. await db.flush() # the id is needed by the autologin sweep below
  114. if existing.is_autologin:
  115. await db.execute(
  116. update(OIDCProvider)
  117. .where(OIDCProvider.id != existing.id, OIDCProvider.is_autologin.is_(True))
  118. .values(is_autologin=False)
  119. )
  120. await db.commit()
  121. logger.info("Env-managed OIDC provider %r applied.", existing.name)