Skip to content

Commit dc51287

Browse files
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.
1 parent fb93fbd commit dc51287

6 files changed

Lines changed: 251 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Changelog
22

3+
## 2.15.11
4+
5+
### Added
6+
7+
- Set `SOCKET_COANA_MIRROR_URL` to download the reachability engine through a
8+
mirror of `storage.googleapis.com/socket-coana-cli`.
9+
310
## 2.15.10
411

512
### Changed: bump pinned Coana CLI to 15.15.12

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.15.10"
9+
version = "2.15.11"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.15.10'
2+
__version__ = '2.15.11'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/core/tools/reachability.py‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111
import tempfile
1212
from dataclasses import dataclass
1313
from typing import Any, Dict, Final, List, Mapping, Optional
14+
from urllib.parse import unquote, urlsplit
1415

1516
import requests
17+
from urllib3.util import parse_url
1618

1719
from socketsecurity import USER_AGENT, __version__
1820
from socketsecurity.core.cli_client import CliClient
@@ -29,6 +31,8 @@
2931
# packages/cli/docs/gcs-releases.md.
3032
_COANA_CACHE_SCRIPT: Final = pathlib.Path(__file__).with_name("coana-cache.mjs")
3133
_COANA_COMPONENT: Final = "cli"
34+
# SOCKET_COANA_MIRROR_URL replaces this prefix of the signed URLs.
35+
_COANA_BUCKET_URL: Final = "https://storage.googleapis.com/socket-coana-cli/"
3236
_NOT_CACHED_EXIT_CODE: Final = 4
3337

3438
_EXACT_VERSION: Final = re.compile(r"\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?")
@@ -75,6 +79,54 @@ def parse(cls, value: object) -> Optional["_CoanaArtifacts"]:
7579
return cls(version=version, cli=_CoanaComponent(sha256=sha256, size=size, url=url))
7680

7781

82+
@dataclass(frozen=True)
83+
class _CoanaMirror:
84+
"""A mirror of Coana's bucket, which SOCKET_COANA_MIRROR_URL names.
85+
86+
"Downloading through a mirror" in coana-package-manager's packages/cli/docs/gcs-releases.md
87+
specifies the rule.
88+
"""
89+
90+
# Ends in "/".
91+
base_url: str
92+
93+
@classmethod
94+
def parse(cls, value: Optional[str]) -> Optional["_CoanaMirror"]:
95+
"""The mirror ``value`` names, or None when it is unset or empty."""
96+
if not value:
97+
return None
98+
try:
99+
parts = urlsplit(value)
100+
# Raises ValueError for an invalid port.
101+
parts.port
102+
except ValueError:
103+
parts = None
104+
# urlsplit drops a bare "?" or "#".
105+
if (
106+
parts is None
107+
or parts.scheme not in ("http", "https")
108+
or not parts.hostname
109+
or "?" in value
110+
or "#" in value
111+
):
112+
# The value may carry credentials.
113+
raise Exception("SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment.")
114+
return cls(value if value.endswith("/") else f"{value}/")
115+
116+
def download_url(self, signed_url: str) -> str:
117+
"""Where to download ``signed_url`` from. The query, which holds the signature, is kept."""
118+
rest = signed_url.removeprefix(_COANA_BUCKET_URL)
119+
# A dot segment could climb out of the bucket, or out of the mirror's base URL.
120+
if rest == signed_url or any(
121+
unquote(segment) in (".", "..") for segment in rest.partition("?")[0].split("/")
122+
):
123+
raise Exception(
124+
f"Socket provided the Coana CLI at {signed_url.partition('?')[0]}, "
125+
f"outside {_COANA_BUCKET_URL}, which SOCKET_COANA_MIRROR_URL mirrors."
126+
)
127+
return self.base_url + rest
128+
129+
78130
class _DownloadRefused(Exception):
79131
"""The download host refused a signed URL with a 4xx, e.g. because it expired."""
80132

@@ -356,18 +408,20 @@ def request_artifacts(spec: str) -> _CoanaArtifacts:
356408
return artifacts
357409

358410
def download(component: _CoanaComponent, dest: pathlib.Path) -> None:
411+
url = component.url if mirror is None else mirror.download_url(component.url)
412+
host = parse_url(url).netloc
359413
with requests.get(
360-
component.url,
414+
url,
361415
headers={"User-Agent": USER_AGENT},
362416
stream=True,
363417
timeout=_DOWNLOAD_TIMEOUT,
364418
verify=not self.client.config.allow_unverified_ssl,
365419
) as response:
366420
if 400 <= response.status_code < 500:
367-
raise _DownloadRefused(
368-
f"The download host refused the Coana CLI URL with status {response.status_code}"
369-
)
370-
response.raise_for_status()
421+
raise _DownloadRefused(f"{host} refused the Coana CLI URL with status {response.status_code}")
422+
# raise_for_status would show the URL, with the mirror's credentials and the signature.
423+
if not response.ok:
424+
raise Exception(f"{host} responded with status {response.status_code} to the Coana CLI download")
371425
digest = hashlib.sha256()
372426
received = 0
373427
with dest.open("wb") as f:
@@ -397,6 +451,8 @@ def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.T
397451
if artifacts.version != version_spec and (cached := lookup(artifacts.version)):
398452
return cached
399453

