pyddock 0.3.0__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {pyddock-0.3.0 → pyddock-0.3.2}/PKG-INFO +1 -1
  2. {pyddock-0.3.0 → pyddock-0.3.2}/pyproject.toml +1 -1
  3. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_audit_enforcement.py +9 -0
  4. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_base.py +41 -0
  5. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_enforcement.py +22 -0
  6. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_fs_enforcement.py +95 -28
  7. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_proxies.py +99 -6
  8. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_subprocess_patch.py +18 -0
  9. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/default_config.toml +53 -9
  10. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/executor.py +10 -1
  11. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/shell_executor.py +86 -29
  12. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_env_policy.py +54 -2
  13. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_executor.py +30 -0
  14. pyddock-0.3.2/tests/test_jailbreak_regression.py +508 -0
  15. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_security_guards.py +78 -0
  16. pyddock-0.3.2/tests/test_trusted_prefixes_uv_cache.py +166 -0
  17. {pyddock-0.3.0 → pyddock-0.3.2}/uv.lock +1 -1
  18. {pyddock-0.3.0 → pyddock-0.3.2}/.gitignore +0 -0
  19. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/.gitignore +0 -0
  20. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/106d94c8123c0256 +0 -0
  21. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/1685e03b3aa38c02 +0 -0
  22. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/1deca112ec6f2f3c +0 -0
  23. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/2488a3a95c48acfb +0 -0
  24. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/2a94d83a13979745 +0 -0
  25. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/499f1d5a639a382a +0 -0
  26. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/4ee6f24fa151b65d +0 -0
  27. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/5b1b2189b70f5ef2 +0 -0
  28. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/5d6f8b26b2137fe1 +0 -0
  29. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/61f9b905d7da14e0 +0 -0
  30. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/67a7f4ab2d372f23 +0 -0
  31. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/6c6f5083ece3f86b +0 -0
  32. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/827e18b40f235443 +0 -0
  33. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/8401e4039d635fbc +0 -0
  34. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/8490e7baefc8c8c3 +0 -0
  35. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/a7c132b836381d0d +0 -0
  36. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/b395547bc71e5c52 +0 -0
  37. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/constants/ca50661510a40488 +0 -0
  38. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/tmp/tmpl8oe65gb +0 -0
  39. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/tmp/tmpqwper0dp +0 -0
  40. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/unicode_data/15.1.0/charmap.json.gz +0 -0
  41. {pyddock-0.3.0 → pyddock-0.3.2}/.hypothesis/unicode_data/15.1.0/codec-utf-8.json.gz +0 -0
  42. {pyddock-0.3.0 → pyddock-0.3.2}/LICENSE +0 -0
  43. {pyddock-0.3.0 → pyddock-0.3.2}/README.md +0 -0
  44. {pyddock-0.3.0 → pyddock-0.3.2}/publish-to-pypi.ps1 +0 -0
  45. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/__init__.py +0 -0
  46. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_import_hook.py +0 -0
  47. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_prewarm.py +0 -0
  48. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_process_utils.py +0 -0
  49. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/_runtime.py +0 -0
  50. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/ast_validator.py +0 -0
  51. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/cli.py +0 -0
  52. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/config.py +0 -0
  53. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/script_registry.py +0 -0
  54. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/server.py +0 -0
  55. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/__init__.py +0 -0
  56. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/fs_append.py +0 -0
  57. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/fs_delete.py +0 -0
  58. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/read_file.py +0 -0
  59. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/stat_file.py +0 -0
  60. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/tools/str_replace.py +0 -0
  61. {pyddock-0.3.0 → pyddock-0.3.2}/src/pyddock/venv_manager.py +0 -0
  62. {pyddock-0.3.0 → pyddock-0.3.2}/tests/__init__.py +0 -0
  63. {pyddock-0.3.0 → pyddock-0.3.2}/tests/_config_helpers.py +0 -0
  64. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_ast_properties.py +0 -0
  65. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_attr_reflection_hardening.py +0 -0
  66. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_audit_hook_backstop.py +0 -0
  67. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_chmod_integration.py +0 -0
  68. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_config.py +0 -0
  69. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_deny_always_wins.py +0 -0
  70. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_deny_messages.py +0 -0
  71. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_file_tools.py +0 -0
  72. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_filesystem_guards.py +0 -0
  73. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_proxy_properties.py +0 -0
  74. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_realistic.py +0 -0
  75. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_runtime.py +0 -0
  76. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_sandbox_escape_hardening.py +0 -0
  77. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_server.py +0 -0
  78. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_shell_arg_paths.py +0 -0
  79. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_shell_executor.py +0 -0
  80. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_shell_properties.py +0 -0
  81. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_subprocess_enforcement.py +0 -0
  82. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_subprocess_properties.py +0 -0
  83. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_subst_trusted_path.py +0 -0
  84. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_venv_stamp.py +0 -0
  85. {pyddock-0.3.0 → pyddock-0.3.2}/tests/test_workspace_imports.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyddock
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: MCP server that gives AI agents pre-approved Python, shell, and file I/O tools with declarative policy controls
5
5
  Project-URL: Homepage, https://github.com/portablestew/pyddock
