test_admin_only_auth_config.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """Configuration that decides who can sign in is admin-only.
  2. A group can be granted the settings permissions. Those reached sign-in
  3. itself: a directory or identity provider that hands out the Administrators
  4. group, the mail server the reset links go through, the address the links
  5. point at, the session length, a whole-database restore, a reset that also
  6. cleared the authentication switch, and a backup holding every password hash.
  7. Like the user and group routes, these are admin-only; the permissions keep
  8. everything else.
  9. """
  10. import pytest
  11. from httpx import AsyncClient
  12. pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
  13. # pragma: allowlist secret — test fixtures only, not real credentials
  14. ADMIN_PW = "AdminConf1!" # noqa: S105
  15. MANAGER_PW = "Manager1pass!" # noqa: S105
  16. MANAGER_PERMISSIONS = [
  17. "settings:read",
  18. "settings:update",
  19. "settings:backup",
  20. "settings:restore",
  21. "github:restore",
  22. ]
  23. async def _login(client: AsyncClient, username: str, password: str) -> dict[str, str]:
  24. resp = await client.post("/api/v1/auth/login", json={"username": username, "password": password})
  25. assert resp.status_code == 200, resp.text
  26. return {"Authorization": f"Bearer {resp.json()['access_token']}"}
  27. @pytest.fixture
  28. async def admin(async_client: AsyncClient) -> dict[str, str]:
  29. await async_client.post(
  30. "/api/v1/auth/setup",
  31. json={"auth_enabled": True, "admin_username": "confadmin", "admin_password": ADMIN_PW},
  32. )
  33. return await _login(async_client, "confadmin", ADMIN_PW)
  34. @pytest.fixture
  35. async def manager(async_client: AsyncClient, admin) -> dict[str, str]:
  36. """A non-admin holding every settings permission."""
  37. group = await async_client.post(
  38. "/api/v1/groups", json={"name": "Settings managers", "permissions": MANAGER_PERMISSIONS}, headers=admin
  39. )
  40. assert group.status_code == 201, group.text
  41. user = await async_client.post(
  42. "/api/v1/users",
  43. json={"username": "confmanager", "password": MANAGER_PW, "group_ids": [group.json()["id"]]},
  44. headers=admin,
  45. )
  46. assert user.status_code == 201, user.text
  47. return await _login(async_client, "confmanager", MANAGER_PW)
  48. ADMIN_ONLY_ROUTES = [
  49. (
  50. "POST",
  51. "/api/v1/auth/oidc/providers",
  52. {"name": "x", "issuer_url": "https://idp.example", "client_id": "c", "client_secret": "s"},
  53. ),
  54. ("PUT", "/api/v1/auth/oidc/providers/1", {"name": "x"}),
  55. ("DELETE", "/api/v1/auth/oidc/providers/1", None),
  56. ("DELETE", "/api/v1/auth/oidc/providers/1/icon", None),
  57. ("POST", "/api/v1/auth/oidc/providers/1/icon/refresh", None),
  58. ("POST", "/api/v1/auth/smtp", {"smtp_host": "mail.example", "smtp_port": 25}),
  59. ("POST", "/api/v1/auth/smtp/test", {"test_recipient": "someone@example.com"}),
  60. ("POST", "/api/v1/auth/ldap/test", None),
  61. ("POST", "/api/v1/settings/reset", None),
  62. ("POST", "/api/v1/local-backup/backups/bambuddy-backup.zip/restore", None),
  63. ("GET", "/api/v1/settings/backup", None),
  64. ("GET", "/api/v1/local-backup/backups/bambuddy-backup.zip/download", None),
  65. # A connected app's redirect address decides where an admin's sign-in goes.
  66. ("POST", "/api/v1/connect/apps", {"name": "x", "redirect_uri": "https://attacker.example/cb"}),
  67. ("PATCH", "/api/v1/connect/apps/1", {"redirect_uri": "https://attacker.example/cb"}),
  68. ("POST", "/api/v1/connect/apps/1/rotate-secret", None),
  69. ("DELETE", "/api/v1/connect/apps/1", None),
  70. ]
  71. @pytest.mark.parametrize(("method", "path", "body"), ADMIN_ONLY_ROUTES)
  72. async def test_a_settings_manager_is_refused(async_client: AsyncClient, manager, method, path, body):
  73. resp = await async_client.request(method, path, json=body, headers=manager)
  74. assert resp.status_code == 403, resp.text
  75. async def test_a_settings_manager_cannot_restore_a_database(async_client: AsyncClient, manager):
  76. resp = await async_client.post(
  77. "/api/v1/settings/restore",
  78. files={"file": ("backup.zip", b"PK\x05\x06" + b"\x00" * 18, "application/zip")},
  79. headers=manager,
  80. )
  81. assert resp.status_code == 403, resp.text
  82. async def test_a_reset_by_a_settings_manager_leaves_authentication_on(async_client: AsyncClient, manager):
  83. await async_client.post("/api/v1/settings/reset", headers=manager)
  84. status = await async_client.get("/api/v1/auth/status")
  85. assert status.json()["auth_enabled"] is True
  86. @pytest.mark.parametrize(
  87. ("key", "value"),
  88. [
  89. ("ldap_server_url", "ldap://attacker.example"),
  90. ("ldap_default_group", "Administrators"),
  91. ("ldap_auto_provision", True),
  92. ("ldap_enabled", True),
  93. ("local_login_enabled", False),
  94. ("session_max_hours", 720),
  95. ("external_url", "https://attacker.example"),
  96. ("prometheus_enabled", True),
  97. ("prometheus_token", "x"),
  98. # A full backup written into a folder the web server hands out.
  99. ("local_backup_path", "/opt/bambuddy/static/img"),
  100. ("external_url", None),
  101. ],
  102. )
  103. async def test_a_settings_manager_cannot_change_sign_in_settings(async_client: AsyncClient, manager, key, value):
  104. for method in ("PUT", "PATCH"):
  105. resp = await async_client.request(method, "/api/v1/settings/", json={key: value}, headers=manager)
  106. assert resp.status_code == 403, (method, resp.text)
  107. async def test_a_settings_manager_still_saves_the_settings_page(async_client: AsyncClient, admin, manager):
  108. """The page sends every field on each save; unchanged sign-in fields pass."""
  109. current = (await async_client.get("/api/v1/settings/", headers=manager)).json()
  110. payload = {k: current[k] for k in ("local_login_enabled", "session_max_hours", "external_url", "ldap_enabled")}
  111. payload["date_format"] = "eu" if current.get("date_format") != "eu" else "us"
  112. resp = await async_client.put("/api/v1/settings/", json=payload, headers=manager)
  113. assert resp.status_code == 200, resp.text
  114. assert resp.json()["date_format"] == payload["date_format"]
  115. async def test_a_refused_save_changes_nothing(async_client: AsyncClient, admin, manager):
  116. before = (await async_client.get("/api/v1/settings/", headers=admin)).json()
  117. flipped = "eu" if before.get("date_format") != "eu" else "us"
  118. resp = await async_client.put(
  119. "/api/v1/settings/",
  120. json={"date_format": flipped, "external_url": "https://attacker.example"},
  121. headers=manager,
  122. )
  123. assert resp.status_code == 403
  124. after = (await async_client.get("/api/v1/settings/", headers=admin)).json()
  125. assert after["date_format"] == before["date_format"]
  126. assert after["external_url"] == before["external_url"]
  127. async def test_an_admin_still_changes_sign_in_settings(async_client: AsyncClient, admin):
  128. resp = await async_client.put(
  129. "/api/v1/settings/", json={"external_url": "https://bambuddy.example", "session_max_hours": 48}, headers=admin
  130. )
  131. assert resp.status_code == 200, resp.text
  132. assert resp.json()["external_url"] == "https://bambuddy.example"
  133. async def test_an_admin_still_reaches_the_admin_only_routes(async_client: AsyncClient, admin):
  134. resp = await async_client.post("/api/v1/auth/ldap/test", headers=admin)
  135. assert resp.status_code != 403
  136. resp = await async_client.get("/api/v1/settings/backup", headers=admin)
  137. assert resp.status_code != 403
  138. async def _git_config(async_client: AsyncClient, admin) -> None:
  139. from unittest.mock import AsyncMock, patch
  140. with patch(
  141. "backend.app.services.github_backup.github_backup_service.test_connection",
  142. new=AsyncMock(
  143. return_value={"success": True, "message": "ok", "permissions": {"push": True}, "is_private": True}
  144. ),
  145. ):
  146. resp = await async_client.post(
  147. "/api/v1/github-backup/config",
  148. headers=admin,
  149. json={
  150. "repository_url": "https://github.com/test/repo",
  151. "access_token": "ghp_testtoken123", # pragma: allowlist secret — test fixture
  152. "branch": "main",
  153. "backup_settings": True,
  154. "enabled": True,
  155. },
  156. )
  157. assert resp.status_code == 200, resp.text
  158. @pytest.mark.parametrize(("who", "as_admin"), [("manager", False), ("admin", True)])
  159. async def test_a_git_restore_keeps_sign_in_settings_unless_an_admin_runs_it(
  160. async_client: AsyncClient, admin, manager, who, as_admin
  161. ):
  162. from unittest.mock import AsyncMock, patch
  163. await _git_config(async_client, admin)
  164. headers = manager if who == "manager" else admin
  165. run = AsyncMock(return_value={"success": True, "message": "ok", "results": {}})
  166. preview = AsyncMock(return_value={"success": True, "message": "ok", "ref": "abc", "categories": []})
  167. with (
  168. patch("backend.app.services.github_restore.github_restore_service.run_restore", new=run),
  169. patch("backend.app.services.github_restore.github_restore_service.preview", new=preview),
  170. ):
  171. restored = await async_client.post(
  172. "/api/v1/github-backup/restore", json={"categories": ["settings"]}, headers=headers
  173. )
  174. previewed = await async_client.get("/api/v1/github-backup/restore/preview", headers=headers)
  175. assert restored.status_code == 200, restored.text
  176. assert previewed.status_code == 200, previewed.text
  177. assert run.await_args.kwargs["as_admin"] is as_admin
  178. assert preview.await_args.kwargs["as_admin"] is as_admin
  179. @pytest.mark.parametrize(("new", "old"), [(True, "true"), (False, "false"), (24, "24"), (None, None)])
  180. def test_a_value_is_the_same_once_stored(new, old):
  181. from backend.app.api.routes.settings import _same_setting_value
  182. assert _same_setting_value(new, old)
  183. @pytest.mark.parametrize(
  184. ("new", "old"),
  185. [
  186. (True, "false"),
  187. (48, "24"),
  188. ("https://a.example", "https://b.example"),
  189. # Stored as written: the text "None" and the spaces would reach the links.
  190. (None, ""),
  191. ("https://b.example ", "https://b.example"),
  192. ],
  193. )
  194. def test_a_different_value_is_a_change(new, old):
  195. from backend.app.api.routes.settings import _same_setting_value
  196. assert not _same_setting_value(new, old)