454+
# Parsed only once a download is certain, so a warm cache never trips on a stale value.
455+
mirror = _CoanaMirror.parse(env.get("SOCKET_COANA_MIRROR_URL"))
400456
log.info(f"Downloading the Coana CLI {artifacts.version}...")
401457
with tempfile.TemporaryDirectory(prefix="socket-coana-cli-") as tmp:
402458
tarball = pathlib.Path(tmp, "cli.tar.gz")

‎tests/unit/test_reachability.py‎

Lines changed: 180 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
"""Tests for launching the Coana CLI from ReachabilityAnalyzer.
22
3-
A fake cli-wrapper.mjs is installed into a temporary cache with the real coana-cache.mjs, so
4-
nothing is mocked. The fake records the args, cwd and environment it was run with.
3+
A fake cli-wrapper.mjs is installed into a temporary cache with the real coana-cache.mjs. The
4+
fake records the args, cwd and environment it was run with. The tests of downloads through the
5+
mirror that SOCKET_COANA_MIRROR_URL names mock the Socket API and the download, and start from an
6+
empty cache.
57
"""
8+
import hashlib
9+
import io
610
import json
711
import os
12+
import pathlib
813
import subprocess
14+
import tarfile
15+
from types import SimpleNamespace
16+
from typing import List, Sequence
917

1018
import pytest
19+
import requests
20+
import urllib3
1121

