oidc_provider.py 11 KB

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