test_notification_photo_attachments.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. """Unit tests for camera snapshot attachments on notifications.
  2. Covers the per-provider attach_photo opt-out, the fetched-URL providers (Home
  3. Assistant, Bark, Slack-format webhooks) and the on-disk store they fetch from,
  4. and the inline image on emails.
  5. """
  6. import json
  7. import os
  8. import time
  9. from types import SimpleNamespace
  10. from unittest.mock import AsyncMock, MagicMock, patch
  11. import pytest
  12. from pydantic import ValidationError
  13. from backend.app.schemas.notification import NotificationProviderCreate, PhotoEvent
  14. from backend.app.schemas.notification_template import EVENT_VARIABLES, PHOTO_CAPABLE_EVENTS
  15. from backend.app.services.email_service import send_email
  16. from backend.app.services.notification_service import NotificationService
  17. from backend.app.utils import notification_photos
  18. def _client_returning(status_code=200, json_body=None):
  19. mock_response = MagicMock()
  20. mock_response.status_code = status_code
  21. mock_response.text = ""
  22. mock_response.json = MagicMock(return_value=json_body or {})
  23. mock_client = AsyncMock()
  24. mock_client.post = AsyncMock(return_value=mock_response)
  25. return mock_client
  26. def _provider(provider_type: str, config: dict, attach_photo: bool = True, photo_skip_events=None):
  27. provider = MagicMock()
  28. provider.provider_type = provider_type
  29. provider.config = json.dumps(config)
  30. provider.quiet_hours_enabled = False
  31. provider.attach_photo = attach_photo
  32. provider.photo_skip_events = photo_skip_events
  33. return provider
  34. @pytest.fixture
  35. def service():
  36. return NotificationService()
  37. class TestNotificationPhotoStore:
  38. """The flat directory HA/Bark/Slack fetch ad-hoc snapshots from."""
  39. @pytest.fixture(autouse=True)
  40. def _base_dir(self, tmp_path, monkeypatch):
  41. monkeypatch.setattr(notification_photos.settings, "base_dir", tmp_path)
  42. self.directory = tmp_path / "notification_photos"
  43. def test_save_then_find_round_trips(self):
  44. filename = notification_photos.save_notification_photo(b"jpeg-bytes", "plate_not_empty")
  45. assert filename.startswith("plate_not_empty_")
  46. assert filename.endswith(".jpg")
  47. found = notification_photos.find_notification_photo(filename)
  48. assert found is not None
  49. assert found.read_bytes() == b"jpeg-bytes"
  50. def test_event_type_is_sanitised_into_the_filename(self):
  51. filename = notification_photos.save_notification_photo(b"x", "../../etc/passwd")
  52. assert "/" not in filename
  53. assert ".." not in filename
  54. assert (self.directory / filename).exists()
  55. def test_filename_embeds_a_urlsafe_token(self):
  56. """The filename is the URL's only credential, so it has to carry the
  57. full 24-byte token, not a guessable suffix."""
  58. with patch.object(notification_photos.secrets, "token_urlsafe", return_value="T" * 32) as mock_token:
  59. filename = notification_photos.save_notification_photo(b"x", "test")
  60. mock_token.assert_called_once_with(24)
  61. assert filename.endswith("_" + "T" * 32 + ".jpg")
  62. def test_filenames_are_unique_per_save(self):
  63. first = notification_photos.save_notification_photo(b"x", "test")
  64. second = notification_photos.save_notification_photo(b"x", "test")
  65. assert first != second
  66. def test_find_rejects_traversal_and_missing_files(self):
  67. notification_photos.save_notification_photo(b"x", "test")
  68. assert notification_photos.find_notification_photo("../secret.jpg") is None
  69. assert notification_photos.find_notification_photo("does_not_exist.jpg") is None
  70. @pytest.mark.parametrize(
  71. "name",
  72. [
  73. # the pre-#3089-review shape: an 8-hex uuid suffix is guessable
  74. "test_20260930_120000_abcdef12.jpg",
  75. # token one character short / long
  76. "test_20260930_120000_" + "A" * 31 + ".jpg",
  77. "test_20260930_120000_" + "A" * 33 + ".jpg",
  78. # other extensions, even if such a file exists on disk
  79. "test_20260930_120000_" + "A" * 32 + ".png",
  80. "test_20260930_120000_" + "A" * 32 + ".jpg.bak",
  81. ],
  82. )
  83. def test_find_serves_only_the_exact_saved_shape(self, name):
  84. self.directory.mkdir(parents=True, exist_ok=True)
  85. (self.directory / name).write_bytes(b"x")
  86. assert notification_photos.find_notification_photo(name) is None
  87. def test_find_refuses_a_photo_past_its_expiry_even_before_prune(self):
  88. """The 3-day age limit is the URL's expiry, so it can't depend on
  89. another notification coming along to trigger a prune."""
  90. filename = notification_photos.save_notification_photo(b"x", "test")
  91. old = time.time() - notification_photos._MAX_AGE_SECONDS - 60
  92. os.utime(self.directory / filename, (old, old))
  93. assert notification_photos.find_notification_photo(filename) is None
  94. def test_save_prunes_photos_older_than_max_age(self):
  95. self.directory.mkdir(parents=True)
  96. stale = self.directory / "stale.jpg"
  97. stale.write_bytes(b"old")
  98. old = time.time() - notification_photos._MAX_AGE_SECONDS - 60
  99. os.utime(stale, (old, old))
  100. fresh = self.directory / "fresh.jpg"
  101. fresh.write_bytes(b"new")
  102. notification_photos.save_notification_photo(b"x", "test")
  103. assert not stale.exists()
  104. assert fresh.exists()
  105. class TestPhotoCapableEvents:
  106. def test_every_photo_capable_event_is_a_known_event(self):
  107. """supports_photo is looked up per EVENT_VARIABLES key, so a typo here
  108. would silently never show the preview."""
  109. assert set(EVENT_VARIABLES) >= PHOTO_CAPABLE_EVENTS
  110. class TestPhotoSkipEvents:
  111. """photo_skip_events turns the snapshot off for single events (#2877)."""
  112. def test_skippable_events_are_the_provider_photo_events(self):
  113. """The skippable events are exactly the photo events a provider sends:
  114. the template editor's set minus the per-user emails, which go to users
  115. rather than through a provider, and the test send."""
  116. provider_events = {e for e in PHOTO_CAPABLE_EVENTS if not e.startswith("user_")} - {"test"}
  117. assert set(PhotoEvent.__args__) == provider_events
  118. def test_unknown_event_is_rejected(self):
  119. with pytest.raises(ValidationError):
  120. NotificationProviderCreate(
  121. name="n", provider_type="ntfy", config={"topic": "t"}, photo_skip_events=["print_progres"]
  122. )
  123. @pytest.mark.asyncio
  124. @pytest.mark.parametrize("skip", [None, []])
  125. async def test_nothing_skipped_keeps_the_photo(self, service, skip):
  126. provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=skip)
  127. with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
  128. await service._send_to_provider(
  129. provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_progress"
  130. )
  131. assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
  132. @pytest.mark.asyncio
  133. async def test_skipped_event_goes_out_without_image(self, service):
  134. provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=["print_progress", "print_start"])
  135. with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
  136. await service._send_to_provider(
  137. provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_progress"
  138. )
  139. mock_send.assert_awaited_once()
  140. assert mock_send.call_args.kwargs.get("image_data") is None
  141. @pytest.mark.asyncio
  142. async def test_event_not_skipped_keeps_its_photo(self, service):
  143. provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=["print_progress"])
  144. with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
  145. await service._send_to_provider(
  146. provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_complete"
  147. )
  148. assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
  149. @pytest.mark.asyncio
  150. @pytest.mark.parametrize(
  151. ("provider_type", "config", "sender"),
  152. [
  153. ("bark", {"device_key": "abc"}, "_send_bark"),
  154. ("gotify", {"server": "https://g.example", "app_token": "t"}, "_send_gotify"),
  155. ("homeassistant", {"service": "notify.mobile_app_x"}, "_send_homeassistant"),
  156. ("webhook", {"webhook_url": "http://hook.local", "payload_format": "slack"}, "_send_webhook"),
  157. ("notify", {"device_id": "IOS-1", "token": "t"}, "_send_notify"),
  158. ],
  159. )
  160. async def test_fetched_url_providers_skip_the_cached_url(self, service, provider_type, config, sender):
  161. """An earlier provider in the same send may have left a photo URL in
  162. the shared cache; a provider skipping this event must not pick it up."""
  163. provider = _provider(provider_type, config, photo_skip_events=["print_progress"])
  164. photo_cache = {"url": "https://bambuddy.example/api/v1/notifications/photos/a.jpg"}
  165. with patch.object(service, sender, new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
  166. await service._send_to_provider(
  167. provider,
  168. "T",
  169. "B",
  170. db=AsyncMock(),
  171. image_data=b"jpeg",
  172. event_type="print_progress",
  173. photo_cache=photo_cache,
  174. )
  175. assert mock_send.call_args.kwargs.get("image_url") is None
  176. @pytest.mark.asyncio
  177. async def test_one_send_photo_only_where_not_skipped(self, service):
  178. """Two providers in one send: the one that skips the event gets no
  179. photo, the other still gets the URL the send persisted."""
  180. keeps = _provider("bark", {"device_key": "abc"})
  181. skips = _provider("homeassistant", {"service": "notify.mobile_app_x"}, photo_skip_events=["print_progress"])
  182. for i, provider in enumerate((keeps, skips)):
  183. provider.id = i
  184. provider.name = f"p{i}"
  185. provider.daily_digest_enabled = False
  186. with (
  187. patch.object(service, "_send_bark", new_callable=AsyncMock, return_value=(True, "OK")) as bark,
  188. patch.object(service, "_send_homeassistant", new_callable=AsyncMock, return_value=(True, "OK")) as ha,
  189. patch.object(service, "_update_provider_status", new_callable=AsyncMock),
  190. patch.object(service, "_log_notification", new_callable=AsyncMock),
  191. patch(
  192. "backend.app.api.routes.settings.get_setting",
  193. new_callable=AsyncMock,
  194. return_value="https://bambuddy.example",
  195. ),
  196. patch("backend.app.services.notification_service.save_notification_photo", return_value="p.jpg"),
  197. ):
  198. await service._send_to_providers(
  199. [keeps, skips], "T", "B", AsyncMock(), event_type="print_progress", image_data=b"jpeg"
  200. )
  201. assert bark.call_args.kwargs["image_url"] == "https://bambuddy.example/api/v1/notifications/photos/p.jpg"
  202. assert ha.call_args.kwargs["image_url"] is None
  203. class TestAttachPhotoOptOut:
  204. """provider.attach_photo=False must keep the photo off every provider type."""
  205. @pytest.mark.asyncio
  206. async def test_byte_upload_provider_gets_no_image_when_opted_out(self, service):
  207. provider = _provider("ntfy", {"topic": "t"}, attach_photo=False)
  208. with patch.object(service, "_send_ntfy", new_callable=AsyncMock) as mock_send:
  209. mock_send.return_value = (True, "OK")
  210. await service._send_to_provider(provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg")
  211. assert mock_send.call_args.kwargs.get("image_data") is None
  212. @pytest.mark.asyncio
  213. async def test_byte_upload_provider_gets_image_by_default(self, service):
  214. provider = _provider("ntfy", {"topic": "t"})
  215. with patch.object(service, "_send_ntfy", new_callable=AsyncMock) as mock_send:
  216. mock_send.return_value = (True, "OK")
  217. await service._send_to_provider(provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg")
  218. assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
  219. @pytest.mark.asyncio
  220. @pytest.mark.parametrize(
  221. ("provider_type", "config", "sender"),
  222. [
  223. ("bark", {"device_key": "abc"}, "_send_bark"),
  224. ("gotify", {"server": "https://g.example", "app_token": "t"}, "_send_gotify"),
  225. ("homeassistant", {"service": "notify.mobile_app_x"}, "_send_homeassistant"),
  226. ("webhook", {"webhook_url": "http://hook.local", "payload_format": "slack"}, "_send_webhook"),
  227. ],
  228. )
  229. async def test_fetched_url_providers_skip_the_url_when_opted_out(self, service, provider_type, config, sender):
  230. """HA/Bark/Slack could otherwise get the URL an earlier provider in the
  231. same send left in the shared photo cache, so they need their own check."""
  232. provider = _provider(provider_type, config, attach_photo=False)
  233. photo_cache = {"url": "https://bambuddy.example/api/v1/notifications/photos/a.jpg"}
  234. with (
  235. patch.object(service, sender, new_callable=AsyncMock) as mock_send,
  236. patch.object(service, "_get_or_build_photo_url", wraps=service._get_or_build_photo_url) as mock_build,
  237. ):
  238. mock_send.return_value = (True, "OK")
  239. await service._send_to_provider(
  240. provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg", photo_cache=photo_cache
  241. )
  242. mock_build.assert_not_called()
  243. assert mock_send.call_args.kwargs.get("image_url") is None
  244. @pytest.mark.asyncio
  245. async def test_one_send_persists_the_photo_once_and_keeps_it_out_of_variables(self, service):
  246. """Every HA/Bark/Slack provider in a send shares one saved photo, and
  247. the URL (the photo's only credential) never reaches the variables a
  248. generic webhook copies into its payload."""
  249. providers = [
  250. _provider("bark", {"device_key": "abc"}),
  251. _provider("homeassistant", {"service": "notify.mobile_app_x"}),
  252. ]
  253. for i, provider in enumerate(providers):
  254. provider.id = i
  255. provider.name = f"p{i}"
  256. provider.daily_digest_enabled = False
  257. variables = {"printer": "X1C"}
  258. with (
  259. patch.object(service, "_send_bark", new_callable=AsyncMock, return_value=(True, "OK")) as bark,
  260. patch.object(service, "_send_homeassistant", new_callable=AsyncMock, return_value=(True, "OK")) as ha,
  261. patch.object(service, "_update_provider_status", new_callable=AsyncMock),
  262. patch.object(service, "_log_notification", new_callable=AsyncMock),
  263. patch(
  264. "backend.app.api.routes.settings.get_setting",
  265. new_callable=AsyncMock,
  266. return_value="https://bambuddy.example",
  267. ),
  268. patch(
  269. "backend.app.services.notification_service.save_notification_photo", return_value="p.jpg"
  270. ) as mock_save,
  271. ):
  272. await service._send_to_providers(
  273. providers, "T", "B", AsyncMock(), event_type="print_complete", image_data=b"jpeg", variables=variables
  274. )
  275. mock_save.assert_called_once()
  276. url = "https://bambuddy.example/api/v1/notifications/photos/p.jpg"
  277. assert bark.call_args.kwargs["image_url"] == url
  278. assert ha.call_args.kwargs["image_url"] == url
  279. assert variables == {"printer": "X1C"}
  280. @pytest.mark.asyncio
  281. async def test_bark_gets_photo_url_when_enabled(self, service):
  282. provider = _provider("bark", {"device_key": "abc"})
  283. with (
  284. patch.object(service, "_send_bark", new_callable=AsyncMock) as mock_send,
  285. patch.object(service, "_get_or_build_photo_url", new_callable=AsyncMock) as mock_build,
  286. ):
  287. mock_send.return_value = (True, "OK")
  288. mock_build.return_value = "https://bambuddy.example/photo.jpg"
  289. await service._send_to_provider(provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg")
  290. assert mock_send.call_args.kwargs.get("image_url") == "https://bambuddy.example/photo.jpg"
  291. @pytest.mark.asyncio
  292. async def test_gotify_gets_photo_url_when_enabled(self, service):
  293. """Gotify takes no uploads, so its photo has to be a URL its app fetches (#2743)."""
  294. provider = _provider("gotify", {"server": "https://g.example", "app_token": "t"})
  295. with (
  296. patch.object(service, "_send_gotify", new_callable=AsyncMock) as mock_send,
  297. patch.object(service, "_get_or_build_photo_url", new_callable=AsyncMock) as mock_build,
  298. ):
  299. mock_send.return_value = (True, "OK")
  300. mock_build.return_value = "https://bambuddy.example/photo.jpg"
  301. await service._send_to_provider(provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg")
  302. assert mock_send.call_args.kwargs.get("image_url") == "https://bambuddy.example/photo.jpg"
  303. @pytest.mark.asyncio
  304. async def test_generic_webhook_never_builds_a_photo_url(self, service):
  305. """The generic format carries base64 bytes, so it must not pay for a disk write."""
  306. provider = _provider("webhook", {"webhook_url": "http://hook.local"})
  307. with (
  308. patch.object(service, "_send_webhook", new_callable=AsyncMock) as mock_send,
  309. patch.object(service, "_get_or_build_photo_url", new_callable=AsyncMock) as mock_build,
  310. ):
  311. mock_send.return_value = (True, "OK")
  312. await service._send_to_provider(provider, "Title", "Body", db=AsyncMock(), image_data=b"jpeg")
  313. mock_build.assert_not_called()
  314. assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
  315. class TestFetchedUrlPayloads:
  316. @pytest.mark.asyncio
  317. async def test_bark_sends_photo_as_icon(self, service):
  318. mock_client = _client_returning(200, {"code": 200})
  319. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  320. await service._send_bark({"device_key": "abc"}, "T", "B", image_url="https://x.example/p.jpg")
  321. assert mock_client.post.call_args.kwargs["json"]["icon"] == "https://x.example/p.jpg"
  322. @pytest.mark.asyncio
  323. async def test_bark_keeps_tap_url_alongside_photo(self, service):
  324. mock_client = _client_returning(200, {"code": 200})
  325. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  326. await service._send_bark(
  327. {"device_key": "abc"}, "T", "B", url="https://x.example/confirm", image_url="https://x.example/p.jpg"
  328. )
  329. payload = mock_client.post.call_args.kwargs["json"]
  330. assert payload["url"] == "https://x.example/confirm"
  331. assert payload["icon"] == "https://x.example/p.jpg"
  332. @pytest.mark.asyncio
  333. async def test_slack_webhook_attaches_photo_url(self, service):
  334. mock_client = _client_returning()
  335. config = {"webhook_url": "http://mattermost.local/hooks/abc", "payload_format": "slack"}
  336. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  337. await service._send_webhook(config, "T", "B", image_data=b"jpeg", image_url="https://x.example/p.jpg")
  338. payload = mock_client.post.call_args.kwargs["json"]
  339. assert payload["attachments"] == [{"fallback": "T", "image_url": "https://x.example/p.jpg"}]
  340. assert "image" not in payload
  341. @pytest.fixture
  342. def ha_settings(self):
  343. with patch(
  344. "backend.app.api.routes.settings.get_homeassistant_settings",
  345. new_callable=AsyncMock,
  346. return_value={"ha_url": "http://ha.local:8123", "ha_token": "tok", "ha_enabled": True},
  347. ):
  348. yield
  349. @pytest.mark.asyncio
  350. async def test_homeassistant_notify_service_gets_data_image(self, service, ha_settings):
  351. mock_client = _client_returning()
  352. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  353. await service._send_homeassistant(
  354. {"service": "notify.mobile_app_x"}, "T", "B", db=AsyncMock(), image_url="https://x.example/p.jpg"
  355. )
  356. assert mock_client.post.call_args.kwargs["json"]["data"] == {"image": "https://x.example/p.jpg"}
  357. @pytest.mark.asyncio
  358. async def test_homeassistant_persistent_notification_never_gets_image(self, service, ha_settings):
  359. """persistent_notification.create 400s on unknown keys, so the default
  360. service must not get a data block just because a photo exists."""
  361. mock_client = _client_returning()
  362. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  363. await service._send_homeassistant({}, "T", "B", db=AsyncMock(), image_url="https://x.example/p.jpg")
  364. assert "data" not in mock_client.post.call_args.kwargs["json"]
  365. @pytest.mark.asyncio
  366. async def test_homeassistant_user_data_image_wins(self, service, ha_settings):
  367. mock_client = _client_returning()
  368. config = {"service": "notify.mobile_app_x", "data": json.dumps({"image": "mine", "ttl": 0})}
  369. with patch.object(service, "_get_client", new_callable=AsyncMock, return_value=mock_client):
  370. await service._send_homeassistant(config, "T", "B", db=AsyncMock(), image_url="https://x.example/p.jpg")
  371. assert mock_client.post.call_args.kwargs["json"]["data"] == {"image": "mine", "ttl": 0}
  372. class TestGetOrBuildPhotoUrl:
  373. @pytest.fixture
  374. def external_url(self):
  375. with patch(
  376. "backend.app.api.routes.settings.get_setting",
  377. new_callable=AsyncMock,
  378. return_value="https://bambuddy.example/",
  379. ):
  380. yield
  381. @pytest.mark.asyncio
  382. async def test_no_image_returns_none(self, service):
  383. assert await service._get_or_build_photo_url(AsyncMock(), None, "x") is None
  384. @pytest.mark.asyncio
  385. async def test_no_external_url_returns_none(self, service):
  386. """A relative path is useless to a service that fetches it itself."""
  387. with (
  388. patch("backend.app.api.routes.settings.get_setting", new_callable=AsyncMock, return_value=""),
  389. patch("backend.app.services.notification_service.save_notification_photo") as mock_save,
  390. ):
  391. result = await service._get_or_build_photo_url(AsyncMock(), b"jpeg", "x")
  392. assert result is None
  393. mock_save.assert_not_called()
  394. @pytest.mark.asyncio
  395. async def test_saves_and_builds_a_url_with_no_token(self, service, external_url):
  396. """The filename is the credential. A camera stream token here would
  397. open every printer's live stream to whoever sees the notification."""
  398. with (
  399. patch(
  400. "backend.app.services.notification_service.save_notification_photo", return_value="first_layer_a.jpg"
  401. ) as mock_save,
  402. patch("backend.app.core.auth.create_camera_stream_token", new_callable=AsyncMock) as mock_token,
  403. ):
  404. result = await service._get_or_build_photo_url(AsyncMock(), b"jpeg", "first_layer_complete")
  405. assert result == "https://bambuddy.example/api/v1/notifications/photos/first_layer_a.jpg"
  406. mock_save.assert_called_once_with(b"jpeg", "first_layer_complete")
  407. mock_token.assert_not_called()
  408. @pytest.mark.asyncio
  409. async def test_print_complete_gets_its_own_photo_not_the_archive_url(self, service, external_url):
  410. """The archive's finish_photo_url needs a media token, so with auth on
  411. HA/Bark/Slack would get a 401 on it. Print Complete must build its own."""
  412. with patch("backend.app.services.notification_service.save_notification_photo", return_value="p.jpg"):
  413. result = await service._get_or_build_photo_url(AsyncMock(), b"jpeg", "print_complete")
  414. assert result == "https://bambuddy.example/api/v1/notifications/photos/p.jpg"
  415. @pytest.mark.asyncio
  416. async def test_cache_is_filled_and_then_reused(self, service, external_url):
  417. photo_cache: dict = {}
  418. with patch(
  419. "backend.app.services.notification_service.save_notification_photo", return_value="p.jpg"
  420. ) as mock_save:
  421. first = await service._get_or_build_photo_url(AsyncMock(), b"jpeg", "x", photo_cache)
  422. second = await service._get_or_build_photo_url(AsyncMock(), b"jpeg", "x", photo_cache)
  423. assert first == second == photo_cache["url"]
  424. mock_save.assert_called_once()
  425. class TestNotificationPhotoRoute:
  426. """GET /notifications/photos/{filename} is public: the filename is the auth."""
  427. @pytest.mark.asyncio
  428. async def test_serves_a_saved_photo_without_credentials(self, tmp_path, monkeypatch):
  429. from backend.app.api.routes.notifications import get_notification_photo
  430. monkeypatch.setattr(notification_photos.settings, "base_dir", tmp_path)
  431. filename = notification_photos.save_notification_photo(b"\xff\xd8jpeg", "test")
  432. response = await get_notification_photo(filename)
  433. assert response.media_type == "image/jpeg"
  434. assert response.headers["cache-control"] == "private, no-store"
  435. @pytest.mark.asyncio
  436. async def test_unknown_name_is_404(self, tmp_path, monkeypatch):
  437. from fastapi import HTTPException
  438. from backend.app.api.routes.notifications import get_notification_photo
  439. monkeypatch.setattr(notification_photos.settings, "base_dir", tmp_path)
  440. with pytest.raises(HTTPException) as exc:
  441. await get_notification_photo("test_20260930_120000_" + "A" * 32 + ".jpg")
  442. assert exc.value.status_code == 404
  443. class TestSendEmailInlineImage:
  444. @pytest.fixture
  445. def smtp_settings(self):
  446. return SimpleNamespace(
  447. smtp_from_name="Bambuddy",
  448. smtp_from_email="bambuddy@example.com",
  449. smtp_security="none",
  450. smtp_auth_enabled=False,
  451. smtp_username=None,
  452. smtp_password=None,
  453. smtp_host="smtp.example.com",
  454. smtp_port=25,
  455. )
  456. def _sent_message(self, smtp_settings, **kwargs):
  457. with patch("backend.app.services.email_service.smtplib.SMTP") as mock_smtp:
  458. send_email(smtp_settings, "to@example.com", "Subject", "text", **kwargs)
  459. return mock_smtp.return_value.__enter__.return_value.send_message.call_args[0][0]
  460. def test_image_with_html_becomes_multipart_related(self, smtp_settings):
  461. msg = self._sent_message(
  462. smtp_settings, body_html='<img src="cid:photo">', image_data=b"\xff\xd8jpeg", image_cid="photo"
  463. )
  464. assert msg.get_content_type() == "multipart/related"
  465. alternative, image = msg.get_payload()
  466. assert alternative.get_content_type() == "multipart/alternative"
  467. assert image.get_content_type() == "image/jpeg"
  468. assert image["Content-ID"] == "<photo>"
  469. assert image.get_payload(decode=True) == b"\xff\xd8jpeg"
  470. def test_image_without_html_is_dropped(self, smtp_settings):
  471. """No HTML part means nowhere to reference the cid, so no attachment."""
  472. msg = self._sent_message(smtp_settings, image_data=b"jpeg")
  473. assert msg.get_content_type() == "multipart/alternative"
  474. assert [part.get_content_type() for part in msg.get_payload()] == ["text/plain"]