diff --git a/python/src/camoufox/addons.py b/python/src/camoufox/addons.py index 32f36bbe..acd874cc 100644 --- a/python/src/camoufox/addons.py +++ b/python/src/camoufox/addons.py @@ -1,7 +1,8 @@ import os import shutil +import tempfile from enum import Enum -from multiprocessing import Lock +from threading import Lock from typing import List, Optional from .exceptions import InvalidAddonPath @@ -10,6 +11,11 @@ from .pkgman import INSTALL_DIR, unzip, webdl # Addons are stored in a shared folder, not per-browser version ADDONS_DIR = INSTALL_DIR / "addons" +# One lock for the module: `with Lock():` on a fresh multiprocessing.Lock per call +# guarded nothing, so concurrent launches in one process raced the same +# check-then-extract (rubenvereecken/camoufox ec08bf9). +_EXTRACT_LOCK = Lock() + class DefaultAddons(Enum): """ @@ -44,17 +50,27 @@ def add_default_addons( addons = [addon for addon in DefaultAddons if addon not in exclude_list] - with Lock(): + with _EXTRACT_LOCK: maybe_download_addons(addons, addons_list) def download_and_extract(url: str, extract_path: str, name: str) -> None: """ - Downloads and extracts an addon from a given URL to a specified path + Downloads and extracts an addon from a given URL to a specified path. + + Extracts into a sibling temp dir and renames it into place last, so a + concurrent launch (another process, which the lock cannot see) never finds + a manifest.json in a directory whose other files are still being written. """ - # Create a temporary file to store the downloaded zip buffer = webdl(url, desc=f"Downloading addon ({name})", bar=False) - unzip(buffer, extract_path, f"Extracting addon ({name})", bar=False) + parent = os.path.dirname(extract_path) + tmp_dir = tempfile.mkdtemp(prefix=f".{name}.tmp-", dir=parent) + try: + unzip(buffer, tmp_dir, f"Extracting addon ({name})", bar=False) + shutil.rmtree(extract_path, ignore_errors=True) + os.replace(tmp_dir, extract_path) + finally: + shutil.rmtree(tmp_dir, ignore_errors=True) def get_addon_path(addon_name: str) -> str: diff --git a/python/tests/test_addons.py b/python/tests/test_addons.py index d448e899..91ed8a1c 100644 --- a/python/tests/test_addons.py +++ b/python/tests/test_addons.py @@ -12,11 +12,13 @@ Run with: """ import os +import threading +import time import pytest from camoufox import addons as addons_mod -from camoufox.addons import DefaultAddons, maybe_download_addons +from camoufox.addons import DefaultAddons, add_default_addons, maybe_download_addons UBO = DefaultAddons.UBO.name @@ -89,3 +91,50 @@ def test_failed_download_removes_partial_dir(addons_dir, monkeypatch): # trusting an addon that has no manifest.json. assert not path.exists() assert out == [] + + +def test_concurrent_launches_download_once(addons_dir, monkeypatch): + # Two launches in one process share the check-then-extract. A lock created + # per call guarded nothing, so both saw no manifest and both downloaded. + calls = [] + + def slow(url, extract_path, name): + calls.append(name) + time.sleep(0.2) + _write_manifest(url, extract_path, name) + + monkeypatch.setattr(addons_mod, "download_and_extract", slow) + + outs = [[], []] + threads = [threading.Thread(target=add_default_addons, args=(out,)) for out in outs] + for t in threads: + t.start() + for t in threads: + t.join() + + assert calls == [UBO] + assert outs == [[str(addons_dir / UBO)]] * 2 + + +def test_extraction_appears_complete_or_not_at_all(tmp_path, monkeypatch): + # Another process checks for manifest.json without the lock, so the addon + # directory must never hold a manifest while its other files are missing. + target = tmp_path / UBO + target.mkdir() + seen = [] + + def fake_unzip(buffer, extract_path, desc=None, bar=True): + seen.append((target / "manifest.json").exists()) + _write_manifest(None, extract_path, UBO) + with open(os.path.join(extract_path, "background.js"), "w") as f: + f.write("") + seen.append((target / "manifest.json").exists()) + + monkeypatch.setattr(addons_mod, "webdl", lambda *a, **k: b"") + monkeypatch.setattr(addons_mod, "unzip", fake_unzip) + + addons_mod.download_and_extract("url", str(target), UBO) + + assert seen == [False, False] + assert sorted(os.listdir(target)) == ["background.js", "manifest.json"] + assert os.listdir(tmp_path) == [UBO] diff --git a/typescript/src/addons.ts b/typescript/src/addons.ts index 15cd2740..64d9783b 100644 --- a/typescript/src/addons.ts +++ b/typescript/src/addons.ts @@ -21,6 +21,10 @@ export type DefaultAddon = keyof typeof DefaultAddons; // Addons are stored in a shared folder, not per-browser version const ADDONS_DIR: string = path.join(INSTALL_DIR, "addons"); +// One chain for the module: concurrent launches in one process would otherwise +// interleave the same check-then-extract at its awaits. +let extractChain: Promise = Promise.resolve(); + /** * Confirms that the addon paths are valid. */ @@ -50,11 +54,17 @@ export async function addDefaultAddons( addons[name] = url; } } - await maybeDownloadAddons(addons, addonsList); + const run = extractChain.then(() => maybeDownloadAddons(addons, addonsList)); + extractChain = run.catch(() => undefined); + await run; } /** * Downloads and extracts an addon from a given URL to a specified path. + * + * Extracts into a sibling temp dir and renames it into place last, so a + * concurrent launch (another process, which the chain cannot see) never finds + * a manifest.json in a directory whose other files are still being written. */ export async function downloadAndExtract( url: string, @@ -62,7 +72,16 @@ export async function downloadAndExtract( name: string, ): Promise { const buffer = await webdl(url, `Downloading addon (${name})`, false); - unzip(buffer, extractPath, `Extracting addon (${name})`, false); + const tmpDir = fs.mkdtempSync( + path.join(path.dirname(extractPath), `.${name}.tmp-`), + ); + try { + unzip(buffer, tmpDir, `Extracting addon (${name})`, false); + fs.rmSync(extractPath, { recursive: true, force: true }); + fs.renameSync(tmpDir, extractPath); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } } /** diff --git a/typescript/tests/addons.test.ts b/typescript/tests/addons.test.ts index 3d23746c..acd1d9ed 100644 --- a/typescript/tests/addons.test.ts +++ b/typescript/tests/addons.test.ts @@ -81,3 +81,20 @@ it("removes the partial directory when a download fails", async () => { ); log.mockRestore(); }); + +it("downloads once for concurrent launches", async () => { + // Two launches in one process share the check-then-extract; unserialized, + // both saw no manifest at the await and both downloaded. + const calls: string[] = []; + addons.addonsDeps.downloadAndExtract = async (_url, extractPath, name) => { + calls.push(name); + await new Promise((resolve) => setTimeout(resolve, 50)); + writeManifest(extractPath); + }; + + const outs: string[][] = [[], []]; + await Promise.all(outs.map((out) => addons.addDefaultAddons(out))); + + expect(calls).toEqual(["UBO"]); + expect(outs).toEqual([[ubo], [ubo]]); +});