1222
from socketsecurity import __version__
1323
from socketsecurity.core.cli_client import CliClient
@@ -187,3 +197,171 @@ def test_env_strips_npm_package_vars(fake_run_path, monkeypatch):
187197
def test_failing_run_raises(fake_run_path):
188198
with pytest.raises(Exception, match="exit code 1"):
189199
_run(fake_run_path, additional_params=["--fail"])
200+
201+
202+
MIRROR_URL = "https://mirror.test/socket-coana-cli"
203+
204+
205+
def _signed_url(signature: str) -> str:
206+
return f"https://storage.googleapis.com/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature={signature}"
207+
208+
209+
@pytest.fixture(scope="module")
210+
def tarball() -> bytes:
211+
archive = io.BytesIO()
212+
with tarfile.open(fileobj=archive, mode="w:gz") as tar:
213+
wrapper = FAKE_CLI_WRAPPER.encode()
214+
member = tarfile.TarInfo("cli-wrapper.mjs")
215+
member.size = len(wrapper)
216+
tar.addfile(member, io.BytesIO(wrapper))
217+
return archive.getvalue()
218+
219+
220+
@pytest.fixture
221+
def downloads() -> List[str]:
222+
"""The URLs that ``install_from_mirror`` downloaded from."""
223+
return []
224+
225+
226+
@pytest.fixture
227+
def install_from_mirror(tarball, downloads, monkeypatch, tmp_path):
228+
"""Installs the Coana CLI from an empty cache, downloading through SOCKET_COANA_MIRROR_URL.
229+
230+
The Socket API answers with ``signed_urls`` in turn. Downloads answer with the statuses in
231+
``answers`` in turn, then with the tarball.
232+
"""
233+
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
234+
sha256 = hashlib.sha256(tarball).hexdigest()
235+
236+
def install(
237+
signed_urls: Sequence[str],
238+
answers: Sequence[int] = (),
239+
mirror_url: str = MIRROR_URL,
240+
version_spec: str = VERSION,
241+
) -> str:
242+
pending_urls, pending_answers = list(signed_urls), list(answers)
243+
244+
def request(path, **kwargs):
245+
body = {
246+
"version": VERSION,
247+
"components": {"cli": {"sha256": sha256, "size": len(tarball), "url": pending_urls.pop(0)}},
248+
}
249+
return SimpleNamespace(json=lambda: body)
250+
251+
def get(url, **kwargs):
252+
downloads.append(url)
253+
status = pending_answers.pop(0) if pending_answers else 200
254+
response = requests.Response()
255+
response.status_code = status
256+
response.raw = urllib3.HTTPResponse(
257+
body=io.BytesIO(tarball if status == 200 else b""), status=status, preload_content=False
258+
)
259+
return response
260+
261+
monkeypatch.setenv("SOCKET_COANA_MIRROR_URL", mirror_url)
262+
monkeypatch.setattr(reachability.requests, "get", get)
263+
analyzer = _analyzer()
264+
analyzer.client.request = request
265+
return analyzer._get_coana_cli_dir(version_spec, "my-org", dict(os.environ))
266+
267+
return install
268+
269+
270+
@pytest.mark.parametrize(
271+
"mirror_url, base_url",
272+
[
273+
(MIRROR_URL, "https://mirror.test/socket-coana-cli/"),
274+
("https://mirror.test/socket-coana-cli/", "https://mirror.test/socket-coana-cli/"),
275+
("http://user:secret@mirror.test:8081/socket-coana-cli", "http://user:secret@mirror.test:8081/socket-coana-cli/"),
276+
],
277+
)
278+
def test_mirror_replaces_the_bucket_prefix_and_keeps_the_signature(
279+
install_from_mirror, downloads, mirror_url, base_url
280+
):
281+
cli_dir = install_from_mirror([_signed_url("first")], mirror_url=mirror_url)
282+
283+
assert (pathlib.Path(cli_dir) / "cli-wrapper.mjs").read_text() == FAKE_CLI_WRAPPER
284+
assert downloads == [f"{base_url}objects/SHA.tar.gz?X-Goog-Signature=first"]
285+
286+
287+
def test_mirror_rewrites_the_url_it_requests_anew_after_the_mirror_refuses_one(install_from_mirror, downloads):
288+
install_from_mirror([_signed_url("first"), _signed_url("second")], answers=[403])
289+
290+
assert downloads == [
291+
"https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=first",
292+
"https://mirror.test/socket-coana-cli/objects/SHA.tar.gz?X-Goog-Signature=second",
293+
]
294+
295+
296+
@pytest.mark.parametrize(
297+
"answers, message",
298+
[
299+
([500], "mirror.test:8081 responded with status 500 to the Coana CLI download"),
300+
([403, 403], "mirror.test:8081 refused the Coana CLI URL with status 403"),
301+
],
302+
)
303+
def test_mirror_host_is_named_without_credentials_when_a_download_fails(install_from_mirror, answers, message):
304+
with pytest.raises(Exception) as error:
305+
install_from_mirror(
306+
[_signed_url("first"), _signed_url("second")],
307+
answers=answers,
308+
mirror_url="https://user:secret@mirror.test:8081/socket-coana-cli",
309+
)
310+
311+
assert str(error.value) == message
312+
313+
314+
def test_mirror_invalid_value_and_url_outside_the_bucket_are_ignored_when_the_version_is_cached(
315+
install_from_mirror, downloads, cache_home, monkeypatch
316+
):
317+
monkeypatch.setenv("XDG_CACHE_HOME", str(cache_home))
318+
319+
cli_dir = install_from_mirror(
320+
["https://example.test/coana.tar.gz"], mirror_url="ftp://mirror.test/", version_spec="^1.2.0"
321+
)
322+
323+
assert (pathlib.Path(cli_dir) / "cli-wrapper.mjs").read_text() == FAKE_CLI_WRAPPER
324+
assert downloads == []
325+
326+
327+
@pytest.mark.parametrize(
328+
"outside",
329+
[
330+
"https://storage.googleapis.com/another-bucket/objects/SHA.tar.gz",
331+
"https://storage.googleapis.com/socket-coana-cli/../another-bucket/objects/SHA.tar.gz",
332+
"https://storage.googleapis.com/socket-coana-cli/%2e%2e/another-bucket/objects/SHA.tar.gz",
333+
"https://storage.googleapis.com/socket-coana-cli/objects/%2E/SHA.tar.gz",
334+
],
335+
)
336+
def test_mirror_refuses_a_url_outside_the_bucket_without_showing_its_signature(
337+
install_from_mirror, downloads, outside
338+
):
339+
with pytest.raises(Exception) as error:
340+
install_from_mirror([f"{outside}?X-Goog-Signature=secret"])
341+
342+
assert str(error.value) == (
343+
f"Socket provided the Coana CLI at {outside}, outside https://storage.googleapis.com/socket-coana-cli/, "
344+
"which SOCKET_COANA_MIRROR_URL mirrors."
345+
)
346+
assert downloads == []
347+
348+
349+
@pytest.mark.parametrize(
350+
"mirror_url",
351+
[
352+
"not a URL",
353+
"ftp://mirror.test/",
354+
"https:mirror.test",
355+
"https://mirror.test:99999/",
356+
"https://mirror.test/?token=secret",
357+
"https://mirror.test/#secret",
358+
"https://mirror.test/?",
359+
"https://mirror.test/#",
360+
],
361+
)
362+
def test_mirror_refuses_an_invalid_value_without_showing_it(install_from_mirror, downloads, mirror_url):
363+
with pytest.raises(Exception) as error:
364+
install_from_mirror([_signed_url("first")], mirror_url=mirror_url)
365+
366+
assert str(error.value) == "SOCKET_COANA_MIRROR_URL must be an http or https URL without a query or fragment."
367+
assert downloads == []

‎uv.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)