Repository navigation
Expand file tree
/
Copy pathtest_reachability.py
More file actions
366 lines (287 loc) · 13.5 KB
/
Copy pathtest_reachability.py
File metadata and controls
366 lines (287 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""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. 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
from socketsecurity.core.socket_config import SocketConfig
from socketsecurity.core.tools import reachability
from socketsecurity.core.tools.reachability import (
ReachabilityAnalyzer,
_build_caller_user_agent,
)
VERSION = "1.2.3"
# Records what it was run with in $FAKE_COANA_RUN, or fails when passed --fail. Like Coana, it
# writes the facts file to the --socket-mode path, resolved against its cwd.
FAKE_CLI_WRAPPER = """
import { writeFileSync } from 'node:fs'
const args = process.argv.slice(2)
if (args.includes('--fail')) process.exit(1)
writeFileSync(process.env.FAKE_COANA_RUN, JSON.stringify({ args, cwd: process.cwd(), env: process.env }))
writeFileSync(args[args.indexOf('--socket-mode') + 1], JSON.stringify({ tier1ReachabilityScanId: 'reach-scan-id' }))
"""
@pytest.fixture(scope="module")
def cache_home(tmp_path_factory):
tmp = tmp_path_factory.mktemp("coana")
extracted = tmp / "extracted"
extracted.mkdir()
(extracted / "cli-wrapper.mjs").write_text(FAKE_CLI_WRAPPER)
subprocess.run(
["node", str(reachability._COANA_CACHE_SCRIPT), "install", VERSION, "cli", "a" * 64, str(extracted)],
env={**os.environ, "XDG_CACHE_HOME": str(tmp / "cache")},
check=True,
capture_output=True,
)
return tmp / "cache"
@pytest.fixture
def fake_run_path(tmp_path, monkeypatch, cache_home):
monkeypatch.setenv("XDG_CACHE_HOME", str(cache_home))
path = tmp_path / "run.json"
monkeypatch.setenv("FAKE_COANA_RUN", str(path))
return path
def _analyzer(api_url="https://api.socket.dev/v0"):
return ReachabilityAnalyzer(CliClient(SocketConfig(api_key="test-api-token", api_url=api_url)))
def _run(fake_run_path, analyzer=None, **kwargs):
"""Run the fake Coana; return the args, cwd and env it recorded."""
(analyzer or _analyzer()).run_reachability_analysis(
org_slug="my-org",
target_directory=str(fake_run_path.parent),
tar_hash="tar-hash-abc123",
output_path=str(fake_run_path.parent / ".socket.facts.json"),
version=VERSION,
**kwargs,
)
return json.loads(fake_run_path.read_text())
def test_build_caller_user_agent_shape():
ua = _build_caller_user_agent()
parts = ua.split(" ")
assert parts[0] == f"socket/{__version__}"
assert parts[1].startswith("python/")
assert "/" in parts[2] # platform/arch
def test_runs_the_cached_cli_wrapper_with_the_args_and_cwd(fake_run_path):
run = _run(fake_run_path)
assert run["args"][:2] == ["run", "."]
assert "--manifests-tar-hash" in run["args"]
assert run["cwd"] == str(fake_run_path.parent)
@pytest.mark.parametrize("absolute", [False, True])
def test_report_path_is_where_coana_wrote_the_facts_file(fake_run_path, tmp_path, monkeypatch, absolute):
target = tmp_path / "project"
target.mkdir()
monkeypatch.chdir(tmp_path)
output_path = str(tmp_path / "out" / "facts.json") if absolute else ".socket.facts.json"
if absolute:
(tmp_path / "out").mkdir()
result = _analyzer().run_reachability_analysis(
org_slug="my-org",
target_directory=str(target),
tar_hash="tar-hash-abc123",
output_path=output_path,
version=VERSION,
)
assert result["report_path"] == (output_path if absolute else str(target / ".socket.facts.json"))
assert result["scan_id"] == "reach-scan-id"
def test_reach_debug_appends_debug_long_flag(fake_run_path):
"""G9: --reach-debug -> coana --debug; does not emit the global -d."""
args = _run(fake_run_path, reach_debug=True)["args"]
assert "--debug" in args
assert "-d" not in args
def test_enable_debug_still_emits_short_d(fake_run_path):
"""G9: existing global --enable-debug -> -d behavior is unchanged."""
args = _run(fake_run_path, enable_debug=True)["args"]
assert "-d" in args
assert "--debug" not in args
def test_disable_external_tool_checks(fake_run_path):
"""G1: --reach-disable-external-tool-checks -> coana --disable-external-tool-checks."""
assert "--disable-external-tool-checks" in _run(fake_run_path, disable_external_tool_checks=True)["args"]
assert "--disable-external-tool-checks" not in _run(fake_run_path)["args"]
def test_always_disables_analysis_splitting(fake_run_path):
assert "--disable-analysis-splitting" in _run(fake_run_path)["args"]
def test_timeout_and_memory_forwarded_verbatim(fake_run_path):
"""coana parses the units; config-file ints are coerced to strings."""
args = _run(fake_run_path, timeout="10m", memory_limit=2048, concurrency=1)["args"]
assert args[args.index("--analysis-timeout") + 1] == "10m"
assert args[args.index("--memory-limit") + 1] == "2048"
assert args[args.index("--concurrency") + 1] == "1"
def test_env_identifies_python_cli(fake_run_path):
"""G5: SOCKET_CLI_VERSION + SOCKET_CALLER_USER_AGENT forwarded to coana."""
env = _run(fake_run_path)["env"]
assert env["SOCKET_CLI_VERSION"] == __version__
assert env["SOCKET_CALLER_USER_AGENT"] == _build_caller_user_agent()
assert env["SOCKET_ORG_SLUG"] == "my-org"
assert env["SOCKET_CLI_API_TOKEN"] == "test-api-token"
@pytest.mark.parametrize("api_url", ["https://api.example.test/v0", "https://api.example.test/v0/"])
def test_env_api_base_url_follows_the_client(fake_run_path, api_url):
env = _run(fake_run_path, analyzer=_analyzer(api_url))["env"]
assert env["SOCKET_CLI_API_BASE_URL"] == "https://api.example.test/v0/"
def test_no_proxy_env_set_by_default(fake_run_path, monkeypatch):
"""coana reads HTTPS_PROXY/HTTP_PROXY itself; SOCKET_CLI_API_PROXY is reserved for a future
explicit --proxy flag."""
monkeypatch.delenv("SOCKET_CLI_API_PROXY", raising=False)
monkeypatch.setenv("HTTPS_PROXY", "http://envproxy:3128")
env = _run(fake_run_path)["env"]
assert env["HTTPS_PROXY"] == "http://envproxy:3128"
assert "SOCKET_CLI_API_PROXY" not in env
def test_repo_and_branch_env(fake_run_path):
"""G6: caller passes None for default sentinels -> env keys omitted (cache hygiene)."""
env = _run(fake_run_path, repo_name="acme/widget", branch_name="main")["env"]
assert env["SOCKET_REPO_NAME"] == "acme/widget"
assert env["SOCKET_BRANCH_NAME"] == "main"
env = _run(fake_run_path)["env"]
assert "SOCKET_REPO_NAME" not in env
assert "SOCKET_BRANCH_NAME" not in env
def test_env_strips_npm_package_vars(fake_run_path, monkeypatch):
"""npm_package_* dropped (E2BIG guard); npm_config_* kept. Parity with the Node CLI."""
monkeypatch.setenv("npm_package_dependencies_foo", "1.0.0")
monkeypatch.setenv("npm_config_registry", "https://example.test")
env = _run(fake_run_path)["env"]
assert "npm_package_dependencies_foo" not in env
assert env["npm_config_registry"] == "https://example.test"
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 == []