auth.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. import re
  2. from typing import Literal
  3. from pydantic import BaseModel, Field, field_validator, model_validator
  4. from backend.app.schemas.group import FilamentRuleSchema
  5. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  6. def _validate_password_complexity(v: str) -> str:
  7. """Enforce minimum password complexity (M-C).
  8. Requires at least one uppercase letter, one lowercase letter, one digit,
  9. and one special character in addition to the min_length=8 Field constraint.
  10. """
  11. if not re.search(r"[A-Z]", v):
  12. raise ValueError("Password must contain at least one uppercase letter")
  13. if not re.search(r"[a-z]", v):
  14. raise ValueError("Password must contain at least one lowercase letter")
  15. if not re.search(r"\d", v):
  16. raise ValueError("Password must contain at least one digit")
  17. if not re.search(r"[^A-Za-z0-9]", v):
  18. raise ValueError("Password must contain at least one special character")
  19. return v
  20. class GroupBrief(BaseModel):
  21. """Brief group info for embedding in user responses."""
  22. id: int
  23. name: str
  24. class Config:
  25. from_attributes = True
  26. class LoginRequest(BaseModel):
  27. username: str = Field(..., max_length=150)
  28. password: str = Field(..., max_length=256)
  29. class LoginResponse(BaseModel):
  30. access_token: str | None = None
  31. token_type: str = "bearer"
  32. user: "UserResponse | None" = None
  33. # Set when 2FA is required; the frontend must call /auth/2fa/verify
  34. requires_2fa: bool = False
  35. pre_auth_token: str | None = None
  36. two_fa_methods: list[str] = []
  37. class UserCreate(BaseModel):
  38. username: str = Field(..., max_length=150)
  39. password: str | None = Field(default=None, max_length=256) # M-NEW-4: cap before pbkdf2
  40. email: str | None = Field(default=None, max_length=254) # L-NEW-5: RFC 5321 max
  41. role: str = "user"
  42. group_ids: list[int] | None = None
  43. @field_validator("password")
  44. @classmethod
  45. def validate_password(cls, v: str | None) -> str | None:
  46. if v is not None:
  47. _validate_password_complexity(v)
  48. return v
  49. class UserUpdate(IgnoresNullForRequiredColumns):
  50. __orm_table__ = "users"
  51. username: str | None = Field(default=None, max_length=150)
  52. password: str | None = Field(default=None, max_length=256) # M-NEW-4: cap before pbkdf2
  53. email: str | None = Field(default=None, max_length=254) # L-NEW-5: RFC 5321 max
  54. role: str | None = None
  55. is_active: bool | None = None
  56. group_ids: list[int] | None = None
  57. @field_validator("password")
  58. @classmethod
  59. def validate_password(cls, v: str | None) -> str | None:
  60. if v is not None:
  61. _validate_password_complexity(v)
  62. return v
  63. class FilamentPolicyBrief(BaseModel):
  64. """One restricted group's filament rules, as the print dialog applies them (#3522)."""
  65. group: str
  66. mode: Literal["allow", "block"]
  67. rules: list[FilamentRuleSchema] = []
  68. class UserResponse(BaseModel):
  69. id: int
  70. username: str
  71. email: str | None = None
  72. role: str # Deprecated, kept for backward compatibility
  73. is_active: bool
  74. is_admin: bool # Computed from role and group membership
  75. auth_source: str = "local" # "local" or "ldap"
  76. groups: list[GroupBrief] = []
  77. permissions: list[str] = [] # All permissions from groups
  78. # None: may print with every filament. Otherwise a filament is allowed when
  79. # any of these policies allows it (#3522); the server enforces the same.
  80. filament_policies: list[FilamentPolicyBrief] | None = None
  81. created_at: str
  82. class Config:
  83. from_attributes = True
  84. class UserSlim(BaseModel):
  85. """Just enough to resolve a user id to a display name (#1894).
  86. Deliberately narrower than ``UserResponse``: no email, role, auth source,
  87. group membership or permission set. Adding a field here widens what every
  88. ``can_read_status`` API key can read about every account, so treat this
  89. shape as the contract rather than a starting point.
  90. """
  91. id: int
  92. username: str
  93. class Config:
  94. from_attributes = True
  95. class LDAPSearchResultResponse(BaseModel):
  96. """One match from GET /auth/ldap/search — surfaced in the admin UI."""
  97. username: str
  98. email: str | None = None
  99. display_name: str | None = None
  100. dn: str
  101. already_provisioned: bool = False # True if this username already exists as a BamBuddy user
  102. class LDAPTestRequest(BaseModel):
  103. """The LDAP settings in the form, tested before they are saved.
  104. A field left out uses the saved value; an empty bind password keeps the
  105. saved one.
  106. """
  107. ldap_server_url: str | None = None
  108. ldap_bind_dn: str | None = None
  109. ldap_bind_password: str | None = None
  110. ldap_search_base: str | None = None
  111. ldap_user_filter: str | None = None
  112. ldap_security: str | None = None
  113. class LDAPProvisionRequest(BaseModel):
  114. """Body for POST /auth/ldap/provision. Username is re-resolved via the
  115. service-account bind, so the request only carries the directory username
  116. the admin picked from the search results."""
  117. username: str = Field(..., max_length=150)
  118. class ChangePasswordRequest(BaseModel):
  119. current_password: str = Field(..., max_length=256) # M-NEW-3: cap before pbkdf2
  120. new_password: str = Field(..., min_length=8, max_length=256)
  121. @field_validator("new_password")
  122. @classmethod
  123. def validate_new_password(cls, v: str) -> str:
  124. return _validate_password_complexity(v)
  125. class SetupRequest(BaseModel):
  126. auth_enabled: bool
  127. admin_username: str | None = Field(default=None, max_length=150)
  128. admin_password: str | None = Field(default=None, max_length=256)
  129. # Password complexity is NOT validated at the schema layer. When re-enabling auth
  130. # with an existing admin user (or when LDAP is the auth backend), the frontend
  131. # still sends whatever is in the password field but the route ignores it.
  132. # Enforcing complexity here would reject those legitimate flows. The route body
  133. # applies the check only when a brand-new local admin is actually being created.
  134. class SetupResponse(BaseModel):
  135. auth_enabled: bool
  136. admin_created: bool | None = None
  137. class ForgotPasswordRequest(BaseModel):
  138. email: str = Field(..., max_length=254) # L-NEW-1: RFC 5321 max; caps memory/CPU before lookup
  139. class ForgotPasswordConfirmRequest(BaseModel):
  140. token: str = Field(..., max_length=128)
  141. new_password: str = Field(..., min_length=8, max_length=256)
  142. @field_validator("new_password")
  143. @classmethod
  144. def validate_new_password(cls, v: str) -> str:
  145. return _validate_password_complexity(v)
  146. class ForgotPasswordResponse(BaseModel):
  147. message: str
  148. class ResetPasswordRequest(BaseModel):
  149. user_id: int
  150. class ResetPasswordResponse(BaseModel):
  151. message: str
  152. class SMTPSettings(BaseModel):
  153. smtp_host: str
  154. smtp_port: int
  155. smtp_username: str | None = None # Optional when auth is disabled
  156. smtp_password: str | None = None # Optional for read operations or when auth is disabled
  157. smtp_security: str = "starttls" # 'starttls', 'ssl', 'none'
  158. smtp_auth_enabled: bool = True
  159. smtp_from_email: str
  160. smtp_from_name: str = "BamBuddy"
  161. # Deprecated field for backward compatibility
  162. smtp_use_tls: bool | None = None
  163. class TestSMTPRequest(BaseModel):
  164. test_recipient: str
  165. # The settings in the form, tested before they are saved; left out, the
  166. # saved ones. An empty password keeps the saved one.
  167. smtp: SMTPSettings | None = None
  168. class TestSMTPResponse(BaseModel):
  169. success: bool
  170. message: str
  171. # ---------------------------------------------------------------------------
  172. # 2FA / MFA schemas
  173. # ---------------------------------------------------------------------------
  174. class TwoFAStatusResponse(BaseModel):
  175. totp_enabled: bool
  176. email_otp_enabled: bool
  177. backup_codes_remaining: int
  178. class TOTPSetupResponse(BaseModel):
  179. """Returned when a user initiates TOTP setup. The frontend should display
  180. the QR code image (base64 PNG) and ask the user to scan it, then call
  181. /auth/2fa/totp/enable with a valid code to confirm."""
  182. secret: str # base32 secret (shown as fallback text)
  183. qr_code_b64: str # base64-encoded PNG of the QR code
  184. issuer: str
  185. class TOTPSetupRequest(BaseModel):
  186. """Optional body for POST /auth/2fa/totp/setup.
  187. Only required when re-initialising setup while an active TOTP record exists.
  188. Provide the current TOTP code (from the existing authenticator app) to
  189. confirm intent — mirrors the verification requirement in disable_totp.
  190. """
  191. code: str | None = Field(default=None, max_length=8) # L-NEW-2: bound before pyotp
  192. class TOTPEnableRequest(BaseModel):
  193. code: str # 6-digit TOTP code from the authenticator app
  194. @field_validator("code")
  195. @classmethod
  196. def validate_code(cls, v: str) -> str:
  197. v = v.strip()
  198. if not v.isdigit() or len(v) != 6:
  199. raise ValueError("TOTP code must be exactly 6 digits")
  200. return v
  201. class TOTPEnableResponse(BaseModel):
  202. message: str
  203. backup_codes: list[str] # plain-text codes shown once; user must save them
  204. class TOTPDisableRequest(BaseModel):
  205. """Requires a valid TOTP code OR a backup code to disable TOTP."""
  206. code: str = Field(..., max_length=128)
  207. class BackupCodesResponse(BaseModel):
  208. backup_codes: list[str]
  209. message: str
  210. class TwoFAVerifyRequest(BaseModel):
  211. pre_auth_token: str = Field(..., max_length=128)
  212. # TOTP/email codes are 6 digits; backup codes are 8 uppercase alphanumeric chars.
  213. # max_length=8 prevents excessively long inputs from reaching pbkdf2/pyotp.
  214. code: str = Field(..., min_length=6, max_length=8)
  215. method: Literal["totp", "email", "backup"] = "totp"
  216. @field_validator("code")
  217. @classmethod
  218. def validate_code_format(cls, v: str) -> str:
  219. v = v.strip()
  220. if not re.match(r"^[A-Za-z0-9]{6,8}$", v):
  221. raise ValueError("Code must be 6–8 alphanumeric characters")
  222. return v.upper() # normalise backup codes to uppercase
  223. class TwoFAVerifyResponse(BaseModel):
  224. access_token: str
  225. token_type: str = "bearer"
  226. user: "UserResponse"
  227. class EmailOTPSendRequest(BaseModel):
  228. pre_auth_token: str = Field(..., max_length=128)
  229. class EmailOTPEnableConfirmRequest(BaseModel):
  230. """Body for the second step of email OTP enable: verify the proof-of-possession code."""
  231. setup_token: str = Field(..., max_length=128)
  232. # L-NEW-3: email OTP setup codes are always exactly 6 digits; reject anything else.
  233. code: str = Field(..., min_length=6, max_length=6)
  234. @field_validator("code")
  235. @classmethod
  236. def validate_code_digits(cls, v: str) -> str:
  237. v = v.strip()
  238. if not v.isdigit() or len(v) != 6:
  239. raise ValueError("Email OTP setup code must be exactly 6 digits")
  240. return v
  241. class EmailOTPDisableRequest(BaseModel):
  242. """Requires the account password to disable email OTP."""
  243. password: str = Field(..., max_length=256)
  244. class AdminDisable2FARequest(BaseModel):
  245. """Admin must supply their own password as re-auth before disabling 2FA for another user.
  246. OIDC/LDAP-only admins (no local password_hash) are exempt from this check.
  247. """
  248. admin_password: str | None = Field(default=None, max_length=256)
  249. # ---------------------------------------------------------------------------
  250. # OIDC schemas
  251. # ---------------------------------------------------------------------------
  252. AUTO_LINK_REQUIREMENTS_ERROR = (
  253. "auto_link_existing_accounts requires require_email_verified=True when email_claim='email'"
  254. )
  255. def _validate_email_claim_name(v: str) -> str:
  256. # Accepts only alphanumeric/underscore/hyphen claim names starting with a letter —
  257. # prevents log injection and limits the attack surface of operator-supplied claim names.
  258. if not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_\-]{0,63}", v):
  259. raise ValueError("Invalid claim name")
  260. return v
  261. def _validate_group_claim_name(v: str) -> str:
  262. """#3107 — like _validate_email_claim_name, but also allows one slash.
  263. Auth0 (and Auth0-compatible providers) only expose custom claims under a
  264. non-reserved namespace, e.g. ``https://example.com/roles`` or ``app/roles``,
  265. so the email-claim charset would refuse every valid Auth0 group claim.
  266. The slash is structurally safe here: the value never reaches a URL, a
  267. path or SQL — it is only a JWT claim lookup key inside ``claims.get`` —
  268. so the wider charset does not widen any injection surface. The 64-char
  269. cap and the "starts with a letter" rule are kept. The full-URL form of
  270. an Auth0 namespace exceeds 64 chars, but that is Auth0's documented
  271. short-namespace territory; the limit matches email_claim and keeps the
  272. column bound meaningful.
  273. """
  274. if not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_\-/]{0,63}", v):
  275. raise ValueError("Invalid claim name")
  276. return v
  277. def _validate_group_mapping(v: dict[str, str]) -> dict[str, str]:
  278. """#3107 — normalise and bound an IdP-group -> Bambuddy-group mapping.
  279. Values must reference Bambuddy group names; existence is checked against
  280. the database in the route handlers (same split as default_group_id), since
  281. the schema layer has no session. Keys are left as-is apart from stripping:
  282. IdP group values are opaque strings (DNs, UUIDs, names) and must match the
  283. claim byte-for-byte, so any normalisation beyond whitespace would silently
  284. break the lookup.
  285. Keys colliding case-insensitively are rejected: the sync matches the IdP
  286. side case-insensitively, so {"Admins": "Administrators", "admins":
  287. "Viewers"} would silently collapse to whichever entry the dict happens to
  288. keep last — a member of "Admins" could end up in Viewers. Rejecting the
  289. pair at save time (here, so the env path gets the same answer) turns an
  290. undiagnosable runtime behaviour into a form error. Two keys differing only
  291. by case and mapping to the SAME group are pointless but harmless, and are
  292. rejected too for the same reason: they read as a mistake.
  293. """
  294. if not isinstance(v, dict):
  295. raise ValueError("group_mapping must be a JSON object")
  296. if len(v) > 100:
  297. raise ValueError("group_mapping must have at most 100 entries")
  298. cleaned: dict[str, str] = {}
  299. seen_ci: dict[str, str] = {}
  300. for key, value in v.items():
  301. if not isinstance(key, str) or not key.strip():
  302. raise ValueError("group_mapping keys must be non-empty strings")
  303. if not isinstance(value, str) or not value.strip():
  304. raise ValueError("group_mapping values must be non-empty group names")
  305. k = key.strip()
  306. ci = k.lower()
  307. if ci in seen_ci:
  308. raise ValueError(
  309. f"group_mapping has two IdP groups differing only by case: "
  310. f"'{seen_ci[ci]}' and '{k}' — the sync matches case-insensitively, "
  311. f"so both cannot be honored"
  312. )
  313. seen_ci[ci] = k
  314. cleaned[k] = value.strip()
  315. return cleaned
  316. def _validate_icon_url(v: str | None) -> str | None:
  317. """Reject non-HTTPS icon URLs and SSRF-unsafe hosts.
  318. Delegates to the runtime SSRF guard ``assert_safe_public_https_url``
  319. so the Pydantic layer enforces the same allowlist as the fetcher —
  320. no policy drift between schema validation and SSRF check. Without
  321. this delegation the validator covered only ``is_private | is_loopback
  322. | is_link_local`` while the runtime additionally rejected numeric-
  323. encoded IPs, cloud-metadata endpoints, multicast, unspecified, and
  324. IPv4-mapped IPv6.
  325. Lazy-imported because ``_oidc_helpers`` lives under ``api/routes/``
  326. and schemas avoid top-level imports from that layer (matches the
  327. existing pattern in ``_validate_issuer_url`` which lazy-imports
  328. ``ipaddress``).
  329. """
  330. if v is None:
  331. return v
  332. if not v.startswith("https://"):
  333. # Surface the same wording the runtime guard would use, but pre-
  334. # checked here so the user-facing error doesn't depend on the
  335. # runtime call path.
  336. raise ValueError("icon_url must start with https://")
  337. from backend.app.api.routes._oidc_helpers import assert_safe_public_https_url
  338. try:
  339. assert_safe_public_https_url(v)
  340. except ValueError as exc:
  341. raise ValueError(f"icon_url: {exc}") from exc
  342. return v
  343. def _validate_issuer_url(v: str | None) -> str | None:
  344. """Reject non-HTTPS issuer URLs and SSRF-unsafe hosts.
  345. An OIDC provider must be reachable over TLS on the public internet, so
  346. this uses the public-internet policy: private, loopback and link-local
  347. addresses are all rejected.
  348. Delegates to the runtime guard ``assert_safe_public_https_url`` for the
  349. same reason ``_validate_icon_url`` does — no policy drift between the
  350. schema layer and the fetcher. The hand-rolled version this replaced
  351. checked only ``is_private | is_loopback | is_link_local``, which left
  352. numeric-encoded IPs (``https://2130706433/``), IPv4-mapped IPv6
  353. (``https://[::ffff:127.0.0.1]/``), multicast and unspecified addresses
  354. able to express a target the policy meant to forbid. The guard's
  355. docstring already claimed the two were consistent; now they are.
  356. Lazy-imported because ``_oidc_helpers`` lives under ``api/routes/`` and
  357. schemas avoid top-level imports from that layer.
  358. """
  359. if v is None:
  360. return v
  361. if not v.startswith("https://"):
  362. raise ValueError("issuer_url must start with https://")
  363. from backend.app.api.routes._oidc_helpers import assert_safe_public_https_url
  364. try:
  365. assert_safe_public_https_url(v)
  366. except ValueError as exc:
  367. # The guard's messages say "icon URL" — rewrite for this field so the
  368. # user sees the setting they actually submitted.
  369. detail = str(exc).replace("icon URL", "issuer_url")
  370. raise ValueError(detail) from exc
  371. return v
  372. def _validate_scopes(v: str | None) -> str | None:
  373. """Nit5: Require that the 'openid' scope is present.
  374. The OpenID Connect spec mandates the 'openid' scope; without it the
  375. response is plain OAuth2, not OIDC, and claims like sub/email are not
  376. guaranteed.
  377. """
  378. if v is None:
  379. return v
  380. scope_list = v.split()
  381. if "openid" not in scope_list:
  382. raise ValueError("scopes must include 'openid'")
  383. return v
  384. class OIDCProviderCreate(BaseModel):
  385. name: str = Field(..., max_length=100) # L-NEW-4
  386. issuer_url: str
  387. client_id: str = Field(..., max_length=256) # L-NEW-4
  388. client_secret: str = Field(..., max_length=512) # L-NEW-4: Fernet input bounded
  389. scopes: str = Field(default="openid email profile", max_length=256) # L-NEW-4
  390. is_enabled: bool = True
  391. auto_create_users: bool = False
  392. auto_link_existing_accounts: bool = False # M-2: conservative default, opt-in only
  393. email_claim: str = Field(default="email", max_length=64)
  394. require_email_verified: bool = True
  395. # #3107 — group sync config. group_mapping empty (default) = no sync.
  396. group_claim: str = Field(default="groups", max_length=64)
  397. group_mapping: dict[str, str] = Field(default_factory=dict)
  398. icon_url: str | None = None
  399. default_group_id: int | None = None
  400. is_autologin: bool = False # #1589 — at most one provider may carry this
  401. @field_validator("issuer_url")
  402. @classmethod
  403. def validate_issuer_url(cls, v: str) -> str:
  404. result = _validate_issuer_url(v)
  405. if result is None:
  406. raise ValueError("issuer_url is required")
  407. return result
  408. @field_validator("scopes")
  409. @classmethod
  410. def validate_scopes(cls, v: str) -> str:
  411. result = _validate_scopes(v)
  412. if result is None:
  413. raise ValueError("scopes is required")
  414. return result
  415. @field_validator("email_claim")
  416. @classmethod
  417. def validate_email_claim(cls, v: str) -> str:
  418. return _validate_email_claim_name(v)
  419. @field_validator("group_claim")
  420. @classmethod
  421. def validate_group_claim(cls, v: str) -> str:
  422. # Namespaced claims allowed here (Auth0 et al) — see _validate_group_claim_name.
  423. return _validate_group_claim_name(v)
  424. @field_validator("group_mapping")
  425. @classmethod
  426. def validate_group_mapping(cls, v: dict[str, str]) -> dict[str, str]:
  427. return _validate_group_mapping(v)
  428. @field_validator("icon_url")
  429. @classmethod
  430. def validate_icon_url(cls, v: str | None) -> str | None:
  431. return _validate_icon_url(v)
  432. # SEC-1: auto_link with email_claim='email' requires require_email_verified=True.
  433. # Fall B (require_email_verified=False + email_claim='email') accepts absent email_verified → account-takeover risk.
  434. # Fall C (custom claim != 'email') is safe: no email_verified gate on that path regardless of require_email_verified.
  435. @model_validator(mode="after")
  436. def check_auto_link_requires_verified(self) -> "OIDCProviderCreate":
  437. if self.auto_link_existing_accounts and self.email_claim == "email" and not self.require_email_verified:
  438. raise ValueError(AUTO_LINK_REQUIREMENTS_ERROR)
  439. return self
  440. class OIDCProviderUpdate(IgnoresNullForRequiredColumns):
  441. __orm_table__ = "oidc_providers"
  442. name: str | None = Field(default=None, max_length=100)
  443. issuer_url: str | None = None
  444. @field_validator("issuer_url")
  445. @classmethod
  446. def validate_issuer_url(cls, v: str | None) -> str | None:
  447. return _validate_issuer_url(v)
  448. client_id: str | None = Field(default=None, max_length=256)
  449. client_secret: str | None = Field(default=None, max_length=512)
  450. scopes: str | None = Field(default=None, max_length=256)
  451. is_enabled: bool | None = None
  452. auto_create_users: bool | None = None
  453. auto_link_existing_accounts: bool | None = None
  454. email_claim: str | None = Field(default=None, max_length=64)
  455. require_email_verified: bool | None = None
  456. # #3107 — group sync config. None = leave unchanged, same as every other
  457. # optional field here; an explicit {} clears the mapping and disables sync.
  458. group_claim: str | None = Field(default=None, max_length=64)
  459. group_mapping: dict[str, str] | None = None
  460. icon_url: str | None = None
  461. default_group_id: int | None = None
  462. is_autologin: bool | None = None # #1589
  463. @field_validator("scopes")
  464. @classmethod
  465. def validate_scopes(cls, v: str | None) -> str | None:
  466. return _validate_scopes(v)
  467. @field_validator("email_claim")
  468. @classmethod
  469. def validate_email_claim(cls, v: str | None) -> str | None:
  470. if v is None:
  471. return None
  472. return _validate_email_claim_name(v)
  473. @field_validator("group_claim")
  474. @classmethod
  475. def validate_group_claim(cls, v: str | None) -> str | None:
  476. if v is None:
  477. return None
  478. return _validate_group_claim_name(v)
  479. @field_validator("group_mapping")
  480. @classmethod
  481. def validate_group_mapping(cls, v: dict[str, str] | None) -> dict[str, str] | None:
  482. if v is None:
  483. return None
  484. return _validate_group_mapping(v)
  485. @field_validator("icon_url")
  486. @classmethod
  487. def validate_icon_url(cls, v: str | None) -> str | None:
  488. return _validate_icon_url(v)
  489. # SEC-1 (schema-level): blocks only when auto_link=True + email_claim='email' + require_email_verified=False
  490. # arrive in the same request. email_claim=None means the request leaves it unchanged (still 'email' by default),
  491. # so that is also treated as 'email'. Partial updates spanning two requests are caught by the
  492. # Combined-State-Guard in the route handler after the setattr loop.
  493. @model_validator(mode="after")
  494. def check_auto_link_requires_verified(self) -> "OIDCProviderUpdate":
  495. if (
  496. self.auto_link_existing_accounts is True
  497. and self.require_email_verified is False
  498. and (self.email_claim is None or self.email_claim == "email")
  499. ):
  500. raise ValueError(AUTO_LINK_REQUIREMENTS_ERROR)
  501. return self
  502. class OIDCProviderResponse(BaseModel):
  503. id: int
  504. name: str
  505. issuer_url: str
  506. client_id: str
  507. scopes: str
  508. is_enabled: bool
  509. auto_create_users: bool
  510. auto_link_existing_accounts: bool = False
  511. email_claim: str = "email"
  512. require_email_verified: bool = True
  513. # #3107 — group sync config, echoed back so the settings UI can render it.
  514. group_claim: str = "groups"
  515. group_mapping: dict[str, str] = {}
  516. icon_url: str | None = None
  517. default_group_id: int | None = None
  518. is_autologin: bool = False # #1589
  519. # #2593 — the UI renders this provider read-only; without the flag it would
  520. # offer editable fields whose writes the API then refuses with 409.
  521. is_env_managed: bool = False
  522. # Set explicitly in the route handler from `icon_content_type is not None`
  523. # rather than `@computed_field` (project policy) or `icon_data is not None`
  524. # (would trigger an async lazy-load on the deferred BLOB column).
  525. # Required (no default) so Pydantic fails loudly if any code path skips
  526. # `_build_provider_response` and tries `model_validate(provider)` directly.
  527. has_icon: bool
  528. class Config:
  529. from_attributes = True
  530. class OIDCProviderPublicResponse(BaseModel):
  531. """#3107 — what the unauthenticated login page is allowed to see.
  532. GET /oidc/providers is public so the login page can render the SSO
  533. buttons, and it needs exactly four fields: id + name for the button,
  534. has_icon for the avatar, is_autologin for the redirect-on-mount (#1589).
  535. The full OIDCProviderResponse carries group_claim / group_mapping —
  536. which IdP group name maps to which Bambuddy group, including
  537. Administrators — and leaking that to anonymous visitors would tell
  538. anyone who can reach the login page exactly which IdP group to aim for.
  539. """
  540. id: int
  541. name: str
  542. has_icon: bool
  543. is_autologin: bool = False
  544. class Config:
  545. from_attributes = True
  546. class OIDCAuthorizeResponse(BaseModel):
  547. auth_url: str
  548. class OIDCExchangeRequest(BaseModel):
  549. oidc_token: str = Field(..., max_length=128)
  550. class OIDCLinkResponse(BaseModel):
  551. id: int
  552. provider_id: int
  553. provider_name: str
  554. provider_email: str | None = None
  555. created_at: str
  556. class EncryptionRowCounts(BaseModel):
  557. oidc_providers: int
  558. user_totp: int
  559. class EncryptionStatusResponse(BaseModel):
  560. key_configured: bool
  561. key_source: Literal["env", "file", "generated", "none"]
  562. legacy_plaintext_rows: EncryptionRowCounts
  563. encrypted_rows: EncryptionRowCounts
  564. # B4: filled by the endpoint after a sample-decrypt of one encrypted row,
  565. # so a wrong-key state (where key_configured=True but rows decrypt to junk)
  566. # is detected, not just the no-key case.
  567. decryption_broken: bool = False
  568. # B2: number of rows skipped during the last legacy re-encryption migration.
  569. # Filled from backend.app.core.database.get_migration_error_count().
  570. migration_error_count: int = 0