|
11 | 11 | import tempfile |
12 | 12 | from dataclasses import dataclass |
13 | 13 | from typing import Any, Dict, Final, List, Mapping, Optional |
| 14 | +from urllib.parse import unquote, urlsplit |
14 | 15 |
|
15 | 16 | import requests |
| 17 | +from urllib3.util import parse_url |
16 | 18 |
|
17 | 19 | from socketsecurity import USER_AGENT, __version__ |
18 | 20 | from socketsecurity.core.cli_client import CliClient |
|
22 | 24 | # Pinned Coana CLI version. Bumped deliberately per Python CLI release so the |
23 | 25 | # reachability engine version only changes through a standard pip upgrade (advance notice). |
24 | 26 | # Pass --reach-version latest to opt into the newest published version instead. |
25 | | -DEFAULT_COANA_CLI_VERSION: Final = "15.15.9" |
| 27 | +DEFAULT_COANA_CLI_VERSION: Final = "15.15.12" |
26 | 28 |
|
27 | 29 | # Vendored from coana-package-manager, where it is generated; the only code that may read or |
28 | 30 | # write the cache Coana shares with the Socket CLIs. See "Launching Coana" in that repo's |
29 | 31 | # packages/cli/docs/gcs-releases.md. |
30 | 32 | _COANA_CACHE_SCRIPT: Final = pathlib.Path(__file__).with_name("coana-cache.mjs") |
31 | 33 | _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/" |
32 | 36 | _NOT_CACHED_EXIT_CODE: Final = 4 |
33 | 37 |
|
34 | 38 | _EXACT_VERSION: Final = re.compile(r"\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?") |
@@ -75,6 +79,54 @@ def parse(cls, value: object) -> Optional["_CoanaArtifacts"]: |
75 | 79 | return cls(version=version, cli=_CoanaComponent(sha256=sha256, size=size, url=url)) |
76 | 80 |
|
77 | 81 |
|
| 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 | + |
78 | 130 | class _DownloadRefused(Exception): |
79 | 131 | """The download host refused a signed URL with a 4xx, e.g. because it expired.""" |
80 | 132 |
|
@@ -356,18 +408,20 @@ def request_artifacts(spec: str) -> _CoanaArtifacts: |
356 | 408 | return artifacts |
357 | 409 |
|
358 | 410 | 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 |
359 | 413 | with requests.get( |
360 | | - component.url, |
| 414 | + url, |
361 | 415 | headers={"User-Agent": USER_AGENT}, |
362 | 416 | stream=True, |
363 | 417 | timeout=_DOWNLOAD_TIMEOUT, |
364 | 418 | verify=not self.client.config.allow_unverified_ssl, |
365 | 419 | ) as response: |
366 | 420 | 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") |
371 | 425 | digest = hashlib.sha256() |
372 | 426 | received = 0 |
373 | 427 | with dest.open("wb") as f: |
@@ -397,6 +451,8 @@ def regular_files_only(member: tarfile.TarInfo, path: str) -> Optional[tarfile.T |
397 | 451 | if artifacts.version != version_spec and (cached := lookup(artifacts.version)): |
398 | 452 | return cached |
399 | 453 |
|
| 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")) |
400 | 456 | log.info(f"Downloading the Coana CLI {artifacts.version}...") |
401 | 457 | with tempfile.TemporaryDirectory(prefix="socket-coana-cli-") as tmp: |
402 | 458 | tarball = pathlib.Path(tmp, "cli.tar.gz") |
|
0 commit comments