Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
11.4 KB
Raw Blame
"""App self-update check (engine/updates.py, api/settings.py) and the bundled
capture-extension version Settings compares against the installed one.

Nothing here touches the network: GitHub's releases feed is faked, and the
opt-in gate (``?check=true``) is asserted by making the fake explode when it
shouldn't be reached."""

from __future__ import annotations

from pathlib import Path

import httpx
import pytest

from azimut import __version__, config
from azimut.engine import extinstall, updates


class FakeResponse:
    def __init__(self, payload):
        self._payload = payload

    def raise_for_status(self):
        return None

    def json(self):
        return self._payload


# -- version comparison ---------------------------------------------------


@pytest.mark.parametrize(
    "latest,current,expected",
    [
        ("v0.2.0", "0.1.1", True),
        ("v0.1.2", "0.1.1", True),
        ("v0.1.1", "0.1.1", False),
        ("v0.1.0", "0.1.1", False),
        ("0.1.10", "0.1.9", True),  # numeric, not lexical
        ("v0.2.0rc1", "0.1.9", True),  # pre-release suffix ignored
    ],
)
def test_is_newer(latest, current, expected):
    assert updates.is_newer(latest, current) is expected


# -- updates.check --------------------------------------------------------


def test_check_reports_a_newer_release(monkeypatch):
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "html_url": "https://x/rel"}),
    )
    result = updates.check("0.1.1")
    assert result == {
        "current": "0.1.1",
        "latest": "v9.9.9",
        "update_available": True,
        "url": "https://x/rel",
        "notes": "",
        "asset": None,
        "download_url": None,
    }


def test_check_carries_release_notes_capped(monkeypatch):
    body = "  ## What's new\n- stuff\n" + "".join(f"- entry {i}\n" for i in range(900))
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "body": body}),
    )
    result = updates.check("0.1.1")
    notes = result["notes"]
    assert notes.startswith("## What's new")  # stripped
    assert len(notes) <= updates.NOTES_LIMIT  # capped
    # cut on a line boundary, so the pop-up never renders half a line
    assert notes.splitlines()[-1] in body.splitlines()


def test_check_caps_a_release_note_with_no_line_break(monkeypatch):
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "body": "x" * 9000}),
    )
    assert len(updates.check("0.1.1")["notes"]) == updates.NOTES_LIMIT


def test_check_up_to_date(monkeypatch):
    monkeypatch.setattr(
        updates.httpx, "get", lambda *a, **k: FakeResponse({"tag_name": "v0.1.1"})
    )
    result = updates.check("0.1.1")
    assert result["update_available"] is False
    assert result["latest"] == "v0.1.1"


def test_check_never_raises_on_network_error(monkeypatch):
    def boom(*a, **k):
        raise httpx.ConnectError("offline")

    monkeypatch.setattr(updates.httpx, "get", boom)
    result = updates.check("0.1.1")
    assert result["update_available"] is False
    assert "offline" in result["error"]


# -- the binary for this machine ------------------------------------------

RELEASE_ASSETS = [
    {"name": "azimut-linux-x86_64"},
    {"name": "azimut-windows-x86_64.exe"},
    {"name": "azimut-macos-arm64"},
    {"name": "azimut-0.3.4-py3-none-any.whl"},
]


@pytest.mark.parametrize(
    "system,machine,expected",
    [
        ("linux", "x86_64", "azimut-linux-x86_64"),
        ("windows", "AMD64", "azimut-windows-x86_64.exe"),
        ("macos", "arm64", "azimut-macos-arm64"),
        ("linux", "aarch64", None),  # no ARM Linux build
        ("macos", "x86_64", None),  # no Intel Mac build
        ("freebsd14", "amd64", None),
    ],
)
def test_asset_name_matches_what_the_release_attaches(system, machine, expected):
    assert updates.asset_name(system, machine) == expected


def test_every_asset_is_one_the_release_workflow_builds():
    workflow = (Path(__file__).resolve().parents[1] / ".github/workflows/release.yml").read_text()
    for asset in updates.ASSETS.values():
        assert f"asset: {asset}" in workflow


def test_check_links_straight_to_this_machines_binary(monkeypatch):
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v0.3.4", "assets": RELEASE_ASSETS}),
    )
    result = updates.check("0.3.3", asset="azimut-windows-x86_64.exe")
    assert result["asset"] == "azimut-windows-x86_64.exe"
    assert result["download_url"] == (
        "https://github.com/OsintMeThat/azimut/releases/download/v0.3.4/azimut-windows-x86_64.exe"
    )


def test_check_offers_no_download_the_release_does_not_carry(monkeypatch):
    # a release still uploading its binaries, or a machine with no build
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v0.3.4", "assets": RELEASE_ASSETS[1:]}),
    )
    assert updates.check("0.3.3", asset="azimut-linux-x86_64")["download_url"] is None
    assert updates.check("0.3.3", asset=None)["download_url"] is None


def test_check_never_links_outside_the_repository(monkeypatch):
    # the response's own download URL is ignored; the link is built from ours
    assets = [{"name": "azimut-linux-x86_64", "browser_download_url": "https://evil.invalid/x"}]
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v0.3.4/../x", "assets": assets}),
    )
    url = updates.check("0.3.3", asset="azimut-linux-x86_64")["download_url"]
    assert url.startswith("https://github.com/OsintMeThat/azimut/releases/download/")
    assert "/../" not in url and "evil" not in url


