Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,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`.

### Changed: bump pinned Coana CLI to 15.15.12

- Bumped the pinned reachability engine (the Coana CLI) from `15.15.11` to
Expand Down
66 changes: 61 additions & 5 deletions socketsecurity/core/tools/reachability.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.-]+)?")
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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}")
# 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()
received = 0
with dest.open("wb") as f:
Expand Down Expand Up @@ -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")
Expand Down
181 changes: 179 additions & 2 deletions tests/unit/test_reachability.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
"""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.
"""
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
Expand Down Expand Up @@ -187,3 +196,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 == []