test_auth_apikey_rbac.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. """Integration tests for API key RBAC enforcement (security fix C1)."""
  2. import pytest
  3. from httpx import AsyncClient
  4. @pytest.fixture
  5. async def api_key_data(async_client: AsyncClient, db_session):
  6. """Create an API key and return its full key value."""
  7. from backend.app.core.auth import generate_api_key
  8. from backend.app.models.api_key import APIKey
  9. full_key, key_hash, key_prefix = generate_api_key()
  10. api_key = APIKey(
  11. name="test-key",
  12. key_hash=key_hash,
  13. key_prefix=key_prefix,
  14. can_queue=True,
  15. can_control_printer=True,
  16. can_read_status=True,
  17. enabled=True,
  18. )
  19. db_session.add(api_key)
  20. await db_session.commit()
  21. return full_key
  22. @pytest.fixture
  23. async def spoolman_settings(db_session):
  24. from backend.app.models.settings import Settings
  25. db_session.add(Settings(key="spoolman_enabled", value="true"))
  26. db_session.add(Settings(key="spoolman_url", value="http://localhost:7912"))
  27. await db_session.commit()
  28. class TestApiKeyRbacDenied:
  29. """API keys must be refused for admin-only endpoints."""
  30. @pytest.mark.asyncio
  31. @pytest.mark.integration
  32. async def test_api_key_cannot_access_settings_update_endpoint(
  33. self, async_client: AsyncClient, db_session, api_key_data
  34. ):
  35. """API key must not be usable for settings:update endpoints (C1)."""
  36. from backend.app.models.settings import Settings
  37. db_session.add(Settings(key="auth_enabled", value="true"))
  38. await db_session.commit()
  39. resp = await async_client.put(
  40. "/api/v1/settings/",
  41. json={},
  42. headers={"X-API-Key": api_key_data},
  43. )
  44. assert resp.status_code == 403
  45. assert "administrative operations" in resp.json()["detail"]
  46. @pytest.mark.asyncio
  47. @pytest.mark.integration
  48. async def test_api_key_bearer_cannot_access_settings_update(
  49. self, async_client: AsyncClient, db_session, api_key_data
  50. ):
  51. """Bearer bb_ API key must also be refused for settings:update (C1)."""
  52. from backend.app.models.settings import Settings
  53. db_session.add(Settings(key="auth_enabled", value="true"))
  54. await db_session.commit()
  55. resp = await async_client.put(
  56. "/api/v1/settings/",
  57. json={},
  58. headers={"Authorization": f"Bearer {api_key_data}"},
  59. )
  60. assert resp.status_code == 403
  61. assert "administrative operations" in resp.json()["detail"]
  62. class TestApiKeyRbacAllowed:
  63. """API keys must still work for non-admin endpoints."""
  64. @pytest.mark.asyncio
  65. @pytest.mark.integration
  66. async def test_api_key_can_access_inventory_read(
  67. self, async_client: AsyncClient, db_session, api_key_data, spoolman_settings
  68. ):
  69. """API key must be accepted for inventory:read endpoints (C1)."""
  70. from unittest.mock import AsyncMock, MagicMock, patch
  71. from backend.app.models.settings import Settings
  72. db_session.add(Settings(key="auth_enabled", value="true"))
  73. await db_session.commit()
  74. mock_client = MagicMock()
  75. mock_client.base_url = "http://localhost:7912"
  76. mock_client.health_check = AsyncMock(return_value=True)
  77. mock_client.get_all_spools = AsyncMock(return_value=[])
  78. mock_client.get_distinct_locations = AsyncMock(return_value=[])
  79. with patch(
  80. "backend.app.api.routes.spoolman_inventory._get_client",
  81. AsyncMock(return_value=mock_client),
  82. ):
  83. resp = await async_client.get(
  84. "/api/v1/spoolman/inventory/spools",
  85. headers={"X-API-Key": api_key_data},
  86. )
  87. assert resp.status_code == 200
  88. class TestApiKeyDenylistIntegrity:
  89. """Drift-detection: assert that admin-tier permissions remain in the denylist."""
  90. def test_admin_permissions_are_denied_for_api_keys(self):
  91. """All known admin-tier permissions must be in _APIKEY_DENIED_PERMISSIONS (H1 guard)."""
  92. from backend.app.core.auth import _APIKEY_DENIED_PERMISSIONS
  93. from backend.app.core.permissions import Permission
  94. expected_denied = {
  95. # SETTINGS_READ is intentionally NOT denied — SpoolBuddy kiosk reads
  96. # settings via API key (e.g. to sync the UI language).
  97. Permission.SETTINGS_UPDATE,
  98. Permission.SETTINGS_BACKUP,
  99. Permission.SETTINGS_RESTORE,
  100. Permission.USERS_READ,
  101. Permission.USERS_CREATE,
  102. Permission.USERS_UPDATE,
  103. Permission.USERS_DELETE,
  104. Permission.GROUPS_READ,
  105. Permission.GROUPS_CREATE,
  106. Permission.GROUPS_UPDATE,
  107. Permission.GROUPS_DELETE,
  108. Permission.API_KEYS_READ,
  109. Permission.API_KEYS_CREATE,
  110. Permission.API_KEYS_UPDATE,
  111. Permission.API_KEYS_DELETE,
  112. Permission.COST_CENTERS_READ_OWN,
  113. Permission.COST_CENTERS_READ_ALL,
  114. Permission.COST_CENTERS_MODIFY,
  115. Permission.COST_CENTERS_CREATE,
  116. Permission.GITHUB_BACKUP,
  117. Permission.GITHUB_RESTORE,
  118. Permission.FIRMWARE_UPDATE,
  119. # Destructive: drop prints from the stats, or scan the network
  120. Permission.LIBRARY_PURGE,
  121. Permission.ARCHIVES_PURGE,
  122. Permission.DISCOVERY_SCAN,
  123. }
  124. missing = expected_denied - _APIKEY_DENIED_PERMISSIONS
  125. assert not missing, (
  126. f"Admin-tier permissions not in API key denylist (add them to _APIKEY_DENIED_PERMISSIONS): {missing}"
  127. )
  128. def test_operational_permissions_are_allowed_for_api_keys(self):
  129. """Core operational permissions must NOT be in the denylist."""
  130. from backend.app.core.auth import _APIKEY_DENIED_PERMISSIONS
  131. from backend.app.core.permissions import Permission
  132. # NOTE: under the GHSA-r2qv-8222-hqg3 allowlist model, INVENTORY_CREATE
  133. # and INVENTORY_UPDATE are administrative (not in the allowlist) and
  134. # therefore denied for API keys regardless of denylist membership.
  135. # This test still guards the small denylist-redundancy set of read-y
  136. # permissions that the SpoolBuddy kiosk + status integrations rely on.
  137. expected_allowed = {
  138. Permission.INVENTORY_READ,
  139. Permission.PRINTERS_READ,
  140. Permission.PRINTERS_CONTROL,
  141. Permission.ARCHIVES_READ,
  142. # #1888: archive delete/update moved off the denylist to the
  143. # can_manage_archives allowlist scope; must not be denied.
  144. Permission.ARCHIVES_DELETE_ALL,
  145. Permission.ARCHIVES_UPDATE_ALL,
  146. # #1893: project CRUD moved off the denylist to the
  147. # can_manage_projects allowlist scope; must not be denied.
  148. Permission.PROJECTS_CREATE,
  149. Permission.PROJECTS_UPDATE,
  150. Permission.PROJECTS_DELETE,
  151. # SpoolBuddy kiosk reads settings (e.g. language) via API key — must stay allowed.
  152. Permission.SETTINGS_READ,
  153. }
  154. incorrectly_denied = expected_allowed & _APIKEY_DENIED_PERMISSIONS
  155. assert not incorrectly_denied, f"Operational permissions incorrectly in API key denylist: {incorrectly_denied}"
  156. def _flags_in_use() -> set[str]:
  157. """Every scope flag named anywhere in the allowlist.
  158. A mapping value is normally one flag but may be a tuple of flags that must
  159. all be held (PIPELINES_RUN). Reading ``.values()`` directly would put that
  160. tuple into the set and make both drift checks below wrong in opposite
  161. directions: an unknown-flag alarm for the tuple, and a false "dead flag"
  162. for whichever flags only appear inside one.
  163. """
  164. from backend.app.core.auth import _APIKEY_SCOPE_BY_PERMISSION
  165. flags: set[str] = set()
  166. for value in _APIKEY_SCOPE_BY_PERMISSION.values():
  167. flags.update((value,) if isinstance(value, str) else value)
  168. return flags
  169. class TestApiKeyScopeAllowlist:
  170. """GHSA-r2qv-8222-hqg3 (CVSS 9.9) — allowlist-based scope enforcement.
  171. Verifies that ``_check_apikey_permissions`` (and the higher-level
  172. dependencies that call it) honour the per-permission scope mapping rather
  173. than the legacy denylist-only model. Failures here would re-open the
  174. "Read Status / Manage Queue / Control Printer / Manage Library checkboxes
  175. are decorative" class of bug.
  176. """
  177. def test_every_permission_has_a_classification(self):
  178. """Structural: every Permission must be either allowlisted or admin-denied.
  179. This is the load-bearing drift-detection test for the allowlist model.
  180. A new Permission added to ``core/permissions.py`` without a matching
  181. entry in ``_APIKEY_SCOPE_BY_PERMISSION`` or ``_APIKEY_DENIED_PERMISSIONS``
  182. is functionally admin-only (allowlist failure → 403) — that's the safe
  183. default, but it should be an explicit choice rather than an oversight.
  184. """
  185. from backend.app.core.auth import (
  186. _APIKEY_DENIED_PERMISSIONS,
  187. _APIKEY_SCOPE_BY_PERMISSION,
  188. )
  189. from backend.app.core.permissions import Permission
  190. unclassified = {
  191. perm
  192. for perm in Permission
  193. if perm not in _APIKEY_SCOPE_BY_PERMISSION and perm not in _APIKEY_DENIED_PERMISSIONS
  194. }
  195. assert not unclassified, (
  196. "Every Permission must be classified for API-key access. "
  197. "Either add to _APIKEY_SCOPE_BY_PERMISSION (with scope flag) or "
  198. f"_APIKEY_DENIED_PERMISSIONS (admin-only). Unclassified: {unclassified}"
  199. )
  200. def test_allowlist_uses_only_valid_scope_flags(self):
  201. """Every value in the scope mapping must be a real bool field on APIKey."""
  202. from backend.app.core.auth import _APIKEY_SCOPE_BY_PERMISSION
  203. from backend.app.models.api_key import APIKey
  204. # can_access_cloud / can_update_energy_cost are narrow opt-in scopes;
  205. # the latter routes through its own ``require_energy_cost_update`` dep
  206. # rather than the central allowlist, so it doesn't appear here.
  207. valid_flags = {
  208. "can_read_status",
  209. "can_queue",
  210. "can_control_printer",
  211. "can_manage_library",
  212. "can_manage_inventory",
  213. "can_manage_maintenance",
  214. "can_manage_archives",
  215. "can_manage_projects",
  216. "can_access_cloud",
  217. }
  218. used_flags = _flags_in_use()
  219. assert used_flags <= valid_flags, f"Unknown scope flags in mapping: {used_flags - valid_flags}"
  220. # And every flag must actually exist on the model.
  221. for flag in valid_flags:
  222. assert hasattr(APIKey, flag), f"APIKey model missing column referenced by allowlist: {flag}"
  223. def test_allowlist_and_denylist_are_disjoint(self):
  224. """A permission classified as allowlisted must not also be in the denylist (and v/v)."""
  225. from backend.app.core.auth import (
  226. _APIKEY_DENIED_PERMISSIONS,
  227. _APIKEY_SCOPE_BY_PERMISSION,
  228. )
  229. overlap = set(_APIKEY_SCOPE_BY_PERMISSION) & _APIKEY_DENIED_PERMISSIONS
  230. assert not overlap, f"Permissions in both allowlist and denylist: {overlap}"
  231. @pytest.mark.parametrize(
  232. "scope_flag",
  233. [
  234. "can_read_status",
  235. "can_queue",
  236. "can_control_printer",
  237. "can_manage_library",
  238. "can_manage_inventory",
  239. "can_manage_maintenance",
  240. "can_manage_archives",
  241. "can_manage_projects",
  242. "can_access_cloud",
  243. ],
  244. )
  245. def test_each_scope_flag_has_at_least_one_permission(self, scope_flag):
  246. """If a scope flag has no permissions, it's dead code — fail loudly."""
  247. assert scope_flag in _flags_in_use(), (
  248. f"No permission maps to {scope_flag} — either remove the flag or classify a permission under it."
  249. )
  250. class _FakeApiKey:
  251. """Bool-attribute stand-in for APIKey used by the scope matrix tests.
  252. The ``_check_apikey_permissions`` function only inspects the four scope
  253. booleans, so a lightweight stub is enough; instantiating the real model
  254. requires a DB session which is overkill for pure-logic verification.
  255. """
  256. def __init__(
  257. self,
  258. can_read_status=False,
  259. can_queue=False,
  260. can_control_printer=False,
  261. can_manage_library=False,
  262. can_manage_inventory=False,
  263. can_manage_maintenance=False,
  264. can_manage_archives=False,
  265. can_manage_projects=False,
  266. ):
  267. self.can_read_status = can_read_status
  268. self.can_queue = can_queue
  269. self.can_control_printer = can_control_printer
  270. self.can_manage_library = can_manage_library
  271. self.can_manage_inventory = can_manage_inventory
  272. self.can_manage_maintenance = can_manage_maintenance
  273. self.can_manage_archives = can_manage_archives
  274. self.can_manage_projects = can_manage_projects
  275. class TestCheckApiKeyPermissionsMatrix:
  276. """Pure-logic matrix: every (scope flag combo × representative permission) outcome.
  277. These are the tests that would have caught GHSA-r2qv-8222-hqg3 — they prove
  278. the actual gate function honours the scope flags, not just that some
  279. helper called by webhook.py does.
  280. """
  281. # (Permission, expected scope flag attribute, category description)
  282. _SCOPE_CASES = [
  283. # can_read_status
  284. ("PRINTERS_READ", "can_read_status", "read printer status"),
  285. ("ARCHIVES_READ", "can_read_status", "read archives"),
  286. ("QUEUE_READ", "can_read_status", "read queue"),
  287. ("SETTINGS_READ", "can_read_status", "SpoolBuddy kiosk settings read"),
  288. ("WEBSOCKET_CONNECT", "can_read_status", "websocket subscribe"),
  289. # can_queue
  290. ("QUEUE_CREATE", "can_queue", "add queue item"),
  291. ("QUEUE_DELETE_ALL", "can_queue", "delete any queue item"),
  292. ("ARCHIVES_REPRINT_ALL", "can_queue", "reprint an archive"),
  293. # can_control_printer
  294. ("PRINTERS_CONTROL", "can_control_printer", "start/stop print"),
  295. ("PRINTERS_FILES", "can_control_printer", "send file to printer"),
  296. ("SMART_PLUGS_CONTROL", "can_control_printer", "smart plug on/off"),
  297. # can_manage_library — OWN and ALL ownership variants both fold into
  298. # the same scope (#1832): API keys have no per-row ownership identity,
  299. # so splitting OWN/ALL across allowlist/denylist made the curation
  300. # surface unreachable. PURGE stays admin-only.
  301. ("LIBRARY_UPLOAD", "can_manage_library", "upload library file"),
  302. ("LIBRARY_UPDATE_OWN", "can_manage_library", "rename own library file"),
  303. ("LIBRARY_UPDATE_ALL", "can_manage_library", "rename any library file"),
  304. ("LIBRARY_DELETE_OWN", "can_manage_library", "delete own library file"),
  305. ("LIBRARY_DELETE_ALL", "can_manage_library", "delete any library file"),
  306. ("MAKERWORLD_IMPORT", "can_manage_library", "import from MakerWorld"),
  307. # can_manage_inventory
  308. ("INVENTORY_CREATE", "can_manage_inventory", "create spool record"),
  309. ("INVENTORY_UPDATE", "can_manage_inventory", "update spool / SpoolBuddy kiosk write"),
  310. ("INVENTORY_DELETE", "can_manage_inventory", "delete spool record"),
  311. ("INVENTORY_FORECAST_WRITE", "can_manage_inventory", "update forecast SKU settings"),
  312. # can_manage_maintenance (#1832 follow-up) — HA "cleaned nozzle" / reset counter
  313. # is the load-bearing use case; MAINTENANCE_UPDATE gates POST /maintenance/items/{id}/perform.
  314. ("MAINTENANCE_CREATE", "can_manage_maintenance", "assign maintenance type to printer"),
  315. ("MAINTENANCE_UPDATE", "can_manage_maintenance", "log maintenance / edit interval"),
  316. ("MAINTENANCE_DELETE", "can_manage_maintenance", "remove custom maintenance item"),
  317. # can_manage_archives (#1888) — prune print history via API key. OWN and
  318. # ALL ownership variants both fold into the same scope (API keys have no
  319. # per-row ownership identity), matching the can_manage_library shape.
  320. # ARCHIVES_PURGE stays admin-only (see _ADMIN_CASES).
  321. ("ARCHIVES_CREATE", "can_manage_archives", "create an archive"),
  322. ("ARCHIVES_UPDATE_OWN", "can_manage_archives", "edit own archive"),
  323. ("ARCHIVES_UPDATE_ALL", "can_manage_archives", "edit any archive"),
  324. ("ARCHIVES_DELETE_OWN", "can_manage_archives", "delete own archive"),
  325. ("ARCHIVES_DELETE_ALL", "can_manage_archives", "delete any archive"),
  326. # can_manage_projects (#1893) — project CRUD + membership via API key.
  327. # Projects gate on plain PROJECTS_* (no OWN/ALL split), so the three
  328. # permissions map directly to the one scope. PROJECTS_READ stays under
  329. # can_read_status. Membership edits (add-archives) gate on PROJECTS_UPDATE.
  330. ("PROJECTS_CREATE", "can_manage_projects", "create a project"),
  331. ("PROJECTS_UPDATE", "can_manage_projects", "update a project / add archives"),
  332. ("PROJECTS_DELETE", "can_manage_projects", "delete a project"),
  333. # Pipeline definitions and run history read as status/config, so they
  334. # ride can_read_status. PIPELINES_RUN needs two flags and has its own
  335. # class below; PIPELINES_WRITE stays admin-only (see _ADMIN_CASES).
  336. ("PIPELINES_READ", "can_read_status", "list pipelines / read run history"),
  337. ]
  338. _ADMIN_CASES = [
  339. # Documented denylist
  340. "SETTINGS_UPDATE",
  341. "USERS_CREATE",
  342. "GROUPS_DELETE",
  343. "API_KEYS_CREATE",
  344. "GITHUB_BACKUP",
  345. "FIRMWARE_UPDATE",
  346. # Unmapped administrative (allowlist fail-closed catches these too)
  347. "PRINTERS_CREATE",
  348. # LIBRARY_DELETE_ALL / LIBRARY_UPDATE_ALL moved to can_manage_library
  349. # under #1832 — covered by the _SCOPE_CASES matrix above.
  350. "LIBRARY_PURGE",
  351. # ARCHIVES_PURGE stays admin-only even though the rest of archive
  352. # management moved to can_manage_archives under #1888 — it drops the
  353. # print's stats contribution, mirroring LIBRARY_PURGE.
  354. "ARCHIVES_PURGE",
  355. "DISCOVERY_SCAN",
  356. # PIPELINES_READ / PIPELINES_RUN became key-usable once PR C landed the
  357. # run dispatch (#1425). Authoring did not: PIPELINES_WRITE rewrites the
  358. # slicer settings and target printer a run then acts on, and clears run
  359. # history.
  360. "PIPELINES_WRITE",
  361. ]
  362. @pytest.mark.parametrize("perm_name,required_flag,_descr", _SCOPE_CASES)
  363. def test_permission_allowed_only_when_scope_flag_is_set(self, perm_name, required_flag, _descr):
  364. """For each (Permission, scope) case, true→allow and false→403."""
  365. from fastapi import HTTPException
  366. from backend.app.core.auth import _check_apikey_permissions
  367. from backend.app.core.permissions import Permission
  368. perm = Permission[perm_name].value
  369. # Flag set → passes
  370. _check_apikey_permissions(_FakeApiKey(**{required_flag: True}), [perm])
  371. # All flags off → 403
  372. with pytest.raises(HTTPException) as exc:
  373. _check_apikey_permissions(_FakeApiKey(), [perm])
  374. assert exc.value.status_code == 403
  375. # Wrong flag set, required flag off → 403 (no cross-scope leakage)
  376. other_flags = {
  377. f
  378. for f in (
  379. "can_read_status",
  380. "can_queue",
  381. "can_control_printer",
  382. "can_manage_library",
  383. "can_manage_inventory",
  384. "can_manage_maintenance",
  385. "can_manage_archives",
  386. "can_manage_projects",
  387. )
  388. if f != required_flag
  389. }
  390. for other in other_flags:
  391. with pytest.raises(HTTPException) as exc:
  392. _check_apikey_permissions(_FakeApiKey(**{other: True}), [perm])
  393. assert exc.value.status_code == 403
  394. @pytest.mark.parametrize("perm_name", _ADMIN_CASES)
  395. def test_admin_permissions_are_403_regardless_of_flags(self, perm_name):
  396. """A fully-flagged API key still cannot use administrative permissions."""
  397. from fastapi import HTTPException
  398. from backend.app.core.auth import _check_apikey_permissions
  399. from backend.app.core.permissions import Permission
  400. from backend.app.models.api_key import APIKey
  401. perm = Permission[perm_name].value
  402. # Every scope flag the model has, so no flag can be what refuses it
  403. all_flags = _FakeApiKey()
  404. for column in APIKey.__table__.columns:
  405. if column.name.startswith("can_"):
  406. setattr(all_flags, column.name, True)
  407. with pytest.raises(HTTPException) as exc:
  408. _check_apikey_permissions(all_flags, [perm])
  409. assert exc.value.status_code == 403
  410. assert "administrative" in exc.value.detail.lower()
  411. def test_unknown_permission_string_is_admin_denied(self):
  412. """An unrecognised permission string must fail closed, not silently pass."""
  413. from fastapi import HTTPException
  414. from backend.app.core.auth import _check_apikey_permissions
  415. all_flags = _FakeApiKey(can_read_status=True, can_queue=True, can_control_printer=True, can_manage_library=True)
  416. with pytest.raises(HTTPException) as exc:
  417. _check_apikey_permissions(all_flags, ["bogus:nonexistent"])
  418. assert exc.value.status_code == 403
  419. def test_empty_perm_list_is_403(self):
  420. """Defence-in-depth: an empty perm list must not silently allow."""
  421. from fastapi import HTTPException
  422. from backend.app.core.auth import _check_apikey_permissions
  423. all_flags = _FakeApiKey(can_read_status=True, can_queue=True, can_control_printer=True, can_manage_library=True)
  424. with pytest.raises(HTTPException) as exc:
  425. _check_apikey_permissions(all_flags, [])
  426. assert exc.value.status_code == 403
  427. def test_require_any_at_least_one_must_pass(self):
  428. """``require_any=True`` matches any-of semantics, but still respects scopes."""
  429. from fastapi import HTTPException
  430. from backend.app.core.auth import _check_apikey_permissions
  431. from backend.app.core.permissions import Permission
  432. # can_read_status only: any-of (PRINTERS_READ, QUEUE_CREATE) passes because the read flag is set.
  433. _check_apikey_permissions(
  434. _FakeApiKey(can_read_status=True),
  435. [Permission.PRINTERS_READ.value, Permission.QUEUE_CREATE.value],
  436. require_any=True,
  437. )
  438. # No flags: any-of fails.
  439. with pytest.raises(HTTPException):
  440. _check_apikey_permissions(
  441. _FakeApiKey(),
  442. [Permission.PRINTERS_READ.value, Permission.QUEUE_CREATE.value],
  443. require_any=True,
  444. )
  445. # All admin perms: any-of fails even with every flag set.
  446. with pytest.raises(HTTPException):
  447. _check_apikey_permissions(
  448. _FakeApiKey(can_read_status=True, can_queue=True, can_control_printer=True, can_manage_library=True),
  449. [Permission.USERS_CREATE.value, Permission.GROUPS_DELETE.value],
  450. require_any=True,
  451. )
  452. def test_require_all_every_perm_must_pass(self):
  453. """Default ``require_any=False``: every permission must pass — single failure → 403."""
  454. from fastapi import HTTPException
  455. from backend.app.core.auth import _check_apikey_permissions
  456. from backend.app.core.permissions import Permission
  457. # Read+queue set, queue+control required → fails because control flag is off.
  458. with pytest.raises(HTTPException) as exc:
  459. _check_apikey_permissions(
  460. _FakeApiKey(can_read_status=True, can_queue=True),
  461. [Permission.QUEUE_CREATE.value, Permission.PRINTERS_CONTROL.value],
  462. )
  463. assert exc.value.status_code == 403
  464. class TestMultiScopePermissions:
  465. """A permission may require several scope flags at once (#1425 follow-up).
  466. Running a slicer pipeline slices the source into a new library file and
  467. then queues one print per copy. Those are two things an operator ticks
  468. separately when minting a key, so PIPELINES_RUN maps to both
  469. ``can_queue`` and ``can_manage_library`` — mapping it to either alone
  470. would quietly hand that flag the other one's authority.
  471. """
  472. def _run_perm(self):
  473. from backend.app.core.permissions import Permission
  474. return Permission.PIPELINES_RUN.value
  475. def test_both_flags_pass(self):
  476. from backend.app.core.auth import _check_apikey_permissions
  477. _check_apikey_permissions(_FakeApiKey(can_queue=True, can_manage_library=True), [self._run_perm()])
  478. @pytest.mark.parametrize(
  479. "flags",
  480. [
  481. {},
  482. {"can_queue": True},
  483. {"can_manage_library": True},
  484. # Neither of the two required flags, however generous the rest.
  485. {"can_read_status": True, "can_control_printer": True, "can_manage_projects": True},
  486. ],
  487. )
  488. def test_a_partial_key_is_refused(self, flags):
  489. """Half the authority is not authority. A queue-only key must not be
  490. able to write into the library through a pipeline, and a library-only
  491. key must not be able to spend filament through one."""
  492. from fastapi import HTTPException
  493. from backend.app.core.auth import _check_apikey_permissions
  494. with pytest.raises(HTTPException) as exc:
  495. _check_apikey_permissions(_FakeApiKey(**flags), [self._run_perm()])
  496. assert exc.value.status_code == 403
  497. def test_the_403_names_every_missing_flag(self):
  498. """Reporting only the first would send the operator round the loop
  499. twice, ticking one box per refusal with no hint a second is needed."""
  500. from fastapi import HTTPException
  501. from backend.app.core.auth import _check_apikey_permissions
  502. with pytest.raises(HTTPException) as exc:
  503. _check_apikey_permissions(_FakeApiKey(), [self._run_perm()])
  504. assert "can_queue" in exc.value.detail
  505. assert "can_manage_library" in exc.value.detail
  506. with pytest.raises(HTTPException) as exc:
  507. _check_apikey_permissions(_FakeApiKey(can_queue=True), [self._run_perm()])
  508. assert "can_manage_library" in exc.value.detail
  509. assert "can_queue" not in exc.value.detail
  510. def test_single_scope_message_is_unchanged(self):
  511. """Existing keys' 403 text is documented in the wiki and matched by
  512. other tests; multi-scope support must not reword the common case."""
  513. from fastapi import HTTPException
  514. from backend.app.core.auth import _check_apikey_permissions
  515. from backend.app.core.permissions import Permission
  516. with pytest.raises(HTTPException) as exc:
  517. _check_apikey_permissions(_FakeApiKey(), [Permission.QUEUE_CREATE.value])
  518. assert exc.value.detail == "API key does not have 'can_queue' permission"
  519. def test_require_any_still_passes_on_a_different_permission(self):
  520. """An any-of route must not be blocked by the multi-scope member when
  521. the key satisfies one of the others."""
  522. from backend.app.core.auth import _check_apikey_permissions
  523. from backend.app.core.permissions import Permission
  524. _check_apikey_permissions(
  525. _FakeApiKey(can_read_status=True),
  526. [self._run_perm(), Permission.PRINTERS_READ.value],
  527. require_any=True,
  528. )
  529. def test_effective_permissions_agree_with_the_gate(self):
  530. """``/auth/me`` reports what a key can do by walking the same mapping.
  531. If it ignored the second flag it would advertise pipelines:run to a
  532. key the gate then refuses — the drift #1894 was about."""
  533. from backend.app.core.auth import apikey_effective_permissions
  534. assert self._run_perm() not in apikey_effective_permissions(_FakeApiKey(can_queue=True))
  535. assert self._run_perm() not in apikey_effective_permissions(_FakeApiKey(can_manage_library=True))
  536. assert self._run_perm() in apikey_effective_permissions(_FakeApiKey(can_queue=True, can_manage_library=True))
  537. def test_effective_permissions_still_narrow_to_the_owner(self):
  538. """A multi-scope permission is no exception to owner narrowing: both
  539. flags set is still capped by what the key's owner may do."""
  540. class _Owner:
  541. def __init__(self, holds):
  542. self._holds = holds
  543. def has_permission(self, perm):
  544. return perm in self._holds
  545. from backend.app.core.auth import apikey_effective_permissions
  546. key = _FakeApiKey(can_queue=True, can_manage_library=True)
  547. assert self._run_perm() not in apikey_effective_permissions(key, _Owner(set()))
  548. assert self._run_perm() in apikey_effective_permissions(key, _Owner({self._run_perm()}))
  549. class TestPipelineRoutesAcceptApiKeys:
  550. """End-to-end: the routes themselves, not just the mapping.
  551. Before this fix every pipeline endpoint answered 403 "API keys cannot be
  552. used for administrative operations", because PR A parked all three
  553. permissions on the denylist until the run dispatch landed. It landed in
  554. PR C.
  555. """
  556. @pytest.fixture
  557. async def auth_on(self, db_session):
  558. from backend.app.models.settings import Settings
  559. db_session.add(Settings(key="auth_enabled", value="true"))
  560. await db_session.commit()
  561. async def _key(self, db_session, **flags):
  562. from backend.app.core.auth import generate_api_key
  563. from backend.app.models.api_key import APIKey
  564. full_key, key_hash, key_prefix = generate_api_key()
  565. db_session.add(
  566. APIKey(
  567. name="pipeline-key",
  568. key_hash=key_hash,
  569. key_prefix=key_prefix,
  570. enabled=True,
  571. **{"can_read_status": False, "can_queue": False, "can_manage_library": False, **flags},
  572. )
  573. )
  574. await db_session.commit()
  575. return full_key
  576. @pytest.mark.asyncio
  577. @pytest.mark.integration
  578. async def test_a_read_key_can_list_pipelines(self, async_client: AsyncClient, db_session, auth_on):
  579. key = await self._key(db_session, can_read_status=True)
  580. resp = await async_client.get("/api/v1/slicer-pipelines/", headers={"X-API-Key": key})
  581. assert resp.status_code == 200
  582. @pytest.mark.asyncio
  583. @pytest.mark.integration
  584. async def test_a_read_key_can_list_runs(self, async_client: AsyncClient, db_session, auth_on):
  585. key = await self._key(db_session, can_read_status=True)
  586. resp = await async_client.get("/api/v1/pipeline-runs", headers={"X-API-Key": key})
  587. assert resp.status_code == 200
  588. @pytest.mark.asyncio
  589. @pytest.mark.integration
  590. async def test_a_read_key_cannot_author_a_pipeline(self, async_client: AsyncClient, db_session, auth_on):
  591. """PIPELINES_WRITE stays admin-only — reading pipelines must not imply
  592. rewriting the slicer settings a run will act on."""
  593. key = await self._key(db_session, can_read_status=True, can_queue=True, can_manage_library=True)
  594. resp = await async_client.post(
  595. "/api/v1/slicer-pipelines/",
  596. json={"name": "x"},
  597. headers={"X-API-Key": key},
  598. )
  599. assert resp.status_code == 403
  600. assert "administrative operations" in resp.json()["detail"]
  601. @pytest.mark.asyncio
  602. @pytest.mark.integration
  603. async def test_a_queue_only_key_cannot_run_a_pipeline(self, async_client: AsyncClient, db_session, auth_on):
  604. key = await self._key(db_session, can_read_status=True, can_queue=True)
  605. resp = await async_client.post(
  606. "/api/v1/slicer-pipelines/1/run",
  607. json={"source_library_file_id": 1},
  608. headers={"X-API-Key": key},
  609. )
  610. assert resp.status_code == 403
  611. assert "can_manage_library" in resp.json()["detail"]
  612. @pytest.mark.asyncio
  613. @pytest.mark.integration
  614. async def test_a_fully_scoped_key_gets_past_the_gate(self, async_client: AsyncClient, db_session, auth_on):
  615. """404 for the missing pipeline, not 403 — the permission check is
  616. what this asserts, and only a request that cleared it reaches the
  617. lookup."""
  618. key = await self._key(db_session, can_read_status=True, can_queue=True, can_manage_library=True)
  619. resp = await async_client.post(
  620. "/api/v1/slicer-pipelines/999999/run",
  621. json={"source_library_file_id": 1},
  622. headers={"X-API-Key": key},
  623. )
  624. assert resp.status_code == 404