def test_a_frozen_binary_names_the_file_to_replace(monkeypatch, tmp_path):
    program = tmp_path / "azimut-linux-x86_64"
    monkeypatch.setattr(updates.sys, "frozen", True, raising=False)
    monkeypatch.setattr(updates.sys, "executable", str(program))
    info = updates.install()
    assert info["kind"] == "binary"
    assert info["program"] == str(program.resolve())


def test_a_pip_install_has_no_file_to_replace(monkeypatch):
    monkeypatch.delattr(updates.sys, "frozen", raising=False)
    assert updates.install() == {"kind": "package", "system": updates.system(), "program": None}


# -- endpoint (opt-in, local-first) ---------------------------------------


def test_update_endpoint_without_check_touches_no_network(client, monkeypatch):
    def boom(*a, **k):
        raise AssertionError("must not reach the network without ?check=true")

    monkeypatch.setattr(updates.httpx, "get", boom)
    body = client.get("/api/settings/update").json()
    install = body.pop("install")
    assert body == {"current": __version__, "latest": None, "update_available": False}
    assert install["kind"] == "package"  # the test run is not a frozen binary
    assert install["workspace"] == str(config.workspace_root())


def test_update_endpoint_with_check_queries_github(client, monkeypatch):
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "html_url": "https://x/rel"}),
    )
    body = client.get("/api/settings/update?check=true").json()
    assert body["update_available"] is True
    assert body["latest"] == "v9.9.9"
    assert body["download_url"] is None  # a pip install updates with pipx


def test_update_endpoint_links_a_binary_to_its_download(client, monkeypatch, tmp_path):
    monkeypatch.setattr(updates.sys, "frozen", True, raising=False)
    monkeypatch.setattr(updates.sys, "executable", str(tmp_path / "azimut.exe"))
    monkeypatch.setattr(updates, "system", lambda: "windows")
    monkeypatch.setattr(updates.platform, "machine", lambda: "AMD64")
    monkeypatch.setattr(
        updates.httpx,
        "get",
        lambda *a, **k: FakeResponse({"tag_name": "v0.3.4", "assets": RELEASE_ASSETS}),
    )
    body = client.get("/api/settings/update?check=true").json()
    assert body["download_url"].endswith("/v0.3.4/azimut-windows-x86_64.exe")
    assert body["install"]["kind"] == "binary"
    assert body["install"]["system"] == "windows"
    assert body["install"]["program"] == str((tmp_path / "azimut.exe").resolve())


# -- bundled extension version --------------------------------------------

# The extension carries the Azimut version whose release last changed it, not
# the current one. Settings turns "bundled > installed" into "replace the
# unpacked folder and reload", so bumping this in lock-step with __version__
# would send every user through a reinstall for a byte-identical zip.
#
# The pair below is the contract, and it moves in one direction only: when a
# shipped file really changes, set the manifest to the current __version__ and
# record the new digest here (the failing test prints it).
EXTENSION_VERSION = "0.3.3"
EXTENSION_PAYLOAD = "0c9a5041432d7045d8e41b6a0881dde2a404bb65869efc43fd4298a4769b92c0"

# The digest itself lives in engine/extinstall.py, because the update button
# compares the same number: what the app ships against what the installed folder
# was written from. One definition, so the gate and the button cannot disagree.
# The constants above are what makes it a gate.


def test_the_shipped_listing_reads_the_same_on_every_platform():
    """The digest above folds the names in order, so the order is part of the gate.

    Sorting `Path` objects would not do: comparing them is case-insensitive on
    Windows and case-sensitive everywhere else, which puts `README.md` first on
    Linux and mid-list on Windows — three CI platforms disagreeing about one
    unchanged extension. Sorted by the posix name instead, which is the same
    string on all three.
    """
    src = extinstall.source_dir()
    assert src is not None
    names = [name for name, _ in extinstall.shipped_files(src)]
    assert names == sorted(names)
    assert all("\\" not in name for name in names)


def test_the_extension_version_moves_only_when_the_extension_does():
    """Both halves of the drift, in one gate.

    A shipped file changed without a version bump: the installed extension and
    the bundled one report the same version while differing, so Settings stays
    quiet and the user keeps running a stale bridge. A version bump with no
    change: everyone is told to reinstall the zip they already have, and a nag
    that cries wolf is a nag nobody reads."""
    digest = extinstall.payload_digest()
    version = extinstall.bundled_version()

    assert digest == EXTENSION_PAYLOAD, (
        f"the shipped extension changed. Set extension/manifest.json to the current "
        f'__version__ ({__version__}) and record EXTENSION_VERSION = "{__version__}", '
        f'EXTENSION_PAYLOAD = "{digest}" here.'
    )
    assert version == EXTENSION_VERSION, (
        f"the extension is unchanged but its version moved to {version}. Put "
        f"extension/manifest.json back to {EXTENSION_VERSION} — a bump users can't "
        f"see is a reinstall prompt they don't need."
    )


def test_the_bundled_extension_is_never_ahead_of_the_app():
    """It is stamped with the Azimut version that shipped it, so it can lag by
    several releases but never lead — a version no release ever carried would
    make the Settings comparison meaningless."""
    assert not updates.is_newer(EXTENSION_VERSION, __version__)


def test_settings_reports_extension_version(client):
    body = client.get("/api/settings").json()
    assert body["extension_version"] == EXTENSION_VERSION