test_queue_creation_attribution.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. """Regression tests: queue items created outside POST /queue/ lost their owner.
  2. `PrintQueueItem.created_by_id` is what the `queue:read_own` / `queue:update_own` /
  3. `queue:delete_own` permissions filter on (`api/routes/print_queue.py`). Two
  4. creation paths never set it, so the rows they produced were ownerless:
  5. - `POST /library/files/add-to-queue` — the bulk "Add to queue" action on the
  6. Library page. The route already required `Permission.QUEUE_CREATE` but bound
  7. the dependency to `_` and threw the user away, so a non-admin who queued
  8. files from the Library could not then see them in their own queue.
  9. - `POST /webhook/queue/add` — API-key inbound. `APIKey.user_id` records the
  10. key's owner, which is the acting identity for everything else the key does.
  11. Ownerless rows are still legitimate for callers with no user behind them (auth
  12. disabled, virtual-printer FTP uploads, legacy keys minted before per-user
  13. ownership), so the tests pin those cases too — the fix must not invent a
  14. placeholder user id. Compare `test_queue_start_user_attribution.py`, which pins
  15. the same NULL-is-meaningful contract on the `/start` path.
  16. """
  17. from __future__ import annotations
  18. from pathlib import Path
  19. import pytest
  20. from httpx import AsyncClient
  21. from sqlalchemy import select
  22. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
  23. from backend.app.core.auth import generate_api_key
  24. from backend.app.core.config import settings as app_settings
  25. from backend.app.models.api_key import APIKey
  26. from backend.app.models.print_queue import PrintQueueItem
  27. from backend.app.models.user import User
  28. async def _read_item(test_engine, item_id: int) -> PrintQueueItem:
  29. """Fresh-session DB read — the `db_session` fixture's connection can look
  30. stale after a route call dispatches through its own `Depends(get_db)`
  31. session. Same helper shape as test_queue_start_user_attribution.py."""
  32. maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  33. async with maker() as fresh:
  34. return (await fresh.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))).scalar_one()
  35. async def _enable_auth_with_admin(client: AsyncClient, username: str) -> tuple[str, dict]:
  36. """Boot auth setup and return (bearer_token, user_dict)."""
  37. await client.post(
  38. "/api/v1/auth/setup",
  39. json={
  40. "auth_enabled": True,
  41. "admin_username": username,
  42. "admin_password": "AdminPass1!",
  43. },
  44. )
  45. login = await client.post(
  46. "/api/v1/auth/login",
  47. json={"username": username, "password": "AdminPass1!"},
  48. )
  49. body = login.json()
  50. return body["access_token"], body["user"]
  51. @pytest.fixture
  52. async def sliced_library_file(db_session):
  53. """A library file that passes both of add-to-queue's gates: the filename
  54. must look sliced, and the bytes must actually exist under `base_dir` (the
  55. route rejects rows whose file is missing from disk)."""
  56. from backend.app.models.library import LibraryFile
  57. rel_path = "archive/library/files/attribution_probe.gcode.3mf"
  58. abs_path = Path(app_settings.base_dir) / rel_path
  59. abs_path.parent.mkdir(parents=True, exist_ok=True)
  60. abs_path.write_bytes(b"probe")
  61. lib_file = LibraryFile(
  62. filename="attribution_probe.gcode.3mf",
  63. file_path=rel_path,
  64. file_size=5,
  65. file_type="3mf",
  66. )
  67. db_session.add(lib_file)
  68. await db_session.commit()
  69. await db_session.refresh(lib_file)
  70. yield lib_file
  71. abs_path.unlink(missing_ok=True)
  72. class TestLibraryAddToQueueAttribution:
  73. @pytest.mark.asyncio
  74. @pytest.mark.integration
  75. async def test_credits_the_authenticated_user(self, async_client: AsyncClient, test_engine, sliced_library_file):
  76. """The Library bulk-add is the path a user reaches for when queueing
  77. many files at once — exactly the case where losing attribution hurts."""
  78. token, user = await _enable_auth_with_admin(async_client, "libqueueadmin")
  79. response = await async_client.post(
  80. "/api/v1/library/files/add-to-queue",
  81. json={"file_ids": [sliced_library_file.id]},
  82. headers={"Authorization": f"Bearer {token}"},
  83. )
  84. assert response.status_code == 200
  85. added = response.json()["added"]
  86. assert len(added) == 1
  87. item = await _read_item(test_engine, added[0]["queue_item_id"])
  88. assert item.created_by_id == user["id"]
  89. @pytest.mark.asyncio
  90. @pytest.mark.integration
  91. async def test_auth_disabled_leaves_item_ownerless(
  92. self, async_client: AsyncClient, test_engine, sliced_library_file
  93. ):
  94. """With auth off the permission dep yields None. The row must stay
  95. NULL rather than gaining a synthetic owner."""
  96. response = await async_client.post(
  97. "/api/v1/library/files/add-to-queue",
  98. json={"file_ids": [sliced_library_file.id]},
  99. )
  100. assert response.status_code == 200
  101. added = response.json()["added"]
  102. assert len(added) == 1
  103. item = await _read_item(test_engine, added[0]["queue_item_id"])
  104. assert item.created_by_id is None
  105. class TestWebhookQueueAddAttribution:
  106. @pytest.fixture
  107. async def printer_and_archive(self, db_session):
  108. from backend.app.models.archive import PrintArchive
  109. from backend.app.models.printer import Printer
  110. printer = Printer(
  111. name="Webhook Target",
  112. ip_address="192.168.2.202",
  113. serial_number="00M00A9876543210",
  114. access_code="12345678",
  115. model="P1S",
  116. )
  117. archive = PrintArchive(
  118. filename="Plate_1.gcode.3mf",
  119. print_name="Plate 1",
  120. file_path="/tmp/webhook_attribution.3mf", # nosec B108
  121. file_size=1024,
  122. content_hash="webhookattributionhash",
  123. status="completed",
  124. )
  125. db_session.add_all([printer, archive])
  126. await db_session.commit()
  127. await db_session.refresh(printer)
  128. await db_session.refresh(archive)
  129. return printer, archive
  130. async def _mint_key(self, db_session, owner_id: int | None) -> str:
  131. full_key, key_hash, key_prefix = generate_api_key()
  132. db_session.add(
  133. APIKey(
  134. name="attribution probe",
  135. key_hash=key_hash,
  136. key_prefix=key_prefix,
  137. user_id=owner_id,
  138. can_queue=True,
  139. )
  140. )
  141. await db_session.commit()
  142. return full_key
  143. @pytest.mark.asyncio
  144. @pytest.mark.integration
  145. async def test_credits_the_key_owner(self, async_client: AsyncClient, db_session, test_engine, printer_and_archive):
  146. printer, archive = printer_and_archive
  147. owner = User(username="keyowner", password_hash="x", is_active=True)
  148. db_session.add(owner)
  149. await db_session.commit()
  150. await db_session.refresh(owner)
  151. key = await self._mint_key(db_session, owner.id)
  152. response = await async_client.post(
  153. "/api/v1/webhook/queue/add",
  154. json={"printer_id": printer.id, "archive_id": archive.id},
  155. headers={"X-API-Key": key},
  156. )
  157. assert response.status_code == 200
  158. item = await _read_item(test_engine, response.json()["id"])
  159. assert item.created_by_id == owner.id
  160. @pytest.mark.asyncio
  161. @pytest.mark.integration
  162. async def test_legacy_ownerless_key_leaves_item_ownerless(
  163. self, async_client: AsyncClient, db_session, test_engine, printer_and_archive
  164. ):
  165. """`APIKey.user_id` is nullable only for keys minted before per-user
  166. ownership existed. Those must produce an ownerless row, not a crash."""
  167. printer, archive = printer_and_archive
  168. key = await self._mint_key(db_session, None)
  169. response = await async_client.post(
  170. "/api/v1/webhook/queue/add",
  171. json={"printer_id": printer.id, "archive_id": archive.id},
  172. headers={"X-API-Key": key},
  173. )
  174. assert response.status_code == 200
  175. item = await _read_item(test_engine, response.json()["id"])
  176. assert item.created_by_id is None