test_oidc_env_apply.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. """Upserting the env-managed OIDC provider (#2593).
  2. Startup applies BAMBUDDY_OIDC_* to the database. The row is updated in place,
  3. never delete-recreated: user_oidc_links.provider_id is FK ON DELETE CASCADE, so
  4. recreating the provider would silently unlink every account bound to it.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import os
  9. import pytest
  10. from sqlalchemy import select
  11. from backend.app.core.oidc_env import apply_env_oidc_provider
  12. from backend.app.models.oidc_provider import OIDCProvider
  13. REQUIRED = {
  14. "BAMBUDDY_OIDC_NAME": "Keycloak",
  15. "BAMBUDDY_OIDC_ISSUER_URL": "https://sso.example.com/realms/main",
  16. "BAMBUDDY_OIDC_CLIENT_ID": "bambuddy",
  17. "BAMBUDDY_OIDC_CLIENT_SECRET": "s3cr3t",
  18. }
  19. ALL_VARS = (
  20. *REQUIRED,
  21. "BAMBUDDY_OIDC_SCOPES",
  22. "BAMBUDDY_OIDC_ENABLED",
  23. "BAMBUDDY_OIDC_AUTO_CREATE_USERS",
  24. "BAMBUDDY_OIDC_AUTO_LINK_EXISTING",
  25. "BAMBUDDY_OIDC_EMAIL_CLAIM",
  26. "BAMBUDDY_OIDC_REQUIRE_EMAIL_VERIFIED",
  27. "BAMBUDDY_OIDC_ICON_URL",
  28. "BAMBUDDY_OIDC_AUTOLOGIN",
  29. "BAMBUDDY_OIDC_DEFAULT_GROUP",
  30. )
  31. @pytest.fixture(autouse=True)
  32. def clean_env(monkeypatch):
  33. for key in ALL_VARS:
  34. monkeypatch.delenv(key, raising=False)
  35. def _configure(monkeypatch, **overrides):
  36. for key, value in REQUIRED.items():
  37. monkeypatch.setenv(key, value)
  38. for key, value in overrides.items():
  39. monkeypatch.setenv(key, value)
  40. async def _env_provider(db_session) -> OIDCProvider | None:
  41. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  42. return result.scalar_one_or_none()
  43. @pytest.mark.asyncio
  44. async def test_creates_the_provider_from_env(db_session, monkeypatch):
  45. _configure(monkeypatch)
  46. await apply_env_oidc_provider(db_session)
  47. provider = await _env_provider(db_session)
  48. assert provider is not None
  49. assert provider.name == "Keycloak"
  50. assert provider.client_id == "bambuddy"
  51. assert provider.is_env_managed is True
  52. assert provider.client_secret == "s3cr3t" # property decrypts
  53. @pytest.mark.asyncio
  54. async def test_a_changed_var_updates_the_same_row(db_session, monkeypatch):
  55. """The id must survive: user_oidc_links references it with ON DELETE
  56. CASCADE, so a delete-recreate would unlink every bound account."""
  57. _configure(monkeypatch)
  58. await apply_env_oidc_provider(db_session)
  59. original_id = (await _env_provider(db_session)).id
  60. monkeypatch.setenv("BAMBUDDY_OIDC_CLIENT_ID", "rotated")
  61. await apply_env_oidc_provider(db_session)
  62. provider = await _env_provider(db_session)
  63. assert provider.id == original_id
  64. assert provider.client_id == "rotated"
  65. @pytest.mark.asyncio
  66. async def test_removing_the_env_config_disables_but_keeps_the_row(db_session, monkeypatch):
  67. _configure(monkeypatch)
  68. await apply_env_oidc_provider(db_session)
  69. original_id = (await _env_provider(db_session)).id
  70. for key in ALL_VARS:
  71. monkeypatch.delenv(key, raising=False)
  72. await apply_env_oidc_provider(db_session)
  73. # Looked up by name, not by the flag: releasing the provider clears the flag,
  74. # and the point of this test is that the ROW survives either way.
  75. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))
  76. provider = result.scalar_one_or_none()
  77. assert provider is not None, "deleting would cascade away every account link"
  78. assert provider.id == original_id
  79. assert provider.is_enabled is False
  80. @pytest.mark.asyncio
  81. async def test_env_autologin_clears_it_on_other_providers(db_session, monkeypatch):
  82. """Only one provider may be the autologin target; the env one wins."""
  83. ui_provider = OIDCProvider(
  84. name="UI provider",
  85. issuer_url="https://other.example.com",
  86. client_id="ui",
  87. is_autologin=True,
  88. )
  89. ui_provider.client_secret = "ui-secret"
  90. db_session.add(ui_provider)
  91. await db_session.commit()
  92. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  93. await apply_env_oidc_provider(db_session)
  94. await db_session.refresh(ui_provider)
  95. assert (await _env_provider(db_session)).is_autologin is True
  96. assert ui_provider.is_autologin is False
  97. @pytest.mark.asyncio
  98. async def test_a_ui_provider_is_otherwise_left_alone(db_session, monkeypatch):
  99. ui_provider = OIDCProvider(name="UI provider", issuer_url="https://other.example.com", client_id="ui")
  100. ui_provider.client_secret = "ui-secret"
  101. db_session.add(ui_provider)
  102. await db_session.commit()
  103. _configure(monkeypatch)
  104. await apply_env_oidc_provider(db_session)
  105. await db_session.refresh(ui_provider)
  106. assert ui_provider.is_env_managed is False
  107. assert ui_provider.is_enabled is True
  108. assert ui_provider.client_id == "ui"
  109. @pytest.mark.asyncio
  110. async def test_an_unsafe_auto_link_config_is_skipped_not_raised(db_session, monkeypatch):
  111. """auto-link + unverified email is the SEC-1 account-takeover shape. The
  112. schema rejects it for the UI, and env config must not be a way around that
  113. -- but a bad variable must not stop the app from booting either."""
  114. _configure(
  115. monkeypatch,
  116. BAMBUDDY_OIDC_AUTO_LINK_EXISTING="true",
  117. BAMBUDDY_OIDC_REQUIRE_EMAIL_VERIFIED="false",
  118. )
  119. await apply_env_oidc_provider(db_session)
  120. assert await _env_provider(db_session) is None
  121. @pytest.mark.asyncio
  122. async def test_a_rejected_config_never_logs_the_client_secret(db_session, monkeypatch, caplog):
  123. """client_secret has max_length=512, so an over-long value raises
  124. string_too_long. The rejection must be logged without the value: str(exc)
  125. embeds input_value=..., which would leak the secret (no-secrets-in-logs)."""
  126. secret = "S3CR3T" * 100 # > 512 chars -> ValidationError on client_secret
  127. _configure(monkeypatch, BAMBUDDY_OIDC_CLIENT_SECRET=secret)
  128. with caplog.at_level(logging.ERROR):
  129. await apply_env_oidc_provider(db_session)
  130. assert await _env_provider(db_session) is None # rejected, not booted-through
  131. assert "rejected" in caplog.text # the rejection was actually logged
  132. assert secret not in caplog.text
  133. assert "S3CR3T" not in caplog.text # not even a fragment of the value
  134. @pytest.mark.asyncio
  135. async def test_a_non_validation_error_is_survivable_and_leaks_nothing(db_session, monkeypatch, caplog):
  136. """The generic except branch handles anything that isn't a ValidationError
  137. (e.g. a library call raising mid-construction). It must not stop boot and,
  138. since such a message could carry a configured value, must log only the
  139. exception class -- never str(exc)."""
  140. # oidc_env imports OIDCProviderCreate inside the function (to avoid an
  141. # import cycle), so patch it at its source module, not on oidc_env.
  142. import backend.app.schemas.auth as auth_schemas
  143. def _raise(**_kwargs):
  144. raise RuntimeError("boom leaked-secret")
  145. monkeypatch.setattr(auth_schemas, "OIDCProviderCreate", _raise)
  146. _configure(monkeypatch, BAMBUDDY_OIDC_CLIENT_SECRET="leaked-secret")
  147. with caplog.at_level(logging.ERROR):
  148. await apply_env_oidc_provider(db_session) # must not raise
  149. assert await _env_provider(db_session) is None
  150. assert "could not be applied" in caplog.text
  151. assert "RuntimeError" in caplog.text # class is logged...
  152. assert "leaked-secret" not in caplog.text # ...but nothing from the message
  153. @pytest.mark.asyncio
  154. async def test_a_commit_failure_is_survivable_and_leaks_nothing(db_session, monkeypatch, caplog):
  155. """The upsert's db.execute/db.commit calls sit outside the inner
  156. ValidationError guard -- a Postgres blip or a SQLite WAL lock at startup
  157. must not propagate out of the lifespan either. Only the exception class
  158. may be logged, never str(exc), since a DB error message can echo a
  159. configured value."""
  160. async def _raise_on_commit():
  161. raise RuntimeError("database is locked")
  162. monkeypatch.setattr(db_session, "commit", _raise_on_commit)
  163. _configure(monkeypatch, BAMBUDDY_OIDC_CLIENT_SECRET="leaked-secret")
  164. with caplog.at_level(logging.ERROR):
  165. await apply_env_oidc_provider(db_session) # must not raise
  166. assert "could not be applied" in caplog.text
  167. assert "RuntimeError" in caplog.text # class is logged...
  168. assert "leaked-secret" not in caplog.text # ...but nothing from the message
  169. @pytest.mark.asyncio
  170. async def test_a_failing_rollback_is_also_survivable(db_session, monkeypatch, caplog):
  171. """The handler rolls back after a failed commit -- but rollback on a wedged
  172. connection can raise too, and 'never raises' has to hold for that as well
  173. or the boot dies on the recovery path. The rollback is suppressed."""
  174. async def _raise_on_commit():
  175. raise RuntimeError("database is locked")
  176. async def _raise_on_rollback():
  177. raise RuntimeError("connection is closed")
  178. monkeypatch.setattr(db_session, "commit", _raise_on_commit)
  179. monkeypatch.setattr(db_session, "rollback", _raise_on_rollback)
  180. _configure(monkeypatch, BAMBUDDY_OIDC_CLIENT_SECRET="leaked-secret")
  181. with caplog.at_level(logging.ERROR):
  182. await apply_env_oidc_provider(db_session) # must not raise, even here
  183. assert "could not be applied" in caplog.text
  184. assert "leaked-secret" not in caplog.text
  185. @pytest.mark.asyncio
  186. async def test_applying_twice_without_changes_is_a_no_op(db_session, monkeypatch):
  187. """Every boot re-applies; the second run must not create a second row."""
  188. _configure(monkeypatch)
  189. await apply_env_oidc_provider(db_session)
  190. await apply_env_oidc_provider(db_session)
  191. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  192. assert len(result.scalars().all()) == 1
  193. # --- identity is the name, not the flag ---------------------------------------
  194. # The provider is looked up by BAMBUDDY_OIDC_NAME, which is unique on the table.
  195. # Matching on is_env_managed instead made three things impossible: adopting a
  196. # provider that already carries the name (the insert hit the unique constraint
  197. # and took startup down with it), releasing the provider when the config goes
  198. # away, and finding it again afterwards.
  199. @pytest.mark.asyncio
  200. async def test_a_name_collision_adopts_the_existing_provider(db_session, monkeypatch):
  201. """An operator who names the env provider after one they created in the UI
  202. must not end up with an app that refuses to boot."""
  203. ui_provider = OIDCProvider(name="Keycloak", issuer_url="https://old.example.com", client_id="ui-client")
  204. ui_provider.client_secret = "ui-secret"
  205. db_session.add(ui_provider)
  206. await db_session.commit()
  207. original_id = ui_provider.id
  208. _configure(monkeypatch)
  209. await apply_env_oidc_provider(db_session)
  210. provider = await _env_provider(db_session)
  211. assert provider is not None
  212. assert provider.id == original_id, "adopted, not duplicated"
  213. assert provider.client_id == "bambuddy"
  214. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))
  215. assert len(result.scalars().all()) == 1
  216. @pytest.mark.asyncio
  217. async def test_adopting_a_ui_provider_logs_a_distinct_warning(db_session, monkeypatch, caplog):
  218. """Overwriting a UI-created provider in place is a bigger deal than a
  219. routine re-apply -- it must not be silent at the same INFO level."""
  220. ui_provider = OIDCProvider(name="Keycloak", issuer_url="https://old.example.com", client_id="ui-client")
  221. ui_provider.client_secret = "ui-secret"
  222. db_session.add(ui_provider)
  223. await db_session.commit()
  224. _configure(monkeypatch)
  225. with caplog.at_level(logging.INFO):
  226. await apply_env_oidc_provider(db_session)
  227. warnings = [r for r in caplog.records if r.levelname == "WARNING"]
  228. assert any("adopted" in r.message for r in warnings)
  229. @pytest.mark.asyncio
  230. async def test_a_routine_reapply_does_not_log_an_adoption_warning(db_session, monkeypatch, caplog):
  231. """The same provider re-applying on the next boot is not an adoption --
  232. it was already env-managed."""
  233. _configure(monkeypatch)
  234. await apply_env_oidc_provider(db_session)
  235. caplog.clear()
  236. with caplog.at_level(logging.INFO):
  237. await apply_env_oidc_provider(db_session)
  238. warnings = [r for r in caplog.records if r.levelname == "WARNING"]
  239. assert not any("adopted" in r.message for r in warnings)
  240. @pytest.mark.asyncio
  241. async def test_removing_the_config_releases_the_provider_to_the_ui(db_session, monkeypatch):
  242. """Nothing manages it any more, so the API must stop refusing edits and
  243. deletes -- otherwise the row is a dead end only reachable via the database."""
  244. _configure(monkeypatch)
  245. await apply_env_oidc_provider(db_session)
  246. for key in ALL_VARS:
  247. monkeypatch.delenv(key, raising=False)
  248. await apply_env_oidc_provider(db_session)
  249. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))
  250. provider = result.scalar_one()
  251. assert provider.is_enabled is False
  252. assert provider.is_env_managed is False
  253. @pytest.mark.asyncio
  254. async def test_restoring_the_config_finds_the_same_row_again(db_session, monkeypatch):
  255. """The account links hang off this row; a second provider would orphan them."""
  256. _configure(monkeypatch)
  257. await apply_env_oidc_provider(db_session)
  258. original_id = (await _env_provider(db_session)).id
  259. for key in ALL_VARS:
  260. monkeypatch.delenv(key, raising=False)
  261. await apply_env_oidc_provider(db_session)
  262. _configure(monkeypatch)
  263. await apply_env_oidc_provider(db_session)
  264. provider = await _env_provider(db_session)
  265. assert provider.id == original_id
  266. assert provider.is_enabled is True
  267. @pytest.mark.asyncio
  268. async def test_the_issuer_and_client_can_change_under_the_same_name(db_session, monkeypatch):
  269. _configure(monkeypatch)
  270. await apply_env_oidc_provider(db_session)
  271. original_id = (await _env_provider(db_session)).id
  272. monkeypatch.setenv("BAMBUDDY_OIDC_ISSUER_URL", "https://sso.example.com/realms/other")
  273. monkeypatch.setenv("BAMBUDDY_OIDC_CLIENT_ID", "rotated")
  274. await apply_env_oidc_provider(db_session)
  275. provider = await _env_provider(db_session)
  276. assert provider.id == original_id
  277. assert provider.issuer_url == "https://sso.example.com/realms/other"
  278. assert provider.client_id == "rotated"
  279. # --- a rename must not leave the old row managed -------------------------------
  280. # Identity is the name, so renaming BAMBUDDY_OIDC_NAME matches nothing and
  281. # creates a second row. Leaving the flag on the first one is what makes that
  282. # fatal: it stays enabled with a stale issuer and secret on the login page, the
  283. # API refuses every edit/disable/delete on it (409), and the release path's
  284. # scalar_one_or_none() then raises MultipleResultsFound out of the lifespan --
  285. # the app stops booting. Both states are reachable by ordinary config edits.
  286. async def _env_managed(db_session) -> list[OIDCProvider]:
  287. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  288. return list(result.scalars().all())
  289. @pytest.mark.asyncio
  290. async def test_renaming_the_provider_releases_the_row_it_managed_before(db_session, monkeypatch):
  291. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  292. await apply_env_oidc_provider(db_session)
  293. old_id = (await _env_provider(db_session)).id
  294. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  295. await apply_env_oidc_provider(db_session)
  296. managed = await _env_managed(db_session)
  297. assert [p.name for p in managed] == ["Authentik"], "exactly one row may carry the flag"
  298. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  299. # Released, not deleted -- user_oidc_links.provider_id cascades.
  300. assert old.is_env_managed is False
  301. assert old.is_enabled is False, "a stale issuer must not stay on the login page"
  302. assert old.is_autologin is False
  303. @pytest.mark.asyncio
  304. async def test_boot_survives_removing_the_config_after_a_rename(db_session, monkeypatch):
  305. """The MultipleResultsFound path: rename, then unset. Must not raise."""
  306. _configure(monkeypatch)
  307. await apply_env_oidc_provider(db_session)
  308. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  309. await apply_env_oidc_provider(db_session)
  310. for key in ALL_VARS:
  311. monkeypatch.delenv(key, raising=False)
  312. await apply_env_oidc_provider(db_session) # must not raise
  313. assert await _env_managed(db_session) == []
  314. names = (await db_session.execute(select(OIDCProvider.name))).scalars().all()
  315. assert sorted(names) == ["Authentik", "Keycloak"], "both rows survive, both released"
  316. @pytest.mark.asyncio
  317. async def test_every_managed_row_is_released_not_just_one(db_session, monkeypatch):
  318. """The upsert's sweep should keep this at one row. Should is not enforced by
  319. the schema, and the cost of being wrong is the whole release path raising
  320. MultipleResultsFound out of the lifespan -- so it releases what it finds."""
  321. for name in ("Keycloak", "Authentik"):
  322. stale = OIDCProvider(
  323. name=name,
  324. issuer_url="https://sso.example.com/realms/main",
  325. client_id="bambuddy",
  326. is_env_managed=True,
  327. )
  328. stale.client_secret = "s3cr3t"
  329. db_session.add(stale)
  330. await db_session.commit()
  331. await apply_env_oidc_provider(db_session) # no vars set -> release path
  332. assert await _env_managed(db_session) == []
  333. @pytest.mark.asyncio
  334. async def test_releasing_the_provider_clears_autologin(db_session, monkeypatch):
  335. """is_enabled and is_env_managed alone leave a UI-editable row carrying a
  336. latent autologin claim: update_oidc_provider only runs the exclusivity
  337. sweep when a request sets is_autologin=True, so merely re-enabling this row
  338. makes it the autologin target again."""
  339. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  340. await apply_env_oidc_provider(db_session)
  341. assert (await _env_provider(db_session)).is_autologin is True
  342. for key in ALL_VARS:
  343. monkeypatch.delenv(key, raising=False)
  344. await apply_env_oidc_provider(db_session)
  345. released = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))).scalar_one()
  346. assert released.is_autologin is False
  347. # --- default group by name -----------------------------------------------------
  348. # Group ids are not stable across installs, so a declarative deployment cannot
  349. # name one by id. Without this, every auto-created user falls back to Viewers
  350. # (routes/mfa.py) and the env lock means the UI cannot correct the provider.
  351. async def _group(db_session, name: str):
  352. from backend.app.models.group import Group
  353. group = Group(name=name, description=f"Test group {name}")
  354. db_session.add(group)
  355. await db_session.commit()
  356. return group
  357. @pytest.mark.asyncio
  358. async def test_the_default_group_is_resolved_by_name(db_session, monkeypatch):
  359. group = await _group(db_session, "Operators")
  360. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  361. await apply_env_oidc_provider(db_session)
  362. assert (await _env_provider(db_session)).default_group_id == group.id
  363. @pytest.mark.asyncio
  364. async def test_an_unknown_group_name_is_rejected_rather_than_defaulted(db_session, monkeypatch, caplog):
  365. """Silently falling back to Viewers is how a typo mints under-privileged
  366. users for weeks. The API answers 400 for a default_group_id that does not
  367. exist; env config gets the same answer, logged and survivable."""
  368. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Nope")
  369. with caplog.at_level(logging.ERROR):
  370. await apply_env_oidc_provider(db_session)
  371. assert await _env_provider(db_session) is None
  372. assert "BAMBUDDY_OIDC_DEFAULT_GROUP" in caplog.text
  373. assert "Nope" in caplog.text
  374. @pytest.mark.asyncio
  375. async def test_an_unknown_group_name_leaves_the_previous_provider_intact(db_session, monkeypatch):
  376. """Rejection happens before the upsert, so the running config survives a
  377. bad edit -- the provider keeps working until the operator fixes the name."""
  378. group = await _group(db_session, "Operators")
  379. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  380. await apply_env_oidc_provider(db_session)
  381. monkeypatch.setenv("BAMBUDDY_OIDC_DEFAULT_GROUP", "Typo")
  382. await apply_env_oidc_provider(db_session)
  383. provider = await _env_provider(db_session)
  384. assert provider is not None
  385. assert provider.default_group_id == group.id
  386. @pytest.mark.asyncio
  387. async def test_no_group_variable_leaves_the_default_group_unset(db_session, monkeypatch):
  388. _configure(monkeypatch)
  389. await apply_env_oidc_provider(db_session)
  390. assert (await _env_provider(db_session)).default_group_id is None
  391. @pytest.mark.asyncio
  392. async def test_removing_the_group_variable_clears_the_default_group(db_session, monkeypatch):
  393. """The environment is the whole truth for this row; a group that is no
  394. longer declared must not linger, since the lock blocks removing it in the UI."""
  395. await _group(db_session, "Operators")
  396. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  397. await apply_env_oidc_provider(db_session)
  398. monkeypatch.delenv("BAMBUDDY_OIDC_DEFAULT_GROUP")
  399. await apply_env_oidc_provider(db_session)
  400. assert (await _env_provider(db_session)).default_group_id is None
  401. @pytest.mark.asyncio
  402. async def test_an_empty_group_variable_counts_as_unset(db_session, monkeypatch):
  403. """Same rule the required vars follow: an empty value in a compose file is
  404. a forgotten value, not a request to reject the config."""
  405. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="")
  406. await apply_env_oidc_provider(db_session)
  407. provider = await _env_provider(db_session)
  408. assert provider is not None
  409. assert provider.default_group_id is None
  410. # --- blank optional strings count as unset, not a refusal ---------------------
  411. # `.env.example` ships `# BAMBUDDY_OIDC_ICON_URL=` commented out, so uncommenting
  412. # it must not take the provider down -- same rule default_group already follows.
  413. @pytest.mark.asyncio
  414. async def test_a_blank_scopes_still_creates_the_provider(db_session, monkeypatch):
  415. _configure(monkeypatch, BAMBUDDY_OIDC_SCOPES="")
  416. await apply_env_oidc_provider(db_session)
  417. provider = await _env_provider(db_session)
  418. assert provider is not None, "a blank optional var must not refuse the whole provider"
  419. assert provider.scopes == "openid email profile"
  420. @pytest.mark.asyncio
  421. async def test_a_blank_email_claim_still_creates_the_provider(db_session, monkeypatch):
  422. _configure(monkeypatch, BAMBUDDY_OIDC_EMAIL_CLAIM="")
  423. await apply_env_oidc_provider(db_session)
  424. provider = await _env_provider(db_session)
  425. assert provider is not None, "a blank optional var must not refuse the whole provider"
  426. assert provider.email_claim == "email"
  427. @pytest.mark.asyncio
  428. async def test_a_blank_icon_url_still_creates_the_provider(db_session, monkeypatch):
  429. _configure(monkeypatch, BAMBUDDY_OIDC_ICON_URL="")
  430. await apply_env_oidc_provider(db_session)
  431. provider = await _env_provider(db_session)
  432. assert provider is not None, "a blank optional var must not refuse the whole provider"
  433. assert provider.icon_url is None
  434. # --- account links and collision behavior ------------------------------------
  435. @pytest.mark.asyncio
  436. async def test_renaming_to_match_a_ui_provider_adopts_it_and_releases_the_old_row(db_session, monkeypatch):
  437. """New name collides with existing UI provider: env config adopts that row,
  438. old env-managed row is released. Identity is the name, so the collision is
  439. resolved by matching the new name against the table."""
  440. # Start with env-managed "Keycloak"
  441. _configure(monkeypatch)
  442. await apply_env_oidc_provider(db_session)
  443. old_id = (await _env_provider(db_session)).id
  444. # Add a UI provider named "Authentik"
  445. ui_provider = OIDCProvider(name="Authentik", issuer_url="https://auth.example.com", client_id="ui-client")
  446. ui_provider.client_secret = "ui-secret"
  447. db_session.add(ui_provider)
  448. await db_session.commit()
  449. ui_id = ui_provider.id
  450. # Rename env provider to "Authentik" — matches the UI provider
  451. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  452. await apply_env_oidc_provider(db_session)
  453. # The UI provider is adopted and becomes env-managed
  454. provider = await _env_provider(db_session)
  455. assert provider.id == ui_id, "adopted the UI provider"
  456. assert provider.name == "Authentik"
  457. assert provider.client_id == "bambuddy" # updated from env
  458. assert provider.is_env_managed is True
  459. # The old Keycloak row is released
  460. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  461. assert old.name == "Keycloak"
  462. assert old.is_env_managed is False
  463. assert old.is_enabled is False
  464. @pytest.mark.asyncio
  465. async def test_account_links_survive_a_provider_rename(db_session, monkeypatch):
  466. """The provider row is never deleted, only updated: user_oidc_links FK
  467. ON DELETE CASCADE must not be triggered by a rename."""
  468. from backend.app.models.oidc_provider import UserOIDCLink
  469. from backend.app.models.user import User
  470. # Create a user and link it to the env-managed provider
  471. _configure(monkeypatch)
  472. await apply_env_oidc_provider(db_session)
  473. provider_id = (await _env_provider(db_session)).id
  474. user = User(username="testuser", email="test@example.com")
  475. db_session.add(user)
  476. await db_session.flush()
  477. link = UserOIDCLink(
  478. user_id=user.id,
  479. provider_id=provider_id,
  480. provider_user_id="oidc-sub-12345",
  481. provider_email="test@idp.example.com",
  482. )
  483. db_session.add(link)
  484. await db_session.commit()
  485. # Rename the env provider
  486. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  487. await apply_env_oidc_provider(db_session)
  488. # The link still exists, pointing to the old row (which is now released)
  489. result = await db_session.execute(select(UserOIDCLink).where(UserOIDCLink.provider_id == provider_id))
  490. links = result.scalars().all()
  491. assert len(links) == 1
  492. assert links[0].provider_user_id == "oidc-sub-12345"
  493. @pytest.mark.asyncio
  494. async def test_renaming_with_autologin_updates_the_exclusivity_sweep(db_session, monkeypatch):
  495. """When renamed env config has autologin=true, the sweep clears autologin
  496. from other rows. The old row is released (autologin cleared there too)."""
  497. # Setup: env provider "Keycloak" with autologin
  498. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  499. await apply_env_oidc_provider(db_session)
  500. old_id = (await _env_provider(db_session)).id
  501. assert (await _env_provider(db_session)).is_autologin is True
  502. # Another UI provider also has autologin
  503. ui_provider = OIDCProvider(name="UI", issuer_url="https://ui.example.com", client_id="ui")
  504. ui_provider.client_secret = "secret"
  505. ui_provider.is_autologin = True
  506. db_session.add(ui_provider)
  507. await db_session.commit()
  508. # Rename env provider to "Authentik" with autologin=true
  509. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  510. await apply_env_oidc_provider(db_session)
  511. # New row is the autologin target
  512. new_provider = await _env_provider(db_session)
  513. assert new_provider.name == "Authentik"
  514. assert new_provider.is_autologin is True
  515. # Old row is released and autologin cleared
  516. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  517. assert old.is_env_managed is False
  518. assert old.is_autologin is False
  519. # UI provider autologin is cleared (only env-managed can be autologin now)
  520. await db_session.refresh(ui_provider)
  521. assert ui_provider.is_autologin is False
  522. @pytest.mark.asyncio
  523. async def test_group_name_matching_is_case_sensitive(db_session, monkeypatch, caplog):
  524. """Group name is resolved by exact match; 'operators' != 'Operators'."""
  525. await _group(db_session, "Operators") # capital O
  526. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="operators") # lowercase
  527. with caplog.at_level(logging.ERROR):
  528. await apply_env_oidc_provider(db_session)
  529. # Config is rejected
  530. assert await _env_provider(db_session) is None
  531. assert "operators" in caplog.text
  532. assert "BAMBUDDY_OIDC_DEFAULT_GROUP" in caplog.text
  533. @pytest.mark.asyncio
  534. async def test_group_name_rejection_does_not_log_the_secret(db_session, monkeypatch, caplog):
  535. """Group resolution happens before schema validation, so the secret is
  536. not yet in scope, but verify it's not leaked by the error path."""
  537. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="NonExistent")
  538. secret = os.environ["BAMBUDDY_OIDC_CLIENT_SECRET"]
  539. with caplog.at_level(logging.ERROR):
  540. await apply_env_oidc_provider(db_session)
  541. # Config is rejected but secret is safe
  542. assert await _env_provider(db_session) is None
  543. assert secret not in caplog.text
  544. @pytest.mark.asyncio
  545. async def test_restoring_env_config_after_rename_then_unset_finds_the_original_row(db_session, monkeypatch):
  546. """Rename Keycloak → Authentik, unset everything, restore Keycloak.
  547. Must re-enable the original row, not create a new one."""
  548. _configure(monkeypatch)
  549. await apply_env_oidc_provider(db_session)
  550. original_id = (await _env_provider(db_session)).id
  551. # Rename to Authentik
  552. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  553. await apply_env_oidc_provider(db_session)
  554. assert (await _env_provider(db_session)).name == "Authentik"
  555. # Unset everything
  556. for key in ALL_VARS:
  557. monkeypatch.delenv(key, raising=False)
  558. await apply_env_oidc_provider(db_session)
  559. # Restore the original Keycloak config
  560. _configure(monkeypatch)
  561. await apply_env_oidc_provider(db_session)
  562. # Same row, re-enabled
  563. provider = await _env_provider(db_session)
  564. assert provider.id == original_id
  565. assert provider.name == "Keycloak"
  566. assert provider.is_enabled is True
  567. assert provider.is_env_managed is True