From dc5128794ab8cb787c4083e779476213d0f87af7 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 11:55:18 +0100 Subject: [PATCH 1/3] Download the Coana CLI through SOCKET_COANA_MIRROR_URL When SOCKET_COANA_MIRROR_URL is set, the signed URL's prefix https://storage.googleapis.com/socket-coana-cli/ is replaced with the mirror's URL, keeping the query that holds the signature. The value is read only after a cache miss. Signed URLs outside the bucket and invalid values are refused without showing the signature or the value, and download errors name the host without credentials. Port of SocketDev/socket-cli#1825. Unlike the Node CLI, http mirrors are accepted, as in Coana. --- CHANGELOG.md | 7 + pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- socketsecurity/core/tools/reachability.py | 66 +++++++- tests/unit/test_reachability.py | 182 +++++++++++++++++++++- uv.lock | 2 +- 6 files changed, 251 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f58fea8..d8ad01e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 2.15.11 + +### Added + +- Set `SOCKET_COANA_MIRROR_URL` to download the reachability engine through a + mirror of `storage.googleapis.com/socket-coana-cli`. + ## 2.15.10 ### Changed: bump pinned Coana CLI to 15.15.12 diff --git a/pyproject.toml b/pyproject.toml index 97889e5f..2cecffd9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.10" +version = "2.15.11" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 967132e7..fa91eedb 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.15.10' +__version__ = '2.15.11' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/core/tools/reachability.py b/socketsecurity/core/tools/reachability.py index 53d8b223..5926e76b 100644 --- a/socketsecurity/core/tools/reachability.py +++ b/socketsecurity/core/tools/reachability.py @@ -11,8 +11,10 @@ import tempfile from dataclasses import dataclass from typing import Any, Dict, Final, List, Mapping, Optional +from urllib.parse import unquote, urlsplit import requests +from urllib3.util import parse_url from socketsecurity import USER_AGENT, __version__ from socketsecurity.core.cli_client import CliClient @@ -29,6 +31,8 @@ # packages/cli/docs/gcs-releases.md. _COANA_CACHE_SCRIPT: Final = pathlib.Path(__file__).with_name("coana-cache.mjs") _COANA_COMPONENT: Final = "cli" +# SOCKET_COANA_MIRROR_URL replaces this prefix of the signed URLs. +_COANA_BUCKET_URL: Final = "https://storage.googleapis.com/socket-coana-cli/" _NOT_CACHED_EXIT_CODE: Final = 4 _EXACT_VERSION: Final = re.compile(r"\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?") @@ -75,6 +79,54 @@ def parse(cls, value: object) -> Optional["_CoanaArtifacts"]: return cls(version=version, cli=_CoanaComponent(sha256=sha256, size=size, url=url)) +@dataclass(frozen=True) +class _CoanaMirror: + """A mirror of Coana's bucket, which SOCKET_COANA_MIRROR_URL names. + + "Downloading through a mirror" in coana-package-manager's packages/cli/docs/gcs-releases.md + specifies the rule. + """ + + # Ends in "/". + base_url: str + + @classmethod + def parse(cls, value: Optional[str]) -> Optional["_CoanaMirror"]: + """The mirror ``value`` names, or None when it is unset or empty.""" + if not value: + return None + try: + parts = urlsplit(value) + # Raises ValueError for an invalid port. + parts.port + except ValueError: + parts = None + # urlsplit drops a bare "?" or "#". + if ( + parts is None + or parts.scheme not in ("http", "https") + or not parts.hostname + or "?" in value + or "#" in value + ): + # The value may carry credentials. + raise Exception("SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment.") + return cls(value if value.endswith("/") else f"{value}/") + + def download_url(self, signed_url: str) -> str: + """Where to download ``signed_url`` from. The query, which holds the signature, is kept.""" + rest = signed_url.removeprefix(_COANA_BUCKET_URL) + # A dot segment could climb out of the bucket, or out of the mirror's base URL. + if rest == signed_url or any( + unquote(segment) in (".", "..") for segment in rest.partition("?")[0].split("/") + ): + raise Exception( + f"Socket provided the Coana CLI at {signed_url.partition('?')[0]}, " + f"outside {_COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors." + ) + return self.base_url + rest + + class _DownloadRefused(Exception): """The download host refused a signed URL with a 4xx, e.g. because it expired.""" @@ -356,18 +408,20 @@ def request_artifacts(spec: str) -> _CoanaArtifacts: return artifacts def download(component: _CoanaComponent, dest: pathlib.Path) -> None: + url = component.url if mirror is None else mirror.download_url(component.url) + host = parse_url(url).netloc with requests.get( - component.url, + url, headers={"User-Agent": USER_AGENT}, stream=True, timeout=_DOWNLOAD_TIMEOUT, verify=not self.client.config.allow_unverified_ssl, ) as response: if 400 <= response.status_code < 500: - raise _DownloadRefused( - f"The download host refused the Coana CLI URL with status {response.status_code}" - ) - response.raise_for_status() + raise _DownloadRefused(f"{host} refused the Coana CLI URL with status {response.status_code}") + # raise_for_status would show the URL, with the mirror's credentials and the signature. + if not response.ok: + raise Exception(f"{host} responded with status {response.status_code} to the Coana CLI download") digest = hashlib.sha256() received = 0 with dest.open("wb") as f: @@ -397,6 +451,8 @@ def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.T if artifacts.version != version_spec and (cached := lookup(artifacts.version)): return cached + # Parsed only once a download is certain, so a warm cache never trips on a stale value. + mirror = _CoanaMirror.parse(env.get("SOCKET_COANA_MIRROR_URL")) log.info(f"Downloading the Coana CLI {artifacts.version}...") with tempfile.TemporaryDirectory(prefix="socket-coana-cli-") as tmp: tarball = pathlib.Path(tmp, "cli.tar.gz") diff --git a/tests/unit/test_reachability.py b/tests/unit/test_reachability.py index 441f9749..78b2dab8 100644 --- a/tests/unit/test_reachability.py +++ b/tests/unit/test_reachability.py @@ -1,13 +1,23 @@ """Tests for launching the Coana CLI from ReachabilityAnalyzer. -A fake cli-wrapper.mjs is installed into a temporary cache with the real coana-cache.mjs, so -nothing is mocked. The fake records the args, cwd and environment it was run with. +A fake cli-wrapper.mjs is installed into a temporary cache with the real coana-cache.mjs. The +fake records the args, cwd and environment it was run with. The tests of downloads through the +mirror that SOCKET_COANA_MIRROR_URL names mock the Socket API and the download, and start from an +empty cache. """ +import hashlib +import io import json import os +import pathlib import subprocess +import tarfile +from types import SimpleNamespace +from typing import List, Sequence import pytest +import requests +import urllib3 from socketsecurity import __version__ from socketsecurity.core.cli_client import CliClient @@ -187,3 +197,171 @@ def test_env_strips_npm_package_vars(fake_run_path, monkeypatch): def test_failing_run_raises(fake_run_path): with pytest.raises(Exception, match="exit code 1"): _run(fake_run_path, additional_params=["--fail"]) + + +MIRROR_URL = "https://mirror.test/socket-coana-cli" + + +def _signed_url(signature: str) -> str: + return f"https://storage.googleapis.com/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature={signature}" + + +@pytest.fixture(scope="module") +def tarball() -> bytes: + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode="w:gz") as tar: + wrapper = FAKE_CLI_WRAPPER.encode() + member = tarfile.TarInfo("cli-wrapper.mjs") + member.size = len(wrapper) + tar.addfile(member, io.BytesIO(wrapper)) + return archive.getvalue() + + +@pytest.fixture +def downloads() -> List[str]: + """The URLs that ``install_from_mirror`` downloaded from.""" + return [] + + +@pytest.fixture +def install_from_mirror(tarball, downloads, monkeypatch, tmp_path): + """Installs the Coana CLI from an empty cache, downloading through SOCKET_COANA_MIRROR_URL. + + The Socket API answers with ``signed_urls`` in turn. Downloads answer with the statuses in + ``answers`` in turn, then with the tarball. + """ + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + sha256 = hashlib.sha256(tarball).hexdigest() + + def install( + signed_urls: Sequence[str], + answers: Sequence[int] = (), + mirror_url: str = MIRROR_URL, + version_spec: str = VERSION, + ) -> str: + pending_urls, pending_answers = list(signed_urls), list(answers) + + def request(path, **kwargs): + body = { + "version": VERSION, + "components": {"cli": {"sha256": sha256, "size": len(tarball), "url": pending_urls.pop(0)}}, + } + return SimpleNamespace(json=lambda: body) + + def get(url, **kwargs): + downloads.append(url) + status = pending_answers.pop(0) if pending_answers else 200 + response = requests.Response() + response.status_code = status + response.raw = urllib3.HTTPResponse( + body=io.BytesIO(tarball if status == 200 else b""), status=status, preload_content=False + ) + return response + + monkeypatch.setenv("SOCKET_COANA_MIRROR_URL", mirror_url) + monkeypatch.setattr(reachability.requests, "get", get) + analyzer = _analyzer() + analyzer.client.request = request + return analyzer._get_coana_cli_dir(version_spec, "my-org", dict(os.environ)) + + return install + + +@pytest.mark.parametrize( + "mirror_url, base_url", + [ + (MIRROR_URL, "https://mirror.test/socket-coana-cli/"), + ("https://mirror.test/socket-coana-cli/", "https://mirror.test/socket-coana-cli/"), + ("http://user:secret@mirror.test:8081/socket-coana-cli", "http://user:secret@mirror.test:8081/socket-coana-cli/"), + ], +) +def test_mirror_replaces_the_bucket_prefix_and_keeps_the_signature( + install_from_mirror, downloads, mirror_url, base_url +): + cli_dir = install_from_mirror([_signed_url("first")], mirror_url=mirror_url) + + assert (pathlib.Path(cli_dir) / "cli-wrapper.mjs").read_text() == FAKE_CLI_WRAPPER + assert downloads == [f"{base_url}objects/SHA.tar.gz?X-Goog-Signature=first"] + + +def test_mirror_rewrites_the_url_it_requests_anew_after_the_mirror_refuses_one(install_from_mirror, downloads): + install_from_mirror([_signed_url("first"), _signed_url("second")], answers=[403]) + + assert downloads == [ + "https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first", + "https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=second", + ] + + +@pytest.mark.parametrize( + "answers, message", + [ + ([500], "mirror.test:8081 responded with status 500 to the Coana CLI download"), + ([403, 403], "mirror.test:8081 refused the Coana CLI URL with status 403"), + ], +) +def test_mirror_host_is_named_without_credentials_when_a_download_fails(install_from_mirror, answers, message): + with pytest.raises(Exception) as error: + install_from_mirror( + [_signed_url("first"), _signed_url("second")], + answers=answers, + mirror_url="https://user:secret@mirror.test:8081/socket-coana-cli", + ) + + assert str(error.value) == message + + +def test_mirror_invalid_value_and_url_outside_the_bucket_are_ignored_when_the_version_is_cached( + install_from_mirror, downloads, cache_home, monkeypatch +): + monkeypatch.setenv("XDG_CACHE_HOME", str(cache_home)) + + cli_dir = install_from_mirror( + ["https://example.test/coana.tar.gz"], mirror_url="ftp://mirror.test/", version_spec="^1.2.0" + ) + + assert (pathlib.Path(cli_dir) / "cli-wrapper.mjs").read_text() == FAKE_CLI_WRAPPER + assert downloads == [] + + +@pytest.mark.parametrize( + "outside", + [ + "https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz", + "https://storage.googleapis.com/socket-coana-cli/../another-bucket/objects/SHA.tar.gz", + "https://storage.googleapis.com/socket-coana-cli/%2e%2e/another-bucket/objects/SHA.tar.gz", + "https://storage.googleapis.com/socket-coana-cli/objects/%2E/SHA.tar.gz", + ], +) +def test_mirror_refuses_a_url_outside_the_bucket_without_showing_its_signature( + install_from_mirror, downloads, outside +): + with pytest.raises(Exception) as error: + install_from_mirror([f"{outside}?X-Goog-Signature=secret"]) + + assert str(error.value) == ( + f"Socket provided the Coana CLI at {outside}, outside https://storage.googleapis.com/socket-coana-cli/, " + "which SOCKET_COANA_MIRROR_URL mirrors." + ) + assert downloads == [] + + +@pytest.mark.parametrize( + "mirror_url", + [ + "not a URL", + "ftp://mirror.test/", + "https:mirror.test", + "https://mirror.test:99999/", + "https://mirror.test/?token=secret", + "https://mirror.test/#secret", + "https://mirror.test/?", + "https://mirror.test/#", + ], +) +def test_mirror_refuses_an_invalid_value_without_showing_it(install_from_mirror, downloads, mirror_url): + with pytest.raises(Exception) as error: + install_from_mirror([_signed_url("first")], mirror_url=mirror_url) + + assert str(error.value) == "SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment." + assert downloads == [] diff --git a/uv.lock b/uv.lock index e78fdb35..48c3bb52 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.15.10" +version = "2.15.11" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From 08d2f8ed3981a3a27c760194a5ee4c9dede0c269 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 11:58:44 +0100 Subject: [PATCH 2/3] Correct two comments on the mirror download --- socketsecurity/core/tools/reachability.py | 2 +- tests/unit/test_reachability.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/socketsecurity/core/tools/reachability.py b/socketsecurity/core/tools/reachability.py index 5926e76b..f177f1fd 100644 --- a/socketsecurity/core/tools/reachability.py +++ b/socketsecurity/core/tools/reachability.py @@ -419,7 +419,7 @@ def download(component: _CoanaComponent, dest: pathlib.Path) -> None: ) as response: if 400 <= response.status_code < 500: raise _DownloadRefused(f"{host} refused the Coana CLI URL with status {response.status_code}") - # raise_for_status would show the URL, with the mirror's credentials and the signature. + # The URL holds the signature, and a mirror's URL may carry credentials. if not response.ok: raise Exception(f"{host} responded with status {response.status_code} to the Coana CLI download") digest = hashlib.sha256() diff --git a/tests/unit/test_reachability.py b/tests/unit/test_reachability.py index 78b2dab8..7ba3a9c4 100644 --- a/tests/unit/test_reachability.py +++ b/tests/unit/test_reachability.py @@ -2,8 +2,7 @@ A fake cli-wrapper.mjs is installed into a temporary cache with the real coana-cache.mjs. The fake records the args, cwd and environment it was run with. The tests of downloads through the -mirror that SOCKET_COANA_MIRROR_URL names mock the Socket API and the download, and start from an -empty cache. +mirror that SOCKET_COANA_MIRROR_URL names mock the Socket API and the download. """ import hashlib import io From fa4b3c61c15b82f3b6a7f634f2d4d89ebafde332 Mon Sep 17 00:00:00 2001 From: Oskar Haarklou Veileborg Date: Fri, 4 Dec 2026 12:51:35 +0100 Subject: [PATCH 3/3] Ride the unreleased 2.15.10 instead of bumping to 2.15.11 --- CHANGELOG.md | 4 +--- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- uv.lock | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8ad01e3..9a1c2c9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,12 @@ # Changelog -## 2.15.11 +## 2.15.10 ### Added - Set `SOCKET_COANA_MIRROR_URL` to download the reachability engine through a mirror of `storage.googleapis.com/socket-coana-cli`. -## 2.15.10 - ### Changed: bump pinned Coana CLI to 15.15.12 - Bumped the pinned reachability engine (the Coana CLI) from `15.15.11` to diff --git a/pyproject.toml b/pyproject.toml index 2cecffd9..97889e5f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.11" +version = "2.15.10" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index fa91eedb..967132e7 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.15.11' +__version__ = '2.15.10' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/uv.lock b/uv.lock index 48c3bb52..e78fdb35 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.15.11" +version = "2.15.10" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" },