test_cloud_token_expiry.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. """Tests for Bambu Cloud sign-in expiry detection.
  2. Bambu's access token is opaque — no readable expiry — and Bambuddy does not
  3. persist the refresh token, so the only authority on whether a stored token still
  4. works is Bambu itself. Bambuddy used to pretend otherwise: ``set_token()``
  5. stamped ``token_expiry = now + 30 days`` *every time a stored token was loaded*,
  6. which reset the expiry check on every request and made ``is_authenticated``
  7. incapable of ever returning False. ``/cloud/status`` therefore reported
  8. "connected" indefinitely while every cloud call 401'd, and the user was shown
  9. Bambu's own ``{"error": "Please login."}`` as a toast — on a UI that was
  10. simultaneously telling them they were signed in.
  11. These tests pin: the expiry is no longer invented, a 401 is recorded durably,
  12. a Bambu outage does not masquerade as an expired sign-in, and a fresh login
  13. clears the flag.
  14. """
  15. from __future__ import annotations
  16. from datetime import datetime, timezone
  17. from unittest.mock import AsyncMock, MagicMock
  18. import httpx
  19. import pytest
  20. from backend.app.api.routes.cloud import (
  21. CLOUD_EMAIL_KEY,
  22. CLOUD_REGION_KEY,
  23. CLOUD_TOKEN_INVALID_KEY,
  24. CLOUD_TOKEN_KEY,
  25. clear_token,
  26. is_cloud_token_invalid,
  27. store_token,
  28. )
  29. from backend.app.models.settings import Settings
  30. from backend.app.services import bambu_cloud as bc
  31. from backend.app.services.bambu_cloud import BambuCloudService
  32. @pytest.fixture(autouse=True)
  33. def _clear_validation_cache():
  34. """The validation verdict cache is module-level; don't leak across tests."""
  35. bc.invalidate_validation_cache()
  36. yield
  37. bc.invalidate_validation_cache()
  38. def _service(status_code: int = 200, *, on_auth_failure=None, raises: Exception | None = None):
  39. svc = BambuCloudService(client=MagicMock(spec=httpx.AsyncClient), on_auth_failure=on_auth_failure)
  40. resp = MagicMock()
  41. resp.status_code = status_code
  42. svc._client.get = AsyncMock(side_effect=raises) if raises else AsyncMock(return_value=resp)
  43. return svc
  44. class TestNoInventedExpiry:
  45. def test_set_token_records_no_expiry(self):
  46. """The bug in one line: this used to be ``now + 30 days``, re-derived on
  47. every request from a token of entirely unknown age."""
  48. svc = _service()
  49. svc.set_token("stored-token-of-unknown-age")
  50. assert svc.token_expiry is None
  51. def test_is_authenticated_means_loaded_not_accepted(self):
  52. """It still answers True for a loaded token — that is all it ever knew.
  53. The point is that nobody may now read it as "Bambu accepts this"."""
  54. svc = _service()
  55. assert svc.is_authenticated is False
  56. svc.set_token("stored-token")
  57. assert svc.is_authenticated is True
  58. class TestValidateToken:
  59. @pytest.mark.asyncio
  60. async def test_accepted_token_returns_true(self):
  61. svc = _service(200)
  62. svc.set_token("good-token")
  63. assert await svc.validate_token() is True
  64. @pytest.mark.asyncio
  65. async def test_rejected_token_returns_false(self):
  66. svc = _service(401)
  67. svc.set_token("dead-token")
  68. assert await svc.validate_token() is False
  69. @pytest.mark.asyncio
  70. async def test_no_token_is_not_authenticated(self):
  71. svc = _service(200)
  72. assert await svc.validate_token() is False
  73. @pytest.mark.asyncio
  74. async def test_network_failure_is_unknown_not_invalid(self):
  75. """A Bambu outage must never present as "your sign-in expired" — that
  76. would sign every user out of a perfectly good session."""
  77. svc = _service(raises=httpx.ConnectError("no route to host"))
  78. svc.set_token("good-token")
  79. assert await svc.validate_token() is None
  80. @pytest.mark.asyncio
  81. async def test_server_error_is_unknown_not_invalid(self):
  82. svc = _service(503)
  83. svc.set_token("good-token")
  84. assert await svc.validate_token() is None
  85. @pytest.mark.asyncio
  86. async def test_cloudflare_challenge_is_unknown_not_invalid(self):
  87. """418/403 from Bambu's anti-abuse edge means the *request* was refused,
  88. not the token. Declaring the credential dead there would log users out
  89. whenever Cloudflare gets suspicious of their IP."""
  90. svc = _service(418)
  91. svc.set_token("good-token")
  92. assert await svc.validate_token() is None
  93. @pytest.mark.asyncio
  94. async def test_verdict_is_cached(self):
  95. """/cloud/status is polled by several components; without the cache each
  96. render would put a Bambu round-trip in front of the settings page."""
  97. svc = _service(200)
  98. svc.set_token("good-token")
  99. assert await svc.validate_token() is True
  100. assert await svc.validate_token() is True
  101. assert svc._client.get.await_count == 1
  102. @pytest.mark.asyncio
  103. async def test_cache_is_keyed_per_token(self):
  104. svc = _service(200)
  105. svc.set_token("token-a")
  106. assert await svc.validate_token() is True
  107. other = _service(401)
  108. other.set_token("token-b")
  109. assert await other.validate_token() is False, "a different token must not inherit the cached verdict"
  110. @pytest.mark.asyncio
  111. async def test_login_drops_a_cached_rejection(self):
  112. """Re-login must not leave the user staring at "sign-in expired" for the
  113. rest of the cache TTL."""
  114. svc = _service(401)
  115. svc.set_token("tok")
  116. assert await svc.validate_token() is False
  117. fresh = _service(200)
  118. fresh._set_tokens({"accessToken": "tok"}) # same string, freshly minted upstream
  119. assert await fresh.validate_token() is True
  120. class TestAuthFailureCallback:
  121. @pytest.mark.asyncio
  122. async def test_401_fires_the_callback(self):
  123. calls: list[int] = []
  124. async def _cb() -> None:
  125. calls.append(1)
  126. svc = _service(401, on_auth_failure=_cb)
  127. svc.set_token("dead-token")
  128. await svc.validate_token()
  129. assert calls == [1]
  130. @pytest.mark.asyncio
  131. async def test_reported_once_per_service(self):
  132. """A route that makes several cloud calls must not write the flag once
  133. per call."""
  134. calls: list[int] = []
  135. async def _cb() -> None:
  136. calls.append(1)
  137. svc = _service(401, on_auth_failure=_cb)
  138. svc.set_token("dead-token")
  139. resp = MagicMock()
  140. resp.status_code = 401
  141. await svc._note_response(resp)
  142. await svc._note_response(resp)
  143. await svc._note_response(resp)
  144. assert calls == [1]
  145. @pytest.mark.asyncio
  146. async def test_success_does_not_fire_the_callback(self):
  147. calls: list[int] = []
  148. async def _cb() -> None:
  149. calls.append(1)
  150. svc = _service(200, on_auth_failure=_cb)
  151. svc.set_token("good-token")
  152. await svc.validate_token()
  153. assert calls == []
  154. @pytest.mark.asyncio
  155. async def test_callback_failure_does_not_mask_the_401(self):
  156. """Recording the dead credential is bookkeeping. If it throws, the caller
  157. must still get the auth failure it was actually waiting for."""
  158. async def _cb() -> None:
  159. raise RuntimeError("database is on fire")
  160. svc = _service(401, on_auth_failure=_cb)
  161. svc.set_token("dead-token")
  162. assert await svc.validate_token() is False
  163. class TestPersistedFlag:
  164. """Auth-disabled deployments keep cloud credentials in the Settings table."""
  165. @pytest.mark.asyncio
  166. async def test_absent_by_default(self, db_session):
  167. assert await is_cloud_token_invalid(db_session, None) is False
  168. @pytest.mark.asyncio
  169. async def test_set_flag_is_read_back(self, db_session):
  170. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value=datetime.now(timezone.utc).isoformat()))
  171. await db_session.commit()
  172. assert await is_cloud_token_invalid(db_session, None) is True
  173. @pytest.mark.asyncio
  174. async def test_fresh_login_clears_the_flag(self, db_session):
  175. """Otherwise the new sign-in is reported as expired the instant it's stored."""
  176. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value="2026-07-14T07:00:00+00:00"))
  177. await db_session.commit()
  178. await store_token(db_session, "brand-new-token", "user@example.com", "global", None)
  179. assert await is_cloud_token_invalid(db_session, None) is False
  180. @pytest.mark.asyncio
  181. async def test_logout_clears_the_flag(self, db_session):
  182. for key, value in [
  183. (CLOUD_TOKEN_KEY, "dead"),
  184. (CLOUD_EMAIL_KEY, "user@example.com"),
  185. (CLOUD_REGION_KEY, "global"),
  186. (CLOUD_TOKEN_INVALID_KEY, "2026-07-14T07:00:00+00:00"),
  187. ]:
  188. db_session.add(Settings(key=key, value=value))
  189. await db_session.commit()
  190. await clear_token(db_session, None)
  191. assert await is_cloud_token_invalid(db_session, None) is False
  192. class TestStatusRoute:
  193. """The endpoint that was lying. ``GET /cloud/status`` drives the "Connected
  194. as ..." bar on the Profiles page and the green dot in Settings."""
  195. async def _store(self, db_session, *, invalid: bool = False):
  196. db_session.add(Settings(key=CLOUD_TOKEN_KEY, value="stored-token"))
  197. db_session.add(Settings(key=CLOUD_EMAIL_KEY, value="user@example.com"))
  198. db_session.add(Settings(key=CLOUD_REGION_KEY, value="global"))
  199. if invalid:
  200. db_session.add(Settings(key=CLOUD_TOKEN_INVALID_KEY, value="2026-07-14T07:00:00+00:00"))
  201. await db_session.commit()
  202. @pytest.mark.asyncio
  203. async def test_no_token_is_not_expired(self, async_client, db_session):
  204. body = (await async_client.get("/api/v1/cloud/status")).json()
  205. assert body["is_authenticated"] is False
  206. assert body["sign_in_expired"] is False
  207. @pytest.mark.asyncio
  208. async def test_token_bambu_rejects_reports_expired(self, async_client, db_session, monkeypatch):
  209. """The whole bug: a stored token Bambu no longer accepts used to come back
  210. as ``is_authenticated: true``, forever."""
  211. await self._store(db_session)
  212. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=False))
  213. body = (await async_client.get("/api/v1/cloud/status")).json()
  214. assert body["is_authenticated"] is False
  215. assert body["sign_in_expired"] is True
  216. assert body["email"] is None
  217. @pytest.mark.asyncio
  218. async def test_token_bambu_accepts_reports_connected(self, async_client, db_session, monkeypatch):
  219. await self._store(db_session)
  220. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=True))
  221. body = (await async_client.get("/api/v1/cloud/status")).json()
  222. assert body["is_authenticated"] is True
  223. assert body["sign_in_expired"] is False
  224. assert body["email"] == "user@example.com"
  225. @pytest.mark.asyncio
  226. async def test_bambu_unreachable_keeps_the_user_signed_in(self, async_client, db_session, monkeypatch):
  227. """Unknown is not invalid. A Bambu outage must not log the whole install
  228. out of the cloud."""
  229. await self._store(db_session)
  230. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=None))
  231. body = (await async_client.get("/api/v1/cloud/status")).json()
  232. assert body["is_authenticated"] is True
  233. assert body["sign_in_expired"] is False
  234. @pytest.mark.asyncio
  235. async def test_bambu_unreachable_does_not_resurrect_a_known_dead_token(self, async_client, db_session, monkeypatch):
  236. """...but "unknown" must fall back to what we last knew, not to True."""
  237. await self._store(db_session, invalid=True)
  238. monkeypatch.setattr(BambuCloudService, "validate_token", AsyncMock(return_value=None))
  239. body = (await async_client.get("/api/v1/cloud/status")).json()
  240. assert body["is_authenticated"] is False
  241. assert body["sign_in_expired"] is True
  242. @pytest.mark.asyncio
  243. async def test_known_dead_token_does_not_re_ask_bambu(self, async_client, db_session, monkeypatch):
  244. """Only a new login can revive it, and that clears the flag — so polling
  245. Bambu on every status call would be pure waste."""
  246. await self._store(db_session, invalid=True)
  247. validate = AsyncMock(return_value=False)
  248. monkeypatch.setattr(BambuCloudService, "validate_token", validate)
  249. await async_client.get("/api/v1/cloud/status")
  250. validate.assert_not_awaited()