test_queue_creation_attribution.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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.group import Group
  27. from backend.app.models.print_queue import PrintQueueItem
  28. from backend.app.models.user import User
  29. async def _read_item(test_engine, item_id: int) -> PrintQueueItem:
  30. """Fresh-session DB read — the `db_session` fixture's connection can look
  31. stale after a route call dispatches through its own `Depends(get_db)`
  32. session. Same helper shape as test_queue_start_user_attribution.py."""
  33. maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  34. async with maker() as fresh:
  35. return (await fresh.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))).scalar_one()
  36. async def _enable_auth_with_admin(client: AsyncClient, username: str) -> tuple[str, dict]:
  37. """Boot auth setup and return (bearer_token, user_dict)."""
  38. await client.post(
  39. "/api/v1/auth/setup",
  40. json={
  41. "auth_enabled": True,
  42. "admin_username": username,
  43. "admin_password": "AdminPass1!",
  44. },
  45. )
  46. login = await client.post(
  47. "/api/v1/auth/login",
  48. json={"username": username, "password": "AdminPass1!"},
  49. )
  50. body = login.json()
  51. return body["access_token"], body["user"]
  52. @pytest.fixture
  53. async def sliced_library_file(db_session):
  54. """A library file that passes both of add-to-queue's gates: the filename
  55. must look sliced, and the bytes must actually exist under `base_dir` (the
  56. route rejects rows whose file is missing from disk)."""
  57. from backend.app.models.library import LibraryFile
  58. rel_path = "archive/library/files/attribution_probe.gcode.3mf"
  59. abs_path = Path(app_settings.base_dir) / rel_path
  60. abs_path.parent.mkdir(parents=True, exist_ok=True)
  61. abs_path.write_bytes(b"probe")
  62. lib_file = LibraryFile(
  63. filename="attribution_probe.gcode.3mf",
  64. file_path=rel_path,
  65. file_size=5,
  66. file_type="3mf",
  67. )
  68. db_session.add(lib_file)
  69. await db_session.commit()
  70. await db_session.refresh(lib_file)
  71. yield lib_file
  72. abs_path.unlink(missing_ok=True)
  73. class TestLibraryAddToQueueAttribution:
  74. @pytest.mark.asyncio
  75. @pytest.mark.integration
  76. async def test_credits_the_authenticated_user(self, async_client: AsyncClient, test_engine, sliced_library_file):
  77. """The Library bulk-add is the path a user reaches for when queueing
  78. many files at once — exactly the case where losing attribution hurts."""
  79. token, user = await _enable_auth_with_admin(async_client, "libqueueadmin")
  80. response = await async_client.post(
  81. "/api/v1/library/files/add-to-queue",
  82. json={"file_ids": [sliced_library_file.id]},
  83. headers={"Authorization": f"Bearer {token}"},
  84. )
  85. assert response.status_code == 200
  86. added = response.json()["added"]
  87. assert len(added) == 1
  88. item = await _read_item(test_engine, added[0]["queue_item_id"])
  89. assert item.created_by_id == user["id"]
  90. @pytest.mark.asyncio
  91. @pytest.mark.integration
  92. async def test_auth_disabled_leaves_item_ownerless(
  93. self, async_client: AsyncClient, test_engine, sliced_library_file
  94. ):
  95. """With auth off the permission dep yields None. The row must stay
  96. NULL rather than gaining a synthetic owner."""
  97. response = await async_client.post(
  98. "/api/v1/library/files/add-to-queue",
  99. json={"file_ids": [sliced_library_file.id]},
  100. )
  101. assert response.status_code == 200
  102. added = response.json()["added"]
  103. assert len(added) == 1
  104. item = await _read_item(test_engine, added[0]["queue_item_id"])
  105. assert item.created_by_id is None
  106. class TestWebhookQueueAddAttribution:
  107. @pytest.fixture
  108. async def printer_and_archive(self, db_session):
  109. from backend.app.models.archive import PrintArchive
  110. from backend.app.models.printer import Printer
  111. printer = Printer(
  112. name="Webhook Target",
  113. ip_address="192.168.2.202",
  114. serial_number="00M00A9876543210",
  115. access_code="12345678",
  116. model="P1S",
  117. )
  118. archive = PrintArchive(
  119. filename="Plate_1.gcode.3mf",
  120. print_name="Plate 1",
  121. file_path="/tmp/webhook_attribution.3mf", # nosec B108
  122. file_size=1024,
  123. content_hash="webhookattributionhash",
  124. status="completed",
  125. )
  126. db_session.add_all([printer, archive])
  127. await db_session.commit()
  128. await db_session.refresh(printer)
  129. await db_session.refresh(archive)
  130. return printer, archive
  131. async def _mint_key(self, db_session, owner_id: int | None) -> str:
  132. full_key, key_hash, key_prefix = generate_api_key()
  133. db_session.add(
  134. APIKey(
  135. name="attribution probe",
  136. key_hash=key_hash,
  137. key_prefix=key_prefix,
  138. user_id=owner_id,
  139. can_queue=True,
  140. )
  141. )
  142. await db_session.commit()
  143. return full_key
  144. @pytest.mark.asyncio
  145. @pytest.mark.integration
  146. async def test_credits_the_key_owner(self, async_client: AsyncClient, db_session, test_engine, printer_and_archive):
  147. printer, archive = printer_and_archive
  148. # The owner needs queue:create in their own right: a key is capped by
  149. # its owner's permissions (#1894), so a bare account with no groups
  150. # cannot queue through a key however its scope flags are set. This test
  151. # is about who the row is credited to, not about the gate.
  152. group = Group(name="queue-writers", description="t", permissions=["queue:create"], is_system=False)
  153. db_session.add(group)
  154. await db_session.flush()
  155. owner = User(username="keyowner", password_hash="x", is_active=True, groups=[group])
  156. db_session.add(owner)
  157. await db_session.commit()
  158. await db_session.refresh(owner)
  159. key = await self._mint_key(db_session, owner.id)
  160. response = await async_client.post(
  161. "/api/v1/webhook/queue/add",
  162. json={"printer_id": printer.id, "archive_id": archive.id},
  163. headers={"X-API-Key": key},
  164. )
  165. assert response.status_code == 200
  166. item = await _read_item(test_engine, response.json()["id"])
  167. assert item.created_by_id == owner.id
  168. @pytest.mark.asyncio
  169. @pytest.mark.integration
  170. async def test_legacy_ownerless_key_leaves_item_ownerless(
  171. self, async_client: AsyncClient, db_session, test_engine, printer_and_archive
  172. ):
  173. """`APIKey.user_id` is nullable only for keys minted before per-user
  174. ownership existed. Those must produce an ownerless row, not a crash."""
  175. printer, archive = printer_and_archive
  176. key = await self._mint_key(db_session, None)
  177. response = await async_client.post(
  178. "/api/v1/webhook/queue/add",
  179. json={"printer_id": printer.id, "archive_id": archive.id},
  180. headers={"X-API-Key": key},
  181. )
  182. assert response.status_code == 200
  183. item = await _read_item(test_engine, response.json()["id"])
  184. assert item.created_by_id is None