test_ownership_permissions.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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. # ========================================================================
  458. # Start / Stop ownership gates (#1625-followup)
  459. # ========================================================================
  460. # Pre-fix /stop required QUEUE_UPDATE_ALL (admin-only) — operators saw the
  461. # Stop button in the queue UI but got 403 on click. /start required
  462. # QUEUE_UPDATE_OWN with no ownership check — operators could start anyone's
  463. # queue items via direct API. Both now use require_ownership_permission.
  464. @pytest.mark.asyncio
  465. @pytest.mark.integration
  466. async def test_operator_can_start_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  467. """Operator can start their own staged queue item."""
  468. item = await queue_item_factory(
  469. created_by_id=auth_setup["operator_user"]["id"],
  470. manual_start=True,
  471. )
  472. response = await async_client.post(
  473. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  474. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  475. )
  476. assert response.status_code == 200
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_operator_cannot_start_others_queue_item(
  480. self, async_client: AsyncClient, auth_setup, queue_item_factory
  481. ):
  482. """Operator cannot start another user's queue item."""
  483. item = await queue_item_factory(
  484. created_by_id=auth_setup["operator2_user"]["id"],
  485. manual_start=True,
  486. )
  487. response = await async_client.post(
  488. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  489. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  490. )
  491. assert response.status_code == 403
  492. @pytest.mark.asyncio
  493. @pytest.mark.integration
  494. async def test_operator_can_start_unowned_queue_item(
  495. self, async_client: AsyncClient, auth_setup, queue_item_factory, db_session
  496. ):
  497. """Operator can start a NULL-owner queue item (VP-uploaded, #1670)
  498. and claims ownership in the process.
  499. Stop and Cancel reject unowned items for _OWN holders (destructive,
  500. no "I own it" claim available), but Start is the entry point for the
  501. VP-import flow where attribution happens at click-time.
  502. """
  503. from backend.app.models.print_queue import PrintQueueItem
  504. item = await queue_item_factory(created_by_id=None, manual_start=True)
  505. response = await async_client.post(
  506. f"/api/v1/queue/{item.id}/start?skip_filament_check=true",
  507. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  508. )
  509. assert response.status_code == 200
  510. # Ownership claimed: operator is now the item's owner.
  511. await db_session.refresh(item)
  512. refetch = await db_session.get(PrintQueueItem, item.id)
  513. assert refetch.created_by_id == auth_setup["operator_user"]["id"]
  514. @pytest.mark.asyncio
  515. @pytest.mark.integration
  516. async def test_operator_can_stop_own_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  517. """Operator can stop their own currently-printing queue item."""
  518. item = await queue_item_factory(
  519. created_by_id=auth_setup["operator_user"]["id"],
  520. status="printing",
  521. )
  522. response = await async_client.post(
  523. f"/api/v1/queue/{item.id}/stop",
  524. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  525. )
  526. assert response.status_code == 200
  527. @pytest.mark.asyncio
  528. @pytest.mark.integration
  529. async def test_operator_cannot_stop_others_queue_item(
  530. self, async_client: AsyncClient, auth_setup, queue_item_factory
  531. ):
  532. """Operator cannot stop another user's printing queue item."""
  533. item = await queue_item_factory(
  534. created_by_id=auth_setup["operator2_user"]["id"],
  535. status="printing",
  536. )
  537. response = await async_client.post(
  538. f"/api/v1/queue/{item.id}/stop",
  539. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  540. )
  541. assert response.status_code == 403
  542. @pytest.mark.asyncio
  543. @pytest.mark.integration
  544. async def test_operator_cannot_stop_unowned_queue_item(
  545. self, async_client: AsyncClient, auth_setup, queue_item_factory
  546. ):
  547. """Operator cannot stop a NULL-owner printing queue item — stop mirrors
  548. cancel (destructive, no claim semantics). Admins with _ALL can still stop it.
  549. """
  550. item = await queue_item_factory(created_by_id=None, status="printing")
  551. response = await async_client.post(
  552. f"/api/v1/queue/{item.id}/stop",
  553. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  554. )
  555. assert response.status_code == 403
  556. @pytest.mark.asyncio
  557. @pytest.mark.integration
  558. async def test_admin_can_stop_any_queue_item(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  559. """Admin with _ALL can stop any printing queue item including unowned."""
  560. item = await queue_item_factory(created_by_id=None, status="printing")
  561. response = await async_client.post(
  562. f"/api/v1/queue/{item.id}/stop",
  563. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  564. )
  565. assert response.status_code == 200
  566. @pytest.mark.asyncio
  567. @pytest.mark.integration
  568. async def test_bulk_update_skips_non_owned_items(self, async_client: AsyncClient, auth_setup, queue_item_factory):
  569. """Bulk update only updates items the user owns."""
  570. # Create items owned by different users
  571. own_item = await queue_item_factory(
  572. created_by_id=auth_setup["operator_user"]["id"],
  573. )
  574. other_item = await queue_item_factory(
  575. created_by_id=auth_setup["operator2_user"]["id"],
  576. )
  577. response = await async_client.patch(
  578. "/api/v1/queue/bulk",
  579. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  580. json={
  581. "item_ids": [own_item.id, other_item.id],
  582. "manual_start": True,
  583. },
  584. )
  585. assert response.status_code == 200
  586. result = response.json()
  587. # Should only update the owned item
  588. assert result["updated_count"] == 1
  589. assert result["skipped_count"] == 1
  590. class TestLibraryOwnershipPermissions(TestOwnershipPermissionsSetup):
  591. """Tests for library file ownership-based permissions."""
  592. @pytest.fixture
  593. async def library_file_factory(self, db_session):
  594. """Factory to create test library files."""
  595. _counter = [0]
  596. async def _create_file(**kwargs):
  597. from backend.app.models.library import LibraryFile
  598. _counter[0] += 1
  599. defaults = {
  600. "filename": f"test_{_counter[0]}.3mf",
  601. "file_path": f"library/test_{_counter[0]}.3mf",
  602. "file_type": "3mf",
  603. "file_size": 1024,
  604. }
  605. defaults.update(kwargs)
  606. file = LibraryFile(**defaults)
  607. db_session.add(file)
  608. await db_session.commit()
  609. await db_session.refresh(file)
  610. return file
  611. return _create_file
  612. @pytest.fixture
  613. async def library_folder_factory(self, db_session):
  614. """Factory to create test library folders."""
  615. _counter = [0]
  616. async def _create_folder(**kwargs):
  617. from backend.app.models.library import LibraryFolder
  618. _counter[0] += 1
  619. defaults = {
  620. "name": f"TestFolder_{_counter[0]}",
  621. }
  622. defaults.update(kwargs)
  623. folder = LibraryFolder(**defaults)
  624. db_session.add(folder)
  625. await db_session.commit()
  626. await db_session.refresh(folder)
  627. return folder
  628. return _create_folder
  629. @pytest.mark.asyncio
  630. @pytest.mark.integration
  631. async def test_admin_can_delete_any_library_file(self, async_client: AsyncClient, auth_setup, library_file_factory):
  632. """Admin can delete any library file."""
  633. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  634. response = await async_client.delete(
  635. f"/api/v1/library/files/{file.id}",
  636. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  637. )
  638. assert response.status_code == 200
  639. @pytest.mark.asyncio
  640. @pytest.mark.integration
  641. async def test_operator_can_delete_own_library_file(
  642. self, async_client: AsyncClient, auth_setup, library_file_factory
  643. ):
  644. """Operator can delete their own library file."""
  645. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  646. response = await async_client.delete(
  647. f"/api/v1/library/files/{file.id}",
  648. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  649. )
  650. assert response.status_code == 200
  651. @pytest.mark.asyncio
  652. @pytest.mark.integration
  653. async def test_operator_cannot_delete_others_library_file(
  654. self, async_client: AsyncClient, auth_setup, library_file_factory
  655. ):
  656. """Operator cannot delete another user's library file."""
  657. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  658. response = await async_client.delete(
  659. f"/api/v1/library/files/{file.id}",
  660. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  661. )
  662. assert response.status_code == 403
  663. @pytest.mark.asyncio
  664. @pytest.mark.integration
  665. async def test_operator_can_update_own_library_file(
  666. self, async_client: AsyncClient, auth_setup, library_file_factory
  667. ):
  668. """Operator can update their own library file."""
  669. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  670. response = await async_client.put(
  671. f"/api/v1/library/files/{file.id}",
  672. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  673. json={"filename": "renamed.3mf"},
  674. )
  675. assert response.status_code == 200
  676. @pytest.mark.asyncio
  677. @pytest.mark.integration
  678. async def test_operator_cannot_update_others_library_file(
  679. self, async_client: AsyncClient, auth_setup, library_file_factory
  680. ):
  681. """Operator cannot update another user's library file."""
  682. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  683. response = await async_client.put(
  684. f"/api/v1/library/files/{file.id}",
  685. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  686. json={"filename": "renamed.3mf"},
  687. )
  688. assert response.status_code == 403
  689. # ========================================================================
  690. # Folder deletion (#1781): folders have no ownership tracking, so users
  691. # with only library:delete_own may delete empty, non-external, non-linked
  692. # folders. Everything else still requires library:delete_all.
  693. # ========================================================================
  694. @pytest.mark.asyncio
  695. @pytest.mark.integration
  696. async def test_operator_can_delete_empty_folder(
  697. self, async_client: AsyncClient, auth_setup, library_folder_factory
  698. ):
  699. """A user with library:delete_own can delete an empty folder (#1781)."""
  700. folder = await library_folder_factory(name="EmptyFolder")
  701. response = await async_client.delete(
  702. f"/api/v1/library/folders/{folder.id}",
  703. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  704. )
  705. assert response.status_code == 200
  706. @pytest.mark.asyncio
  707. @pytest.mark.integration
  708. async def test_viewer_cannot_delete_empty_folder(
  709. self, async_client: AsyncClient, auth_setup, library_folder_factory
  710. ):
  711. """No delete permission at all still means no folder deletion."""
  712. folder = await library_folder_factory(name="EmptyFolder")
  713. response = await async_client.delete(
  714. f"/api/v1/library/folders/{folder.id}",
  715. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  716. )
  717. assert response.status_code == 403
  718. @pytest.mark.asyncio
  719. @pytest.mark.integration
  720. async def test_operator_cannot_delete_folder_with_files(
  721. self, async_client: AsyncClient, auth_setup, library_folder_factory, library_file_factory
  722. ):
  723. """Non-empty folders still require library:delete_all."""
  724. folder = await library_folder_factory(name="FullFolder")
  725. await library_file_factory(folder_id=folder.id, created_by_id=auth_setup["operator_user"]["id"])
  726. response = await async_client.delete(
  727. f"/api/v1/library/folders/{folder.id}",
  728. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  729. )
  730. assert response.status_code == 403
  731. @pytest.mark.asyncio
  732. @pytest.mark.integration
  733. async def test_operator_cannot_delete_folder_with_trashed_file(
  734. self, async_client: AsyncClient, auth_setup, library_folder_factory, library_file_factory
  735. ):
  736. """Trashed files count as content: cascade would hard-drop them and
  737. silently break trash restore for their owner."""
  738. from datetime import datetime, timezone
  739. folder = await library_folder_factory(name="TrashedContentFolder")
  740. await library_file_factory(
  741. folder_id=folder.id,
  742. created_by_id=auth_setup["operator2_user"]["id"],
  743. deleted_at=datetime.now(timezone.utc),
  744. )
  745. response = await async_client.delete(
  746. f"/api/v1/library/folders/{folder.id}",
  747. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  748. )
  749. assert response.status_code == 403
  750. @pytest.mark.asyncio
  751. @pytest.mark.integration
  752. async def test_operator_cannot_delete_folder_with_subfolder(
  753. self, async_client: AsyncClient, auth_setup, library_folder_factory
  754. ):
  755. """A folder containing subfolders (even empty ones) is not empty."""
  756. parent = await library_folder_factory(name="ParentFolder")
  757. await library_folder_factory(name="ChildFolder", parent_id=parent.id)
  758. response = await async_client.delete(
  759. f"/api/v1/library/folders/{parent.id}",
  760. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  761. )
  762. assert response.status_code == 403
  763. @pytest.mark.asyncio
  764. @pytest.mark.integration
  765. async def test_operator_cannot_delete_external_folder(
  766. self, async_client: AsyncClient, auth_setup, library_folder_factory
  767. ):
  768. """Deleting an external folder unmounts an operator-configured mount
  769. for everyone — stays behind library:delete_all even when empty."""
  770. folder = await library_folder_factory(name="ExternalFolder", is_external=True, external_path="/mnt/models")
  771. response = await async_client.delete(
  772. f"/api/v1/library/folders/{folder.id}",
  773. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  774. )
  775. assert response.status_code == 403
  776. @pytest.mark.asyncio
  777. @pytest.mark.integration
  778. async def test_operator_cannot_delete_linked_folder(
  779. self, async_client: AsyncClient, auth_setup, library_folder_factory, db_session
  780. ):
  781. """Project/archive links are created via update_all, so unlinking by
  782. deletion stays admin-only even for empty folders."""
  783. from backend.app.models.project import Project
  784. project = Project(name="LinkTestProject")
  785. db_session.add(project)
  786. await db_session.commit()
  787. await db_session.refresh(project)
  788. folder = await library_folder_factory(name="LinkedFolder", project_id=project.id)
  789. response = await async_client.delete(
  790. f"/api/v1/library/folders/{folder.id}",
  791. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  792. )
  793. assert response.status_code == 403
  794. @pytest.mark.asyncio
  795. @pytest.mark.integration
  796. async def test_admin_can_delete_folder_with_contents(
  797. self, async_client: AsyncClient, auth_setup, library_folder_factory, library_file_factory
  798. ):
  799. """library:delete_all keeps full cascade deletion."""
  800. folder = await library_folder_factory(name="AdminFolder")
  801. await library_file_factory(folder_id=folder.id, created_by_id=auth_setup["operator_user"]["id"])
  802. response = await async_client.delete(
  803. f"/api/v1/library/folders/{folder.id}",
  804. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  805. )
  806. assert response.status_code == 200
  807. @pytest.mark.asyncio
  808. @pytest.mark.integration
  809. async def test_bulk_delete_operator_folders_empty_only(
  810. self, async_client: AsyncClient, auth_setup, library_folder_factory, library_file_factory
  811. ):
  812. """Bulk delete applies the same rule: empty folders go, non-empty are skipped."""
  813. empty_folder = await library_folder_factory(name="BulkEmpty")
  814. full_folder = await library_folder_factory(name="BulkFull")
  815. await library_file_factory(folder_id=full_folder.id, created_by_id=auth_setup["operator2_user"]["id"])
  816. response = await async_client.post(
  817. "/api/v1/library/bulk-delete",
  818. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  819. json={"file_ids": [], "folder_ids": [empty_folder.id, full_folder.id]},
  820. )
  821. assert response.status_code == 200
  822. result = response.json()
  823. assert result["deleted_folders"] == 1
  824. assert result["deleted_files"] == 0
  825. @pytest.mark.asyncio
  826. @pytest.mark.integration
  827. async def test_bulk_delete_skips_non_owned_files(self, async_client: AsyncClient, auth_setup, library_file_factory):
  828. """Bulk delete only deletes files the user owns."""
  829. own_file = await library_file_factory(
  830. filename="own.3mf",
  831. created_by_id=auth_setup["operator_user"]["id"],
  832. )
  833. other_file = await library_file_factory(
  834. filename="other.3mf",
  835. created_by_id=auth_setup["operator2_user"]["id"],
  836. )
  837. response = await async_client.post(
  838. "/api/v1/library/bulk-delete",
  839. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  840. json={"file_ids": [own_file.id, other_file.id], "folder_ids": []},
  841. )
  842. assert response.status_code == 200
  843. result = response.json()
  844. # Should only delete the owned file; other_file is skipped (but skipped count not in response)
  845. assert result["deleted_files"] == 1
  846. class TestAuthDisabledPermissions:
  847. """Tests that verify all operations are allowed when auth is disabled."""
  848. @pytest.mark.asyncio
  849. @pytest.mark.integration
  850. async def test_delete_archive_without_auth(
  851. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  852. ):
  853. """When auth is disabled, anyone can delete archives."""
  854. printer = await printer_factory()
  855. archive = await archive_factory(printer.id)
  856. response = await async_client.delete(f"/api/v1/archives/{archive.id}")
  857. assert response.status_code == 200
  858. @pytest.mark.asyncio
  859. @pytest.mark.integration
  860. async def test_update_archive_without_auth(
  861. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  862. ):
  863. """When auth is disabled, anyone can update archives."""
  864. printer = await printer_factory()
  865. archive = await archive_factory(printer.id)
  866. response = await async_client.patch(
  867. f"/api/v1/archives/{archive.id}",
  868. json={"print_name": "Updated Name"},
  869. )
  870. assert response.status_code == 200
  871. class TestUserItemsCountAndDeletion(TestOwnershipPermissionsSetup):
  872. """Tests for user items count endpoint and deletion with items."""
  873. @pytest.mark.asyncio
  874. @pytest.mark.integration
  875. async def test_get_user_items_count(
  876. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  877. ):
  878. """Verify items count endpoint returns correct counts."""
  879. printer = await printer_factory()
  880. user_id = auth_setup["operator_user"]["id"]
  881. # Create some items for the operator
  882. await archive_factory(printer.id, created_by_id=user_id)
  883. await archive_factory(printer.id, created_by_id=user_id)
  884. response = await async_client.get(
  885. f"/api/v1/users/{user_id}/items-count",
  886. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  887. )
  888. assert response.status_code == 200
  889. counts = response.json()
  890. assert counts["archives"] >= 2
  891. assert "queue_items" in counts
  892. assert "library_files" in counts
  893. @pytest.mark.asyncio
  894. @pytest.mark.integration
  895. async def test_delete_user_keeps_items(
  896. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  897. ):
  898. """Verify deleting user without delete_items keeps items (ownerless)."""
  899. printer = await printer_factory()
  900. user_id = auth_setup["operator2_user"]["id"]
  901. # Create archive for operator2
  902. archive = await archive_factory(printer.id, created_by_id=user_id)
  903. archive_id = archive.id
  904. # Delete user without deleting items
  905. response = await async_client.delete(
  906. f"/api/v1/users/{user_id}?delete_items=false",
  907. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  908. )
  909. assert response.status_code == 204
  910. # Verify archive still exists but is now ownerless
  911. archive_response = await async_client.get(
  912. f"/api/v1/archives/{archive_id}",
  913. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  914. )
  915. assert archive_response.status_code == 200
  916. assert archive_response.json()["created_by_id"] is None
  917. @pytest.mark.asyncio
  918. @pytest.mark.integration
  919. async def test_delete_user_with_items(
  920. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  921. ):
  922. """Verify deleting user with delete_items=true removes their items."""
  923. printer = await printer_factory()
  924. # Create a new user with items
  925. create_response = await async_client.post(
  926. "/api/v1/users/",
  927. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  928. json={
  929. "username": "deletewithitems",
  930. "password": "Password123!",
  931. },
  932. )
  933. user_id = create_response.json()["id"]
  934. # Create archive for this user
  935. archive = await archive_factory(printer.id, created_by_id=user_id)
  936. archive_id = archive.id
  937. # Delete user WITH deleting items
  938. response = await async_client.delete(
  939. f"/api/v1/users/{user_id}?delete_items=true",
  940. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  941. )
  942. assert response.status_code == 204
  943. # Verify archive was deleted
  944. archive_response = await async_client.get(
  945. f"/api/v1/archives/{archive_id}",
  946. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  947. )
  948. assert archive_response.status_code == 404
  949. class TestReadIDORClosure(TestOwnershipPermissionsSetup):
  950. """Regression tests pinning maziggy/bambuddy-security #2 — IDOR on
  951. archives / library / queue read paths.
  952. Before the fix, ARCHIVES_READ / LIBRARY_READ / QUEUE_READ were flat
  953. "see everything" permissions even though the write side was split into
  954. OWN/ALL. An operator with only ARCHIVES_READ could read, download, and
  955. queue any user's archive via direct id reference. These tests pin the
  956. bambuddy_archive_idor.py and bambuddy_archive_viewer_idor.py PoC paths
  957. so the IDOR can't regress silently.
  958. """
  959. @pytest.mark.asyncio
  960. @pytest.mark.integration
  961. async def test_operator_get_others_archive_returns_404_not_200(
  962. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  963. ):
  964. """PoC #2 read path. operator1 GET /archives/{id} where id is admin's
  965. archive must NOT leak the row. 404 (not 403) so the operator can't
  966. enumerate which ids exist — same shape as a nonexistent id."""
  967. printer = await printer_factory()
  968. archive = await archive_factory(
  969. printer.id,
  970. print_name="Admin Archive",
  971. created_by_id=auth_setup["admin_user"]["id"],
  972. )
  973. response = await async_client.get(
  974. f"/api/v1/archives/{archive.id}",
  975. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  976. )
  977. assert response.status_code == 404
  978. @pytest.mark.asyncio
  979. @pytest.mark.integration
  980. async def test_operator_download_others_archive_returns_404(
  981. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  982. ):
  983. """Viewer-IDOR PoC path: GET /archives/{id}/download on admin's archive.
  984. Before the fix this streamed the 3MF body straight to a viewer-tier
  985. token."""
  986. printer = await printer_factory()
  987. archive = await archive_factory(
  988. printer.id,
  989. print_name="Admin Archive 2",
  990. created_by_id=auth_setup["admin_user"]["id"],
  991. )
  992. response = await async_client.get(
  993. f"/api/v1/archives/{archive.id}/download",
  994. headers={"Authorization": f"Bearer {auth_setup['viewer_token']}"},
  995. )
  996. assert response.status_code == 404
  997. @pytest.mark.asyncio
  998. @pytest.mark.integration
  999. async def test_operator_list_archives_excludes_others(
  1000. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1001. ):
  1002. """GET /archives/ must filter to own archives only for OWN-level callers."""
  1003. printer = await printer_factory()
  1004. own = await archive_factory(
  1005. printer.id, print_name="Operator's Own", created_by_id=auth_setup["operator_user"]["id"]
  1006. )
  1007. others = await archive_factory(printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"])
  1008. response = await async_client.get(
  1009. "/api/v1/archives/",
  1010. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1011. )
  1012. assert response.status_code == 200
  1013. returned_ids = {a["id"] for a in response.json()}
  1014. assert own.id in returned_ids
  1015. assert others.id not in returned_ids
  1016. @pytest.mark.asyncio
  1017. @pytest.mark.integration
  1018. async def test_admin_list_archives_includes_all(
  1019. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1020. ):
  1021. """ARCHIVES_READ_ALL → admin sees own + every user's archives."""
  1022. printer = await printer_factory()
  1023. admin_archive = await archive_factory(
  1024. printer.id, print_name="Admin's", created_by_id=auth_setup["admin_user"]["id"]
  1025. )
  1026. operator_archive = await archive_factory(
  1027. printer.id, print_name="Operator's", created_by_id=auth_setup["operator_user"]["id"]
  1028. )
  1029. response = await async_client.get(
  1030. "/api/v1/archives/",
  1031. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1032. )
  1033. assert response.status_code == 200
  1034. returned_ids = {a["id"] for a in response.json()}
  1035. assert admin_archive.id in returned_ids
  1036. assert operator_archive.id in returned_ids
  1037. @pytest.mark.asyncio
  1038. @pytest.mark.integration
  1039. async def test_operator_cannot_queue_others_archive(
  1040. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1041. ):
  1042. """PoC #2 queue path. POST /queue/ with admin's archive_id as
  1043. operator1 must return 404, not create a queue item. Before the fix
  1044. this returned 201 and queued the admin archive (Landon's CONFIRMED
  1045. line in the PoC)."""
  1046. printer = await printer_factory()
  1047. archive = await archive_factory(
  1048. printer.id,
  1049. print_name="Admin Archive (queue-target)",
  1050. created_by_id=auth_setup["admin_user"]["id"],
  1051. )
  1052. response = await async_client.post(
  1053. "/api/v1/queue/",
  1054. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1055. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  1056. )
  1057. assert response.status_code == 404
  1058. @pytest.mark.asyncio
  1059. @pytest.mark.integration
  1060. async def test_admin_can_queue_others_archive(
  1061. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1062. ):
  1063. """Belt-and-suspenders for the ALL path: admin (ARCHIVES_READ_ALL) can
  1064. queue a user's archive on their behalf — common workshop pattern."""
  1065. printer = await printer_factory()
  1066. archive = await archive_factory(
  1067. printer.id,
  1068. print_name="Operator's archive (queue by admin)",
  1069. created_by_id=auth_setup["operator_user"]["id"],
  1070. )
  1071. response = await async_client.post(
  1072. "/api/v1/queue/",
  1073. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1074. json={"archive_id": archive.id, "printer_id": printer.id, "quantity": 1},
  1075. )
  1076. assert response.status_code == 200
  1077. @pytest.mark.asyncio
  1078. @pytest.mark.integration
  1079. async def test_operator_get_others_library_file_returns_404(
  1080. self, async_client: AsyncClient, auth_setup, db_session
  1081. ):
  1082. """Library IDOR closure (same shape as archives — closed in the same PR
  1083. per maziggy/bambuddy-security #2)."""
  1084. from backend.app.models.library import LibraryFile
  1085. admin_file = LibraryFile(
  1086. filename="admin_secret.3mf",
  1087. file_path="library/admin_secret.3mf",
  1088. file_type="3mf",
  1089. file_size=2048,
  1090. created_by_id=auth_setup["admin_user"]["id"],
  1091. )
  1092. db_session.add(admin_file)
  1093. await db_session.commit()
  1094. await db_session.refresh(admin_file)
  1095. response = await async_client.get(
  1096. f"/api/v1/library/files/{admin_file.id}",
  1097. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1098. )
  1099. assert response.status_code == 404
  1100. @pytest.mark.asyncio
  1101. @pytest.mark.integration
  1102. async def test_operator_list_library_files_excludes_others(self, async_client: AsyncClient, auth_setup, db_session):
  1103. from backend.app.models.library import LibraryFile
  1104. own = LibraryFile(
  1105. filename="my_file.3mf",
  1106. file_path="library/my_file.3mf",
  1107. file_type="3mf",
  1108. file_size=1024,
  1109. created_by_id=auth_setup["operator_user"]["id"],
  1110. )
  1111. others = LibraryFile(
  1112. filename="admin_file.3mf",
  1113. file_path="library/admin_file.3mf",
  1114. file_type="3mf",
  1115. file_size=1024,
  1116. created_by_id=auth_setup["admin_user"]["id"],
  1117. )
  1118. db_session.add_all([own, others])
  1119. await db_session.commit()
  1120. await db_session.refresh(own)
  1121. await db_session.refresh(others)
  1122. response = await async_client.get(
  1123. "/api/v1/library/files",
  1124. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1125. )
  1126. assert response.status_code == 200
  1127. returned_ids = {f["id"] for f in response.json()}
  1128. assert own.id in returned_ids
  1129. assert others.id not in returned_ids
  1130. @pytest.mark.asyncio
  1131. @pytest.mark.integration
  1132. async def test_operator_queue_list_excludes_others_items(
  1133. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1134. ):
  1135. """GET /queue/ must filter to own queue items only for OWN callers —
  1136. same shape as the archive list."""
  1137. from backend.app.models.print_queue import PrintQueueItem
  1138. printer = await printer_factory()
  1139. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["operator_user"]["id"])
  1140. own_item = PrintQueueItem(
  1141. archive_id=archive.id,
  1142. printer_id=printer.id,
  1143. status="pending",
  1144. position=1,
  1145. created_by_id=auth_setup["operator_user"]["id"],
  1146. )
  1147. admin_item = PrintQueueItem(
  1148. archive_id=archive.id,
  1149. printer_id=printer.id,
  1150. status="pending",
  1151. position=2,
  1152. created_by_id=auth_setup["admin_user"]["id"],
  1153. )
  1154. db_session.add_all([own_item, admin_item])
  1155. await db_session.commit()
  1156. await db_session.refresh(own_item)
  1157. await db_session.refresh(admin_item)
  1158. response = await async_client.get(
  1159. "/api/v1/queue/",
  1160. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1161. )
  1162. assert response.status_code == 200
  1163. returned_ids = {q["id"] for q in response.json()}
  1164. assert own_item.id in returned_ids
  1165. assert admin_item.id not in returned_ids
  1166. @pytest.mark.asyncio
  1167. @pytest.mark.integration
  1168. async def test_operator_get_others_queue_item_returns_404(
  1169. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1170. ):
  1171. """Direct-id queue item access — same enumeration risk as archive get."""
  1172. from backend.app.models.print_queue import PrintQueueItem
  1173. printer = await printer_factory()
  1174. archive = await archive_factory(printer.id, print_name="A", created_by_id=auth_setup["admin_user"]["id"])
  1175. admin_item = PrintQueueItem(
  1176. archive_id=archive.id,
  1177. printer_id=printer.id,
  1178. status="pending",
  1179. position=1,
  1180. created_by_id=auth_setup["admin_user"]["id"],
  1181. )
  1182. db_session.add(admin_item)
  1183. await db_session.commit()
  1184. await db_session.refresh(admin_item)
  1185. response = await async_client.get(
  1186. f"/api/v1/queue/{admin_item.id}",
  1187. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1188. )
  1189. assert response.status_code == 404
  1190. @pytest.mark.asyncio
  1191. @pytest.mark.integration
  1192. async def test_auth_disabled_preserves_single_tenant_read_all(
  1193. self, async_client: AsyncClient, archive_factory, printer_factory
  1194. ):
  1195. """With auth disabled, ARCHIVES_READ resolves to read-all (can_modify_all=True
  1196. in require_ownership_permission's auth-disabled branch). Existing
  1197. single-user installs see no behavior change."""
  1198. printer = await printer_factory()
  1199. archive = await archive_factory(printer.id, print_name="Anonymous", created_by_id=None)
  1200. # No Authorization header — auth-disabled mode.
  1201. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  1202. # Either 200 (auth disabled in this test session) or 401 (auth enabled
  1203. # from a prior test) — both are acceptable; the IDOR closure does not
  1204. # change auth-enable/disable behavior. Pin not-404 to avoid masking a
  1205. # regression where auth-disabled callers would lose access.
  1206. assert response.status_code in (200, 401)
  1207. # Every archive WRITE sub-resource route: (id, http method, path suffix, request kwargs).
  1208. # The ownership gate (_ensure_archive_visible) fires immediately after the fetch,
  1209. # before any resource-specific logic, so a not-owned / ownerless row 404s regardless
  1210. # of whether the timelapse / photo / source / f3d actually exists. Upload routes still
  1211. # need a body so FastAPI reaches the handler instead of 422-ing on the missing File(...).
  1212. _WRITE_SUBRESOURCE_ROUTES = [
  1213. ("favorite", "post", "/favorite", {}),
  1214. ("timelapse_delete", "delete", "/timelapse", {}),
  1215. ("photo_upload", "post", "/photos", {"files": {"file": ("x.jpg", b"\x89PNG\r\n\x1a\n", "image/jpeg")}}),
  1216. ("photo_delete", "delete", "/photos/nonexistent.jpg", {}),
  1217. ("project_page", "patch", "/project-page", {"json": {"title": "hijacked"}}),
  1218. ("source_upload", "post", "/source", {"files": {"file": ("x.3mf", b"PK\x03\x04", "application/octet-stream")}}),
  1219. ("source_delete", "delete", "/source", {}),
  1220. ("f3d_upload", "post", "/f3d", {"files": {"file": ("x.f3d", b"f3d-bytes", "application/octet-stream")}}),
  1221. ("f3d_delete", "delete", "/f3d", {}),
  1222. ]
  1223. class TestWriteSubResourceIDORClosure(TestOwnershipPermissionsSetup):
  1224. """Regression tests for the archive write SUB-RESOURCE IDOR.
  1225. The read sub-resource routes were closed under maziggy/bambuddy-security #2
  1226. via ``_ensure_archive_visible``, but the *write* sub-resource routes
  1227. (favorite, timelapse, photos, project-page, source, f3d) were left gating
  1228. on the bare ``RequirePermissionIfAuthEnabled(ARCHIVES_*_OWN)`` scope and
  1229. fetched the row by id only — never comparing ``created_by_id`` to the
  1230. caller. An operator holding only ``ARCHIVES_*_OWN`` (or an API key with
  1231. ``can_manage_archives``) could delete/overwrite files on ANY user's
  1232. archive, most severely rewriting the project-page metadata inside another
  1233. user's ``.3mf`` on disk. Each route is now gated by
  1234. ``require_ownership_permission`` + ``_ensure_archive_visible`` → 404 (not
  1235. 403, to stay non-enumerable and match the read side) on a not-owned or
  1236. ownerless row.
  1237. """
  1238. @pytest.mark.parametrize(
  1239. "name,method,suffix,kwargs",
  1240. _WRITE_SUBRESOURCE_ROUTES,
  1241. ids=[r[0] for r in _WRITE_SUBRESOURCE_ROUTES],
  1242. )
  1243. @pytest.mark.asyncio
  1244. @pytest.mark.integration
  1245. async def test_operator_cannot_write_others_archive_subresource(
  1246. self,
  1247. async_client: AsyncClient,
  1248. auth_setup,
  1249. archive_factory,
  1250. printer_factory,
  1251. db_session,
  1252. name,
  1253. method,
  1254. suffix,
  1255. kwargs,
  1256. ):
  1257. """SECURITY.md rule 4: right credentials, wrong ownership → 404.
  1258. operator1 (ARCHIVES_*_OWN) targeting a route on admin's archive.
  1259. """
  1260. printer = await printer_factory()
  1261. archive = await archive_factory(
  1262. printer.id,
  1263. print_name="Admin's Archive",
  1264. created_by_id=auth_setup["admin_user"]["id"],
  1265. )
  1266. response = await getattr(async_client, method)(
  1267. f"/api/v1/archives/{archive.id}{suffix}",
  1268. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1269. **kwargs,
  1270. )
  1271. assert response.status_code == 404, f"{name}: expected 404, got {response.status_code}"
  1272. @pytest.mark.parametrize(
  1273. "name,method,suffix,kwargs",
  1274. _WRITE_SUBRESOURCE_ROUTES,
  1275. ids=[r[0] for r in _WRITE_SUBRESOURCE_ROUTES],
  1276. )
  1277. @pytest.mark.asyncio
  1278. @pytest.mark.integration
  1279. async def test_operator_cannot_write_ownerless_archive_subresource(
  1280. self,
  1281. async_client: AsyncClient,
  1282. auth_setup,
  1283. archive_factory,
  1284. printer_factory,
  1285. db_session,
  1286. name,
  1287. method,
  1288. suffix,
  1289. kwargs,
  1290. ):
  1291. """Ownerless rows (created_by_id = null, legacy data) require *_ALL — an
  1292. operator with only *_OWN has no 'I own this' claim, so fail closed → 404."""
  1293. printer = await printer_factory()
  1294. archive = await archive_factory(
  1295. printer.id,
  1296. print_name="Ownerless Archive",
  1297. created_by_id=None,
  1298. )
  1299. response = await getattr(async_client, method)(
  1300. f"/api/v1/archives/{archive.id}{suffix}",
  1301. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1302. **kwargs,
  1303. )
  1304. assert response.status_code == 404, f"{name}: expected 404, got {response.status_code}"
  1305. @pytest.mark.asyncio
  1306. @pytest.mark.integration
  1307. async def test_operator_can_favorite_own_archive(
  1308. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1309. ):
  1310. """Positive control: the owner still gets through the new gate. Favorite
  1311. is the one write sub-resource that needs no pre-existing file, so it
  1312. cleanly proves the *_OWN happy path returns 200 (not a false 404)."""
  1313. printer = await printer_factory()
  1314. archive = await archive_factory(
  1315. printer.id,
  1316. print_name="Operator's Own",
  1317. created_by_id=auth_setup["operator_user"]["id"],
  1318. )
  1319. response = await async_client.post(
  1320. f"/api/v1/archives/{archive.id}/favorite",
  1321. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1322. )
  1323. assert response.status_code == 200
  1324. assert response.json()["is_favorite"] is True
  1325. @pytest.mark.asyncio
  1326. @pytest.mark.integration
  1327. async def test_admin_can_favorite_any_archive(
  1328. self, async_client: AsyncClient, auth_setup, archive_factory, printer_factory, db_session
  1329. ):
  1330. """Positive control for the *_ALL path: admin can act on a user's archive."""
  1331. printer = await printer_factory()
  1332. archive = await archive_factory(
  1333. printer.id,
  1334. print_name="Operator's Own",
  1335. created_by_id=auth_setup["operator_user"]["id"],
  1336. )
  1337. response = await async_client.post(
  1338. f"/api/v1/archives/{archive.id}/favorite",
  1339. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1340. )
  1341. assert response.status_code == 200
  1342. class TestSliceOwnershipPermissions(TestOwnershipPermissionsSetup):
  1343. """IDOR regression: slicing and slice-job polling must honour per-row ownership.
  1344. Before the fix, ``POST /library/files/{id}/slice`` and
  1345. ``POST /archives/{id}/slice`` gated only on ``LIBRARY_UPLOAD``, so a
  1346. READ_OWN operator could slice another user's model by raw id even though a
  1347. direct GET on that id returned 404 — the sliced output was then attributed
  1348. to and downloadable by the requester. ``GET /slice-jobs/{id}`` had no owner
  1349. scoping at all. ``POST /slicer-pipelines/{id}/run`` (and check-eligibility)
  1350. resolved the source by raw id with the same gap.
  1351. The slice route enforces the gate before touching the source bytes, so the
  1352. owner/READ_ALL "control" cases reach the later on-disk check (a distinct 404
  1353. detail) rather than a real slice — enough to prove the gate lets them past.
  1354. """
  1355. # Any preset triplet: the ownership 404 fires before preset resolution.
  1356. _SLICE_BODY = {"printer_preset_id": 1, "process_preset_id": 2, "filament_preset_id": 3}
  1357. @pytest.fixture
  1358. async def library_file_factory(self, db_session):
  1359. _counter = [0]
  1360. async def _create_file(**kwargs):
  1361. from backend.app.models.library import LibraryFile
  1362. _counter[0] += 1
  1363. defaults = {
  1364. "filename": f"slice_src_{_counter[0]}.3mf",
  1365. "file_path": f"library/slice_src_{_counter[0]}.3mf",
  1366. "file_type": "3mf",
  1367. "file_size": 1024,
  1368. }
  1369. defaults.update(kwargs)
  1370. row = LibraryFile(**defaults)
  1371. db_session.add(row)
  1372. await db_session.commit()
  1373. await db_session.refresh(row)
  1374. return row
  1375. return _create_file
  1376. # --- library file slice ------------------------------------------------
  1377. @pytest.mark.asyncio
  1378. @pytest.mark.integration
  1379. async def test_operator_cannot_slice_others_library_file(self, async_client, auth_setup, library_file_factory):
  1380. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1381. resp = await async_client.post(
  1382. f"/api/v1/library/files/{file.id}/slice",
  1383. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1384. json=self._SLICE_BODY,
  1385. )
  1386. assert resp.status_code == 404
  1387. # 404 (not 403) so a probing operator can't tell the id exists.
  1388. assert resp.json()["detail"] == "File not found"
  1389. @pytest.mark.asyncio
  1390. @pytest.mark.integration
  1391. async def test_operator_can_slice_own_library_file(self, async_client, auth_setup, library_file_factory):
  1392. file = await library_file_factory(created_by_id=auth_setup["operator_user"]["id"])
  1393. resp = await async_client.post(
  1394. f"/api/v1/library/files/{file.id}/slice",
  1395. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1396. json=self._SLICE_BODY,
  1397. )
  1398. # Past the ownership gate — only the on-disk source is missing in tests.
  1399. assert resp.status_code == 404
  1400. assert resp.json()["detail"] == "Source file missing on disk"
  1401. @pytest.mark.asyncio
  1402. @pytest.mark.integration
  1403. async def test_admin_can_slice_any_library_file(self, async_client, auth_setup, library_file_factory):
  1404. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1405. resp = await async_client.post(
  1406. f"/api/v1/library/files/{file.id}/slice",
  1407. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1408. json=self._SLICE_BODY,
  1409. )
  1410. # READ_ALL passes the gate even on another user's file.
  1411. assert resp.status_code == 404
  1412. assert resp.json()["detail"] == "Source file missing on disk"
  1413. # --- archive slice -----------------------------------------------------
  1414. @pytest.mark.asyncio
  1415. @pytest.mark.integration
  1416. async def test_operator_cannot_slice_others_archive(
  1417. self, async_client, auth_setup, archive_factory, printer_factory
  1418. ):
  1419. printer = await printer_factory()
  1420. archive = await archive_factory(printer.id, created_by_id=auth_setup["operator2_user"]["id"])
  1421. resp = await async_client.post(
  1422. f"/api/v1/archives/{archive.id}/slice",
  1423. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1424. json=self._SLICE_BODY,
  1425. )
  1426. assert resp.status_code == 404
  1427. assert resp.json()["detail"] == "Archive not found"
  1428. @pytest.mark.asyncio
  1429. @pytest.mark.integration
  1430. async def test_operator_can_slice_own_archive(self, async_client, auth_setup, archive_factory, printer_factory):
  1431. printer = await printer_factory()
  1432. archive = await archive_factory(printer.id, created_by_id=auth_setup["operator_user"]["id"])
  1433. resp = await async_client.post(
  1434. f"/api/v1/archives/{archive.id}/slice",
  1435. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1436. json=self._SLICE_BODY,
  1437. )
  1438. # Past the gate — the archive's source file isn't on disk in tests.
  1439. assert resp.status_code == 404
  1440. assert resp.json()["detail"] == "Archive source file missing on disk"
  1441. # --- slice-job polling -------------------------------------------------
  1442. @pytest.mark.asyncio
  1443. @pytest.mark.integration
  1444. async def test_slice_job_polling_is_owner_scoped(self, async_client, auth_setup):
  1445. from backend.app.services.slice_dispatch import slice_dispatch
  1446. async def _noop(_job_id):
  1447. return {}
  1448. job = await slice_dispatch.enqueue(
  1449. kind="library_file",
  1450. source_id=1,
  1451. source_name="secret_model.3mf",
  1452. owner_id=auth_setup["operator2_user"]["id"],
  1453. run=_noop,
  1454. )
  1455. # Non-owner without READ_ALL cannot see the job (404, not 403).
  1456. other = await async_client.get(
  1457. f"/api/v1/slice-jobs/{job.id}",
  1458. headers={"Authorization": f"Bearer {auth_setup['operator_token']}"},
  1459. )
  1460. assert other.status_code == 404
  1461. # The owner and a READ_ALL admin can.
  1462. owner = await async_client.get(
  1463. f"/api/v1/slice-jobs/{job.id}",
  1464. headers={"Authorization": f"Bearer {auth_setup['operator2_token']}"},
  1465. )
  1466. assert owner.status_code == 200
  1467. admin = await async_client.get(
  1468. f"/api/v1/slice-jobs/{job.id}",
  1469. headers={"Authorization": f"Bearer {auth_setup['admin_token']}"},
  1470. )
  1471. assert admin.status_code == 200
  1472. # --- pipeline source resolution ----------------------------------------
  1473. @pytest.mark.asyncio
  1474. @pytest.mark.integration
  1475. async def test_pipeline_run_cannot_reference_others_library_file(
  1476. self, async_client, auth_setup, library_file_factory, db_session
  1477. ):
  1478. """A pipeline runner with READ_OWN cannot resolve another user's source.
  1479. The built-in Operators group has no pipeline permissions, so this uses a
  1480. custom group carrying PIPELINES_RUN + READ_OWN — the realistic shape of
  1481. the exposure. check-eligibility resolves the source before any
  1482. eligibility work, so the ownership gate is what returns 404.
  1483. """
  1484. from backend.app.models.slicer_pipeline import SlicerPipeline
  1485. admin_headers = {"Authorization": f"Bearer {auth_setup['admin_token']}"}
  1486. group_resp = await async_client.post(
  1487. "/api/v1/groups/",
  1488. headers=admin_headers,
  1489. json={
  1490. "name": "pipeline_runners",
  1491. "permissions": [
  1492. "pipelines:read",
  1493. "pipelines:run",
  1494. "library:read_own",
  1495. "archives:read_own",
  1496. ],
  1497. },
  1498. )
  1499. assert group_resp.status_code == 201, group_resp.text
  1500. group_id = group_resp.json()["id"]
  1501. await async_client.post(
  1502. "/api/v1/users/",
  1503. headers=admin_headers,
  1504. json={"username": "runner1", "password": "Runnerpass1!", "group_ids": [group_id]},
  1505. )
  1506. runner_login = await async_client.post(
  1507. "/api/v1/auth/login",
  1508. json={"username": "runner1", "password": "Runnerpass1!"},
  1509. )
  1510. runner_token = runner_login.json()["access_token"]
  1511. pipeline = SlicerPipeline(
  1512. name="Cross-user pipeline",
  1513. printer_preset_source="local",
  1514. printer_preset_id="1",
  1515. process_preset_source="local",
  1516. process_preset_id="2",
  1517. filament_presets_json="[]",
  1518. target_kind="printer_class",
  1519. target_model_class="Bambu Lab X1 Carbon",
  1520. )
  1521. db_session.add(pipeline)
  1522. await db_session.commit()
  1523. await db_session.refresh(pipeline)
  1524. # Source owned by operator2, not the runner.
  1525. file = await library_file_factory(created_by_id=auth_setup["operator2_user"]["id"])
  1526. resp = await async_client.post(
  1527. f"/api/v1/slicer-pipelines/{pipeline.id}/check-eligibility",
  1528. headers={"Authorization": f"Bearer {runner_token}"},
  1529. json={"source_library_file_id": file.id},
  1530. )
  1531. assert resp.status_code == 404
  1532. assert resp.json()["detail"] == "File not found"