oidc_provider.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from sqlalchemy import (
  4. JSON,
  5. Boolean,
  6. CheckConstraint,
  7. DateTime,
  8. ForeignKey,
  9. Integer,
  10. LargeBinary,
  11. String,
  12. Text,
  13. UniqueConstraint,
  14. func,
  15. true,
  16. )
  17. from sqlalchemy.orm import Mapped, mapped_column, relationship
  18. from backend.app.core.database import Base
  19. from backend.app.core.encryption import mfa_decrypt, mfa_encrypt
  20. class OIDCProvider(Base):
  21. """OpenID Connect provider configuration.
  22. Supports any standards-compliant OIDC provider such as PocketID,
  23. Authentik, Keycloak, Authelia, Google, etc.
  24. The issuer_url must point to the root issuer (e.g. ``https://id.example.com``).
  25. The OIDC discovery document is fetched from
  26. ``{issuer_url}/.well-known/openid-configuration`` at runtime.
  27. """
  28. __tablename__ = "oidc_providers"
  29. __table_args__ = (
  30. # DB-level enforcement of SEC-1: blocks only Fall B (email_claim='email' + require_ev=False).
  31. # Fall C (custom claim) is safe — no email_verified gate on that path.
  32. # Enforced on new installations; existing tables updated via _migrate_update_auto_link_constraint.
  33. CheckConstraint(
  34. "auto_link_existing_accounts = FALSE OR email_claim != 'email' OR require_email_verified = TRUE",
  35. name="ck_auto_link_requires_verified_email_claim",
  36. ),
  37. # All-or-nothing icon-cache record (#1333). The application keeps the
  38. # triplet consistent via _fetch_icon_or_400 + DELETE /icon, but a CHECK
  39. # constraint at the DB layer prevents drift from raw SQL maintenance
  40. # scripts, manual UPDATEs during incident recovery, etc.
  41. # Fresh installs (SQLite + PostgreSQL) get this via metadata.create_all.
  42. # Stale PostgreSQL installs get it via ALTER TABLE ADD CONSTRAINT in
  43. # run_migrations. SQLite cannot ADD CONSTRAINT to an existing table —
  44. # stale SQLite installs rely on the application layer, the same
  45. # trade-off documented for the default_group_id FK ON DELETE SET NULL.
  46. CheckConstraint(
  47. "(icon_data IS NULL) = (icon_content_type IS NULL) AND (icon_content_type IS NULL) = (icon_etag IS NULL)",
  48. name="ck_oidc_icon_triplet_co_null",
  49. ),
  50. )
  51. id: Mapped[int] = mapped_column(primary_key=True)
  52. # Human-readable name shown on the login button (e.g. "PocketID", "Google")
  53. name: Mapped[str] = mapped_column(String(100), unique=True)
  54. # Full OIDC issuer URL (e.g. "https://id.example.com")
  55. issuer_url: Mapped[str] = mapped_column(String(500))
  56. client_id: Mapped[str] = mapped_column(String(255))
  57. # Encrypted at rest when MFA_ENCRYPTION_KEY is set.
  58. # Use .client_secret / .client_secret setter rather than _client_secret_enc directly.
  59. _client_secret_enc: Mapped[str] = mapped_column("client_secret", String(512))
  60. @property
  61. def client_secret(self) -> str:
  62. return mfa_decrypt(self._client_secret_enc)
  63. @client_secret.setter
  64. def client_secret(self, value: str) -> None:
  65. self._client_secret_enc = mfa_encrypt(value)
  66. # Space-separated scopes; must include "openid"
  67. scopes: Mapped[str] = mapped_column(String(500), default="openid email profile")
  68. is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
  69. # When True, a new local user is created automatically on first OIDC login
  70. auto_create_users: Mapped[bool] = mapped_column(Boolean, default=False)
  71. # When True, an existing local user whose email matches the OIDC claim is
  72. # automatically linked on first SSO login. Default is False (conservative):
  73. # operators must explicitly opt-in to prevent an attacker-controlled IdP from
  74. # silently hijacking local accounts via email matching (M-2 fix).
  75. auto_link_existing_accounts: Mapped[bool] = mapped_column(Boolean, default=False)
  76. # JWT claim name used as the email identity (default "email").
  77. # Set to "preferred_username" or "upn" for Azure Entra ID, which does not send
  78. # email_verified — using a custom claim skips the email_verified check entirely
  79. # and is the recommended Azure configuration.
  80. # Has no interaction with require_email_verified when set to a non-"email" value:
  81. # custom claims never perform an email_verified check regardless of that setting.
  82. email_claim: Mapped[str] = mapped_column(String(64), default="email", server_default="email")
  83. # When True (default), the "email" claim is only trusted when email_verified=True.
  84. # Set to False to accept the email even when email_verified is absent — required
  85. # for providers like Azure Entra ID that never send email_verified and where a
  86. # custom claim (email_claim != "email") is not preferred.
  87. # Has no effect when email_claim is not "email": the custom-claim path never
  88. # performs an email_verified check regardless of this setting.
  89. require_email_verified: Mapped[bool] = mapped_column(Boolean, default=True, server_default=true())
  90. # Nullable FK — configurable default group for auto-created OIDC users.
  91. # Falls back to "Viewers" when None. ON DELETE SET NULL fires on PostgreSQL;
  92. # SQLite ignores it (no PRAGMA foreign_keys=ON), so runtime resolution handles dangling refs.
  93. default_group_id: Mapped[int | None] = mapped_column(
  94. Integer, ForeignKey("groups.id", ondelete="SET NULL"), nullable=True, default=None
  95. )
  96. # #3107 — JWT claim name the group sync reads IdP groups from. Defaults to
  97. # "groups". Providers put groups in different claims (Keycloak: "groups"
  98. # as a JSON array after a client mapper; Authentik: "groups" as an array,
  99. # but some setups ship "roles" or a custom claim), so it is configurable
  100. # like email_claim. Same character rules enforced by _validate_email_claim_name.
  101. group_claim: Mapped[str] = mapped_column(String(64), default="groups", server_default="groups")
  102. # #3107 — mapping of IdP group value -> Bambuddy group name. Empty dict
  103. # (the default) disables group sync entirely: the provider behaves exactly
  104. # as it did before the column existed. Only groups named in the values are
  105. # managed by the sync; everything else on the user is a manual assignment
  106. # and survives logins (#1292 semantics, same as the LDAP sync).
  107. group_mapping: Mapped[dict[str, str]] = mapped_column(JSON, default=dict, server_default="{}")
  108. # Optional icon URL the admin entered. The actual image bytes are fetched
  109. # server-side and cached in icon_data — the SPA never hotlinks this URL
  110. # (would require loosening img-src CSP; see PR #1333 / issue #1333).
  111. icon_url: Mapped[str | None] = mapped_column(Text, nullable=True, default=None)
  112. # Cached icon bytes (PNG/JPEG/WebP/GIF). Marked deferred=True so that
  113. # list-style queries (`GET /oidc/providers`) don't pull the BLOB on every
  114. # login-page render — only the GET /icon endpoint un-defers it via
  115. # `select(...).options(undefer(...))`.
  116. icon_data: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True, default=None, deferred=True)
  117. # MIME type derived from the fetched icon (e.g. "image/png"). Also serves
  118. # as the "has-icon" indicator — checked instead of icon_data so we never
  119. # accidentally trigger an async lazy-load on the deferred BLOB column.
  120. # Width 20 is plenty: the longest whitelisted value is "image/jpeg" (10
  121. # chars). Tighter than 50 so the schema documents the intent.
  122. icon_content_type: Mapped[str | None] = mapped_column(String(20), nullable=True, default=None)
  123. # SHA-256 hex of icon_data, served as the ETag header so clients can
  124. # revalidate via If-None-Match and receive 304 Not Modified.
  125. icon_etag: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
  126. # When True, the LoginPage redirects unauthenticated visitors straight to
  127. # this provider's authorize URL on mount (#1589). At most one provider can
  128. # carry this flag at a time; setting it on a new provider clears it on the
  129. # previous one. The frontend always falls back to the local form if the
  130. # authorize-URL fetch fails or times out, and ``/login?fallback=local``
  131. # plus ``BAMBUDDY_LOCAL_LOGIN=true`` provide a documented recovery path.
  132. is_autologin: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")
  133. # Marks the single provider defined by BAMBUDDY_OIDC_* env vars. Upserted on
  134. # startup; UI/API writes to it are rejected. Never delete-recreated (user_oidc_links
  135. # FK is ON DELETE CASCADE).
  136. is_env_managed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")
  137. @property
  138. def has_icon(self) -> bool:
  139. """True when cached icon bytes exist. Reads the non-deferred
  140. ``icon_content_type`` column so accessing this never triggers an
  141. async lazy-load on the deferred ``icon_data`` BLOB."""
  142. return self.icon_content_type is not None
  143. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  144. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  145. # Relationship to linked user accounts
  146. user_links: Mapped[list[UserOIDCLink]] = relationship(
  147. "UserOIDCLink",
  148. back_populates="provider",
  149. cascade="all, delete-orphan",
  150. )
  151. def __repr__(self) -> str:
  152. return f"<OIDCProvider {self.name!r}>"
  153. class UserOIDCLink(Base):
  154. """Links a local Bambuddy user account to an identity at an OIDC provider."""
  155. __tablename__ = "user_oidc_links"
  156. __table_args__ = (
  157. # T2: Prevent duplicate OIDC identities and duplicate provider links.
  158. # (provider_id, provider_user_id) — one OIDC sub per provider maps to at most one local user.
  159. UniqueConstraint("provider_id", "provider_user_id", name="uq_oidc_link_provider_sub"),
  160. # (user_id, provider_id) — one local user can link to each provider at most once.
  161. UniqueConstraint("user_id", "provider_id", name="uq_oidc_link_user_provider"),
  162. )
  163. id: Mapped[int] = mapped_column(primary_key=True)
  164. user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"), index=True)
  165. provider_id: Mapped[int] = mapped_column(Integer, ForeignKey("oidc_providers.id", ondelete="CASCADE"), index=True)
  166. # The "sub" claim from the OIDC ID token — stable identifier for the user
  167. provider_user_id: Mapped[str] = mapped_column(String(500))
  168. # Email returned by the provider (informational; may differ from local email)
  169. provider_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
  170. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  171. provider: Mapped[OIDCProvider] = relationship("OIDCProvider", back_populates="user_links")
  172. def __repr__(self) -> str:
  173. return f"<UserOIDCLink user_id={self.user_id} provider_id={self.provider_id}>"