Repository navigation
Expand file tree
/
Copy pathtest_input_handler.py
More file actions
468 lines (386 loc) · 17.5 KB
/
Copy pathtest_input_handler.py
File metadata and controls
468 lines (386 loc) · 17.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for skillspector input_handler (resolve directory, zip, single file)."""
import ctypes
import os
import sys
from errno import ENOENT
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from skillspector.input_handler import (
ALLOWED_GIT_HOSTS,
InputHandler,
_open_regular_file_from_windows_handle,
_open_regular_file_no_follow,
)
def _mock_windows_secure_open(
monkeypatch: pytest.MonkeyPatch,
source: Path,
*,
handle: int = 1,
attributes: int = 0,
final_path: str | None = None,
) -> None:
"""Install a handle-level Windows open simulation on any platform."""
def get_file_information(_handle: int, information: object) -> bool:
information._obj.dwFileAttributes = attributes # type: ignore[attr-defined]
return True
def get_final_path(_handle: int, buffer: object, _size: int, _flags: int) -> int:
opened_path = final_path or str(source)
buffer.value = opened_path # type: ignore[attr-defined]
return len(opened_path)
kernel32 = SimpleNamespace(
CreateFileW=lambda *_args: handle,
GetFileInformationByHandle=get_file_information,
GetFinalPathNameByHandleW=get_final_path,
CloseHandle=lambda _handle: True,
)
msvcrt = SimpleNamespace(open_osfhandle=lambda _handle, _flags: os.open(source, os.O_RDONLY))
monkeypatch.setattr(ctypes, "WinDLL", lambda *_args, **_kwargs: kernel32, raising=False)
monkeypatch.setattr(os, "O_BINARY", 0, raising=False)
monkeypatch.setitem(sys.modules, "msvcrt", msvcrt)
def test_resolve_directory(tmp_path: Path) -> None:
"""Resolving a local directory returns path and source_type directory."""
(tmp_path / "SKILL.md").write_text("# Skill", encoding="utf-8")
handler = InputHandler()
try:
resolved, source_type = handler.resolve(str(tmp_path))
assert resolved.is_dir()
assert (resolved / "SKILL.md").exists()
assert source_type == "directory"
finally:
handler.cleanup()
def test_resolve_single_md_file(tmp_path: Path) -> None:
"""Resolving a single .md file wraps it in a temp dir."""
f = tmp_path / "doc.md"
f.write_text("# Doc", encoding="utf-8")
handler = InputHandler()
try:
resolved, source_type = handler.resolve(str(f))
assert resolved.is_dir()
assert (resolved / "doc.md").exists()
assert source_type == "file"
finally:
handler.cleanup()
def test_resolve_single_symlinked_file_raises(tmp_path: Path) -> None:
"""Standalone file inputs must not dereference symlinks before scanning."""
secret = tmp_path / "external_secret.md"
secret.write_text("AWS_SECRET=hunter2", encoding="utf-8")
symlink = tmp_path / "SKILL.md"
try:
symlink.symlink_to(secret)
except OSError:
pytest.skip("symlinks are not supported on this filesystem")
handler = InputHandler()
try:
with pytest.raises(ValueError, match="symlinked input"):
handler.resolve(str(symlink))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_resolve_file_with_symlinked_parent_raises(tmp_path: Path) -> None:
"""Standalone file inputs must not traverse a symlinked parent directory."""
external_dir = tmp_path / "external"
external_dir.mkdir()
(external_dir / "secret.md").write_text("AWS_SECRET=hunter2", encoding="utf-8")
symlinked_parent = tmp_path / "linked"
try:
symlinked_parent.symlink_to(external_dir, target_is_directory=True)
except OSError:
pytest.skip("symlinks are not supported on this filesystem")
handler = InputHandler()
try:
with pytest.raises(ValueError, match="symlinked parent"):
handler.resolve(str(symlinked_parent / "secret.md"))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_resolve_directory_with_symlinked_parent_raises(tmp_path: Path) -> None:
"""Directory inputs must not escape through a symlinked ancestor."""
external_skill = tmp_path / "external" / "skill"
external_skill.mkdir(parents=True)
(external_skill / "SKILL.md").write_text("# External skill", encoding="utf-8")
symlinked_parent = tmp_path / "linked"
try:
symlinked_parent.symlink_to(external_skill.parent, target_is_directory=True)
except OSError:
pytest.skip("symlinks are not supported on this filesystem")
handler = InputHandler()
try:
with pytest.raises(ValueError, match="symlinked parent"):
handler.resolve(str(symlinked_parent / external_skill.name))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_resolve_junctioned_directory_raises(tmp_path: Path) -> None:
"""Directory inputs must reject terminal Windows junctions too."""
skill_dir = tmp_path / "skill"
skill_dir.mkdir()
handler = InputHandler()
try:
with patch.object(Path, "is_junction", autospec=True) as is_junction:
is_junction.side_effect = lambda path: path == skill_dir
with pytest.raises(ValueError, match="junctioned input"):
handler.resolve(str(skill_dir))
finally:
handler.cleanup()
def test_resolve_file_with_junction_parent_raises(tmp_path: Path) -> None:
"""Standalone file inputs must not traverse Windows junctions."""
source = tmp_path / "linked" / "SKILL.md"
source.parent.mkdir()
source.write_text("# Skill", encoding="utf-8")
handler = InputHandler()
try:
with patch.object(Path, "is_junction", autospec=True) as is_junction:
is_junction.side_effect = lambda path: path == source.parent
with pytest.raises(ValueError, match="symlinked parent"):
handler.resolve(str(source))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_resolve_file_through_root_owned_system_alias(tmp_path: Path) -> None:
"""Root-owned system aliases do not prevent scanning ordinary local files."""
root_alias = Path("/var")
try:
relative_path = tmp_path.relative_to("/private/var")
except ValueError:
pytest.skip("temporary directory is not below the macOS /var alias")
if not root_alias.is_symlink():
pytest.skip("/var is not a system alias on this platform")
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
handler = InputHandler()
try:
resolved, source_type = handler.resolve(str(root_alias / relative_path / source.name))
assert (resolved / source.name).read_text(encoding="utf-8") == "# Skill"
assert source_type == "file"
finally:
handler.cleanup()
def test_resolve_symlinked_zip_raises(tmp_path: Path) -> None:
"""Local archives must be rejected before their symlink target is opened."""
archive = tmp_path / "external_archive.zip"
archive.write_bytes(b"not opened")
symlink = tmp_path / "skill.zip"
try:
symlink.symlink_to(archive)
except OSError:
pytest.skip("symlinks are not supported on this filesystem")
handler = InputHandler()
try:
with pytest.raises(ValueError, match="symlinked input"):
handler.resolve(str(symlink))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_resolve_file_open_failure_does_not_create_temp_dir(tmp_path: Path) -> None:
"""Failed secure opens leave no handler-owned temporary directory behind."""
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
handler = InputHandler()
try:
with patch("skillspector.input_handler.os.open", side_effect=OSError("denied")):
with pytest.raises(ValueError, match="Could not safely open"):
handler.resolve(str(source))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
@pytest.mark.skipif(not hasattr(os, "O_PATH"), reason="requires O_PATH (Linux)")
@pytest.mark.skipif(
hasattr(os, "geteuid") and os.geteuid() == 0, reason="root bypasses directory permissions"
)
def test_secure_open_traverses_search_only_ancestors(tmp_path: Path) -> None:
"""Traversal needs search access on ancestors, not read access."""
parent = tmp_path / "search_only"
parent.mkdir()
source = parent / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
os.chmod(parent, 0o111)
try:
with _open_regular_file_no_follow(source) as opened:
assert opened.read() == b"# Skill"
finally:
os.chmod(parent, 0o755)
def test_resolve_file_rejects_platform_without_safe_open_support(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Scanning must fail closed when neither secure-open implementation is available."""
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
handler = InputHandler()
try:
monkeypatch.setattr("skillspector.input_handler._HAS_SECURE_DIR_FD", False)
monkeypatch.setattr("skillspector.input_handler._IS_WINDOWS", False)
with pytest.raises(ValueError, match="Secure no-follow file opens are unavailable"):
handler.resolve(str(source))
assert handler.temp_dir_for_cleanup() is None
finally:
handler.cleanup()
def test_windows_no_follow_open_reads_verified_regular_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Windows secure-open accepts a verified regular file handle."""
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
_mock_windows_secure_open(monkeypatch, source)
with _open_regular_file_from_windows_handle(source) as opened:
assert opened.read() == b"# Skill"
def test_windows_no_follow_open_rejects_missing_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Windows secure-open reports a missing file without exposing a handle."""
source = tmp_path / "missing.md"
_mock_windows_secure_open(monkeypatch, source, handle=ctypes.c_void_p(-1).value)
monkeypatch.setattr(
"skillspector.input_handler._windows_last_error", lambda: OSError(ENOENT, "missing")
)
with pytest.raises(FileNotFoundError, match="File not found"):
_open_regular_file_from_windows_handle(source)
def test_windows_no_follow_open_rejects_reparse_point(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Windows secure-open rejects a reparse-point handle before reading it."""
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
_mock_windows_secure_open(monkeypatch, source, attributes=0x00000400)
with pytest.raises(ValueError, match="Could not safely open"):
_open_regular_file_from_windows_handle(source)
def test_windows_no_follow_open_rejects_canonical_path_mismatch(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Windows secure-open rejects a handle whose resolved path changed."""
source = tmp_path / "SKILL.md"
source.write_text("# Skill", encoding="utf-8")
_mock_windows_secure_open(monkeypatch, source, final_path=str(tmp_path / "outside.md"))
with pytest.raises(ValueError, match="Could not safely open"):
_open_regular_file_from_windows_handle(source)
def test_resolve_zip_file(tmp_path: Path) -> None:
"""Resolving a .zip file extracts and returns the extract dir."""
import zipfile
(tmp_path / "SKILL.md").write_text("# Skill", encoding="utf-8")
zip_path = tmp_path / "skill.zip"
with zipfile.ZipFile(zip_path, "w") as zf:
zf.write(tmp_path / "SKILL.md", "SKILL.md")
handler = InputHandler()
try:
resolved, source_type = handler.resolve(str(zip_path))
assert resolved.is_dir()
assert source_type == "zip"
finally:
handler.cleanup()
def test_resolve_nonexistent_raises() -> None:
"""Resolving a nonexistent path raises FileNotFoundError or ValueError."""
handler = InputHandler()
with pytest.raises((FileNotFoundError, ValueError)):
handler.resolve("/nonexistent/path/xyz")
def test_resolve_single_non_md_file(tmp_path: Path) -> None:
"""Resolving a single non-.md file (e.g. .txt) wraps it in a temp dir."""
f = tmp_path / "readme.txt"
f.write_text("Read me", encoding="utf-8")
handler = InputHandler()
try:
resolved, source_type = handler.resolve(str(f))
assert resolved.is_dir()
assert (resolved / "readme.txt").exists()
assert source_type == "file"
finally:
handler.cleanup()
def test_cleanup_idempotent(tmp_path: Path) -> None:
"""cleanup() can be called after resolve and does not raise."""
(tmp_path / "a.md").write_text("x", encoding="utf-8")
handler = InputHandler()
handler.resolve(str(tmp_path / "a.md"))
handler.cleanup()
handler.cleanup()
def test_clone_git_disables_symlinks() -> None:
"""git clone must prevent symlinked entries from materializing as links."""
handler = InputHandler()
try:
def fake_clone(command: list[str], **_kwargs: object) -> MagicMock:
Path(command[-1]).mkdir(parents=True)
process = MagicMock()
process.poll.return_value = 0
process.wait.return_value = 0
return process
with (
patch.object(handler, "_validate_url_host", return_value="github.com"),
patch(
"skillspector.input_handler.subprocess.Popen",
side_effect=fake_clone,
) as mock_run,
):
handler._clone_git("https://github.com/example/repo.git")
cmd = mock_run.call_args.args[0]
assert cmd[:2] == ["git", "-c"]
assert "core.symlinks=false" in cmd
assert cmd.index("-c") < cmd.index("clone")
finally:
handler.cleanup()
def test_scp_url_is_git_url() -> None:
"""scp-style SSH URL is recognised as a Git URL."""
assert InputHandler()._is_git_url("git@github.com:org/repo.git") is True
def test_http_urls_are_not_accepted_as_remote_inputs() -> None:
"""Network inputs require HTTPS unless they use SSH's scp-style syntax."""
handler = InputHandler()
assert handler._is_git_url("http://github.com/org/repo.git") is False
assert handler._is_file_url("http://raw.githubusercontent.com/org/repo/SKILL.md") is False
def test_validate_url_host_scp_extracts_github() -> None:
"""_validate_url_host extracts 'github.com' from an scp-style URL."""
with patch("skillspector.input_handler._is_private_ip", return_value=False):
host = InputHandler()._validate_url_host("git@github.com:org/repo.git", ALLOWED_GIT_HOSTS)
assert host == "github.com"
def test_scp_valid_host_clones() -> None:
"""resolve() calls git clone with the scp URL when the host is allowed."""
handler = InputHandler()
try:
def fake_clone(command: list[str], **_kwargs: object) -> MagicMock:
Path(command[-1]).mkdir(parents=True)
process = MagicMock()
process.poll.return_value = 0
process.wait.return_value = 0
return process
with (
patch("skillspector.input_handler._is_private_ip", return_value=False),
patch(
"skillspector.input_handler.subprocess.Popen", side_effect=fake_clone
) as mock_run,
):
handler.resolve("git@github.com:org/repo.git")
assert mock_run.called
call_args = mock_run.call_args[0][0]
assert "git@github.com:org/repo.git" in call_args
finally:
handler.cleanup()
def test_scp_disallowed_host_raises() -> None:
"""_validate_url_host rejects an scp URL whose host is not in the allowlist."""
with pytest.raises(ValueError, match="not in the allowed hosts"):
InputHandler()._validate_url_host("git@malicious.internal:org/repo.git", ALLOWED_GIT_HOSTS)
def test_scp_private_ip_raises() -> None:
"""_validate_url_host rejects an scp URL whose extracted host is not in the allowlist."""
with pytest.raises(ValueError):
InputHandler()._validate_url_host("git@169.254.169.254:org/repo.git", ALLOWED_GIT_HOSTS)
def test_https_url_unchanged() -> None:
"""https URLs continue to extract the host via urlparse without hitting the scp fallback."""
with patch("skillspector.input_handler._is_private_ip", return_value=False):
host = InputHandler()._validate_url_host(
"https://github.com/org/repo.git", ALLOWED_GIT_HOSTS
)
assert host == "github.com"
def test_scp_ssrf_gate_fires() -> None:
"""SSRF gate raises ValueError for an scp URL whose host resolves to a private IP."""
with patch("skillspector.input_handler._is_private_ip", return_value=True):
with pytest.raises(ValueError, match="private/internal IP"):
InputHandler()._validate_url_host("git@github.com:org/repo.git", ALLOWED_GIT_HOSTS)