Skip to content

Commit eb4ae61

Browse files
Download the Coana CLI through SOCKET_COANA_MIRROR_URL (#486)
* 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. * Correct two comments on the mirror download * Ride the unreleased 2.15.10 instead of bumping to 2.15.11
1 parent fb93fbd commit eb4ae61

3 files changed

Lines changed: 245 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
## 2.15.10
44

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+
510
### Changed: bump pinned Coana CLI to 15.15.12
611

712
- Bumped the pinned reachability engine (the Coana CLI) from `15.15.11` to

‎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+
# The URL holds the signature, and a mirror's URL may carry credentials.
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: 179 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
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.
56
"""
7+
import hashlib
8+
import io
69
import json
710
import os
11+
import pathlib
812
import subprocess
13+
import tarfile
14+
from types import SimpleNamespace
15+
from typing import List, Sequence
916

1017
import pytest
18+
import requests
19+
import urllib3
1120

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

0 commit comments

Comments
 (0)