diff --git a/roles/dsk-gnt-cursor/meta/packages.yml b/roles/dsk-gnt-cursor/meta/packages.yml index 3a2011f4d8..f64756824d 100644 --- a/roles/dsk-gnt-cursor/meta/packages.yml +++ b/roles/dsk-gnt-cursor/meta/packages.yml @@ -4,5 +4,17 @@ cursor: source: aur names: - cursor-bin - Debian: [] # nocheck: empty - Cursor ships only as a vendor AppImage and deb outside any Debian or Ubuntu archive; TODO: install the vendor build through a build source once its signature is pinned - RedHat: [] # nocheck: empty - Cursor ships no rpm and is carried by neither Fedora nor EPEL; TODO: install the vendor AppImage through a build source once its signature is pinned + Debian: + source: download + names: + - cursor + download: + url: https://downloads.cursor.com/production/f7119520544accb8dcf6d27119b9f1963d8ee5ae/linux/x64/deb/amd64/deb/cursor_3.27.6_amd64.deb + checksum: sha256:cf5f443556a5ac5cbf308eeae8f33e44ea34e5421a6910b1c34f977c2541e67f + RedHat: + source: download + names: + - cursor + download: + url: https://downloads.cursor.com/production/f7119520544accb8dcf6d27119b9f1963d8ee5ae/linux/x64/rpm/x86_64/cursor-3.27.6.el8.x86_64.rpm + checksum: sha256:f06d4f18f16a843fb94f9124692745857bc2e52ae8d33f26491fbf81b4072d02 diff --git a/tests/lint/repository/test_packages_plans.py b/tests/lint/repository/test_packages_plans.py index 302e814401..b1d0366bbe 100644 --- a/tests/lint/repository/test_packages_plans.py +++ b/tests/lint/repository/test_packages_plans.py @@ -20,9 +20,11 @@ from . import PROJECT_ROOT ALLOWED_MODULES: frozenset[str] = frozenset( { + "ansible.builtin.apt", "ansible.builtin.command", "ansible.builtin.dnf", "ansible.builtin.file", + "ansible.builtin.get_url", "ansible.builtin.lineinfile", "ansible.builtin.package", "ansible.builtin.replace", diff --git a/tests/unit/python/utils/packages/test_plan.py b/tests/unit/python/utils/packages/test_plan.py index cbb0c50b2b..9987640239 100644 --- a/tests/unit/python/utils/packages/test_plan.py +++ b/tests/unit/python/utils/packages/test_plan.py @@ -7,16 +7,27 @@ from utils.packages.schema import ( SOURCE_AUR, SOURCE_BUILD, SOURCE_COPR, + SOURCE_DOWNLOAD, SOURCE_FLATPAK, PackageSpec, ) from utils.packages.sources import ( AUR_BUILDER_USER, + DOWNLOAD_CACHE_DIR, FLATPAK_COMMAND_DIR, FLATPAK_EXPORT_DIR, PACMAN_CONF, ) +_DEB = { + "url": "https://vendor.example/pool/editor_1.2.3_amd64.deb", + "checksum": "sha256:" + "a" * 64, +} +_RPM = { + "url": "https://vendor.example/pool/editor-1.2.3.el8.x86_64.rpm", + "checksum": "sha256:" + "b" * 64, +} + class TestExternalFetchRetries(unittest.TestCase): """Every call that fetches over the network carries a retry policy, the @@ -200,6 +211,97 @@ class TestBuildPlan(unittest.TestCase): ) +class TestDownloadSource(unittest.TestCase): + """A vendor artefact is fetched against its pin and installed from disk, + so what the package manager receives is the file the registry describes.""" + + def test_the_deb_is_fetched_with_its_checksum_then_installed(self): + plan = build_plan( + PackageSpec(("editor",), source=SOURCE_DOWNLOAD, download=_DEB), + STATE_PRESENT, + ) + self.assertEqual( + _modules(plan), + [ + "ansible.builtin.file", + "ansible.builtin.get_url", + "ansible.builtin.apt", + "ansible.builtin.package", + ], + ) + cache, fetch, install, confirm = plan + self.assertEqual(cache.args["path"], DOWNLOAD_CACHE_DIR) + self.assertEqual(cache.args["owner"], "root") + self.assertEqual(confirm.args["name"], ["editor"]) + self.assertEqual(fetch.args["url"], _DEB["url"]) + self.assertEqual(fetch.args["checksum"], _DEB["checksum"]) + self.assertEqual( + fetch.args["dest"], f"{DOWNLOAD_CACHE_DIR}/editor_1.2.3_amd64.deb" + ) + self.assertEqual(install.args["deb"], fetch.args["dest"]) + + def test_the_rpm_is_installed_from_the_fetched_path(self): + plan = build_plan( + PackageSpec(("editor",), source=SOURCE_DOWNLOAD, download=_RPM), + STATE_PRESENT, + ) + self.assertEqual( + _modules(plan), + [ + "ansible.builtin.file", + "ansible.builtin.get_url", + "ansible.builtin.dnf", + "ansible.builtin.package", + ], + ) + _cache, fetch, install, confirm = plan + self.assertEqual(install.args["name"], [fetch.args["dest"]]) + self.assertEqual(install.args["state"], STATE_PRESENT) + self.assertEqual(confirm.args["name"], ["editor"]) + + def test_an_unsupported_artefact_is_refused(self): + spec = PackageSpec( + ("editor",), + source=SOURCE_DOWNLOAD, + download={"url": "https://vendor.example/editor.AppImage", "checksum": "x"}, + ) + with self.assertRaises(ValueError) as caught: + build_plan(spec, STATE_PRESENT) + self.assertIn(".AppImage", str(caught.exception)) + + def test_a_query_string_does_not_hide_the_artefact_type(self): + spec = PackageSpec( + ("editor",), + source=SOURCE_DOWNLOAD, + download={**_DEB, "url": _DEB["url"] + "?token=abc"}, + ) + plan = build_plan(spec, STATE_PRESENT) + self.assertEqual(plan[2].module, "ansible.builtin.apt") + self.assertEqual( + plan[1].args["dest"], f"{DOWNLOAD_CACHE_DIR}/editor_1.2.3_amd64.deb" + ) + + def test_the_source_without_its_block_is_refused(self): + spec = PackageSpec(("editor",), source=SOURCE_DOWNLOAD) + with self.assertRaises(ValueError): + build_plan(spec, STATE_PRESENT) + + def test_the_fetch_is_retried(self): + plan = build_plan( + PackageSpec(("editor",), source=SOURCE_DOWNLOAD, download=_DEB), + STATE_PRESENT, + ) + self.assertIsNotNone(plan[1].retry) + + def test_removal_goes_through_the_host_manager(self): + plan = build_plan( + PackageSpec(("editor",), source=SOURCE_DOWNLOAD, download=_DEB), + STATE_ABSENT, + ) + self.assertEqual(_modules(plan), ["ansible.builtin.package"]) + self.assertEqual(plan[0].args["name"], ["editor"]) + + class TestFlatpakSource(unittest.TestCase): """A Flatpak id is installed from a remote and exposed under the name the role actually invokes.""" diff --git a/tests/unit/python/utils/packages/test_registry.py b/tests/unit/python/utils/packages/test_registry.py index cc631a1300..3b232049be 100644 --- a/tests/unit/python/utils/packages/test_registry.py +++ b/tests/unit/python/utils/packages/test_registry.py @@ -165,6 +165,95 @@ class TestRegistry(unittest.TestCase): with self.assertRaises(PackagesShapeError): resolve(self._declaration("git"), "debian") + def test_download_without_a_checksum_raises(self): + _write_role( + self.root, + "role-a", + { + "editor": { + "Debian": { + "names": ["editor"], + "source": "download", + "download": {"url": "https://vendor.example/editor.deb"}, + } + } + }, + ) + with self.assertRaises(PackagesShapeError) as ctx: + resolve(self._declaration("editor"), "debian") + self.assertIn("checksum", str(ctx.exception)) + + def test_download_rejects_a_weak_digest(self): + _write_role( + self.root, + "role-a", + { + "editor": { + "Debian": { + "names": ["editor"], + "source": "download", + "download": { + "url": "https://vendor.example/editor.deb", + "checksum": "md5:" + "a" * 32, + }, + } + } + }, + ) + with self.assertRaises(PackagesShapeError): + resolve(self._declaration("editor"), "debian") + + def test_download_rejects_a_plaintext_url(self): + _write_role( + self.root, + "role-a", + { + "editor": { + "Debian": { + "names": ["editor"], + "source": "download", + "download": { + "url": "http://vendor.example/editor.deb", + "checksum": "sha256:" + "a" * 64, + }, + } + } + }, + ) + with self.assertRaises(PackagesShapeError) as ctx: + resolve(self._declaration("editor"), "debian") + self.assertIn("https", str(ctx.exception)) + + def test_download_source_without_its_block_raises(self): + _write_role( + self.root, + "role-a", + {"editor": {"Debian": {"names": ["editor"], "source": "download"}}}, + ) + with self.assertRaises(PackagesShapeError): + resolve(self._declaration("editor"), "debian") + + def test_a_pinned_download_resolves(self): + _write_role( + self.root, + "role-a", + { + "editor": { + "Debian": { + "names": ["editor"], + "source": "download", + "download": { + "url": "https://vendor.example/editor.deb", + "checksum": "sha256:" + "a" * 64, + }, + } + } + }, + ) + spec = resolve(self._declaration("editor"), "debian") + self.assertEqual(spec.source, "download") + self.assertEqual(spec.download["url"], "https://vendor.example/editor.deb") + def test_unknown_distro_raises_without_family(self): _write_role(self.root, "role-a", {"git": {"Debian": ["git"]}}) with self.assertRaises(PackagesShapeError): diff --git a/utils/packages/plan.py b/utils/packages/plan.py index a0a1a564ec..cbc9eb3391 100644 --- a/utils/packages/plan.py +++ b/utils/packages/plan.py @@ -3,7 +3,7 @@ Turns a resolved :class:`~utils.packages.registry.PackageSpec` into the ordered module calls that acquire it. Keeping this pure means every acquisition path - distribution repository, AUR, COPR, PPA, source build, -Flatpak remote - is unit-testable without an Ansible connection; the action +pinned vendor download, Flatpak remote - is unit-testable without an Ansible connection; the action plugin only executes what it is handed. """ @@ -19,6 +19,7 @@ from utils.packages.schema import ( SOURCE_AUR, SOURCE_BUILD, SOURCE_COPR, + SOURCE_DOWNLOAD, SOURCE_FLATPAK, SOURCE_PPA, PackageSpec, @@ -26,6 +27,7 @@ from utils.packages.schema import ( from utils.packages.sources import ( aur_calls, build_calls, + download_calls, flatpak_calls, repository_calls, ) @@ -48,6 +50,11 @@ def build_plan(spec: PackageSpec, state: str) -> list[ModuleCall]: raise ValueError("source 'build' requires a 'build' block") return build_calls(spec.build) + if spec.source == SOURCE_DOWNLOAD: + if not spec.download: + raise ValueError("source 'download' requires a 'download' block") + return download_calls(names, spec.download) + if spec.source == SOURCE_FLATPAK: return flatpak_calls(names, spec.flatpak) diff --git a/utils/packages/schema.py b/utils/packages/schema.py index ecfd5ee400..ec8e782cff 100644 --- a/utils/packages/schema.py +++ b/utils/packages/schema.py @@ -48,6 +48,22 @@ pulls them from a Flatpak remote:: named after the application id, not after the binary inside it, so without this key a role calling ``blender`` finds nothing on PATH. +``source: download`` fetches one vendor artefact and installs it locally, +for a vendor that publishes a ``.deb`` or ``.rpm`` but runs no repository:: + + cursor: + Debian: + source: download + names: [cursor] + download: + url: https://downloads.cursor.com/.../cursor_3.27.6_amd64.deb + checksum: sha256:cf5f44... + +``names`` is what the artefact installs as, so removal still goes through +the package manager. ``checksum`` is mandatory: the URL alone would install +whatever the vendor serves today, and a mismatch must abort the fetch +rather than reach the package manager. + A bare list is shorthand for ``{names: [...], source: repo}``. An empty list states that the package is deliberately not installed on that family, which counts as covered; a *missing* key is a coverage gap. @@ -76,6 +92,7 @@ SOURCE_AUR = "aur" SOURCE_COPR = "copr" SOURCE_PPA = "ppa" SOURCE_BUILD = "build" +SOURCE_DOWNLOAD = "download" SOURCE_FLATPAK = "flatpak" SOURCES: tuple[str, ...] = ( SOURCE_REPO, @@ -83,14 +100,20 @@ SOURCES: tuple[str, ...] = ( SOURCE_COPR, SOURCE_PPA, SOURCE_BUILD, + SOURCE_DOWNLOAD, SOURCE_FLATPAK, ) """How the names are acquired. ``repo`` is the distribution's own package manager; ``aur``, ``copr`` and ``ppa`` are the community managers Arch, Fedora and Ubuntu ship alongside it; ``build`` compiles from source where -no manager carries the package at all; ``flatpak`` installs an application -id from a Flatpak remote, which is the only upstream channel for much of -the desktop set on EL.""" +no manager carries the package at all; ``download`` installs a checksum- +pinned vendor artefact where the vendor publishes a package file but no +repository; ``flatpak`` installs an application id from a Flatpak remote, +which is the only upstream channel for much of the desktop set on EL.""" + +DOWNLOAD_CHECKSUM_PREFIXES: tuple[str, ...] = ("sha256:", "sha512:") +"""Digest algorithms strong enough to pin a vendor artefact. ``get_url`` +also accepts md5 and sha1, which a prefix check must keep out.""" REPO_KEYS: frozenset[str] = frozenset( { @@ -126,6 +149,7 @@ class PackageSpec: virtual: bool = False build: dict[str, Any] | None = None flatpak: dict[str, Any] | None = None + download: dict[str, Any] | None = None def _validate_repo(package_id: str, key: str, repo: Any, path: Path) -> None: @@ -153,6 +177,42 @@ def _validate_build( ) +def _validate_download( + package_id: str, key: str, source: str, download: Any, path: Path +) -> None: + if download is None: + if source == SOURCE_DOWNLOAD: + raise PackagesShapeError( + f"{path}: {package_id}.{key} declares source " + f"'{SOURCE_DOWNLOAD}' but no download block." + ) + return + if source != SOURCE_DOWNLOAD: + raise PackagesShapeError( + f"{path}: {package_id}.{key} declares a download block without " + f"source '{SOURCE_DOWNLOAD}'." + ) + if not isinstance(download, dict): + raise PackagesShapeError( + f"{path}: {package_id}.{key}.download must be a mapping, " + f"got {type(download).__name__}." + ) + url = download.get("url") + if not isinstance(url, str) or not url.startswith("https://"): + raise PackagesShapeError( + f"{path}: {package_id}.{key}.download.url must be an https URL." + ) + checksum = download.get("checksum") + if not isinstance(checksum, str) or not checksum.startswith( + DOWNLOAD_CHECKSUM_PREFIXES + ): + raise PackagesShapeError( + f"{path}: {package_id}.{key}.download.checksum must be one of " + f"{sorted(DOWNLOAD_CHECKSUM_PREFIXES)} followed by the digest; " + "without it the URL installs whatever the vendor serves today." + ) + + def _validate_flatpak( package_id: str, key: str, source: str, flatpak: Any, path: Path ) -> None: @@ -210,7 +270,12 @@ def normalize_entry(package_id: str, key: str, value: Any, path: Path) -> Packag build = value.get("build") _validate_build(package_id, key, source, build, path) + download = value.get("download") + _validate_download(package_id, key, source, download, path) + flatpak = value.get("flatpak") _validate_flatpak(package_id, key, source, flatpak, path) - return PackageSpec(tuple(names), str(source), repo, virtual, build, flatpak) + return PackageSpec( + tuple(names), str(source), repo, virtual, build, flatpak, download + ) diff --git a/utils/packages/sources.py b/utils/packages/sources.py index 20c4da72e9..d23b58d9c7 100644 --- a/utils/packages/sources.py +++ b/utils/packages/sources.py @@ -7,7 +7,9 @@ about the others. from __future__ import annotations +from pathlib import PurePosixPath from typing import Any +from urllib.parse import urlsplit from utils.packages.calls import ( AUR_FETCH, @@ -26,6 +28,14 @@ AUR_MAKEPKG_ARGS = "--skipinteg" source, which makepkg can only reject; integrity rests on the pinned upstream tag fetched over HTTPS.""" +DOWNLOAD_CACHE_DIR = "/var/cache/infinito/packages" +"""Where a pinned vendor artefact is kept: root-owned, so no other local +account can pre-create the path between the checksum check and the +install, and persistent, so a rerun matches the cached file and skips the +transfer.""" + +DOWNLOAD_CACHE_MODE = "0755" + FLATPAK_PACKAGE = "flatpak" FLATPAK_METHOD = "system" FLATPAK_EXPORT_DIR = "/var/lib/flatpak/exports/bin" @@ -78,6 +88,71 @@ def build_calls(build: dict[str, Any]) -> list[ModuleCall]: ] +def download_calls(names: list[str], download: dict[str, Any]) -> list[ModuleCall]: + """Fetch the pinned vendor artefact, install it, confirm what it gave. + + The cache directory is created first and owned by root, because a + world-writable one lets another account swap the file between the + checksum check and the install. + + ``get_url`` compares the checksum before and after the transfer, so a + file the vendor has replaced fails the task instead of reaching the + package manager, and a cached file that still matches is not refetched. + + The closing call names the declared packages. They are installed by + then, so it reaches no repository; it fails loudly when the artefact + registered under some other name, which would leave ``state: absent`` + with nothing to remove. + + Raises: + ValueError: the URL names neither a ``.deb`` nor an ``.rpm``, which + are the only artefacts a local install here can hand over. + """ + url = str(download["url"]) + artefact = PurePosixPath(urlsplit(url).path) + dest = f"{DOWNLOAD_CACHE_DIR}/{artefact.name}" + + if artefact.suffix == ".deb": + install = ModuleCall("ansible.builtin.apt", {"deb": dest}) + elif artefact.suffix == ".rpm": + install = ModuleCall( + "ansible.builtin.dnf", + # A vendor that runs no repository ships no signing key either, so + # dnf would reject every such rpm; the checksum is the control. + {"name": [dest], "state": STATE_PRESENT, "disable_gpg_check": True}, + ) + else: + raise ValueError( + f"download source cannot install a '{artefact.suffix}' artefact; " + "expected '.deb' or '.rpm'" + ) + + return [ + ModuleCall( + "ansible.builtin.file", + { + "path": DOWNLOAD_CACHE_DIR, + "state": "directory", + "owner": "root", + "group": "root", + "mode": DOWNLOAD_CACHE_MODE, + }, + ), + ModuleCall( + "ansible.builtin.get_url", + { + "url": url, + "dest": dest, + "checksum": download["checksum"], + "mode": "0644", + }, + retry=EXTERNAL_FETCH, + ), + install, + package_call(names, STATE_PRESENT), + ] + + def flatpak_calls(names: list[str], flatpak: dict[str, Any] | None) -> list[ModuleCall]: """Bring up the Flatpak runtime and remote, install the ids, expose them.