Repository navigation
Expand file tree
/
Copy pathtest_installed_conformance.py
More file actions
429 lines (354 loc) · 14.5 KB
/
Copy pathtest_installed_conformance.py
File metadata and controls
429 lines (354 loc) · 14.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""The installed wheel, driven from a directory that is not the repository.
`test_wheel.py` installs the wheel into a clean venv but runs its commands from
wherever pytest was started, which in CI is the checkout. Every test here runs
with its working directory set to a fresh temporary directory, so a relative
import, a `python -m` that finds the source tree first, or an example that only
works beside `src/` goes red instead of passing by accident.
Three claims:
- **The documented entry points import from the venv.** `python -I` keeps the
working directory, the script directory and the user site off `sys.path`, so
the only `visionset` it can find is the installed one.
- **`visionset mcp` speaks clean JSON-RPC on stdout**, offers the destructive tools
only on the documented opt-in, and does not import packages planted in an
untrusted working directory (#1308).
- **The five surface examples run against the wheel.** Each is named by absolute
path, so nothing from the checkout is importable.
"""
from __future__ import annotations
import json
import os
import queue
import subprocess
import threading
from pathlib import Path
from typing import Any
import pytest
from tests.packaging._wheel import (
REPO_ROOT,
VERSION,
bin_dir,
clean_env,
console_script,
interpreter,
wheel_path,
)
wheel_path()
#: The four tools `docs/content/mcp.md` promises are absent unless asked for.
DESTRUCTIVE_TOOLS = frozenset(
{"delete_project", "delete_batch", "delete_inference_connection", "delete_preprocessing_recipe"}
)
ALLOW_DESTRUCTIVE_ENV = "VISIONSET_MCP_ALLOW_DESTRUCTIVE"
#: One JSON-RPC answer from a server that has to import fastapi, pydantic and
#: sqlalchemy cold on a shared runner. A ceiling, not a sleep.
RESPONSE_TIMEOUT_SECONDS = 60.0
EXAMPLE_TIMEOUT_SECONDS = 600
# --- the SDK and the console script -------------------------------------------
SDK_PROBE = """
import json, sys
import visionset
from visionset.kernel.domain import GeometryType, LabelClass, SplitRecipe
from visionset.kernel.services import (
AnnotationService, BatchService, DatasetService, IngestService, JobService,
ProjectService, ReleaseService, SchemaService, SourceService, WorkspaceService,
)
from visionset.formats.registry import exporters
from visionset.preprocessing.registry import drivers
with WorkspaceService.init(sys.argv[1]) as workspace:
project = ProjectService(workspace).create("probe")
print(json.dumps({
"version": visionset.__version__,
"file": visionset.__file__,
"exporters": sorted(exporters()),
"drivers": sorted(drivers()),
"project": project.name,
}))
"""
def test_the_documented_sdk_entry_points_import_from_the_venv(
installed: Path, foreign_cwd: Path, tmp_path: Path
) -> None:
result = subprocess.run(
[str(interpreter(installed)), "-I", "-c", SDK_PROBE, str(tmp_path / "ws")],
cwd=foreign_cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stderr
probe = json.loads(result.stdout)
assert probe["version"] == VERSION
assert Path(probe["file"]).resolve().is_relative_to(installed.resolve())
assert {"coco", "ultralytics", "voc"} <= set(probe["exporters"])
assert {"augment", "resize"} <= set(probe["drivers"])
assert probe["project"] == "probe"
def test_the_console_script_runs_from_a_foreign_directory(
installed: Path, foreign_cwd: Path, workspace: Path
) -> None:
def run(*arguments: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[str(console_script(installed)), *arguments],
cwd=foreign_cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
version = run("--version")
assert version.returncode == 0, version.stderr
assert version.stdout.strip() == VERSION
listing = run("project", "list", "--workspace", str(workspace))
assert listing.returncode == 0, listing.stderr
assert listing.stdout.splitlines()[0].split()[0] == "ID"
assert list(foreign_cwd.iterdir()) == []
# --- `visionset mcp` over a real pipe -----------------------------------------
class _Stdio:
"""A JSON-RPC client over a subprocess's pipes that keeps every stdout line.
Both streams are drained on threads so a chatty stderr cannot fill its pipe
and stall the server, and so a missing answer is a timeout, not a hang.
"""
def __init__(self, argv: list[str], *, cwd: Path, env: dict[str, str]) -> None:
self._process = subprocess.Popen(
argv,
cwd=cwd,
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
)
self.stdout_lines: list[str] = []
self._stderr: list[str] = []
self._lines: queue.Queue[str | None] = queue.Queue()
self._next_id = 0
threading.Thread(target=self._pump_stdout, daemon=True).start()
threading.Thread(target=self._pump_stderr, daemon=True).start()
def _pump_stdout(self) -> None:
assert self._process.stdout is not None
for line in self._process.stdout:
self.stdout_lines.append(line)
self._lines.put(line)
self._lines.put(None)
def _pump_stderr(self) -> None:
assert self._process.stderr is not None
self._stderr.extend(self._process.stderr)
def _send(self, message: dict[str, Any]) -> None:
assert self._process.stdin is not None
self._process.stdin.write(json.dumps(message) + "\n")
self._process.stdin.flush()
def notify(self, method: str, params: dict[str, Any] | None = None) -> None:
self._send({"jsonrpc": "2.0", "method": method, "params": params or {}})
def request(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
self._next_id += 1
message = {"jsonrpc": "2.0", "id": self._next_id, "method": method, "params": params or {}}
self._send(message)
while True:
try:
line = self._lines.get(timeout=RESPONSE_TIMEOUT_SECONDS)
except queue.Empty:
raise AssertionError(f"no answer to {method}; stderr:\n{self.stderr}") from None
if line is None:
raise AssertionError(f"the server exited before answering {method}:\n{self.stderr}")
try:
frame = json.loads(line)
except json.JSONDecodeError:
raise AssertionError(f"stdout carried a non-protocol line: {line!r}") from None
if frame.get("id") == self._next_id:
assert "error" not in frame, frame
return dict(frame["result"])
def close(self) -> int:
if self._process.stdin is not None and not self._process.stdin.closed:
self._process.stdin.close()
try:
return self._process.wait(timeout=20)
except subprocess.TimeoutExpired:
self._process.kill()
return self._process.wait(timeout=20)
@property
def stderr(self) -> str:
return "".join(self._stderr)
def _tool_names(argv: list[str], *, cwd: Path, env: dict[str, str]) -> tuple[set[str], _Stdio]:
"""Initialize, list the tools, close stdin, and wait for a clean exit."""
client = _Stdio(argv, cwd=cwd, env=env)
try:
client.request(
"initialize",
{
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "visionset-packaging-tests", "version": "0"},
},
)
client.notify("notifications/initialized")
names = {tool["name"] for tool in client.request("tools/list")["tools"]}
finally:
returncode = client.close()
assert returncode == 0, client.stderr
return names, client
def _mcp_env(**overrides: str) -> dict[str, str]:
env = {k: v for k, v in clean_env().items() if k != "PYTHONSAFEPATH"}
env.pop(ALLOW_DESTRUCTIVE_ENV, None)
env.update(overrides)
return env
def test_stdout_carries_only_protocol_frames_and_the_banner_goes_to_stderr(
installed: Path, foreign_cwd: Path, workspace: Path
) -> None:
names, client = _tool_names(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=foreign_cwd,
env=_mcp_env(),
)
assert "list_projects" in names
assert f"VisionSet {VERSION}" in client.stderr
assert "destructive tools not offered" in client.stderr
assert client.stdout_lines
for line in client.stdout_lines:
assert json.loads(line)["jsonrpc"] == "2.0", line
def test_destructive_tools_are_absent_by_default(
installed: Path, foreign_cwd: Path, workspace: Path
) -> None:
names, _ = _tool_names(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=foreign_cwd,
env=_mcp_env(),
)
assert not names & DESTRUCTIVE_TOOLS
def test_the_flag_offers_the_destructive_tools(
installed: Path, foreign_cwd: Path, workspace: Path
) -> None:
names, client = _tool_names(
[
str(console_script(installed)),
"mcp",
"--workspace",
str(workspace),
"--allow-destructive",
],
cwd=foreign_cwd,
env=_mcp_env(),
)
assert names >= DESTRUCTIVE_TOOLS
assert "destructive tools offered" in client.stderr
def test_an_inherited_env_var_does_not_arm_the_console_command(
installed: Path, foreign_cwd: Path, workspace: Path
) -> None:
"""`visionset mcp` states the variable for its child; only the flag arms it."""
names, _ = _tool_names(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=foreign_cwd,
env=_mcp_env(**{ALLOW_DESTRUCTIVE_ENV: "1"}),
)
assert not names & DESTRUCTIVE_TOOLS
@pytest.mark.parametrize(("value", "offered"), [("1", True), ("0", False)])
def test_the_env_var_arms_the_module_form(
installed: Path, foreign_cwd: Path, workspace: Path, value: str, offered: bool
) -> None:
names, _ = _tool_names(
[str(interpreter(installed)), "-I", "-m", "visionset.mcp.main"],
cwd=foreign_cwd,
env=_mcp_env(VISIONSET_WORKSPACE=str(workspace), **{ALLOW_DESTRUCTIVE_ENV: value}),
)
assert (names >= DESTRUCTIVE_TOOLS) is offered
assert offered or not names & DESTRUCTIVE_TOOLS
RELATIVE_PYTHONPATHS = (":", ".")
@pytest.mark.parametrize(
("shadow", "pythonpath"),
[
(shadow, pythonpath)
for shadow in ("mcp", "visionset")
for pythonpath in (None, "", *RELATIVE_PYTHONPATHS)
if not (shadow == "visionset" and pythonpath in RELATIVE_PYTHONPATHS)
],
)
def test_packages_planted_in_an_untrusted_cwd_are_not_imported(
installed: Path, tmp_path: Path, workspace: Path, shadow: str, pythonpath: str | None
) -> None:
"""#1308 against the installed artifact, with a real protocol exchange.
The fix covers the server child: `-P`, and dropping relative `PYTHONPATH`
entries. A shadowing `visionset/` with a relative `PYTHONPATH` is the launcher
residual pinned by `test_launcher_residual_*` below.
"""
hostile = tmp_path / "untrusted-project"
marker = tmp_path / "planted-code-ran"
(hostile / shadow).mkdir(parents=True)
(hostile / shadow / "__init__.py").write_text(
f"from pathlib import Path\nPath({str(marker)!r}).write_text('imported')\n",
encoding="utf-8",
)
env = _mcp_env()
if pythonpath is not None:
env["PYTHONPATH"] = pythonpath
names, client = _tool_names(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=hostile,
env=env,
)
assert not marker.exists(), client.stderr
assert "list_projects" in names
@pytest.mark.parametrize("pythonpath", RELATIVE_PYTHONPATHS)
def test_launcher_residual_a_relative_pythonpath_imports_a_planted_visionset(
installed: Path, tmp_path: Path, workspace: Path, pythonpath: str
) -> None:
"""A known limit of #1308, pinned so a fix flips it deliberately (see docs/content/security.md).
The `visionset` console launcher imports `visionset` itself, and
`PYTHONPATH=.` puts the hostile cwd ahead of site-packages before any of our
code can drop the entry. Planted code runs and the launcher then dies on the
missing submodule. When it is fixed, replace this with the matrix case above.
"""
hostile = tmp_path / "untrusted-project"
marker = tmp_path / "planted-code-ran"
(hostile / "visionset").mkdir(parents=True)
(hostile / "visionset" / "__init__.py").write_text(
f"from pathlib import Path\nPath({str(marker)!r}).write_text('imported')\n",
encoding="utf-8",
)
completed = subprocess.run(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=hostile,
env={**_mcp_env(), "PYTHONPATH": pythonpath},
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=RESPONSE_TIMEOUT_SECONDS,
check=False,
)
assert marker.exists()
assert completed.returncode != 0
assert completed.stdout == ""
# --- the surface examples, against the wheel ----------------------------------
EXAMPLES = (
"sdk_end_to_end.py",
"ingest_end_to_end.py",
"http_end_to_end.py",
"cli_end_to_end.sh",
"mcp_end_to_end.py",
)
@pytest.mark.parametrize("example", EXAMPLES)
def test_the_example_runs_against_the_installed_wheel(
installed: Path, foreign_cwd: Path, tmp_path: Path, example: str
) -> None:
"""The venv's `bin/` leads PATH, so `visionset` and `python3` are the wheel's.
The Python examples run under `-I`, so neither `examples/` nor the working
directory is on their import path. The shell example's own `python3` blocks
import only Pillow.
"""
script = REPO_ROOT / "examples" / example
dest = tmp_path / "out"
if script.suffix == ".sh":
argv = ["bash", str(script), str(dest)]
else:
argv = [str(interpreter(installed)), "-I", str(script), str(dest)]
env = clean_env()
env["PATH"] = os.pathsep.join([str(bin_dir(installed)), env.get("PATH", "")])
env.pop("VIRTUAL_ENV", None)
result = subprocess.run(
argv,
cwd=foreign_cwd,
env=env,
capture_output=True,
text=True,
timeout=EXAMPLE_TIMEOUT_SECONDS,
check=False,
)
assert result.returncode == 0, f"{result.stdout}\n{result.stderr}"
assert list(foreign_cwd.iterdir()) == []