test_oidc_env_apply.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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_applying_twice_without_changes_is_a_no_op(db_session, monkeypatch):
  171. """Every boot re-applies; the second run must not create a second row."""
  172. _configure(monkeypatch)
  173. await apply_env_oidc_provider(db_session)
  174. await apply_env_oidc_provider(db_session)
  175. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  176. assert len(result.scalars().all()) == 1
  177. # --- identity is the name, not the flag ---------------------------------------
  178. # The provider is looked up by BAMBUDDY_OIDC_NAME, which is unique on the table.
  179. # Matching on is_env_managed instead made three things impossible: adopting a
  180. # provider that already carries the name (the insert hit the unique constraint
  181. # and took startup down with it), releasing the provider when the config goes
  182. # away, and finding it again afterwards.
  183. @pytest.mark.asyncio
  184. async def test_a_name_collision_adopts_the_existing_provider(db_session, monkeypatch):
  185. """An operator who names the env provider after one they created in the UI
  186. must not end up with an app that refuses to boot."""
  187. ui_provider = OIDCProvider(name="Keycloak", issuer_url="https://old.example.com", client_id="ui-client")
  188. ui_provider.client_secret = "ui-secret"
  189. db_session.add(ui_provider)
  190. await db_session.commit()
  191. original_id = ui_provider.id
  192. _configure(monkeypatch)
  193. await apply_env_oidc_provider(db_session)
  194. provider = await _env_provider(db_session)
  195. assert provider is not None
  196. assert provider.id == original_id, "adopted, not duplicated"
  197. assert provider.client_id == "bambuddy"
  198. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))
  199. assert len(result.scalars().all()) == 1
  200. @pytest.mark.asyncio
  201. async def test_removing_the_config_releases_the_provider_to_the_ui(db_session, monkeypatch):
  202. """Nothing manages it any more, so the API must stop refusing edits and
  203. deletes -- otherwise the row is a dead end only reachable via the database."""
  204. _configure(monkeypatch)
  205. await apply_env_oidc_provider(db_session)
  206. for key in ALL_VARS:
  207. monkeypatch.delenv(key, raising=False)
  208. await apply_env_oidc_provider(db_session)
  209. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))
  210. provider = result.scalar_one()
  211. assert provider.is_enabled is False
  212. assert provider.is_env_managed is False
  213. @pytest.mark.asyncio
  214. async def test_restoring_the_config_finds_the_same_row_again(db_session, monkeypatch):
  215. """The account links hang off this row; a second provider would orphan them."""
  216. _configure(monkeypatch)
  217. await apply_env_oidc_provider(db_session)
  218. original_id = (await _env_provider(db_session)).id
  219. for key in ALL_VARS:
  220. monkeypatch.delenv(key, raising=False)
  221. await apply_env_oidc_provider(db_session)
  222. _configure(monkeypatch)
  223. await apply_env_oidc_provider(db_session)
  224. provider = await _env_provider(db_session)
  225. assert provider.id == original_id
  226. assert provider.is_enabled is True
  227. @pytest.mark.asyncio
  228. async def test_the_issuer_and_client_can_change_under_the_same_name(db_session, monkeypatch):
  229. _configure(monkeypatch)
  230. await apply_env_oidc_provider(db_session)
  231. original_id = (await _env_provider(db_session)).id
  232. monkeypatch.setenv("BAMBUDDY_OIDC_ISSUER_URL", "https://sso.example.com/realms/other")
  233. monkeypatch.setenv("BAMBUDDY_OIDC_CLIENT_ID", "rotated")
  234. await apply_env_oidc_provider(db_session)
  235. provider = await _env_provider(db_session)
  236. assert provider.id == original_id
  237. assert provider.issuer_url == "https://sso.example.com/realms/other"
  238. assert provider.client_id == "rotated"
  239. # --- a rename must not leave the old row managed -------------------------------
  240. # Identity is the name, so renaming BAMBUDDY_OIDC_NAME matches nothing and
  241. # creates a second row. Leaving the flag on the first one is what makes that
  242. # fatal: it stays enabled with a stale issuer and secret on the login page, the
  243. # API refuses every edit/disable/delete on it (409), and the release path's
  244. # scalar_one_or_none() then raises MultipleResultsFound out of the lifespan --
  245. # the app stops booting. Both states are reachable by ordinary config edits.
  246. async def _env_managed(db_session) -> list[OIDCProvider]:
  247. result = await db_session.execute(select(OIDCProvider).where(OIDCProvider.is_env_managed.is_(True)))
  248. return list(result.scalars().all())
  249. @pytest.mark.asyncio
  250. async def test_renaming_the_provider_releases_the_row_it_managed_before(db_session, monkeypatch):
  251. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  252. await apply_env_oidc_provider(db_session)
  253. old_id = (await _env_provider(db_session)).id
  254. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  255. await apply_env_oidc_provider(db_session)
  256. managed = await _env_managed(db_session)
  257. assert [p.name for p in managed] == ["Authentik"], "exactly one row may carry the flag"
  258. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  259. # Released, not deleted -- user_oidc_links.provider_id cascades.
  260. assert old.is_env_managed is False
  261. assert old.is_enabled is False, "a stale issuer must not stay on the login page"
  262. assert old.is_autologin is False
  263. @pytest.mark.asyncio
  264. async def test_boot_survives_removing_the_config_after_a_rename(db_session, monkeypatch):
  265. """The MultipleResultsFound path: rename, then unset. Must not raise."""
  266. _configure(monkeypatch)
  267. await apply_env_oidc_provider(db_session)
  268. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  269. await apply_env_oidc_provider(db_session)
  270. for key in ALL_VARS:
  271. monkeypatch.delenv(key, raising=False)
  272. await apply_env_oidc_provider(db_session) # must not raise
  273. assert await _env_managed(db_session) == []
  274. names = (await db_session.execute(select(OIDCProvider.name))).scalars().all()
  275. assert sorted(names) == ["Authentik", "Keycloak"], "both rows survive, both released"
  276. @pytest.mark.asyncio
  277. async def test_every_managed_row_is_released_not_just_one(db_session, monkeypatch):
  278. """The upsert's sweep should keep this at one row. Should is not enforced by
  279. the schema, and the cost of being wrong is the whole release path raising
  280. MultipleResultsFound out of the lifespan -- so it releases what it finds."""
  281. for name in ("Keycloak", "Authentik"):
  282. stale = OIDCProvider(
  283. name=name,
  284. issuer_url="https://sso.example.com/realms/main",
  285. client_id="bambuddy",
  286. is_env_managed=True,
  287. )
  288. stale.client_secret = "s3cr3t"
  289. db_session.add(stale)
  290. await db_session.commit()
  291. await apply_env_oidc_provider(db_session) # no vars set -> release path
  292. assert await _env_managed(db_session) == []
  293. @pytest.mark.asyncio
  294. async def test_releasing_the_provider_clears_autologin(db_session, monkeypatch):
  295. """is_enabled and is_env_managed alone leave a UI-editable row carrying a
  296. latent autologin claim: update_oidc_provider only runs the exclusivity
  297. sweep when a request sets is_autologin=True, so merely re-enabling this row
  298. makes it the autologin target again."""
  299. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  300. await apply_env_oidc_provider(db_session)
  301. assert (await _env_provider(db_session)).is_autologin is True
  302. for key in ALL_VARS:
  303. monkeypatch.delenv(key, raising=False)
  304. await apply_env_oidc_provider(db_session)
  305. released = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.name == "Keycloak"))).scalar_one()
  306. assert released.is_autologin is False
  307. # --- default group by name -----------------------------------------------------
  308. # Group ids are not stable across installs, so a declarative deployment cannot
  309. # name one by id. Without this, every auto-created user falls back to Viewers
  310. # (routes/mfa.py) and the env lock means the UI cannot correct the provider.
  311. async def _group(db_session, name: str):
  312. from backend.app.models.group import Group
  313. group = Group(name=name, description=f"Test group {name}")
  314. db_session.add(group)
  315. await db_session.commit()
  316. return group
  317. @pytest.mark.asyncio
  318. async def test_the_default_group_is_resolved_by_name(db_session, monkeypatch):
  319. group = await _group(db_session, "Operators")
  320. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  321. await apply_env_oidc_provider(db_session)
  322. assert (await _env_provider(db_session)).default_group_id == group.id
  323. @pytest.mark.asyncio
  324. async def test_an_unknown_group_name_is_rejected_rather_than_defaulted(db_session, monkeypatch, caplog):
  325. """Silently falling back to Viewers is how a typo mints under-privileged
  326. users for weeks. The API answers 400 for a default_group_id that does not
  327. exist; env config gets the same answer, logged and survivable."""
  328. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Nope")
  329. with caplog.at_level(logging.ERROR):
  330. await apply_env_oidc_provider(db_session)
  331. assert await _env_provider(db_session) is None
  332. assert "BAMBUDDY_OIDC_DEFAULT_GROUP" in caplog.text
  333. assert "Nope" in caplog.text
  334. @pytest.mark.asyncio
  335. async def test_an_unknown_group_name_leaves_the_previous_provider_intact(db_session, monkeypatch):
  336. """Rejection happens before the upsert, so the running config survives a
  337. bad edit -- the provider keeps working until the operator fixes the name."""
  338. group = await _group(db_session, "Operators")
  339. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  340. await apply_env_oidc_provider(db_session)
  341. monkeypatch.setenv("BAMBUDDY_OIDC_DEFAULT_GROUP", "Typo")
  342. await apply_env_oidc_provider(db_session)
  343. provider = await _env_provider(db_session)
  344. assert provider is not None
  345. assert provider.default_group_id == group.id
  346. @pytest.mark.asyncio
  347. async def test_no_group_variable_leaves_the_default_group_unset(db_session, monkeypatch):
  348. _configure(monkeypatch)
  349. await apply_env_oidc_provider(db_session)
  350. assert (await _env_provider(db_session)).default_group_id is None
  351. @pytest.mark.asyncio
  352. async def test_removing_the_group_variable_clears_the_default_group(db_session, monkeypatch):
  353. """The environment is the whole truth for this row; a group that is no
  354. longer declared must not linger, since the lock blocks removing it in the UI."""
  355. await _group(db_session, "Operators")
  356. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="Operators")
  357. await apply_env_oidc_provider(db_session)
  358. monkeypatch.delenv("BAMBUDDY_OIDC_DEFAULT_GROUP")
  359. await apply_env_oidc_provider(db_session)
  360. assert (await _env_provider(db_session)).default_group_id is None
  361. @pytest.mark.asyncio
  362. async def test_an_empty_group_variable_counts_as_unset(db_session, monkeypatch):
  363. """Same rule the required vars follow: an empty value in a compose file is
  364. a forgotten value, not a request to reject the config."""
  365. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="")
  366. await apply_env_oidc_provider(db_session)
  367. provider = await _env_provider(db_session)
  368. assert provider is not None
  369. assert provider.default_group_id is None
  370. # --- account links and collision behavior ------------------------------------
  371. @pytest.mark.asyncio
  372. async def test_renaming_to_match_a_ui_provider_adopts_it_and_releases_the_old_row(db_session, monkeypatch):
  373. """New name collides with existing UI provider: env config adopts that row,
  374. old env-managed row is released. Identity is the name, so the collision is
  375. resolved by matching the new name against the table."""
  376. # Start with env-managed "Keycloak"
  377. _configure(monkeypatch)
  378. await apply_env_oidc_provider(db_session)
  379. old_id = (await _env_provider(db_session)).id
  380. # Add a UI provider named "Authentik"
  381. ui_provider = OIDCProvider(name="Authentik", issuer_url="https://auth.example.com", client_id="ui-client")
  382. ui_provider.client_secret = "ui-secret"
  383. db_session.add(ui_provider)
  384. await db_session.commit()
  385. ui_id = ui_provider.id
  386. # Rename env provider to "Authentik" — matches the UI provider
  387. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  388. await apply_env_oidc_provider(db_session)
  389. # The UI provider is adopted and becomes env-managed
  390. provider = await _env_provider(db_session)
  391. assert provider.id == ui_id, "adopted the UI provider"
  392. assert provider.name == "Authentik"
  393. assert provider.client_id == "bambuddy" # updated from env
  394. assert provider.is_env_managed is True
  395. # The old Keycloak row is released
  396. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  397. assert old.name == "Keycloak"
  398. assert old.is_env_managed is False
  399. assert old.is_enabled is False
  400. @pytest.mark.asyncio
  401. async def test_account_links_survive_a_provider_rename(db_session, monkeypatch):
  402. """The provider row is never deleted, only updated: user_oidc_links FK
  403. ON DELETE CASCADE must not be triggered by a rename."""
  404. from backend.app.models.oidc_provider import UserOIDCLink
  405. from backend.app.models.user import User
  406. # Create a user and link it to the env-managed provider
  407. _configure(monkeypatch)
  408. await apply_env_oidc_provider(db_session)
  409. provider_id = (await _env_provider(db_session)).id
  410. user = User(username="testuser", email="test@example.com")
  411. db_session.add(user)
  412. await db_session.flush()
  413. link = UserOIDCLink(
  414. user_id=user.id,
  415. provider_id=provider_id,
  416. provider_user_id="oidc-sub-12345",
  417. provider_email="test@idp.example.com",
  418. )
  419. db_session.add(link)
  420. await db_session.commit()
  421. # Rename the env provider
  422. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  423. await apply_env_oidc_provider(db_session)
  424. # The link still exists, pointing to the old row (which is now released)
  425. result = await db_session.execute(select(UserOIDCLink).where(UserOIDCLink.provider_id == provider_id))
  426. links = result.scalars().all()
  427. assert len(links) == 1
  428. assert links[0].provider_user_id == "oidc-sub-12345"
  429. @pytest.mark.asyncio
  430. async def test_renaming_with_autologin_updates_the_exclusivity_sweep(db_session, monkeypatch):
  431. """When renamed env config has autologin=true, the sweep clears autologin
  432. from other rows. The old row is released (autologin cleared there too)."""
  433. # Setup: env provider "Keycloak" with autologin
  434. _configure(monkeypatch, BAMBUDDY_OIDC_AUTOLOGIN="true")
  435. await apply_env_oidc_provider(db_session)
  436. old_id = (await _env_provider(db_session)).id
  437. assert (await _env_provider(db_session)).is_autologin is True
  438. # Another UI provider also has autologin
  439. ui_provider = OIDCProvider(name="UI", issuer_url="https://ui.example.com", client_id="ui")
  440. ui_provider.client_secret = "secret"
  441. ui_provider.is_autologin = True
  442. db_session.add(ui_provider)
  443. await db_session.commit()
  444. # Rename env provider to "Authentik" with autologin=true
  445. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  446. await apply_env_oidc_provider(db_session)
  447. # New row is the autologin target
  448. new_provider = await _env_provider(db_session)
  449. assert new_provider.name == "Authentik"
  450. assert new_provider.is_autologin is True
  451. # Old row is released and autologin cleared
  452. old = (await db_session.execute(select(OIDCProvider).where(OIDCProvider.id == old_id))).scalar_one()
  453. assert old.is_env_managed is False
  454. assert old.is_autologin is False
  455. # UI provider autologin is cleared (only env-managed can be autologin now)
  456. await db_session.refresh(ui_provider)
  457. assert ui_provider.is_autologin is False
  458. @pytest.mark.asyncio
  459. async def test_group_name_matching_is_case_sensitive(db_session, monkeypatch, caplog):
  460. """Group name is resolved by exact match; 'operators' != 'Operators'."""
  461. await _group(db_session, "Operators") # capital O
  462. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="operators") # lowercase
  463. with caplog.at_level(logging.ERROR):
  464. await apply_env_oidc_provider(db_session)
  465. # Config is rejected
  466. assert await _env_provider(db_session) is None
  467. assert "operators" in caplog.text
  468. assert "BAMBUDDY_OIDC_DEFAULT_GROUP" in caplog.text
  469. @pytest.mark.asyncio
  470. async def test_group_name_rejection_does_not_log_the_secret(db_session, monkeypatch, caplog):
  471. """Group resolution happens before schema validation, so the secret is
  472. not yet in scope, but verify it's not leaked by the error path."""
  473. _configure(monkeypatch, BAMBUDDY_OIDC_DEFAULT_GROUP="NonExistent")
  474. secret = os.environ["BAMBUDDY_OIDC_CLIENT_SECRET"]
  475. with caplog.at_level(logging.ERROR):
  476. await apply_env_oidc_provider(db_session)
  477. # Config is rejected but secret is safe
  478. assert await _env_provider(db_session) is None
  479. assert secret not in caplog.text
  480. @pytest.mark.asyncio
  481. async def test_restoring_env_config_after_rename_then_unset_finds_the_original_row(db_session, monkeypatch):
  482. """Rename Keycloak → Authentik, unset everything, restore Keycloak.
  483. Must re-enable the original row, not create a new one."""
  484. _configure(monkeypatch)
  485. await apply_env_oidc_provider(db_session)
  486. original_id = (await _env_provider(db_session)).id
  487. # Rename to Authentik
  488. monkeypatch.setenv("BAMBUDDY_OIDC_NAME", "Authentik")
  489. await apply_env_oidc_provider(db_session)
  490. assert (await _env_provider(db_session)).name == "Authentik"
  491. # Unset everything
  492. for key in ALL_VARS:
  493. monkeypatch.delenv(key, raising=False)
  494. await apply_env_oidc_provider(db_session)
  495. # Restore the original Keycloak config
  496. _configure(monkeypatch)
  497. await apply_env_oidc_provider(db_session)
  498. # Same row, re-enabled
  499. provider = await _env_provider(db_session)
  500. assert provider.id == original_id
  501. assert provider.name == "Keycloak"
  502. assert provider.is_enabled is True
  503. assert provider.is_env_managed is True