test_ownership_permissions.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. """Integration tests for ownership-based permission system.
  2. Tests the ownership permission model where users can have:
  3. - *_all permissions: can modify any item
  4. - *_own permissions: can only modify items they created
  5. - Ownerless items (created_by_id = null) require *_all permission
  6. """
  7. import pytest
  8. from httpx import AsyncClient
  9. class TestOwnershipPermissionsSetup:
  10. """Helper fixture class for ownership permission tests."""
  11. @pytest.fixture
  12. async def auth_setup(self, async_client: AsyncClient):
  13. """Setup auth with admin, create test users with different permission levels."""
  14. # Enable auth with admin user
  15. await async_client.post(
  16. "/api/v1/auth/setup",
  17. json={
  18. "auth_enabled": True,
  19. "admin_username": "ownershipadmin",
  20. "admin_password": "AdminPass1!",
  21. },
  22. )
  23. # Login as admin
  24. admin_login = await async_client.post(
  25. "/api/v1/auth/login",
  26. json={"username": "ownershipadmin", "password": "AdminPass1!"},
  27. )
  28. admin_token = admin_login.json()["access_token"]
  29. admin_user = admin_login.json()["user"]
  30. # Get group IDs
  31. groups_response = await async_client.get(
  32. "/api/v1/groups/",
  33. headers={"Authorization": f"Bearer {admin_token}"},
  34. )
  35. groups = groups_response.json()
  36. operators_group = next(g for g in groups if g["name"] == "Operators")
  37. viewers_group = next(g for g in groups if g["name"] == "Viewers")
  38. # Create operator user (has *_own permissions)
  39. operator_response = await async_client.post(
  40. "/api/v1/users/",
  41. headers={"Authorization": f"Bearer {admin_token}"},
  42. json={
  43. "username": "operator1",
  44. "password": "Operatorpass1!",
  45. "group_ids": [operators_group["id"]],
  46. },
  47. )
  48. operator_user = operator_response.json()
  49. # Login as operator
  50. operator_login = await async_client.post(
  51. "/api/v1/auth/login",
  52. json={"username": "operator1", "password": "Operatorpass1!"},
  53. )
  54. operator_token = operator_login.json()["access_token"]
  55. # Create second operator (for cross-user tests)
  56. operator2_response = await async_client.post(
  57. "/api/v1/users/",
  58. headers={"Authorization": f"Bearer {admin_token}"},
  59. json={
  60. "username": "operator2",
  61. "password": "Operatorpass1!",
  62. "group_ids": [operators_group["id"]],
  63. },
  64. )
  65. operator2_user = operator2_response.json()
  66. operator2_login = await async_client.post(
  67. "/api/v1/auth/login",
  68. json={"username": "operator2", "password": "Operatorpass1!"},
  69. )
  70. operator2_token = operator2_login.json()["access_token"]
  71. # Create viewer user (has no update/delete permissions)
  72. await async_client.post(
  73. "/api/v1/users/",
  74. headers={"Authorization": f"Bearer {admin_token}"},
  75. json={
  76. "username": "viewer1",
  77. "password": "Viewerpass1!",
  78. "group_ids": [viewers_group["id"]],
  79. },
  80. )
  81. viewer_login = await async_client.post(
  82. "/api/v1/auth/login",
  83. json={"username": "viewer1", "password": "Viewerpass1!"},
  84. )
  85. viewer_token = viewer_login.json()["access_token"]
  86. return {
  87. "admin_token": admin_token,
  88. "admin_user": admin_user,
  89. "operator_token": operator_token,
  90. "operator_user": operator_user,
  91. "operator2_token": operator2_token,
  92. "operator2_user": operator2_user,
  93. "viewer_token": viewer_token,
  94. }
  95. class TestArchiveOwnershipPermissions(TestOwnershipPermissionsSetup):
  96. """Tests for archive ownership-based permissions."""
  97. # ========================================================================
  98. # DELETE permissions
  99. # ========================================================================
  100. @pytest.mark.asyncio
  101. @pytest.mark.integration
  102. async def test_admin_can_delete_any_archive(
  103. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  104. ):
  105. """Admin with *_all permissions can delete any archive."""
  106. printer = await printer_factory()
  107. # Create archive owned by operator
  108. archive = await archive_factory(
  109. printer.id,
  110. print_name="Operator Archive",
  111. created_by_id=auth_setup["operator_user"]["id"],
  112. )
  113. # Admin deletes it
  114. response = await async_client.delete(
  115. f"/api/v1/archives/{archive.id}",
  116. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  117. )
  118. assert response.status_code == 200
  119. @pytest.mark.asyncio
  120. @pytest.mark.integration
  121. async def test_operator_can_delete_own_archive(
  122. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  123. ):
  124. """Operator with *_own permissions can delete their own archive."""
  125. printer = await printer_factory()
  126. archive = await archive_factory(
  127. printer.id,
  128. print_name="My Archive",
  129. created_by_id=auth_setup["operator_user"]["id"],
  130. )
  131. response = await async_client.delete(
  132. f"/api/v1/archives/{archive.id}",
  133. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  134. )
  135. assert response.status_code == 200
  136. @pytest.mark.asyncio
  137. @pytest.mark.integration
  138. async def test_operator_cannot_delete_others_archive(
  139. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  140. ):
  141. """Operator with *_own permissions cannot delete another user's archive."""
  142. printer = await printer_factory()
  143. # Archive created by operator2
  144. archive = await archive_factory(
  145. printer.id,
  146. print_name="Other's Archive",
  147. created_by_id=auth_setup["operator2_user"]["id"],
  148. )
  149. # operator1 tries to delete it
  150. response = await async_client.delete(
  151. f"/api/v1/archives/{archive.id}",
  152. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  153. )
  154. assert response.status_code == 403
  155. assert "your own" in response.json()["detail"].lower()
  156. @pytest.mark.asyncio
  157. @pytest.mark.integration
  158. async def test_operator_cannot_delete_ownerless_archive(
  159. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  160. ):
  161. """Operator with *_own permissions cannot delete ownerless archive."""
  162. printer = await printer_factory()
  163. # Archive with no owner (legacy data)
  164. archive = await archive_factory(
  165. printer.id,
  166. print_name="Ownerless Archive",
  167. created_by_id=None,
  168. )
  169. response = await async_client.delete(
  170. f"/api/v1/archives/{archive.id}",
  171. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  172. )
  173. assert response.status_code == 403
  174. @pytest.mark.asyncio
  175. @pytest.mark.integration
  176. async def test_viewer_cannot_delete_archive(
  177. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  178. ):
  179. """Viewer with no delete permissions cannot delete any archive."""
  180. printer = await printer_factory()
  181. archive = await archive_factory(printer.id, print_name="Any Archive")
  182. response = await async_client.delete(
  183. f"/api/v1/archives/{archive.id}",
  184. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  185. )
  186. assert response.status_code == 403
  187. # ========================================================================
  188. # UPDATE permissions
  189. # ========================================================================
  190. @pytest.mark.asyncio
  191. @pytest.mark.integration
  192. async def test_admin_can_update_any_archive(
  193. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  194. ):
  195. """Admin can update any archive."""
  196. printer = await printer_factory()
  197. archive = await archive_factory(
  198. printer.id,
  199. print_name="Original Name",
  200. created_by_id=auth_setup["operator_user"]["id"],
  201. )
  202. response = await async_client.patch(
  203. f"/api/v1/archives/{archive.id}",
  204. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  205. json={"print_name": "Admin Updated"},
  206. )
  207. assert response.status_code == 200
  208. assert response.json()["print_name"] == "Admin Updated"
  209. @pytest.mark.asyncio
  210. @pytest.mark.integration
  211. async def test_operator_can_update_own_archive(
  212. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  213. ):
  214. """Operator can update their own archive."""
  215. printer = await printer_factory()
  216. archive = await archive_factory(
  217. printer.id,
  218. print_name="Original Name",
  219. created_by_id=auth_setup["operator_user"]["id"],
  220. )
  221. response = await async_client.patch(
  222. f"/api/v1/archives/{archive.id}",
  223. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  224. json={"print_name": "Operator Updated"},
  225. )
  226. assert response.status_code == 200
  227. assert response.json()["print_name"] == "Operator Updated"
  228. @pytest.mark.asyncio
  229. @pytest.mark.integration
  230. async def test_operator_cannot_update_others_archive(
  231. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  232. ):
  233. """Operator cannot update another user's archive."""
  234. printer = await printer_factory()
  235. archive = await archive_factory(
  236. printer.id,
  237. print_name="Other's Archive",
  238. created_by_id=auth_setup["operator2_user"]["id"],
  239. )
  240. response = await async_client.patch(
  241. f"/api/v1/archives/{archive.id}",
  242. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  243. json={"print_name": "Attempted Update"},
  244. )
  245. assert response.status_code == 403
  246. # ========================================================================
  247. # Legacy reprint endpoint
  248. # ========================================================================
  249. @pytest.mark.asyncio
  250. @pytest.mark.integration
  251. async def test_reprint_endpoint_is_gone_for_all_callers(
  252. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  253. ):
  254. """Direct archive reprint no longer exists; callers must use the queue."""
  255. printer = await printer_factory()
  256. archive = await archive_factory(
  257. printer.id,
  258. created_by_id=auth_setup["operator2_user"]["id"],
  259. )
  260. response = await async_client.post(
  261. f"/api/v1/archives/{archive.id}/reprint?printer_id={printer.id}",
  262. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  263. )
  264. assert response.status_code == 410
  265. # ========================================================================
  266. # Queue route — archives:reprint_* gate (#1625)
  267. # ========================================================================
  268. # The unified /queue/ route replaced the legacy /reprint endpoint; the
  269. # reprint permission gate must move with it. Without these checks a
  270. # caller with QUEUE_CREATE + ARCHIVES_READ_OWN could reprint their own
  271. # archives even if explicitly denied ARCHIVES_REPRINT_OWN.
  272. @pytest.mark.asyncio
  273. @pytest.mark.integration
  274. async def test_queue_route_operator_can_reprint_own_archive(
  275. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  276. ):
  277. """Operator with REPRINT_OWN can queue their own archive."""
  278. printer = await printer_factory()
  279. archive = await archive_factory(
  280. printer.id,
  281. created_by_id=auth_setup["operator_user"]["id"],
  282. )
  283. response = await async_client.post(
  284. "/api/v1/queue/",
  285. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  286. json={"printer_id": printer.id, "archive_id": archive.id},
  287. )
  288. assert response.status_code == 200
  289. @pytest.mark.asyncio
  290. @pytest.mark.integration
  291. async def test_queue_route_user_without_reprint_gets_403(
  292. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  293. ):
  294. """User with QUEUE_CREATE + ARCHIVES_READ_OWN but no reprint perm → 403.
  295. Custom group mirrors a real operator policy where someone is allowed
  296. to enqueue freshly-uploaded library files but explicitly NOT allowed
  297. to re-run completed archives.
  298. """
  299. # Create custom group with queue:create + archives:read_own but no reprint perm.
  300. admin_headers = {"Authorization": f"Bearer {auth_setup['admin_token']}"}
  301. group_resp = await async_client.post(
  302. "/api/v1/groups/",
  303. headers=admin_headers,
  304. json={
  305. "name": "QueueOnlyNoReprint",
  306. "description": "Test group: can queue library files but not reprint",
  307. "permissions": [
  308. "queue:create",
  309. "queue:read_own",
  310. "archives:read_own",
  311. "library:read_own",
  312. "library:upload",
  313. "printers:read",
  314. ],
  315. },
  316. )
  317. assert group_resp.status_code in (200, 201)
  318. group_id = group_resp.json()["id"]
  319. await async_client.post(
  320. "/api/v1/users/",
  321. headers=admin_headers,
  322. json={
  323. "username": "noreprint_user",
  324. "password": "NoreprintPass1!",
  325. "group_ids": [group_id],
  326. },
  327. )
  328. login = await async_client.post(
  329. "/api/v1/auth/login",
  330. json={"username": "noreprint_user", "password": "NoreprintPass1!"},
  331. )
  332. token = login.json()["access_token"]
  333. user_id = login.json()["user"]["id"]
  334. # Archive owned by the no-reprint user.
  335. printer = await printer_factory()
  336. archive = await archive_factory(printer.id, created_by_id=user_id)
  337. response = await async_client.post(
  338. "/api/v1/queue/",
  339. headers={"Authorization": f"Bearer {token}"},
  340. json={"printer_id": printer.id, "archive_id": archive.id},
  341. )
  342. assert response.status_code == 403
  343. assert "reprint" in response.json()["detail"].lower()
  344. @pytest.mark.asyncio
  345. @pytest.mark.integration
  346. async def test_queue_route_ownerless_archive_requires_reprint_all(
  347. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  348. ):
  349. """Ownerless archive (created_by_id=null) requires REPRINT_ALL.
  350. Pre-IDOR-fix legacy data has no creator; an operator with
  351. REPRINT_OWN can't fall back to "I own this" — fail-closed.
  352. The existing IDOR check returns 404 first (operator lacks
  353. READ_ALL and doesn't own the row), so this is also a regression
  354. guard against accidentally surfacing 403-instead-of-404 if the
  355. IDOR check is ever loosened.
  356. """
  357. printer = await printer_factory()
  358. archive = await archive_factory(printer.id, created_by_id=None)
  359. response = await async_client.post(
  360. "/api/v1/queue/",
  361. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  362. json={"printer_id": printer.id, "archive_id": archive.id},
  363. )
  364. # IDOR returns 404 before the new gate fires for this operator.
  365. assert response.status_code == 404
  366. class TestQueueOwnershipPermissions(TestOwnershipPermissionsSetup):
  367. """Tests for print queue ownership-based permissions."""
  368. @pytest.fixture
  369. async def queue_item_factory(self, db_session, printer_factory, archive_factory):
  370. """Factory to create test queue items."""
  371. async def _create_item(**kwargs):
  372. from backend.app.models.print_queue import PrintQueueItem
  373. printer = await printer_factory()
  374. # Create an archive to link to the queue item
  375. archive = await archive_factory(printer.id)
  376. defaults = {
  377. "printer_id": printer.id,
  378. "archive_id": archive.id,
  379. "status": "pending",
  380. "position": 0,
  381. }
  382. defaults.update(kwargs)
  383. item = PrintQueueItem(**defaults)
  384. db_session.add(item)
  385. await db_session.commit()
  386. await db_session.refresh(item)
  387. return item
  388. return _create_item
  389. @pytest.mark.asyncio
  390. @pytest.mark.integration
  391. async def test_admin_can_delete_any_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  392. """Admin can delete any queue item."""
  393. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  394. response = await async_client.delete(
  395. f"/api/v1/queue/{item.id}",
  396. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  397. )
  398. assert response.status_code == 200
  399. @pytest.mark.asyncio
  400. @pytest.mark.integration
  401. async def test_operator_can_delete_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  402. """Operator can delete their own queue item."""
  403. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  404. response = await async_client.delete(
  405. f"/api/v1/queue/{item.id}",
  406. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  407. )
  408. assert response.status_code == 200
  409. @pytest.mark.asyncio
  410. @pytest.mark.integration
  411. async def test_operator_cannot_delete_others_queue_item(
  412. self, async_client: AsyncClient, auth_setup, queue_item_factory
  413. ):
  414. """Operator cannot delete another user's queue item."""
  415. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  416. response = await async_client.delete(
  417. f"/api/v1/queue/{item.id}",
  418. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  419. )
  420. assert response.status_code == 403
  421. @pytest.mark.asyncio
  422. @pytest.mark.integration
  423. async def test_operator_can_update_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  424. """Operator can update their own queue item."""
  425. item = await queue_item_factory(created_by_id=auth_setup["operator_user"]["id"])
  426. response = await async_client.patch(
  427. f"/api/v1/queue/{item.id}",
  428. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  429. json={"position": 10},
  430. )
  431. assert response.status_code == 200
  432. @pytest.mark.asyncio
  433. @pytest.mark.integration
  434. async def test_operator_cannot_update_others_queue_item(
  435. self, async_client: AsyncClient, auth_setup, queue_item_factory
  436. ):
  437. """Operator cannot update another user's queue item."""
  438. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  439. response = await async_client.patch(
  440. f"/api/v1/queue/{item.id}",
  441. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  442. json={"position": 10},
  443. )
  444. assert response.status_code == 403
  445. @pytest.mark.asyncio
  446. @pytest.mark.integration
  447. async def test_operator_cannot_cancel_others_queue_item(
  448. self, async_client: AsyncClient, auth_setup, queue_item_factory
  449. ):
  450. """Operator cannot cancel another user's queue item."""
  451. item = await queue_item_factory(created_by_id=auth_setup["operator2_user"]["id"])
  452. response = await async_client.post(
  453. f"/api/v1/queue/{item.id}/cancel",
  454. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  455. )
  456. assert response.status_code == 403
  457. @pytest.mark.asyncio
  458. @pytest.mark.integration
  459. async def test_bulk_update_skips_non_owned_items(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  460. """Bulk update only updates items the user owns."""
  461. # Create items owned by different users
  462. own_item = await queue_item_factory(
  463. created_by_id=auth_setup["operator_user"]["id"],
  464. )
  465. other_item = await queue_item_factory(
  466. created_by_id=auth_setup["operator2_user"]["id"],
  467. )
  468. response = await async_client.patch(
  469. "/api/v1/queue/bulk",
  470. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  471. json={
  472. "item_ids": [own_item.id, other_item.id],
  473. "manual_start": True,
  474. },
  475. )
  476. assert response.status_code == 200
  477. result = response.json()
  478. # Should only update the owned item
  479. assert result["updated_count"] == 1
  480. assert result["skipped_count"] == 1
  481. class TestLibraryOwnershipPermissions(TestOwnershipPermissionsSetup):
  482. """Tests for library file ownership-based permissions."""
  483. @pytest.fixture
  484. async def library_file_factory(self, db_session):
  485. """Factory to create test library files."""
  486. _counter = [0]
  487. async def _create_file(**kwargs):
  488. from backend.app.models.library import LibraryFile
  489. _counter[0] += 1
  490. defaults = {
  491. "filename": f"test_{_counter[0]}.3mf",
  492. "file_path": f"library/test_{_counter[0]}.3mf",
  493. "file_type": "3mf",
  494. "file_size": 1024,
  495. }
  496. defaults.update(kwargs)
  497. file = LibraryFile(**defaults)
  498. db_session.add(file)
  499. await db_session.commit()
  500. await db_session.refresh(file)
  501. return file
  502. return _create_file
  503. @pytest.fixture
  504. async def library_folder_factory(self, db_session):
  505. """Factory to create test library folders."""
  506. _counter = [0]
  507. async def _create_folder(**kwargs):
  508. from backend.app.models.library import LibraryFolder
  509. _counter[0] += 1
  510. defaults = {
  511. "name": f"TestFolder_{_counter[0]}",
  512. }
  513. defaults.update(kwargs)
  514. folder = LibraryFolder(**defaults)
  515. db_session.add(folder)
  516. await db_session.commit()
  517. await db_session.refresh(folder)
  518. return folder
  519. return _create_folder
  520. @pytest.mark.asyncio
  521. @pytest.mark.integration
  522. async def test_admin_can_delete_any_library_file(self, async_client: AsyncClient, auth_setup, library_file_factory):
  523. """Admin can delete any library file."""
  524. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  525. response = await async_client.delete(
  526. f"/api/v1/library/files/{file.id}",
  527. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  528. )
  529. assert response.status_code == 200
  530. @pytest.mark.asyncio
  531. @pytest.mark.integration
  532. async def test_operator_can_delete_own_library_file(
  533. self, async_client: AsyncClient, auth_setup, library_file_factory
  534. ):
  535. """Operator can delete their own library file."""
  536. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  537. response = await async_client.delete(
  538. f"/api/v1/library/files/{file.id}",
  539. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  540. )
  541. assert response.status_code == 200
  542. @pytest.mark.asyncio
  543. @pytest.mark.integration
  544. async def test_operator_cannot_delete_others_library_file(
  545. self, async_client: AsyncClient, auth_setup, library_file_factory
  546. ):
  547. """Operator cannot delete another user's library file."""
  548. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  549. response = await async_client.delete(
  550. f"/api/v1/library/files/{file.id}",
  551. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  552. )
  553. assert response.status_code == 403
  554. @pytest.mark.asyncio
  555. @pytest.mark.integration
  556. async def test_operator_can_update_own_library_file(
  557. self, async_client: AsyncClient, auth_setup, library_file_factory
  558. ):
  559. """Operator can update their own library file."""
  560. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  561. response = await async_client.put(
  562. f"/api/v1/library/files/{file.id}",
  563. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  564. json={"filename": "renamed.3mf"},
  565. )
  566. assert response.status_code == 200
  567. @pytest.mark.asyncio
  568. @pytest.mark.integration
  569. async def test_operator_cannot_update_others_library_file(
  570. self, async_client: AsyncClient, auth_setup, library_file_factory
  571. ):
  572. """Operator cannot update another user's library file."""
  573. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  574. response = await async_client.put(
  575. f"/api/v1/library/files/{file.id}",
  576. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  577. json={"filename": "renamed.3mf"},
  578. )
  579. assert response.status_code == 403
  580. @pytest.mark.asyncio
  581. @pytest.mark.integration
  582. async def test_folders_require_all_permission(self, async_client: AsyncClient, auth_setup, library_folder_factory):
  583. """Folders require *_all permission (no ownership tracking on folders)."""
  584. folder = await library_folder_factory(name="TestFolder")
  585. # Operator cannot delete folder (needs *_all)
  586. response = await async_client.delete(
  587. f"/api/v1/library/folders/{folder.id}",
  588. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  589. )
  590. assert response.status_code == 403
  591. @pytest.mark.asyncio
  592. @pytest.mark.integration
  593. async def test_bulk_delete_skips_non_owned_files(self, async_client: AsyncClient, auth_setup, library_file_factory):
  594. """Bulk delete only deletes files the user owns."""
  595. own_file = await library_file_factory(
  596. filename="own.3mf",
  597. created_by_id=auth_setup["operator_user"]["id"],
  598. )
  599. other_file = await library_file_factory(
  600. filename="other.3mf",
  601. created_by_id=auth_setup["operator2_user"]["id"],
  602. )
  603. response = await async_client.post(
  604. "/api/v1/library/bulk-delete",
  605. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  606. json={"file_ids": [own_file.id, other_file.id], "folder_ids": []},
  607. )
  608. assert response.status_code == 200
  609. result = response.json()
  610. # Should only delete the owned file; other_file is skipped (but skipped count not in response)
  611. assert result["deleted_files"] == 1
  612. class TestAuthDisabledPermissions:
  613. """Tests that verify all operations are allowed when auth is disabled."""
  614. @pytest.mark.asyncio
  615. @pytest.mark.integration
  616. async def test_delete_archive_without_auth(
  617. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  618. ):
  619. """When auth is disabled, anyone can delete archives."""
  620. printer = await printer_factory()
  621. archive = await archive_factory(printer.id)
  622. response = await async_client.delete(f"/api/v1/archives/{archive.id}")
  623. assert response.status_code == 200
  624. @pytest.mark.asyncio
  625. @pytest.mark.integration
  626. async def test_update_archive_without_auth(
  627. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  628. ):
  629. """When auth is disabled, anyone can update archives."""
  630. printer = await printer_factory()
  631. archive = await archive_factory(printer.id)
  632. response = await async_client.patch(
  633. f"/api/v1/archives/{archive.id}",
  634. json={"print_name": "Updated Name"},
  635. )
  636. assert response.status_code == 200
  637. class TestUserItemsCountAndDeletion(TestOwnershipPermissionsSetup):
  638. """Tests for user items count endpoint and deletion with items."""
  639. @pytest.mark.asyncio
  640. @pytest.mark.integration
  641. async def test_get_user_items_count(
  642. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  643. ):
  644. """Verify items count endpoint returns correct counts."""
  645. printer = await printer_factory()
  646. user_id = auth_setup["operator_user"]["id"]
  647. # Create some items for the operator
  648. await archive_factory(printer.id, created_by_id=user_id)
  649. await archive_factory(printer.id, created_by_id=user_id)
  650. response = await async_client.get(
  651. f"/api/v1/users/{user_id}/items-count",
  652. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  653. )
  654. assert response.status_code == 200
  655. counts = response.json()
  656. assert counts["archives"] >= 2
  657. assert "queue_items" in counts
  658. assert "library_files" in counts
  659. @pytest.mark.asyncio
  660. @pytest.mark.integration
  661. async def test_delete_user_keeps_items(
  662. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  663. ):
  664. """Verify deleting user without delete_items keeps items (ownerless)."""
  665. printer = await printer_factory()
  666. user_id = auth_setup["operator2_user"]["id"]
  667. # Create archive for operator2
  668. archive = await archive_factory(printer.id, created_by_id=user_id)
  669. archive_id = archive.id
  670. # Delete user without deleting items
  671. response = await async_client.delete(
  672. f"/api/v1/users/{user_id}?delete_items=false",
  673. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  674. )
  675. assert response.status_code == 204
  676. # Verify archive still exists but is now ownerless
  677. archive_response = await async_client.get(
  678. f"/api/v1/archives/{archive_id}",
  679. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  680. )
  681. assert archive_response.status_code == 200
  682. assert archive_response.json()["created_by_id"] is None
  683. @pytest.mark.asyncio
  684. @pytest.mark.integration
  685. async def test_delete_user_with_items(
  686. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  687. ):
  688. """Verify deleting user with delete_items=true removes their items."""
  689. printer = await printer_factory()
  690. # Create a new user with items
  691. create_response = await async_client.post(
  692. "/api/v1/users/",
  693. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  694. json={
  695. "username": "deletewithitems",
  696. "password": "Password123!",
  697. },
  698. )
  699. user_id = create_response.json()["id"]
  700. # Create archive for this user
  701. archive = await archive_factory(printer.id, created_by_id=user_id)
  702. archive_id = archive.id
  703. # Delete user WITH deleting items
  704. response = await async_client.delete(
  705. f"/api/v1/users/{user_id}?delete_items=true",
  706. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  707. )
  708. assert response.status_code == 204
  709. # Verify archive was deleted
  710. archive_response = await async_client.get(
  711. f"/api/v1/archives/{archive_id}",
  712. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  713. )
  714. assert archive_response.status_code == 404
  715. class TestReadIDORClosure(TestOwnershipPermissionsSetup):
  716. """Regression tests pinning maziggy/bambuddy-security #2 — IDOR on
  717. archives / library / queue read paths.
  718. Before the fix, ARCHIVES_READ / LIBRARY_READ / QUEUE_READ were flat
  719. "see everything" permissions even though the write side was split into
  720. OWN/ALL. An operator with only ARCHIVES_READ could read, download, and
  721. queue any user's archive via direct id reference. These tests pin the
  722. bambuddy_archive_idor.py and bambuddy_archive_viewer_idor.py PoC paths
  723. so the IDOR can't regress silently.
  724. """
  725. @pytest.mark.asyncio
  726. @pytest.mark.integration
  727. async def test_operator_get_others_archive_returns_404_not_200(
  728. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  729. ):
  730. """PoC #2 read path. operator1 GET /archives/{id} where id is admin's
  731. archive must NOT leak the row. 404 (not 403) so the operator can't
  732. enumerate which ids exist — same shape as a nonexistent id."""
  733. printer = await printer_factory()
  734. archive = await archive_factory(
  735. printer.id,
  736. print_name="Admin Archive",
  737. created_by_id=auth_setup["admin_user"]["id"],
  738. )
  739. response = await async_client.get(
  740. f"/api/v1/archives/{archive.id}",
  741. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  742. )
  743. assert response.status_code == 404
  744. @pytest.mark.asyncio
  745. @pytest.mark.integration
  746. async def test_operator_download_others_archive_returns_404(
  747. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  748. ):
  749. """Viewer-IDOR PoC path: GET /archives/{id}/download on admin's archive.
  750. Before the fix this streamed the 3MF body straight to a viewer-tier
  751. token."""
  752. printer = await printer_factory()
  753. archive = await archive_factory(
  754. printer.id,
  755. print_name="Admin Archive 2",
  756. created_by_id=auth_setup["admin_user"]["id"],
  757. )
  758. response = await async_client.get(
  759. f"/api/v1/archives/{archive.id}/download",
  760. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  761. )
  762. assert response.status_code == 404
  763. @pytest.mark.asyncio
  764. @pytest.mark.integration
  765. async def test_operator_list_archives_excludes_others(
  766. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  767. ):
  768. """GET /archives/ must filter to own archives only for OWN-level callers."""
  769. printer = await printer_factory()
  770. own = await archive_factory(
  771. printer.id, print_name="Operator's Own", created_by_id=auth_setup["operator_user"]["id"]
  772. )
  773. others = await archive_factory(printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"])
  774. response = await async_client.get(
  775. "/api/v1/archives/",
  776. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  777. )
  778. assert response.status_code == 200
  779. returned_ids = {a["id"] for a in response.json()}
  780. assert own.id in returned_ids
  781. assert others.id not in returned_ids
  782. @pytest.mark.asyncio
  783. @pytest.mark.integration
  784. async def test_admin_list_archives_includes_all(
  785. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  786. ):
  787. """ARCHIVES_READ_ALL → admin sees own + every user's archives."""
  788. printer = await printer_factory()
  789. admin_archive = await archive_factory(
  790. printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"]
  791. )
  792. operator_archive = await archive_factory(
  793. printer.id, print_name="Operator's", created_by_id=auth_setup["operator_user"]["id"]
  794. )
  795. response = await async_client.get(
  796. "/api/v1/archives/",
  797. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  798. )
  799. assert response.status_code == 200
  800. returned_ids = {a["id"] for a in response.json()}
  801. assert admin_archive.id in returned_ids
  802. assert operator_archive.id in returned_ids
  803. @pytest.mark.asyncio
  804. @pytest.mark.integration
  805. async def test_operator_cannot_queue_others_archive(
  806. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  807. ):
  808. """PoC #2 queue path. POST /queue/ with admin's archive_id as
  809. operator1 must return 404, not create a queue item. Before the fix
  810. this returned 201 and queued the admin archive (Landon's CONFIRMED
  811. line in the PoC)."""
  812. printer = await printer_factory()
  813. archive = await archive_factory(
  814. printer.id,
  815. print_name="Admin Archive (queue-target)",
  816. created_by_id=auth_setup["admin_user"]["id"],
  817. )
  818. response = await async_client.post(
  819. "/api/v1/queue/",
  820. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  821. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  822. )
  823. assert response.status_code == 404
  824. @pytest.mark.asyncio
  825. @pytest.mark.integration
  826. async def test_admin_can_queue_others_archive(
  827. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  828. ):
  829. """Belt-and-suspenders for the ALL path: admin (ARCHIVES_READ_ALL) can
  830. queue a user's archive on their behalf — common workshop pattern."""
  831. printer = await printer_factory()
  832. archive = await archive_factory(
  833. printer.id,
  834. print_name="Operator's archive (queue by admin)",
  835. created_by_id=auth_setup["operator_user"]["id"],
  836. )
  837. response = await async_client.post(
  838. "/api/v1/queue/",
  839. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  840. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  841. )
  842. assert response.status_code == 200
  843. @pytest.mark.asyncio
  844. @pytest.mark.integration
  845. async def test_operator_get_others_library_file_returns_404(
  846. self, async_client: AsyncClient, auth_setup, db_session
  847. ):
  848. """Library IDOR closure (same shape as archives — closed in the same PR
  849. per maziggy/bambuddy-security #2)."""
  850. from backend.app.models.library import LibraryFile
  851. admin_file = LibraryFile(
  852. filename="admin_secret.3mf",
  853. file_path="library/admin_secret.3mf",
  854. file_type="3mf",
  855. file_size=2048,
  856. created_by_id=auth_setup["admin_user"]["id"],
  857. )
  858. db_session.add(admin_file)
  859. await db_session.commit()
  860. await db_session.refresh(admin_file)
  861. response = await async_client.get(
  862. f"/api/v1/library/files/{admin_file.id}",
  863. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  864. )
  865. assert response.status_code == 404
  866. @pytest.mark.asyncio
  867. @pytest.mark.integration
  868. async def test_operator_list_library_files_excludes_others(self, async_client: AsyncClient, auth_setup, db_session):
  869. from backend.app.models.library import LibraryFile
  870. own = LibraryFile(
  871. filename="my_file.3mf",
  872. file_path="library/my_file.3mf",
  873. file_type="3mf",
  874. file_size=1024,
  875. created_by_id=auth_setup["operator_user"]["id"],
  876. )
  877. others = LibraryFile(
  878. filename="admin_file.3mf",
  879. file_path="library/admin_file.3mf",
  880. file_type="3mf",
  881. file_size=1024,
  882. created_by_id=auth_setup["admin_user"]["id"],
  883. )
  884. db_session.add_all([own, others])
  885. await db_session.commit()
  886. await db_session.refresh(own)
  887. await db_session.refresh(others)
  888. response = await async_client.get(
  889. "/api/v1/library/files",
  890. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  891. )
  892. assert response.status_code == 200
  893. returned_ids = {f["id"] for f in response.json()}
  894. assert own.id in returned_ids
  895. assert others.id not in returned_ids
  896. @pytest.mark.asyncio
  897. @pytest.mark.integration
  898. async def test_operator_queue_list_excludes_others_items(
  899. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  900. ):
  901. """GET /queue/ must filter to own queue items only for OWN callers —
  902. same shape as the archive list."""
  903. from backend.app.models.print_queue import PrintQueueItem
  904. printer = await printer_factory()
  905. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["operator_user"]["id"])
  906. own_item = PrintQueueItem(
  907. archive_id=archive.id,
  908. printer_id=printer.id,
  909. status="pending",
  910. position=1,
  911. created_by_id=auth_setup["operator_user"]["id"],
  912. )
  913. admin_item = PrintQueueItem(
  914. archive_id=archive.id,
  915. printer_id=printer.id,
  916. status="pending",
  917. position=2,
  918. created_by_id=auth_setup["admin_user"]["id"],
  919. )
  920. db_session.add_all([own_item, admin_item])
  921. await db_session.commit()
  922. await db_session.refresh(own_item)
  923. await db_session.refresh(admin_item)
  924. response = await async_client.get(
  925. "/api/v1/queue/",
  926. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  927. )
  928. assert response.status_code == 200
  929. returned_ids = {q["id"] for q in response.json()}
  930. assert own_item.id in returned_ids
  931. assert admin_item.id not in returned_ids
  932. @pytest.mark.asyncio
  933. @pytest.mark.integration
  934. async def test_operator_get_others_queue_item_returns_404(
  935. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  936. ):
  937. """Direct-id queue item access — same enumeration risk as archive get."""
  938. from backend.app.models.print_queue import PrintQueueItem
  939. printer = await printer_factory()
  940. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["admin_user"]["id"])
  941. admin_item = PrintQueueItem(
  942. archive_id=archive.id,
  943. printer_id=printer.id,
  944. status="pending",
  945. position=1,
  946. created_by_id=auth_setup["admin_user"]["id"],
  947. )
  948. db_session.add(admin_item)
  949. await db_session.commit()
  950. await db_session.refresh(admin_item)
  951. response = await async_client.get(
  952. f"/api/v1/queue/{admin_item.id}",
  953. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  954. )
  955. assert response.status_code == 404
  956. @pytest.mark.asyncio
  957. @pytest.mark.integration
  958. async def test_auth_disabled_preserves_single_tenant_read_all(
  959. self, async_client: AsyncClient, archive_factory, printer_factory
  960. ):
  961. """With auth disabled, ARCHIVES_READ resolves to read-all (can_modify_all=True
  962. in require_ownership_permission's auth-disabled branch). Existing
  963. single-user installs see no behavior change."""
  964. printer = await printer_factory()
  965. archive = await archive_factory(printer.id, print_name="Anonymous", created_by_id=None)
  966. # No Authorization header — auth-disabled mode.
  967. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  968. # Either 200 (auth disabled in this test session) or 401 (auth enabled
  969. # from a prior test) — both are acceptable; the IDOR closure does not
  970. # change auth-enable/disable behavior. Pin not-404 to avoid masking a
  971. # regression where auth-disabled callers would lose access.
  972. assert response.status_code in (200, 401)