6
6
  Project-URL: Repository, https://github.com/portablestew/pyddock
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyddock"
3
- version = "0.3.0"
3
+ version = "0.3.2"
4
4
  description = "MCP server that gives AI agents pre-approved Python, shell, and file I/O tools with declarative policy controls"
5
5
  requires-python = ">=3.11"
6
6
  license = "MIT"
@@ -457,6 +457,15 @@ def install_audit_enforcement(
457
457
  pass
458
458
 
459
459
  def _enforce_fs(disp: str, event: str, args: tuple) -> None:
460
+ # NOTE on path-resolution TOCTOU: every fs audit event carries the path
461
+ # value the syscall actually uses — primitives resolve __fspath__ ONCE
462
+ # and raise the event with that resolved str (verified: builtins.open /
463
+ # io.open / os.open / os.mkdir / os.remove / os.scandir deliver a str;
464
+ # _io.FileIO raises 'open' first with its single resolved str, then a
465
+ # redundant event with the original object). So the check here always
466
+ # sees the true target — there is no second, independent resolution to
467
+ # exploit. The materialize-once name-patch layer closes the only real
468
+ # gap (its separate check/use resolutions). Hence no object-type guard.
460
469
  if disp == "fs": # open
461
470
  path = _extract_path(args[0] if args else None)
462
471
  if path is None:
@@ -25,6 +25,7 @@ _PYDDOCK_DIR = _os_for_path.path.dirname(_os_for_path.path.abspath(__file__))
25
25
  _normcase = _os_for_path.path.normcase
26
26
  _realpath = _os_for_path.path.realpath
27
27
  _abspath = _os_for_path.path.abspath
28
+ _os_name = _os_for_path.name
28
29
  del _os_for_path
29
30
 
30
31
  # Module-level dict for storing original (unpatched) function references.
@@ -35,6 +36,46 @@ del _os_for_path
35
36
  _ORIGINALS: dict[str, Any] = {}
36
37
 
37
38
 
39
+ def has_ntfs_stream(path: Any) -> bool:
40
+ """Detect an NTFS alternate-data-stream (ADS) reference in a path.
41
+
42
+ On Windows, ``name:stream`` (and ``name::$DATA``, ``dir:stream``) addresses a
43
+ *different* securable object than the path's lexical components imply: a write
44
+ to ``.pyddock:pwned`` lands a data stream on the ``.pyddock`` directory, yet
45
+ the lexical leaf ``.pyddock:pwned`` is not a child of ``.pyddock`` — so a
46
+ ``relative_to('.pyddock')`` containment check decides "not protected" and the
47
+ write slips through. ``realpath`` does not reliably normalize the stream away
48
+ (a not-yet-existing stream resolves to the literal), so the only sound defense
49
+ is to reject the syntax up front.
50
+
51
+ A ``:`` is only legal as the drive designator at index 1 of the FIRST path
52
+ component (``C:\\...`` or the drive-relative ``C:rest``). A ``:`` anywhere else
53
+ is a stream reference. Returns False on non-Windows, where ``:`` is an
54
+ ordinary, legal filename character.
55
+
56
+ NOTE: this primitive is deliberately strict and makes NO exception for
57
+ URL-looking strings (``https://...``). It guards real filesystem operations
58
+ (``open``/``Path.write_*``), where the argument is always a local path and a
59
+ ``scheme:`` prefix would still carry a stream-bearing ``:``. The one place a
60
+ URL is a legitimate value — a shell CLI argument — filters URLs out *before*
61
+ they reach this check (see ``_looks_like_path`` in shell_executor), so URLs
62
+ never get here in the first place.
63
+ """
64
+ if _os_name != "nt":
65
+ return False
66
+ parts = str(path).replace("/", "\\").split("\\")
67
+ for idx, comp in enumerate(parts):
68
+ if not comp:
69
+ continue
70
+ start = 0
71
+ # First component may carry a 'X:' drive designator (X: or X:rest).
72
+ if idx == 0 and len(comp) >= 2 and comp[0].isalpha() and comp[1] == ":":
73
+ start = 2
74
+ if ":" in comp[start:]:
75
+ return True
76
+ return False
77
+
78
+
38
79
  def canonical_path(path: Any) -> pathlib.Path:
39
80
  """Canonicalize a filesystem path for security containment checks.
40
81
 
@@ -264,6 +264,28 @@ class RuntimeEnforcement:
264
264
  name, _trusted, _skip_proxy, _ws_module_names,
265
265
  include_private=True,
266
266
  )
267
+ # `from <pkg> import <submodule>` loads the submodule through
268
+ # importlib's _handle_fromlist -> _gcd_import, which BYPASSES this
269
+ # hook. So the submodule never reaches the "." in name path above,
270
+ # and the package name is never registered in _loading_names —
271
+ # which made a re-entrant `from <pkg> import <sub>` inside the
272
+ # package's own __init__.py look "outermost" and (before the
273
+ # _initializing guard in _proxy_module_universal) freeze a partial
274
+ # proxy. Proxy the fromlist submodules here, after the parent (and
275
+ # the submodule) have fully loaded, so `from cryptography import
276
+ # x509` yields the same full-API proxy as `import cryptography.x509`.
277
+ if is_outermost:
278
+ fromlist = args[2] if len(args) > 2 else kwargs.get("fromlist")
279
+ if fromlist:
280
+ for entry in fromlist:
281
+ if not isinstance(entry, str) or entry == "*":
282
+ continue
283
+ submod = name + "." + entry
284
+ if submod in sys.modules:
285
+ _proxy_module_universal(
286
+ submod, _trusted, _skip_proxy,
287
+ _ws_module_names, include_private=True,
288
+ )
267
289
  return result
268
290
  # If the module was explicitly pre-warmed as a stdlib internal
269
291
  # (e.g. _strptime), allow re-import from cache. These are lazily
@@ -14,7 +14,7 @@ import tempfile as _tempfile_module
14
14
  import _io as _cio_module
15
15
  from typing import Any
16
16
 
17
- from pyddock._base import _ORIGINALS, _PYDDOCK_DIR, _find_deny_hint, canonical_path
17
+ from pyddock._base import _ORIGINALS, _PYDDOCK_DIR, _find_deny_hint, canonical_path, has_ntfs_stream
18
18
  from pyddock._import_hook import _caller_is_trusted
19
19
  from pyddock._audit_enforcement import install_audit_enforcement
20
20
  from pyddock._process_utils import make_child_env
@@ -239,8 +239,16 @@ def apply_filesystem_scoping(
239
239
 
240
240
  def _check_read(path: pathlib.Path) -> None:
241
241
  """Raise PermissionError if path is outside readable scope."""
242
+ if isinstance(path, bytes):
243
+ path = _real_os.fsdecode(path)
242
244
  if _is_null_device(path):
243
245
  return
246
+ if has_ntfs_stream(path):
247
+ raise PermissionError(
248
+ f"PermissionError: Cannot read '{path}' — NTFS alternate data "
249
+ f"streams (':' in a path component) are not permitted. Use a "
250
+ f"standard file path."
251
+ )
244
252
  resolved = _abspath(path)
245
253
  # Check guards first (first match wins)
246
254
  guard_result = _check_guard(resolved, "read")
@@ -259,8 +267,18 @@ def apply_filesystem_scoping(
259
267
 
260
268
  def _check_write(path: pathlib.Path) -> None:
261
269
  """Raise PermissionError if path is outside writable scope."""
270
+ if isinstance(path, bytes):
271
+ path = _real_os.fsdecode(path)
262
272
  if _is_null_device(path):
263
273
  return
274
+ if has_ntfs_stream(path):
275
+ raise PermissionError(
276
+ f"PermissionError: Cannot write to '{path}' — NTFS alternate "
277
+ f"data streams (':' in a path component) are not permitted. A "
278
+ f"stream reference can address a protected object (e.g. "
279
+ f"'.pyddock:x' writes onto the .pyddock directory). Use a "
280
+ f"standard file path."
281
+ )
264
282
  resolved = _abspath(path)
265
283
  # Check guards first (first match wins)
266
284
  guard_result = _check_guard(resolved, "write")
@@ -338,18 +356,58 @@ def apply_filesystem_scoping(
338
356
  # Any mode containing w, a, x, or + (except bare r) is a write mode
339
357
  return any(c in mode for c in "wax+")
340
358
 
359
+ def _materialize_pathlike(file: Any) -> Any:
360
+ """Resolve a path argument to a frozen str/bytes exactly once (TOCTOU).
361
+
362
+ The patched open-family functions previously checked ``Path(file)`` and
363
+ then handed the ORIGINAL ``file`` object to the real primitive — two
364
+ independent resolutions. A path-like object with a call-counting
365
+ ``__fspath__`` (or a mutable ``bytearray``/``memoryview`` buffer) can
366
+ return a benign value to the check and the protected value to the real
367
+ open. We close that by resolving ONCE here and forcing callers to pass
368
+ the returned value to BOTH the check and the real primitive, so the
369
+ kernel sees exactly what was validated.
370
+
371
+ - ``str``/``bytes`` (incl. subclasses): immutable content — returned as-is.
372
+ - ``bytearray``/``memoryview``: mutable buffer — rejected (a concurrent
373
+ thread could flip it between check and syscall).
374
+ - ``os.PathLike`` (incl. pathlib.Path and any subclass): ``os.fspath`` is
375
+ invoked exactly once; the result must be ``str``/``bytes``.
376
+ Non-path-like objects fall through to ``os.fspath`` which raises the same
377
+ ``TypeError`` the real open would.
378
+ """
379
+ if isinstance(file, (str, bytes)):
380
+ return file
381
+ if isinstance(file, (bytearray, memoryview)):
382
+ raise PermissionError(
383
+ "PermissionError: a mutable path buffer (bytearray/memoryview) "
384
+ "is not permitted as a file path — its contents can change "
385
+ "between the security check and the open (TOCTOU). Pass a str "
386
+ "or bytes path."
387
+ )
388
+ name = _real_os.fspath(file) # single __fspath__ call
389
+ if not isinstance(name, (str, bytes)) or isinstance(name, (bytearray, memoryview)):
390
+ raise PermissionError(
391
+ "PermissionError: __fspath__ must return a str or bytes path."
392
+ )
393
+ return name
394
+
341
395
  # Patch builtins.open
342
396
  _ORIGINALS["builtins.open"] = builtins.open
343
397
 
344
398
  def _patched_open(
345
399
  file: Any, mode: str = "r", *args: Any, **kwargs: Any
346
400
  ) -> Any:
347
- path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
401
+ # Integer file descriptors are already-open handles — no path to check.
402
+ if isinstance(file, int):
403
+ return _ORIGINALS["builtins.open"](file, mode, *args, **kwargs)
404
+ name = _materialize_pathlike(file) # resolve once
348
405
  if _is_write_mode(mode):
349
- _check_write(path)
406
+ _check_write(name)
350
407
  else:
351
- _check_read(path)
352
- return _ORIGINALS["builtins.open"](file, mode, *args, **kwargs)
408
+ _check_read(name)
409
+ # Forward the FROZEN value, never the original object.
410
+ return _ORIGINALS["builtins.open"](name, mode, *args, **kwargs)
353
411
 
354
412
  builtins.open = _patched_open
355
413
 
@@ -513,12 +571,12 @@ def apply_filesystem_scoping(
513
571
  # Skip path checking for integer file descriptors (used internally by subprocess)
514
572
  if isinstance(file, int):
515
573
  return _ORIGINALS["io.open"](file, mode, *args, **kwargs)
516
- path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
574
+ name = _materialize_pathlike(file) # resolve once
517
575
  if _is_write_mode(mode):
518
- _check_write(path)
576
+ _check_write(name)
519
577
  else:
520
- _check_read(path)
521
- return _ORIGINALS["io.open"](file, mode, *args, **kwargs)
578
+ _check_read(name)
579
+ return _ORIGINALS["io.open"](name, mode, *args, **kwargs)
522
580
 
523
581
  _io_module.open = _patched_io_open
524
582
 
@@ -536,12 +594,12 @@ def apply_filesystem_scoping(
536
594
  caller = sys._getframe(1)
537
595
  if caller and caller.f_code.co_filename.startswith("<frozen"):
538
596
  return _ORIGINALS["_io.open"](file, mode, *args, **kwargs)
539
- path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
597
+ name = _materialize_pathlike(file) # resolve once
540
598
  if _is_write_mode(mode):
541
- _check_write(path)
599
+ _check_write(name)
542
600
  else:
543
- _check_read(path)
544
- return _ORIGINALS["_io.open"](file, mode, *args, **kwargs)
601
+ _check_read(name)
602
+ return _ORIGINALS["_io.open"](name, mode, *args, **kwargs)
545
603
 
546
604
  _cio_module.open = _patched_cio_open
547
605
 
@@ -554,13 +612,16 @@ def apply_filesystem_scoping(
554
612
  """FileIO subclass that enforces filesystem scoping on construction."""
555
613
 
556
614
  def __init__(self, file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> None:
557
- if not isinstance(file, int):
558
- path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
559
- if _is_write_mode(mode):
560
- _check_write(path)
561
- else:
562
- _check_read(path)
563
- super().__init__(file, mode, *args, **kwargs)
615
+ if isinstance(file, int):
616
+ super().__init__(file, mode, *args, **kwargs)
617
+ return
618
+ name = _materialize_pathlike(file) # resolve once
619
+ if _is_write_mode(mode):
620
+ _check_write(name)
621
+ else:
622
+ _check_read(name)
623
+ # Construct with the FROZEN value, never the original object.
624
+ super().__init__(name, mode, *args, **kwargs)
564
625
 
565
626
  _io_module.FileIO = _PatchedFileIO
566
627
  _cio_module.FileIO = _PatchedFileIO
@@ -606,14 +667,19 @@ def apply_filesystem_scoping(
606
667
 
607
668
  # Patch os.makedirs and os.mkdir on the safe os proxy to use _check_write.
608
669
  # This ensures .pyddock/, workspace module dirs, and other protected paths
609
- # are enforced (not just the workspace boundary check).
610
-
611
- def _safe_makedirs(name: str, mode: int = 0o777, exist_ok: bool = False) -> None:
612
- _check_write(pathlib.Path(name))
670
+ # are enforced (not just the workspace boundary check). Each resolves the
671
+ # path-like ONCE (_materialize_pathlike) and forwards that frozen value to
672
+ # the real call, so the check and the syscall can't see different paths
673
+ # (the same TOCTOU defense as the open family).
674
+
675
+ def _safe_makedirs(name: Any, mode: int = 0o777, exist_ok: bool = False) -> None:
676
+ name = _materialize_pathlike(name)
677
+ _check_write(name)
613
678
  _real_os.makedirs(name, mode, exist_ok=exist_ok)
614
679
 
615
- def _safe_mkdir(name: str, mode: int = 0o777) -> None:
616
- _check_write(pathlib.Path(name))
680
+ def _safe_mkdir(name: Any, mode: int = 0o777) -> None:
681
+ name = _materialize_pathlike(name)
682
+ _check_write(name)
617
683
  _real_os.mkdir(name, mode)
618
684
 
619
685
  if "os" in sys.modules:
@@ -622,9 +688,10 @@ def apply_filesystem_scoping(
622
688
  safe_os.mkdir = _safe_mkdir
623
689
 
624
690
  # Expose os.chmod with the same validation as Path.chmod.
625
- def _safe_chmod(path: str, mode: int) -> None:
691
+ def _safe_chmod(path: Any, mode: int) -> None:
626
692
  _validate_chmod(mode, "os.chmod()")
627
- _check_write(pathlib.Path(path))
693
+ path = _materialize_pathlike(path)
694
+ _check_write(path)
628
695
  _real_os.chmod(path, mode)
629
696
 
630
697
  if "os" in sys.modules:
@@ -11,6 +11,7 @@ internal state via object.__getattribute__.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import logging
14
15
  import pathlib
15
16
  import re
16
17
  import sys
@@ -20,6 +21,8 @@ from typing import Any
20
21
  from pyddock._base import _find_deny_hint, _is_module_bound_builtin, _wrap_safe_callable
21
22
  from pyddock._import_hook import _caller_is_trusted
22
23
 
24
+ logger = logging.getLogger(__name__)
25
+
23
26
  # ---------------------------------------------------------------------------
24
27
  # MethodFilterProxy
25
28
  # ---------------------------------------------------------------------------
@@ -426,7 +429,16 @@ def _build_trusted_prefixes(
426
429
 
427
430
  Returns normalized, resolved path prefixes for:
428
431
  1. Workspace module directories (editable installs)
429
- 2. The venv's site-packages (transitive deps)
432
+ 2. The .pyddock/venv site-packages — the single authoritative source of
433
+ third-party library code — plus the realpath targets of the venv's own
434
+ symlinked entries (so uv's symlink link-mode, where the venv's packages
435
+ physically live in a shared cache, still resolves as trusted). The venv
436
+ is deliberately the ONLY library location trusted: this keeps the trusted
437
+ set a closed, config-pinned unit so sandbox behavior is repeatable across
438
+ machines and install methods, and does not depend on how pyddock itself
439
+ was installed (e.g. a uvx tool cache on sys.path) or on shared-cache
440
+ contents. A package missing from the venv therefore fails loudly rather
441
+ than being silently trusted from elsewhere on sys.path.
430
442
  3. The Python stdlib Lib directory
431
443
  """
432
444
  _os = real_os if real_os is not None else __import__("os")
@@ -439,22 +451,92 @@ def _build_trusted_prefixes(
439
451
  )
440
452
  prefixes.append(abs_path)
441
453
 
442
- # 2. Venv site-packages (transitive deps of allowed packages)
454
+ # 2. The .pyddock/venv site-packages (the authoritative library location).
455
+ #
456
+ # The trusted set must match where library code physically lives, because
457
+ # _caller_is_trusted compares each caller frame's realpath()-resolved
458
+ # filename against these prefixes. We trust the venv's site-packages and the
459
+ # realpath targets of ITS symlinked entries — nothing else on sys.path.
460
+ #
461
+ # We intentionally do NOT trust arbitrary site-packages/dist-packages dirs
462
+ # found on sys.path (e.g. a uvx tool cache that the bootstrap places on the
463
+ # path, or the per-user site). Trusting those would make the trusted set
464
+ # depend on install layout and shared-cache state, hurting repeatability and
465
+ # widening the attack surface. The companion fix in executor.py appends
466
+ # pyddock's install dir to sys.path (instead of prepending it) so allowed
467
+ # packages resolve from this venv, not from such a cache.
468
+ candidate_site_dirs: list[str] = []
443
469
  if venv_path is not None and venv_path.is_dir():
444
470
  # Find site-packages inside the venv (Windows: Lib/site-packages)
445
471
  for root, dirs, _files in _os.walk(str(venv_path / "Lib")):
446
472
  if "site-packages" in dirs:
447
- sp = _os.path.join(root, "site-packages")
448
- prefixes.append(_os.path.normcase(_os.path.realpath(sp)))
473
+ candidate_site_dirs.append(_os.path.join(root, "site-packages"))
449
474
  break
450
475
  else:
451
476
  # Unix-style layout: lib/pythonX.Y/site-packages
452
477
  for root, dirs, _files in _os.walk(str(venv_path / "lib")):
453
478
  if "site-packages" in dirs:
454
- sp = _os.path.join(root, "site-packages")
455
- prefixes.append(_os.path.normcase(_os.path.realpath(sp)))
479
+ candidate_site_dirs.append(
480
+ _os.path.join(root, "site-packages")
481
+ )
456
482
  break
457
483
 
484
+ # A site-packages dir INSIDE the workspace (other than the write-protected
485
+ # .pyddock/venv) is agent-writable (writable_paths defaults to ["."]), so
486
+ # trusting it would let agent code plant a shadowing module and have it run
487
+ # with full library privileges (free imports, deny-agent secret reads). Skip
488
+ # such dirs and warn — this fires only in the rare case one actually exists
489
+ # (e.g. a symlink target resolving back into the workspace), so it does not
490
+ # pollute normal snippet output.
491
+ _ws_real = _os.path.normcase(_os.path.realpath(str(workspace_root)))
492
+ _venv_real = (
493
+ _os.path.normcase(_os.path.realpath(str(venv_path)))
494
+ if venv_path is not None
495
+ else None
496
+ )
497
+
498
+ def _within(child: str, parent: str) -> bool:
499
+ return child == parent or child.startswith(parent + _os.sep)
500
+
501
+ def _is_agent_writable(resolved: str) -> bool:
502
+ if not _within(resolved, _ws_real):
503
+ return False # outside the workspace (shared cache, system site) — fine
504
+ if _venv_real is not None and _within(resolved, _venv_real):
505
+ return False # the managed, write-protected .pyddock/venv — fine
506
+ return True # inside workspace, outside the managed venv — agent-writable
507
+
508
+ def _add_trusted(resolved: str, *, origin: str) -> None:
509
+ if not _os.path.isdir(resolved):
510
+ return
511
+ if _is_agent_writable(resolved):
512
+ logger.warning(
513
+ "Refusing to trust site-packages directory inside the workspace "
514
+ "(agent-writable, import-shadowing risk): %s (via %s)",
515
+ resolved, origin,
516
+ )
517
+ return
518
+ prefixes.append(resolved)
519
+
520
+ # Trust the venv site-packages and, for uv symlink-mode venvs, the realpath
521
+ # targets of the venv's symlinked entries (the venv's own packages stored in
522
+ # a shared cache). This stays scoped to the venv's declared contents — we do
523
+ # not scan sys.path.
524
+ for _sp in candidate_site_dirs:
525
+ _add_trusted(
526
+ _os.path.normcase(_os.path.realpath(_sp)), origin="venv site-packages"
527
+ )
528
+ try:
529
+ _entries = _os.listdir(_sp)
530
+ except OSError:
531
+ continue
532
+ for _name in _entries:
533
+ _child = _os.path.join(_sp, _name)
534
+ if _os.path.islink(_child):
535
+ _target_dir = _os.path.dirname(
536
+ _os.path.normcase(_os.path.realpath(_child))
537
+ )
538
+ _add_trusted(_target_dir, origin="venv symlink target")
539
+
458
540
  # 3. Python stdlib Lib directory
459
541
  # Use sys.base_prefix to handle virtualenvs correctly — it points to
460
542
  # the original Python installation, not the venv.
@@ -513,6 +595,17 @@ def _proxy_module_universal(
513
595
  if name in skip_modules or top_level in skip_modules:
514
596
  return
515
597
 
598
+ # Never proxy a partially-initialized module. A re-entrant import from inside
599
+ # a package's own __init__.py (e.g. `from cryptography.x509 import oid`,
600
+ # executed before x509 has bound its public classes) can reach here with the
601
+ # module still mid-init; proxying now would freeze an incomplete exported API
602
+ # (the original `from cryptography import x509` -> missing `x509.Name` bug).
603
+ # __spec__._initializing is True only while the module body is executing and
604
+ # flips to False once init completes; proxy only after the module is fully
605
+ # loaded. getattr fallback: a module without __spec__ is treated as complete.
606
+ if getattr(getattr(module, "__spec__", None), "_initializing", False):
607
+ return
608
+
516
609
  # Compute the exported API — these attrs are always accessible to agent code.
517
610
  # Workspace modules get stricter filtering: foreign classes are excluded
518
611
  # to prevent leakage of network-capable factories (e.g. Jira, SSHClient),
@@ -161,13 +161,31 @@ def apply_subprocess_patch(
161
161
  receives the known-good snapshot rather than inheriting the sandbox
162
162
  process environment. Raises PermissionError if an override violates the
163
163
  resolved [env] / [shell.<cmd>.env] policy.
164
+
165
+ The resolution bases (the spawn's effective cwd plus the workspace root)
166
+ let the inert-value filter reject a separator-less value that names a
167
+ real file/dir — a tool may resolve such a bare token as a path relative
168
+ to its cwd (e.g. p4 loading P4EDITOR/P4DIFF from a bare P4ENVIRO file).
164
169
  """
165
170
  deny_patterns, env_default = resolve_env_policy(_env_base, policy)
171
+ resolve_bases: list[pathlib.Path] = [_ws_root]
172
+ cwd = kwargs.get("cwd")
173
+ if cwd is not None:
174
+ cwd_str = (
175
+ cwd.decode("utf-8", "surrogateescape")
176
+ if isinstance(cwd, (bytes, bytearray))
177
+ else str(cwd)
178
+ )
179
+ # `_ws_root / cwd_str` yields cwd_str unchanged when it is absolute,
180
+ # and resolves it against the workspace when relative — matching how
181
+ # the child process resolves its own cwd.
182
+ resolve_bases.append(_ws_root / cwd_str)
166
183
  kwargs["env"] = filter_child_env(
167
184
  kwargs.get("env"),
168
185
  _env_snapshot,
169
186
  deny_patterns=deny_patterns,
170
187
  default=env_default,
188
+ resolve_bases=tuple(resolve_bases),
171
189
  )
172
190
 
173
191
  def _validated_run(cmd: Any, *args: Any, **kwargs: Any) -> Any:
@@ -90,6 +90,8 @@ readable_paths = ["*"]
90
90
  '/\.ssh/' = "deny-agent" # SSH keys — paramiko/GitPython may need access
91
91
  '/\.aws/credentials$' = "deny-agent" # AWS credentials — boto3 needs access
92
92
  '/\.aws/sso/cache/' = "deny-agent" # AWS SSO tokens — boto3 needs access
93
+ '/\.aws/login/cache/' = "deny-agent" # AWS SSO/OIDC login token cache — boto3 needs access
94
+ '/\.aws/cli/cache/' = "deny-agent" # AWS assume-role credential cache — boto3 needs access
93
95
  '/\.docker/config\.json$' = "deny-agent" # Docker registry auth — docker SDK may need access
94
96
  '/\.kube/config$' = "deny-agent" # Kubernetes credentials — k8s client may need access
95
97
  '/\.gnupg/' = "deny-all" # GPG private keys — no library reader in sandbox
@@ -332,7 +334,19 @@ mode = "deny"
332
334
  # upload/receive-pack hooks (local RCE), regardless of the allow-list below.
333
335
  # Also blocks config/command-injection globals that, if injected before the
334
336
  # subcommand, enable arbitrary code execution (-c core.sshCommand=..., etc.).
335
- deny = ["ext::", "--upload-pack", "--receive-pack", "^-c(\\s|$)", "--config-env", "--exec-path"]
337
+ deny = [
338
+ "ext::", "--upload-pack", "--receive-pack", "^-c(\\s|$)",
339
+ "--config-env", "--exec-path",
340
+ # rebase/push/fetch --exec: runs an arbitrary per-commit shell command
341
+ # (git rebase -x/--exec) and is also the documented synonym for
342
+ # --receive-pack (push) / --upload-pack (fetch). No legitimate sandbox use —
343
+ # safe to deny in every subcommand. Does NOT match --exec-path (above).
344
+ "--exec(\\s|=|$)",
345
+ # rebase short form: git rebase -x <cmd> (and "git pull --rebase ... -x").
346
+ # Scoped to the rebase token via re.search so it does NOT clobber the
347
+ # unrelated, legitimate "git clean -x" (remove ignored files).
348
+ "\\brebase\\b.*\\s-x(\\s|$)",
349
+ ]
336
350
  allow = [
337
351
  # Read-only queries
338
352
  "status(\\s|$)", "log(\\s|$)", "diff(\\s|$)", "show(\\s|$)", "rev-parse(\\s|$)",
@@ -396,7 +410,21 @@ allow = [
396
410
  ]
397
411
 
398
412
  [shell.p4.env]
399
- deny = ["P4PORT", "P4CONFIG", "P4DIFF", "P4MERGE", "P4EDITOR", "P4LOGINSSO"]
413
+ # p4 honors several vars that run an external program or load settings (which
414
+ # can themselves re-introduce an exec var) — the env-side equivalents of the
415
+ # command-execution denials. P4CONFIG and P4ENVIRO point to settings files that
416
+ # can define P4EDITOR/P4DIFF/etc., so locking only the exec vars without locking
417
+ # the loaders leaves a redirect (a bare `P4ENVIRO=z.txt` carries no separator,
418
+ # so the inert filter alone won't stop it — hence the hard-lock here).
419
+ deny = [
420
+ "P4PORT", "P4CONFIG", "P4ENVIRO", # connection target / settings-file loaders
421
+ "P4DIFF.*", # arbitrary command on diff (incl. P4DIFFUNICODE)
422
+ "P4MERGE.*", # arbitrary command on resolve/merge (incl. P4MERGEUNICODE)
423
+ "P4EDITOR", # arbitrary command on spec edit (p4 change, ...)
424
+ "P4PAGER", # arbitrary command on paged output
425
+ "P4LOGINSSO", # arbitrary command on SSO login
426
+ "P4ALIASES", # aliases file can rewrite an allowed verb into a denied one (allow-list bypass)
427
+ ]
400
428
 
401
429
  [shell.docker]
402
430
  # Read-only / inspection ONLY. All container lifecycle (compose up/down/build/
@@ -463,15 +491,31 @@ deny = ["DOCKER_HOST", "DOCKER_CONFIG", "DOCKER_CONTEXT"]
463
491
  # layer (captured-reference spawns like GitPython) enforces these locks only.
464
492
  [env]
465
493
  default = "inert"
494
+ # Patterns are re.fullmatch against the KEY name, matched CASE-INSENSITIVELY
495
+ # (see _env_key_locked) — Windows env names are case-insensitive, so a
496
+ # case-sensitive lock would be bypassable via `Path`/`home`. No (?i) needed here.
466
497
  deny = [
467
- "PATH", "PATHEXT", # command resolution hijack
468
- "LD_.*", "DYLD_.*", # ELF / Mach-O loader injection (LD_PRELOAD, ...)
469
- "PSModulePath", # PowerShell module hijack (.ps1 mapping)
470
- "PYTHON.*", # python mapping (.py) — startup/home/path
471
- "TMPDIR", "TEMP", "TMP", # scratch-file redirection
498
+ # --- command / library resolution (PATH family + dynamic loaders) ---
499
+ ".*PATH.*", # PATH, PATHEXT, PYTHONPATH, PSModulePath, GIT_EXEC_PATH,
500
+ # HOMEPATH, CLASSPATH, NODE_PATH, MANPATH, ... (resolution hijack)
501
+ "LD_.*", "DYLD_.*", # ELF / Mach-O loader injection (LD_PRELOAD, DYLD_INSERT_LIBRARIES, ...)
502
+ "PYTHON.*", # python (.py) startup/home/path (PYTHONSTARTUP, PYTHONHOME, ...)
472
503
  "COMSPEC", # cmd /c mapping (.bat)
473
- "BASH_ENV", "ENV", "BASH_FUNC_.*", "PROMPT_COMMAND", # shell startup exec
474
- "EDITOR", "VISUAL", "PAGER", # generic external-command hooks
504
+ # --- home / config discovery (redirect a tool to attacker-controlled config) ---
505
+ ".*HOME.*", # HOME, HOMEDRIVE, HOMEPATH, GNUPGHOME, JAVA_HOME, XDG_*_HOME, ...
506
+ "USERPROFILE", # Windows home fallback — git global ~/.gitconfig discovery
507
+ "XDG_.*", # XDG_CONFIG_HOME/_DIRS, XDG_DATA_HOME/_DIRS, XDG_CACHE_HOME (config/data discovery)
508
+ # --- shell / interpreter startup & option injection ---
509
+ "BASH.*", "ENV", "PROMPT_COMMAND", # shell startup exec (BASH_ENV, BASH_FUNC_*, ...)
510
+ "PERL5.*", # PERL5OPT (-M<module> runs code), PERL5LIB
511
+ "_?JAVA.*", # JAVA_TOOL_OPTIONS, _JAVA_OPTIONS (JVM arg injection); JAVA_HOME also via .*HOME.*
512
+ "NODE_OPTIONS", # node --require / --import code injection
513
+ "RUBY.*", # RUBYOPT (-r<lib> runs code), RUBYLIB
514
+ "LESS.*", # LESSOPEN / LESSCLOSE input-preprocessor command exec
515
+ # --- scratch-file redirection ---
516
+ "TMPDIR", "TEMP", "TMP",
517
+ # --- generic external-command hooks ---
518
+ "EDITOR", "VISUAL", "PAGER",
475
519
  ]
476
520
 
477
521
  # Custom denial hints — appended to rejection messages when the pattern matches
@@ -173,7 +173,16 @@ class SubprocessExecutor:
173
173
  "import sys",
174
174
  "import ast as _ast",
175
175
  "import types as _pyddock_types",
176
- f"sys.path.insert(0, {pyddock_src_path!r})",
176
+ # APPEND (not insert at 0) so pyddock stays importable without letting
177
+ # pyddock's install location win the import-resolution race against the
178
+ # .pyddock/venv. When pyddock is provisioned by a tool like uv, its
179
+ # install dir is a shared cache that also contains pyddock's deps
180
+ # (e.g. cryptography). Prepending it shadowed the venv copy, so those
181
+ # packages loaded from the (untrusted) cache and their internal imports
182
+ # (`from __future__ import annotations`, `import warnings`, ...) were
183
+ # rejected. Appending lets the venv's site-packages take precedence;
184
+ # pyddock itself is only in this dir, so it is still found here.
185
+ f"sys.path.append({pyddock_src_path!r})",
177
186
  f"sys.argv = [{SNIPPET_FILENAME!r}] + {args!r}",
178
187
  "",
179
188
  "# Apply runtime enforcement",