test_updates_api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """Integration tests for Updates API endpoints."""
  2. from pathlib import Path
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestUpdatesAPI:
  7. @pytest.mark.asyncio
  8. async def test_get_version(self, async_client: AsyncClient):
  9. response = await async_client.get("/api/v1/updates/version")
  10. assert response.status_code == 200
  11. @pytest.mark.asyncio
  12. async def test_apply_update_docker_rejection(self, async_client: AsyncClient):
  13. with patch("backend.app.api.routes.updates._is_docker_environment", return_value=True):
  14. response = await async_client.post("/api/v1/updates/apply")
  15. result = response.json()
  16. assert result["success"] is False
  17. assert result["is_docker"] is True
  18. @pytest.mark.asyncio
  19. async def test_apply_update_non_docker(self, async_client: AsyncClient):
  20. """Test non-Docker path - mock _perform_update + _discover_target_release
  21. to prevent side effects (network call to GitHub releases API + actual
  22. git/pip subprocesses)."""
  23. with (
  24. patch("backend.app.api.routes.updates._is_docker_environment", return_value=False),
  25. patch(
  26. "backend.app.api.routes.updates._discover_target_release",
  27. new_callable=AsyncMock,
  28. return_value="v9.9.9",
  29. ),
  30. patch("backend.app.api.routes.updates._perform_update", new_callable=AsyncMock),
  31. ):
  32. response = await async_client.post("/api/v1/updates/apply")
  33. assert response.json()["success"] is True
  34. def test_is_docker_with_dockerenv(self):
  35. from backend.app.api.routes.updates import _is_docker_environment
  36. with patch("os.path.exists", return_value=True):
  37. assert _is_docker_environment() is True
  38. def test_parse_version(self):
  39. from backend.app.api.routes.updates import parse_version
  40. assert parse_version("0.1.5")[:3] == (0, 1, 5)
  41. def test_is_newer_version(self):
  42. from backend.app.api.routes.updates import is_newer_version
  43. assert is_newer_version("0.1.5", "0.1.5b7") is True
  44. def test_parse_github_remote_recognises_ssh_https_and_dotgit(self):
  45. """`_parse_github_remote` must accept the four canonical forms `git
  46. remote -v` prints; anything else returns None so callers can treat
  47. it as 'reset to expected URL'."""
  48. from backend.app.api.routes.updates import _parse_github_remote
  49. assert _parse_github_remote("git@github.com:maziggy/bambuddy.git") == (
  50. "maziggy",
  51. "bambuddy",
  52. )
  53. assert _parse_github_remote("git@github.com:maziggy/bambuddy") == (
  54. "maziggy",
  55. "bambuddy",
  56. )
  57. assert _parse_github_remote("https://github.com/maziggy/bambuddy.git") == (
  58. "maziggy",
  59. "bambuddy",
  60. )
  61. assert _parse_github_remote("https://github.com/maziggy/bambuddy") == (
  62. "maziggy",
  63. "bambuddy",
  64. )
  65. # Non-GitHub host → None (we don't claim ownership over arbitrary
  66. # forge URLs).
  67. assert _parse_github_remote("git@gitlab.com:maziggy/bambuddy.git") is None
  68. # Empty / malformed → None.
  69. assert _parse_github_remote("") is None
  70. assert _parse_github_remote("not-a-url") is None
  71. assert _parse_github_remote("https://github.com/maziggy") is None # no /repo
  72. @pytest.mark.asyncio
  73. async def test_perform_update_preserves_ssh_origin_when_pointing_at_correct_repo(self, tmp_path):
  74. """Regression for the developer-checkout footgun: if origin already
  75. points at github.com/maziggy/bambuddy via SSH, the updater must
  76. leave it alone instead of clobbering it with HTTPS. Pre-fix, every
  77. Apply Update click rewrote `git@github.com:...` to `https://...`,
  78. breaking subsequent `git push` for any developer testing the
  79. upgrade flow against their own checkout."""
  80. from backend.app.api.routes import updates as updates_module
  81. app_dir = tmp_path / "app"
  82. data_dir = tmp_path / "app" / "data"
  83. app_dir.mkdir()
  84. data_dir.mkdir()
  85. (app_dir / "requirements.txt").write_text("fastapi\n")
  86. calls: list[dict] = []
  87. async def fake_create_subprocess_exec(*args, **kwargs):
  88. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  89. proc = MagicMock()
  90. # When the updater asks `git remote get-url origin`, return the
  91. # SSH URL. Every other subprocess returns successfully with no
  92. # output.
  93. if "get-url" in args and "origin" in args:
  94. proc.communicate = AsyncMock(return_value=(b"git@github.com:maziggy/bambuddy.git\n", b""))
  95. else:
  96. proc.communicate = AsyncMock(return_value=(b"", b""))
  97. proc.returncode = 0
  98. return proc
  99. with (
  100. patch.object(updates_module.settings, "base_dir", data_dir),
  101. patch.object(updates_module.settings, "app_dir", app_dir),
  102. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  103. patch.object(
  104. updates_module.asyncio,
  105. "create_subprocess_exec",
  106. side_effect=fake_create_subprocess_exec,
  107. ),
  108. ):
  109. await updates_module._perform_update("v0.2.4b1")
  110. # The updater MUST NOT have run `git remote set-url origin <https>`
  111. # because origin already pointed at the right repo over SSH.
  112. set_url_calls = [c for c in calls if "set-url" in c["args"] and "origin" in c["args"]]
  113. assert not set_url_calls, (
  114. "Updater clobbered an SSH origin pointing at the correct repo. "
  115. "Captured set-url calls: " + repr([c["args"] for c in set_url_calls])
  116. )
  117. @pytest.mark.asyncio
  118. async def test_perform_update_resets_origin_when_pointing_elsewhere(self, tmp_path):
  119. """Defensive: if origin points at a fork or unrelated repo (or is
  120. missing), the updater should still rewrite it to the canonical
  121. HTTPS URL so subsequent fetch / reset works against the right
  122. repo. This is the original behaviour that the SSH-preservation
  123. fix above must NOT regress."""
  124. from backend.app.api.routes import updates as updates_module
  125. from backend.app.core.config import GITHUB_REPO
  126. app_dir = tmp_path / "app"
  127. data_dir = tmp_path / "app" / "data"
  128. app_dir.mkdir()
  129. data_dir.mkdir()
  130. (app_dir / "requirements.txt").write_text("fastapi\n")
  131. calls: list[dict] = []
  132. async def fake_create_subprocess_exec(*args, **kwargs):
  133. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  134. proc = MagicMock()
  135. # origin is set to a fork — must be rewritten.
  136. if "get-url" in args and "origin" in args:
  137. proc.communicate = AsyncMock(return_value=(b"git@github.com:somefork/bambuddy.git\n", b""))
  138. else:
  139. proc.communicate = AsyncMock(return_value=(b"", b""))
  140. proc.returncode = 0
  141. return proc
  142. with (
  143. patch.object(updates_module.settings, "base_dir", data_dir),
  144. patch.object(updates_module.settings, "app_dir", app_dir),
  145. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  146. patch.object(
  147. updates_module.asyncio,
  148. "create_subprocess_exec",
  149. side_effect=fake_create_subprocess_exec,
  150. ),
  151. ):
  152. await updates_module._perform_update("v0.2.4b1")
  153. set_url_calls = [c for c in calls if "set-url" in c["args"] and "origin" in c["args"]]
  154. assert set_url_calls, "Updater must rewrite origin when it points at a fork."
  155. rewritten_to = set_url_calls[0]["args"][-1]
  156. assert rewritten_to == f"https://github.com/{GITHUB_REPO}.git", (
  157. f"Expected origin to be reset to canonical HTTPS URL; got: {rewritten_to}"
  158. )
  159. @pytest.mark.asyncio
  160. async def test_perform_update_resets_to_target_ref_not_hardcoded_main(self, tmp_path):
  161. """Regression for the hardcoded-`origin/main` limitation: the in-app
  162. updater must reset to the caller-supplied target ref (typically a
  163. release tag like `v0.2.4b1` discovered from the GitHub releases API)
  164. so beta releases that don't live on main can actually be installed.
  165. Pre-fix, `_perform_update` issued `git reset --hard origin/main`
  166. verbatim and silently no-op'd whenever the latest release wasn't on
  167. main — leaving a 0.2.3.x user clicking *Apply Update* stranded on
  168. 0.2.3.x. Also asserts the fetch step uses `--tags` so a tag ref is
  169. actually resolvable post-fetch."""
  170. from backend.app.api.routes import updates as updates_module
  171. app_dir = tmp_path / "app"
  172. data_dir = tmp_path / "app" / "data"
  173. app_dir.mkdir()
  174. data_dir.mkdir()
  175. (app_dir / "requirements.txt").write_text("fastapi\n")
  176. calls: list[dict] = []
  177. async def fake_create_subprocess_exec(*args, **kwargs):
  178. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  179. proc = MagicMock()
  180. if "get-url" in args and "origin" in args:
  181. proc.communicate = AsyncMock(return_value=(b"git@github.com:maziggy/bambuddy.git\n", b""))
  182. else:
  183. proc.communicate = AsyncMock(return_value=(b"", b""))
  184. proc.returncode = 0
  185. return proc
  186. with (
  187. patch.object(updates_module.settings, "base_dir", data_dir),
  188. patch.object(updates_module.settings, "app_dir", app_dir),
  189. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  190. patch.object(
  191. updates_module.asyncio,
  192. "create_subprocess_exec",
  193. side_effect=fake_create_subprocess_exec,
  194. ),
  195. ):
  196. await updates_module._perform_update("v0.2.4b1")
  197. # Reset target must be the caller-supplied ref, not "origin/main".
  198. reset_calls = [c for c in calls if "reset" in c["args"] and "--hard" in c["args"]]
  199. assert reset_calls, "git reset must be invoked"
  200. reset_target = reset_calls[0]["args"][-1]
  201. assert reset_target == "v0.2.4b1", (
  202. f"Expected reset target to be the caller-supplied ref 'v0.2.4b1'; "
  203. f"got {reset_target!r}. Regression to a hardcoded 'origin/main' "
  204. "would re-introduce the in-app-updater-can't-install-betas bug."
  205. )
  206. # Fetch must include --tags so v0.2.4b1 (a tag) is locally resolvable.
  207. fetch_calls = [c for c in calls if "fetch" in c["args"]]
  208. assert fetch_calls
  209. assert "--tags" in fetch_calls[0]["args"], (
  210. "Fetch must use --tags so release-tag refs (the production path "
  211. "for tag-based updates) are resolvable for the subsequent reset. "
  212. f"Captured fetch call: {fetch_calls[0]['args']}"
  213. )
  214. @pytest.mark.asyncio
  215. async def test_apply_update_passes_discovered_release_to_perform_update(self, async_client: AsyncClient):
  216. """End-to-end glue: the route handler calls `_discover_target_release`
  217. to pick the tag (respecting include_beta_updates), then schedules
  218. `_perform_update` with that tag — not with no arg, not with main."""
  219. from backend.app.api.routes import updates as updates_module
  220. captured_ref: list[str] = []
  221. async def fake_perform_update(target_ref):
  222. captured_ref.append(target_ref)
  223. async def fake_discover(_db):
  224. return "v0.2.4b1"
  225. with (
  226. patch.object(updates_module, "_is_docker_environment", return_value=False),
  227. patch.object(updates_module, "_perform_update", side_effect=fake_perform_update),
  228. patch.object(updates_module, "_discover_target_release", side_effect=fake_discover),
  229. ):
  230. response = await async_client.post("/api/v1/updates/apply")
  231. assert response.json()["success"] is True
  232. assert captured_ref == ["v0.2.4b1"], (
  233. f"apply_update must pass the discovered tag to _perform_update; captured invocations: {captured_ref}"
  234. )
  235. @pytest.mark.asyncio
  236. async def test_apply_update_returns_clear_error_when_no_release_resolves(self, async_client: AsyncClient):
  237. """If GitHub is unreachable or no release matches the user's channel,
  238. the route returns a useful error instead of silently kicking off an
  239. update that can't possibly land. Avoids the previous failure mode
  240. where in-app update appeared to succeed but did nothing."""
  241. from backend.app.api.routes import updates as updates_module
  242. async def fake_discover(_db):
  243. return None
  244. # The route guards against a concurrent update via the module-global
  245. # `_update_status` — reset it so a previous test that left the status
  246. # mid-flight doesn't short-circuit this one.
  247. updates_module._update_status = {"status": "idle", "progress": 0, "message": "", "error": None}
  248. with (
  249. patch.object(updates_module, "_is_docker_environment", return_value=False),
  250. patch.object(updates_module, "_discover_target_release", side_effect=fake_discover),
  251. ):
  252. response = await async_client.post("/api/v1/updates/apply")
  253. body = response.json()
  254. assert body["success"] is False
  255. assert "release" in body["message"].lower()
  256. @pytest.mark.asyncio
  257. async def test_perform_update_runs_pip_in_app_dir_not_data_dir(self, tmp_path):
  258. """Native install: `requirements.txt` lives at INSTALL_PATH (the source-
  259. code dir), NOT at DATA_DIR (where systemd sets DATA_DIR=INSTALL_PATH/data).
  260. Pre-fix, the updater ran `pip install -r requirements.txt` with
  261. `cwd=settings.base_dir`, which on a native install resolves to the data
  262. dir — `requirements.txt` isn't there and pip fails with `Could not open
  263. requirements file`. The fix: pip's cwd is `settings.app_dir` (the source
  264. tree) so it can actually find the file.
  265. This test mocks every subprocess so it can capture the cwd of each call
  266. and assert that the pip step runs in app_dir while git steps continue
  267. to run in base_dir (their existing behaviour — git walks up to find
  268. `.git` so that path keeps working)."""
  269. from backend.app.api.routes import updates as updates_module
  270. # Set up fake install layout: app_dir has requirements.txt, data_dir is
  271. # a sibling (mirroring `INSTALL_PATH=/opt/bambuddy`, `DATA_DIR=/opt/bambuddy/data`).
  272. app_dir = tmp_path / "app"
  273. data_dir = tmp_path / "app" / "data"
  274. app_dir.mkdir()
  275. data_dir.mkdir()
  276. (app_dir / "requirements.txt").write_text("fastapi\n")
  277. # Capture every subprocess call's cwd + the executable token.
  278. calls: list[dict] = []
  279. async def fake_create_subprocess_exec(*args, **kwargs):
  280. calls.append({"args": args, "cwd": kwargs.get("cwd")})
  281. proc = MagicMock()
  282. proc.communicate = AsyncMock(return_value=(b"", b""))
  283. proc.returncode = 0
  284. return proc
  285. with (
  286. patch.object(updates_module.settings, "base_dir", data_dir),
  287. patch.object(updates_module.settings, "app_dir", app_dir),
  288. patch.object(updates_module, "_find_executable", return_value="/usr/bin/git"),
  289. patch.object(
  290. updates_module.asyncio,
  291. "create_subprocess_exec",
  292. side_effect=fake_create_subprocess_exec,
  293. ),
  294. ):
  295. await updates_module._perform_update("v0.2.4b1")
  296. # Find the pip invocation (sys.executable + "-m" + "pip" + "install").
  297. pip_calls = [c for c in calls if "pip" in c["args"] and "install" in c["args"]]
  298. assert pip_calls, "pip install was never invoked. Captured: " + repr([c["args"] for c in calls])
  299. pip_cwd = pip_calls[0]["cwd"]
  300. assert pip_cwd == str(app_dir), (
  301. f"pip install must run in app_dir ({app_dir}) so it finds "
  302. f"requirements.txt; got cwd={pip_cwd}. Regression to base_dir "
  303. f"breaks every native-install upgrade."
  304. )
  305. # Sanity check: the requirements.txt that pip would read actually exists
  306. # at the captured cwd. If this fails the cwd is wrong even if it isn't
  307. # base_dir — useful diagnostic if someone refactors path handling.
  308. assert (Path(pip_cwd) / "requirements.txt").exists()