pyddock 0.1.0__py3-none-any.whl

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.
pyddock/_runtime.py ADDED
@@ -0,0 +1,1975 @@
1
+ """Runtime enforcement module for pyddock.
2
+
3
+ This module runs INSIDE the subprocess before user code executes.
4
+ It applies runtime restrictions that complement the static AST analysis:
5
+ - Import hook (blocks non-allowlisted imports)
6
+ - Filesystem scoping (restricts read/write paths)
7
+ - Module and class restrictions (deny/allow patterns for module attrs and class methods)
8
+
9
+ The RuntimeEnforcement class accepts a serialized config dict and workspace_root string.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import _io as _cio_module
15
+ import builtins
16
+ import importlib
17
+ import pathlib
18
+ import re
19
+ import sys
20
+ import tempfile as _tempfile_module
21
+ import types
22
+ from typing import Any
23
+
24
+ from pyddock import SNIPPET_FILENAME
25
+
26
+ # Resolved at module load time (before the import hook activates).
27
+ # Used by _caller_is_trusted to skip pyddock's own frames.
28
+ import os as _os_for_path
29
+ _PYDDOCK_DIR = _os_for_path.path.dirname(_os_for_path.path.abspath(__file__))
30
+ # Cache path helpers for _caller_is_trusted (avoids repeated attribute lookups).
31
+ _normcase = _os_for_path.path.normcase
32
+ _realpath = _os_for_path.path.realpath
33
+ del _os_for_path
34
+
35
+ # Module-level dict for storing original (unpatched) function references.
36
+ # Security-critical wrappers look up originals here instead of capturing them
37
+ # in closure cells. This prevents agent code from extracting originals via
38
+ # function.__closure__[N].cell_contents or descriptor-protocol introspection.
39
+ # Since pyddock._runtime is not importable by agent code, this dict is inaccessible.
40
+ _ORIGINALS: dict[str, Any] = {}
41
+
42
+
43
+ def _is_infra_frame(filename: str) -> bool:
44
+ """Return True if the frame belongs to import infrastructure or pyddock itself.
45
+
46
+ These frames are skipped during stack inspection — they're not
47
+ considered "the real caller" of an import.
48
+ """
49
+ return (
50
+ filename.startswith("<frozen")
51
+ or filename.startswith(_PYDDOCK_DIR)
52
+ )
53
+
54
+
55
+ def _caller_is_trusted(trusted_prefixes: tuple[str, ...]) -> bool:
56
+ """Check if the import call originates from trusted code.
57
+
58
+ Walks the entire call stack. If any frame between the import guard and
59
+ the agent snippet belongs to trusted code (workspace module or
60
+ site-packages), the import is allowed. If the agent snippet is reached
61
+ with no trusted frame found, the import is blocked.
62
+
63
+ Infrastructure frames (frozen importlib, pyddock enforcement) are skipped.
64
+ All other frames are checked against trusted_prefixes or SNIPPET_FILENAME.
65
+ """
66
+ frame = sys._getframe(1)
67
+ found_trusted = False
68
+ while frame is not None:
69
+ filename = frame.f_code.co_filename
70
+ # Skip import machinery and pyddock enforcement frames
71
+ if _is_infra_frame(filename):
72
+ frame = frame.f_back
73
+ continue
74
+ # Agent snippet code — verdict based on whether we found trusted code
75
+ if filename == SNIPPET_FILENAME:
76
+ return found_trusted
77
+ # Resolve symlinks/subst drives and normalize case so that trusted
78
+ # prefix comparison works regardless of path indirection.
79
+ resolved = _normcase(_realpath(filename))
80
+ # Any frame in a trusted path means this import chain was initiated
81
+ # by trusted code (even if it went through stdlib or other libs).
82
+ if resolved.startswith(trusted_prefixes):
83
+ found_trusted = True
84
+ frame = frame.f_back
85
+ return found_trusted
86
+
87
+
88
+
89
+ class _ImportBlocker:
90
+ """Custom import hook that blocks modules not in the allowlist.
91
+
92
+ Installed via sys.meta_path. Raises ImportError with a helpful message
93
+ listing allowed imports when a disallowed module is imported.
94
+
95
+ Uses the modern MetaPathFinder interface (find_spec) which is the
96
+ standard mechanism in Python 3.4+.
97
+
98
+ The hook uses a pure allowlist: only top-level modules explicitly listed
99
+ in the allowlist are permitted — unless the import originates from a
100
+ trusted path (workspace module or its transitive dependency in site-packages).
101
+ """
102
+
103
+ def __init__(self, allowed: list[str], trusted_prefixes: list[str]) -> None:
104
+ self._allowed = set(allowed)
105
+ self._trusted_prefixes = tuple(trusted_prefixes)
106
+
107
+ def find_module(self, fullname: str, path: Any = None) -> _ImportBlocker | None:
108
+ """Legacy import hook interface for compatibility."""
109
+ if self._should_block(fullname):
110
+ return self
111
+ return None
112
+
113
+ def load_module(self, fullname: str) -> None:
114
+ """Raise ImportError for blocked modules (legacy interface)."""
115
+ allowed_list = ", ".join(sorted(self._allowed))
116
+ raise ImportError(
117
+ f"ImportError: '{fullname}' is not an allowed import. "
118
+ f"Please use one of the following allowed imports instead: {allowed_list}"
119
+ )
120
+
121
+ def find_spec(
122
+ self, fullname: str, path: Any = None, target: Any = None
123
+ ) -> None:
124
+ """Modern import hook interface (Python 3.4+).
125
+
126
+ Returns None for allowed imports (letting other finders handle them).
127
+ Raises ImportError directly for blocked imports.
128
+ """
129
+ if self._should_block(fullname):
130
+ allowed_list = ", ".join(sorted(self._allowed))
131
+ raise ImportError(
132
+ f"ImportError: '{fullname}' is not an allowed import. "
133
+ f"Please use one of the following allowed imports instead: "
134
+ f"{allowed_list}"
135
+ )
136
+ return None
137
+
138
+ def _should_block(self, fullname: str) -> bool:
139
+ top_level = fullname.split(".")[0]
140
+ if top_level in self._allowed:
141
+ return False
142
+ # Check if the import originates from trusted code (workspace module
143
+ # or its transitive dependency in site-packages).
144
+ if self._trusted_prefixes and _caller_is_trusted(self._trusted_prefixes):
145
+ return False
146
+ return True
147
+
148
+
149
+ class MethodFilterProxy:
150
+ """Proxy that intercepts attribute access and blocks disallowed methods.
151
+
152
+ Used by FactoryProxy to wrap objects returned by factory functions.
153
+ Only methods matching at least one allow pattern are permitted.
154
+ """
155
+
156
+ def __init__(self, wrapped: Any, allow_patterns: list[re.Pattern[str]]) -> None:
157
+ object.__setattr__(self, "_wrapped", wrapped)
158
+ object.__setattr__(self, "_allow_patterns", allow_patterns)
159
+
160
+ def __getattr__(self, name: str) -> Any:
161
+ allow_patterns = object.__getattribute__(self, "_allow_patterns")
162
+ wrapped = object.__getattribute__(self, "_wrapped")
163
+
164
+ if name.startswith("__") and name.endswith("__"):
165
+ # Allow dunder access for internal Python machinery (repr, str, etc.)
166
+ return getattr(wrapped, name)
167
+
168
+ if not any(p.match(name) for p in allow_patterns):
169
+ patterns_str = ", ".join(p.pattern for p in allow_patterns)
170
+ raise PermissionError(
171
+ f"PermissionError: '{name}' is not permitted. "
172
+ f"Allowed method patterns: {patterns_str}. "
173
+ f"Please use one of the allowed methods instead."
174
+ )
175
+ return getattr(wrapped, name)
176
+
177
+
178
+ class FactoryProxy:
179
+ """Wraps a factory function to return proxied objects.
180
+
181
+ Objects returned by the factory are wrapped in MethodFilterProxy,
182
+ which enforces the allow-pattern list on method access.
183
+ """
184
+
185
+ def __init__(
186
+ self, original_factory: Any, allow_patterns: list[re.Pattern[str]]
187
+ ) -> None:
188
+ self._original = original_factory
189
+ self._allow_patterns = allow_patterns
190
+
191
+ def __call__(self, *args: Any, **kwargs: Any) -> MethodFilterProxy:
192
+ obj = self._original(*args, **kwargs)
193
+ return MethodFilterProxy(obj, self._allow_patterns)
194
+
195
+
196
+ def _expand_patterns(
197
+ patterns: list[str], module: types.ModuleType
198
+ ) -> frozenset[str]:
199
+ """Pre-compute the set of attribute names matching any regex pattern.
200
+
201
+ Evaluates each pattern against dir(module) at proxy creation time.
202
+ This avoids regex evaluation on every attribute access.
203
+
204
+ Args:
205
+ patterns: List of regex pattern strings (from module_allow config).
206
+ module: The real module to scan.
207
+
208
+ Returns:
209
+ Frozenset of concrete attribute names that match at least one pattern.
210
+ """
211
+ matched: set[str] = set()
212
+ for name in dir(module):
213
+ for pattern in patterns:
214
+ if re.match(pattern, name):
215
+ matched.add(name)
216
+ break
217
+ return frozenset(matched)
218
+
219
+
220
+ def _compute_exported_api(
221
+ module: types.ModuleType,
222
+ *,
223
+ exclude_foreign_classes: bool = False,
224
+ ) -> frozenset[str]:
225
+ """Determine which attributes constitute a module's public API.
226
+
227
+ Algorithm:
228
+ 1. If module defines __all__, use exactly those names.
229
+ 2. Otherwise, include all attributes that are NOT instances of
230
+ types.ModuleType (excludes re-exported imports like `os`, `sys`).
231
+ Also exclude private names (starting with _).
232
+ 3. If exclude_foreign_classes is True, also exclude classes whose
233
+ __module__ belongs to a different top-level package. This prevents
234
+ workspace modules from leaking network-capable factory classes
235
+ (e.g. Jira, SSHClient) imported from third-party dependencies.
236
+
237
+ Args:
238
+ module: The module to compute the exported API for.
239
+ exclude_foreign_classes: If True, classes defined in a different
240
+ top-level package are excluded from the exported API. Workspace
241
+ modules that intentionally expose such classes should define
242
+ __all__ to opt in.
243
+
244
+ Returns:
245
+ Frozenset of attribute names considered part of the exported API.
246
+ """
247
+ if hasattr(module, "__all__"):
248
+ return frozenset(module.__all__)
249
+
250
+ module_name = getattr(module, "__name__", "") or ""
251
+ top_level_pkg = module_name.split(".")[0]
252
+
253
+ exported: set[str] = set()
254
+ for name in dir(module):
255
+ if name.startswith("_"):
256
+ continue
257
+ val = getattr(module, name, None)
258
+ if isinstance(val, types.ModuleType):
259
+ continue
260
+ # Exclude foreign classes on workspace modules to prevent leakage
261
+ # of network-capable factories (e.g. atlassian.Jira, paramiko.SSHClient).
262
+ if exclude_foreign_classes and isinstance(val, type):
263
+ cls_module = getattr(val, "__module__", "") or ""
264
+ cls_top_level = cls_module.split(".")[0]
265
+ if cls_module == "builtins":
266
+ # Built-in types (str, int, Exception, etc.) are always safe
267
+ exported.add(name)
268
+ elif cls_top_level == top_level_pkg:
269
+ # Class defined within the same package — safe
270
+ exported.add(name)
271
+ # else: foreign class — exclude from exported API
272
+ continue
273
+ exported.add(name)
274
+ return frozenset(exported)
275
+
276
+
277
+ # Internal state for _CallerScopedModuleProxy instances. Stored here (not on
278
+ # proxy instances) so agent code cannot extract it via object.__getattribute__.
279
+ _PROXY_STATE: dict[int, tuple] = {}
280
+
281
+
282
+ class _CallerScopedModuleProxy(types.ModuleType):
283
+ """Caller-scoped module proxy that enforces attribute access control.
284
+
285
+ Operates in two modes:
286
+
287
+ Simple mode (trusted_prefixes=None):
288
+ - always_allowed: Pre-cached on instance, returned without stack walk.
289
+ - always_blocked: Always raise AttributeError.
290
+ - Everything else: Raise AttributeError (deny by default).
291
+ - Used by: deny-mode modules (boto3), workspace modules.
292
+ - No _caller_is_trusted() invocation — O(1) set check only.
293
+
294
+ Caller-scoped mode (trusted_prefixes provided):
295
+ - always_allowed: Pre-cached on instance, returned without stack walk.
296
+ - always_blocked: Always raise AttributeError.
297
+ - Everything else: Returned only if _caller_is_trusted() is True.
298
+ - Used by: sys proxy only.
299
+ """
300
+
301
+ def __init__(
302
+ self,
303
+ module_name: str,
304
+ real_module: types.ModuleType,
305
+ always_allowed: frozenset[str],
306
+ always_blocked: frozenset[str],
307
+ trusted_prefixes: tuple[str, ...] | None = None, # None = simple mode
308
+ *,
309
+ custom_attrs: dict[str, Any] | None = None,
310
+ ) -> None:
311
+ """
312
+ Args:
313
+ module_name: Name for the proxy module (e.g. "sys", "boto3").
314
+ real_module: The real module being proxied.
315
+ always_allowed: Attribute names always accessible to any caller.
316
+ always_blocked: Attribute names that always raise AttributeError.
317
+ trusted_prefixes: Tuple passed to _caller_is_trusted(). If None,
318
+ the proxy operates in simple mode (allowlist-only,
319
+ no stack walk). If provided, operates in caller-
320
+ scoped mode (sys proxy).
321
+ custom_attrs: Optional dict of custom attribute implementations
322
+ (e.g. sys.exit replacement, FactoryProxy-wrapped
323
+ callables). These are pre-cached and override real
324
+ module values. The real module is NOT mutated.
325
+ """
326
+ super().__init__(module_name)
327
+ # Store internal state in module-level dict, NOT on the instance.
328
+ # This prevents agent code from using object.__getattribute__(proxy, '_real_module').
329
+ _PROXY_STATE[id(self)] = (
330
+ real_module, always_blocked, always_allowed, trusted_prefixes, module_name
331
+ )
332
+
333
+ _custom = custom_attrs or {}
334
+ _MISSING = object()
335
+
336
+ # Pre-cache all always_allowed attributes on the instance.
337
+ # Check custom_attrs first, then fall back to real module.
338
+ # Note: getattr may trigger lazy __getattr__ on modules, which can
339
+ # import submodules that use blocked patterns (e.g. six using
340
+ # attrgetter('__closure__')). We skip those gracefully.
341
+ for name in always_allowed:
342
+ if name in _custom:
343
+ object.__setattr__(self, name, _custom[name])
344
+ else:
345
+ try:
346
+ val = getattr(real_module, name, _MISSING)
347
+ except (PermissionError, ImportError):
348
+ continue
349
+ if val is not _MISSING:
350
+ object.__setattr__(self, name, val)
351
+
352
+ # Pre-cache ALL custom_attrs entries (some may not be in always_allowed).
353
+ for name, val in _custom.items():
354
+ object.__setattr__(self, name, val)
355
+
356
+ # Forward package metadata so Python's import machinery treats this
357
+ # proxy as a proper package (needed for `import boto3.s3` etc.).
358
+ for meta_attr in ("__path__", "__package__", "__file__", "__spec__"):
359
+ val = getattr(real_module, meta_attr, _MISSING)
360
+ if val is not _MISSING:
361
+ object.__setattr__(self, meta_attr, val)
362
+
363
+ def __dir__(self) -> list[str]:
364
+ _, _, always_allowed, _, _ = _PROXY_STATE[id(self)]
365
+ return list(always_allowed)
366
+
367
+ def __getattr__(self, name: str) -> Any:
368
+ """Intercept attribute access for non-cached attributes.
369
+
370
+ Only invoked for EXTERNAL access. Internal module code (code within
371
+ the proxied module) accesses attributes through __globals__ which is
372
+ the module's __dict__ — this method is never called for internal access.
373
+ """
374
+ real_module, always_blocked, always_allowed, trusted_prefixes, module_name = (
375
+ _PROXY_STATE[id(self)]
376
+ )
377
+
378
+ if name in always_blocked:
379
+ raise AttributeError(
380
+ f"module '{module_name}' has no attribute '{name}'"
381
+ )
382
+
383
+ # Fallback for always-allowed (shouldn't fire normally due to pre-caching)
384
+ if name in always_allowed:
385
+ if hasattr(real_module, name):
386
+ return getattr(real_module, name)
387
+ raise AttributeError(
388
+ f"module '{module_name}' has no attribute '{name}'"
389
+ )
390
+
391
+ # Caller-scoped mode (all universal proxies + sys proxy)
392
+ if trusted_prefixes is not None:
393
+ if _caller_is_trusted(trusted_prefixes):
394
+ if hasattr(real_module, name):
395
+ return getattr(real_module, name)
396
+
397
+ # Simple mode or untrusted caller in caller-scoped mode
398
+ raise AttributeError(
399
+ f"module '{module_name}' has no attribute '{name}'"
400
+ )
401
+
402
+
403
+ def _build_trusted_prefixes(
404
+ workspace_root: pathlib.Path,
405
+ workspace_imports: dict[str, str],
406
+ venv_path: pathlib.Path | None,
407
+ real_os: types.ModuleType | None = None,
408
+ ) -> tuple[str, ...]:
409
+ """Build the complete set of trusted path prefixes.
410
+
411
+ Returns normalized, resolved path prefixes for:
412
+ 1. Workspace module directories (editable installs)
413
+ 2. The venv's site-packages (transitive deps)
414
+ 3. The Python stdlib Lib directory
415
+
416
+ This extracts and extends the existing inline prefix-building logic
417
+ from install_import_hook(). The current implementation builds prefixes
418
+ inline; this refactor moves it to a standalone function and adds the
419
+ stdlib Lib directory as a trusted prefix. Called from install_import_hook()
420
+ in place of the inline prefix construction.
421
+
422
+ Args:
423
+ workspace_root: Absolute path to workspace directory.
424
+ workspace_imports: Dict of {module_name: relative_path} from config.
425
+ venv_path: Path to .pyddock/venv if it exists, else None.
426
+ real_os: The real os module (saved in apply_all()). By the time this
427
+ runs, os in sys.modules may be the safe proxy. If None, falls back
428
+ to importing os directly (only safe during early init).
429
+
430
+ Returns:
431
+ Tuple of normalized, lowercased path prefixes with no duplicates.
432
+ """
433
+ _os = real_os if real_os is not None else __import__("os")
434
+ prefixes: list[str] = []
435
+
436
+ # 1. Workspace module directories (editable installs)
437
+ for _name, rel_path in workspace_imports.items():
438
+ abs_path = _os.path.normcase(
439
+ _os.path.realpath(str(workspace_root / rel_path))
440
+ )
441
+ prefixes.append(abs_path)
442
+
443
+ # 2. Venv site-packages (transitive deps of allowed packages)
444
+ if venv_path is not None and venv_path.is_dir():
445
+ # Find site-packages inside the venv (Windows: Lib/site-packages)
446
+ for root, dirs, _files in _os.walk(str(venv_path / "Lib")):
447
+ if "site-packages" in dirs:
448
+ sp = _os.path.join(root, "site-packages")
449
+ prefixes.append(_os.path.normcase(_os.path.realpath(sp)))
450
+ break
451
+ else:
452
+ # Unix-style layout: lib/pythonX.Y/site-packages
453
+ for root, dirs, _files in _os.walk(str(venv_path / "lib")):
454
+ if "site-packages" in dirs:
455
+ sp = _os.path.join(root, "site-packages")
456
+ prefixes.append(_os.path.normcase(_os.path.realpath(sp)))
457
+ break
458
+
459
+ # 3. Python stdlib Lib directory
460
+ # Use sys.base_prefix to handle virtualenvs correctly — it points to
461
+ # the original Python installation, not the venv.
462
+ stdlib_lib = _os.path.join(sys.base_prefix, "Lib")
463
+ if not _os.path.isdir(stdlib_lib):
464
+ # Unix layout: lib/pythonX.Y/
465
+ stdlib_lib = _os.path.join(
466
+ sys.base_prefix, "lib", f"python{sys.version_info.major}.{sys.version_info.minor}"
467
+ )
468
+ prefixes.append(_os.path.normcase(_os.path.realpath(stdlib_lib)))
469
+
470
+ # Deduplicate while preserving order
471
+ seen: set[str] = set()
472
+ unique_prefixes: list[str] = []
473
+ for p in prefixes:
474
+ if p not in seen:
475
+ seen.add(p)
476
+ unique_prefixes.append(p)
477
+
478
+ return tuple(unique_prefixes)
479
+
480
+
481
+ def _proxy_module_universal(
482
+ name: str,
483
+ trusted_prefixes: tuple[str, ...],
484
+ skip_modules: frozenset[str],
485
+ workspace_module_names: frozenset[str] = frozenset(),
486
+ ) -> None:
487
+ """Wrap a module in a caller-scoped proxy (universal mode).
488
+
489
+ Every allowed module gets caller-scoped mode. The always_allowed set
490
+ is the module's exported API (non-ModuleType, non-private attrs).
491
+ Trusted code (stdlib, site-packages, workspace) can access anything.
492
+ Agent code can only access the exported API.
493
+
494
+ Args:
495
+ name: Fully-qualified module name (e.g. "pathlib", "json.decoder").
496
+ trusted_prefixes: Tuple of trusted path prefixes for _caller_is_trusted().
497
+ skip_modules: Set of module names that must not be proxied — only
498
+ {"os", "sys"} plus restriction module names.
499
+ workspace_module_names: Set of top-level workspace module names. Modules
500
+ in this set get stricter filtering that excludes foreign
501
+ classes from the exported API.
502
+ """
503
+ module = sys.modules.get(name)
504
+ if module is None or isinstance(module, _CallerScopedModuleProxy):
505
+ return
506
+ # Skip if this module OR its top-level package is in the skip set.
507
+ # This ensures submodules of os (os.path), sys, and threading are also skipped.
508
+ top_level = name.split(".")[0]
509
+ if name in skip_modules or top_level in skip_modules:
510
+ return
511
+
512
+ # Compute the exported API — these attrs are always accessible to agent code.
513
+ # Workspace modules get stricter filtering: foreign classes are excluded
514
+ # to prevent leakage of network-capable factories (e.g. Jira, SSHClient).
515
+ is_workspace = top_level in workspace_module_names
516
+ always_allowed = _compute_exported_api(module, exclude_foreign_classes=is_workspace)
517
+
518
+ # Include already-loaded submodule names so `import json; json.decoder` works
519
+ prefix = name + "."
520
+ submod_names = frozenset(
521
+ key[len(prefix):].split(".")[0]
522
+ for key in sys.modules
523
+ if key.startswith(prefix)
524
+ )
525
+ always_allowed = always_allowed | submod_names
526
+
527
+ # Always include module metadata attrs
528
+ always_allowed = always_allowed | frozenset({
529
+ "__name__", "__doc__", "__loader__", "__spec__",
530
+ "__package__", "__path__", "__file__",
531
+ })
532
+
533
+ proxy = _CallerScopedModuleProxy(
534
+ module_name=name,
535
+ real_module=module,
536
+ always_allowed=always_allowed,
537
+ always_blocked=frozenset(),
538
+ trusted_prefixes=trusted_prefixes, # caller-scoped mode for ALL
539
+ )
540
+ sys.modules[name] = proxy
541
+
542
+ # Update parent module's reference to point to the proxy.
543
+ # Skip the update if the parent's existing attribute is callable — this
544
+ # handles the case where a package re-exports a function from a submodule
545
+ # (e.g. polars.functions.lit is both a module AND a function attribute).
546
+ # Replacing the callable with a non-callable proxy would break internal calls.
547
+ parts = name.rsplit(".", 1)
548
+ if len(parts) == 2:
549
+ parent_name, child_name = parts
550
+ parent = sys.modules.get(parent_name)
551
+ if parent is not None:
552
+ try:
553
+ existing = object.__getattribute__(parent, child_name) if hasattr(parent, child_name) else None
554
+ except (AttributeError, TypeError):
555
+ existing = None
556
+ # Only update if the existing attr isn't a callable function/class
557
+ # that would be broken by replacing it with a non-callable proxy.
558
+ if existing is None or isinstance(existing, types.ModuleType) or isinstance(existing, _CallerScopedModuleProxy):
559
+ try:
560
+ object.__setattr__(parent, child_name, proxy)
561
+ except (AttributeError, TypeError):
562
+ pass
563
+
564
+
565
+ class RuntimeEnforcement:
566
+ """Applies runtime enforcement inside the subprocess.
567
+
568
+ Constructor accepts:
569
+ config: dict — serialized PyddockConfig (plain dict from executor)
570
+ workspace_root: str — absolute path to the workspace directory
571
+
572
+ Call apply_all() to install all enforcement hooks in order.
573
+ """
574
+
575
+ def __init__(self, config: dict, workspace_root: str) -> None:
576
+ self._config = config
577
+ # Use abspath (not resolve) to preserve symlinks/subst drives
578
+ import os as _os_init
579
+ self._workspace_root = pathlib.Path(_os_init.path.abspath(workspace_root))
580
+
581
+ def apply_all(self) -> None:
582
+ """Apply all enforcement in order: import hook, filesystem, proxies, patches, subprocess."""
583
+ # Save references to modules before safe proxies replace them in sys.modules
584
+ import os as _real_os
585
+ self._real_os = _real_os
586
+ import sys as _real_sys
587
+ self._real_sys = _real_sys
588
+ try:
589
+ import subprocess as _subprocess_module
590
+ self._subprocess_module = _subprocess_module
591
+ except ImportError:
592
+ self._subprocess_module = None
593
+
594
+ # Import resolve_command before the hook blocks pyddock
595
+ from pyddock.shell_executor import resolve_command, _looks_like_path, _extract_path_candidates
596
+ self._resolve_command = resolve_command
597
+ self._looks_like_path = _looks_like_path
598
+ self._extract_path_candidates = _extract_path_candidates
599
+
600
+ # Pre-import modules needed by enforcement methods before the hook activates.
601
+ # These are runtime-internal dependencies, not user-facing.
602
+ import operator as _operator_module
603
+ self._operator_module = _operator_module
604
+ import types as _types_module
605
+ self._types_module = _types_module
606
+ import io as _io_module
607
+ self._io_module = _io_module
608
+ import traceback as _traceback_module
609
+ self._traceback_module = _traceback_module
610
+
611
+ self.install_import_hook()
612
+ self.apply_attrgetter_guard()
613
+ self.apply_filesystem_scoping()
614
+ self.apply_restrictions()
615
+ self.apply_subprocess_patch()
616
+ self.install_module_proxies()
617
+
618
+ def apply_attrgetter_guard(self) -> None:
619
+ """Patch operator.attrgetter and builtins.getattr to reject blocked attribute names.
620
+
621
+ This closes bypasses where attrgetter('__globals__') or
622
+ getattr(obj, '__globals__') is used to access dangerous attributes
623
+ at runtime, bypassing AST-level attribute checks.
624
+ """
625
+ operator = self._operator_module
626
+
627
+ blocked_attrs = set(
628
+ self._config.get("ast", {}).get("block_attributes", [])
629
+ )
630
+ _ORIGINALS["attrgetter"] = operator.attrgetter
631
+ _ORIGINALS["getattr"] = builtins.getattr
632
+
633
+ def _safe_attrgetter(*names: str) -> Any:
634
+ for name in names:
635
+ # Check each dotted component (attrgetter supports 'a.b.c')
636
+ for part in name.split("."):
637
+ if part in blocked_attrs:
638
+ raise PermissionError(
639
+ f"PermissionError: attrgetter access to '{part}' is "
640
+ f"not permitted. Please rewrite your snippet to avoid "
641
+ f"this attribute."
642
+ )
643
+ return _ORIGINALS["attrgetter"](*names)
644
+
645
+ def _safe_getattr(obj: Any, name: str, *default: Any) -> Any:
646
+ if isinstance(name, str) and name in blocked_attrs:
647
+ raise PermissionError(
648
+ f"PermissionError: getattr access to '{name}' is "
649
+ f"not permitted. Please rewrite your snippet to avoid "
650
+ f"this attribute."
651
+ )
652
+ return _ORIGINALS["getattr"](obj, name, *default)
653
+
654
+ operator.attrgetter = _safe_attrgetter
655
+ builtins.getattr = _safe_getattr
656
+
657
+ def install_import_hook(self) -> None:
658
+ """Install a pure-allowlist import hook with stack-aware bypass.
659
+
660
+ Pre-imports all allowed modules first so their transitive dependencies
661
+ are cached in sys.modules before the hook is active. Then installs
662
+ two enforcement points:
663
+ 1. _ImportBlocker on sys.meta_path (fires for uncached modules)
664
+ 2. _guarded_import on builtins.__import__ (fires for ALL imports)
665
+
666
+ Both use the same logic: top-level module in allowlist → allow,
667
+ caller is inside a trusted path (workspace module or site-packages) → allow,
668
+ else → block.
669
+
670
+ Trusted paths include:
671
+ - Workspace module directories (editable installs)
672
+ - The venv's site-packages (transitive dependencies)
673
+ """
674
+ allowed = self._config.get("imports", {}).get("allowed", [])
675
+ allowed_set = set(allowed)
676
+ workspace_imports = self._config.get("imports", {}).get("workspace", {})
677
+
678
+ # Pre-import allowed modules so their transitive dependencies
679
+ # are in sys.modules before the hook activates
680
+ for module_name in allowed:
681
+ try:
682
+ importlib.import_module(module_name)
683
+ except ImportError:
684
+ # Module not installed yet — that's fine, skip it
685
+ pass
686
+
687
+ # Build trusted path prefixes for stack-aware bypass.
688
+ # These are directories where code is allowed to import freely.
689
+ # Includes workspace module dirs, venv site-packages, and stdlib Lib.
690
+ venv_path = self._workspace_root / ".pyddock" / "venv"
691
+ trusted_prefixes_tuple = _build_trusted_prefixes(
692
+ workspace_root=self._workspace_root,
693
+ workspace_imports=workspace_imports,
694
+ venv_path=venv_path if venv_path.is_dir() else None,
695
+ real_os=self._real_os,
696
+ )
697
+ self._trusted_prefixes = trusted_prefixes_tuple
698
+
699
+ # Warm up codecs that may be lazily loaded after the hook activates.
700
+ # Codec lookups trigger imports (e.g. encodings.idna → stringprep)
701
+ # that would be blocked by the pure allowlist. Pre-loading them here
702
+ # caches everything before the hook is installed.
703
+ try:
704
+ import codecs
705
+ for codec_name in ("idna", "utf-8", "ascii", "latin-1", "cp1252", "utf-16-le"):
706
+ try:
707
+ codecs.lookup(codec_name)
708
+ except LookupError:
709
+ pass
710
+ except ImportError:
711
+ pass
712
+
713
+ blocker = _ImportBlocker(allowed, trusted_prefixes_tuple)
714
+ # Insert at the beginning so it's checked first
715
+ sys.meta_path.insert(0, blocker)
716
+
717
+ # Patch builtins.__import__ to enforce the allowlist directly.
718
+ # This closes the bypass where attacker accesses __import__ from
719
+ # a function's __globals__['__builtins__'] dict.
720
+ _ORIGINALS["import"] = builtins.__import__
721
+ _trusted = trusted_prefixes_tuple
722
+ _loading_depth = [0] # reentrant counter: >0 while loading an allowed module
723
+ # Modules that must NOT be wrapped by _proxy_module_universal:
724
+ # os: plain types.ModuleType with safe attrs only (not a _CallerScopedModuleProxy)
725
+ # sys: specialized caller-scoped proxy with custom_attrs
726
+ # threading: _shutdown() called from C/frozen frames during interpreter exit
727
+ # Restriction modules are NOT skipped — mode="deny" modules already have a
728
+ # _CallerScopedModuleProxy (isinstance early-return), and mode="allow" modules
729
+ # need caller-scoped proxying to block ModuleType attr leakage (e.g. polars.os).
730
+ _skip_proxy = frozenset({"os", "sys", "threading"})
731
+ _ws_module_names = frozenset(workspace_imports.keys())
732
+
733
+ def _guarded_import(name: str, *args: Any, **kwargs: Any) -> Any:
734
+ # For relative imports (level > 0), the name is relative to the
735
+ # calling package which is already allowed. Let them through.
736
+ # args[3] is 'level' in the __import__ signature:
737
+ # __import__(name, globals, locals, fromlist, level)
738
+ level = args[3] if len(args) > 3 else kwargs.get("level", 0)
739
+ if level and level > 0:
740
+ return _ORIGINALS["import"](name, *args, **kwargs)
741
+ top_level = name.split(".")[0]
742
+ if top_level in allowed_set:
743
+ # Track that we're loading an allowed module — imports
744
+ # triggered by frozen import machinery during this load
745
+ # are allowed (e.g. _io for .pyc cache writing).
746
+ _loading_depth[0] += 1
747
+ try:
748
+ result = _ORIGINALS["import"](name, *args, **kwargs)
749
+ finally:
750
+ _loading_depth[0] -= 1
751
+ # Proxy ANY submodule import so agent code can't access
752
+ # leaked imports (e.g. pathlib.os, tempfile.os, json.decoder.os).
753
+ if "." in name:
754
+ _proxy_module_universal(name, _trusted, _skip_proxy, _ws_module_names)
755
+ return result
756
+ # If we're inside the loading of an allowed module AND the
757
+ # immediate caller is frozen import machinery, permit the import.
758
+ # This narrowly handles internal machinery needs (codec loading,
759
+ # .pyc writing) without opening a general bypass.
760
+ if _loading_depth[0] > 0:
761
+ caller = sys._getframe(1)
762
+ if caller and caller.f_code.co_filename.startswith("<frozen"):
763
+ return _ORIGINALS["import"](name, *args, **kwargs)
764
+ # Stack-aware bypass: allow imports from trusted code paths
765
+ # (workspace modules, their transitive deps in site-packages).
766
+ if _trusted and _caller_is_trusted(_trusted):
767
+ return _ORIGINALS["import"](name, *args, **kwargs)
768
+ allowed_list = ", ".join(sorted(allowed_set))
769
+ raise ImportError(
770
+ f"ImportError: '{name}' is not an allowed import. "
771
+ f"Please use one of the following allowed imports "
772
+ f"instead: {allowed_list}"
773
+ )
774
+
775
+ builtins.__import__ = _guarded_import
776
+
777
+ # Install a safe sys proxy if 'sys' is in the allowlist.
778
+ # This gives user code access to sys.argv, sys.platform, etc.
779
+ # without exposing sys.modules, sys.meta_path, or other dangerous attrs.
780
+ # Trusted code (workspace modules, site-packages) gets full sys access.
781
+ if "sys" in allowed_set:
782
+ self._install_safe_sys(trusted_prefixes_tuple)
783
+
784
+ # Install a safe os proxy if 'os' is in the allowlist.
785
+ # Exposes os.environ, os.getcwd(), os.name, os.sep, os.path, etc.
786
+ # without exposing os.system, os.popen, os.exec*, os.spawn*, etc.
787
+ if "os" in allowed_set:
788
+ self._install_safe_os()
789
+
790
+ # Install module proxies on ALL allowed modules to prevent attribute
791
+ # leakage. This blocks agent code from accessing imported modules via
792
+ # e.g. pathlib.os, tempfile.os, workspace_pkg.sys, etc.
793
+ # Skip: os/sys (have specialized proxies), restriction modules (handled
794
+ # by apply_restrictions()), and anything already proxied.
795
+ # NOTE: This is called later by install_module_proxies() after all
796
+ # patches are applied, so proxies capture the patched versions.
797
+ self._allowed_set = allowed_set
798
+
799
+ def install_module_proxies(self) -> None:
800
+ """Wrap ALL allowed modules in caller-scoped proxies.
801
+
802
+ Replaces the old implementation that only proxied workspace modules
803
+ and patched os references on stdlib modules.
804
+
805
+ Called LAST in apply_all() so that all runtime patches are applied first.
806
+ The proxies then pre-cache the patched versions of attributes.
807
+
808
+ This blocks agent code from accessing imported modules via e.g.
809
+ pathlib.os, tempfile.os, workspace_pkg.sys, etc.
810
+ """
811
+ # Build the skip set: only os/sys/threading need skipping.
812
+ # subprocess and tempfile are NOT skipped — they are patched on the real module
813
+ # before proxying, and the proxy pre-caches the patched versions (since
814
+ # install_module_proxies runs last). threading IS skipped because _shutdown()
815
+ # is called during interpreter exit from C code / frozen frames, not from
816
+ # stdlib code with a file path — so _caller_is_trusted() would return False.
817
+ # Restriction modules are NOT skipped:
818
+ # - mode="deny" (boto3): already a _CallerScopedModuleProxy → isinstance early-return
819
+ # - mode="allow" (polars): real module with _blocked stubs → gets caller-scoped
820
+ # proxy to block ModuleType attr leakage (e.g. polars.os)
821
+ skip_modules = frozenset({"os", "sys", "threading"})
822
+
823
+ # Identify workspace module names for stricter class filtering.
824
+ workspace_imports = self._config.get("imports", {}).get("workspace", {})
825
+ workspace_module_names = frozenset(workspace_imports.keys())
826
+
827
+ for mod_name in list(sys.modules.keys()):
828
+ top = mod_name.split(".")[0]
829
+ if top not in self._allowed_set:
830
+ continue
831
+ _proxy_module_universal(
832
+ mod_name, self._trusted_prefixes, skip_modules, workspace_module_names
833
+ )
834
+
835
+ def _install_safe_sys(self, trusted_prefixes: tuple[str, ...]) -> None:
836
+ """Replace sys in sys.modules with a caller-scoped proxy.
837
+
838
+ The proxy has three access tiers:
839
+ 1. SAFE_ATTRS: Always accessible by anyone (argv, platform, stdout, etc.)
840
+ 2. BLOCKED_ATTRS: Always blocked for everyone (meta_path, _getframe —
841
+ these would allow sandbox escape even from trusted code)
842
+ 3. Everything else: Accessible only to trusted callers (workspace modules,
843
+ site-packages). Agent snippet code gets AttributeError.
844
+
845
+ This allows libraries like pywin32 (running from site-packages) to access
846
+ sys.modules, sys.path, etc. during their bootstrap, while preventing agent
847
+ code from using those attributes to escape the sandbox.
848
+ """
849
+ _real_sys = sys
850
+ _traceback_mod = self._traceback_module
851
+
852
+ # Attributes always safe for anyone (read-only values, streams, etc.)
853
+ _SAFE_ATTRS = frozenset({
854
+ "argv", "platform", "version", "version_info", "maxsize",
855
+ "byteorder", "executable", "prefix", "exec_prefix",
856
+ "stdout", "stderr", "stdin",
857
+ "float_info", "int_info", "hash_info",
858
+ "getdefaultencoding", "getfilesystemencoding",
859
+ "getrecursionlimit",
860
+ "path", # frozen tuple copy for agent code (read-only)
861
+ "exit",
862
+ "exc_info",
863
+ "_pyddock_format_tb",
864
+ # Module metadata attrs Python expects on all modules
865
+ "__name__", "__doc__", "__loader__", "__spec__",
866
+ "__package__", "__path__",
867
+ })
868
+
869
+ # Attributes NEVER exposed — even trusted code shouldn't remove
870
+ # the import hook or inspect frames through the proxy.
871
+ _BLOCKED_ATTRS = frozenset({
872
+ "meta_path", # removing import blocker = sandbox escape
873
+ "path_hooks", # manipulating import machinery
874
+ "path_importer_cache",
875
+ "_getframe", # frame access = globals access = sandbox escape
876
+ "_current_frames",
877
+ })
878
+
879
+ # Build custom_attrs dict with sys-specific custom implementations.
880
+
881
+ # sys.exit — harmless in subprocess (raises SystemExit)
882
+ def _safe_exit(code: int = 0) -> None:
883
+ raise SystemExit(code)
884
+
885
+ # sys.exc_info() — strip traceback to prevent frame access
886
+ def _safe_exc_info() -> tuple:
887
+ typ, val, _tb = _real_sys.exc_info()
888
+ return (typ, val, None)
889
+
890
+ # sys._pyddock_format_tb() — safe traceback alternative
891
+ def _safe_format_tb() -> list[tuple[str, int, str, str | None]]:
892
+ _typ, _val, tb = _real_sys.exc_info()
893
+ if tb is None:
894
+ return []
895
+ entries = _traceback_mod.extract_tb(tb)
896
+ return [(e.filename, e.lineno, e.name, e.line) for e in entries]
897
+
898
+ custom_attrs = {
899
+ "exit": _safe_exit,
900
+ "exc_info": _safe_exc_info,
901
+ "path": tuple(_real_sys.path),
902
+ "_pyddock_format_tb": _safe_format_tb,
903
+ }
904
+
905
+ # Instantiate the unified caller-scoped proxy for sys
906
+ proxy = _CallerScopedModuleProxy(
907
+ module_name="sys",
908
+ real_module=_real_sys,
909
+ always_allowed=_SAFE_ATTRS,
910
+ always_blocked=_BLOCKED_ATTRS,
911
+ trusted_prefixes=tuple(trusted_prefixes),
912
+ custom_attrs=custom_attrs,
913
+ )
914
+
915
+ # Put the caller-scoped proxy where 'import sys' will find it
916
+ _real_sys.modules["sys"] = proxy
917
+
918
+ def _install_safe_os(self) -> None:
919
+ """Replace os in sys.modules with a safe proxy exposing only benign attrs."""
920
+ _real_os = self._real_os
921
+ types = self._types_module
922
+
923
+ safe_os = types.ModuleType("os")
924
+ safe_os.__doc__ = "Safe os proxy provided by pyddock."
925
+ safe_os._pyddock_safe = True
926
+
927
+ # Safe constants and attributes
928
+ _safe_attrs = [
929
+ "name", "sep", "altsep", "extsep", "pathsep", "linesep",
930
+ "curdir", "pardir", "devnull",
931
+ "cpu_count", "PathLike", "fspath",
932
+ ]
933
+ for attr in _safe_attrs:
934
+ if hasattr(_real_os, attr):
935
+ setattr(safe_os, attr, getattr(_real_os, attr))
936
+
937
+ # Safe functions (read-only operations)
938
+ _safe_funcs = [
939
+ "getcwd", "getpid", "getlogin",
940
+ "getenv",
941
+ "listdir", "scandir", "walk",
942
+ "stat", "lstat", "fstat",
943
+ "path", # os.path submodule (pure path manipulation)
944
+ ]
945
+ for attr in _safe_funcs:
946
+ if hasattr(_real_os, attr):
947
+ setattr(safe_os, attr, getattr(_real_os, attr))
948
+
949
+ # os.environ — expose as read-only (MappingProxyType)
950
+ MappingProxyType = self._types_module.MappingProxyType
951
+ safe_os.environ = MappingProxyType(dict(_real_os.environ))
952
+
953
+ # Workspace-scoped directory operations are patched in apply_filesystem_scoping()
954
+ # where the full _check_write logic (including .pyddock/ and workspace module
955
+ # protection) is available. Here we just expose stubs that will be replaced.
956
+
957
+ # Put the safe proxy where 'import os' will find it
958
+ sys.modules["os"] = safe_os
959
+ # Also update os.path reference to use the real os.path
960
+ sys.modules["os.path"] = _real_os.path
961
+
962
+ def apply_filesystem_scoping(self) -> None:
963
+ """Patch filesystem operations to enforce path restrictions.
964
+
965
+ Patches:
966
+ - builtins.open (read and write modes)
967
+ - pathlib.Path.write_text, write_bytes, open (write modes)
968
+ - pathlib.Path.read_text, read_bytes
969
+ """
970
+ fs_config = self._config.get("filesystem", {})
971
+ writable_paths = fs_config.get("writable_paths", ["."])
972
+ readable_paths = fs_config.get("readable_paths", ["."])
973
+ workspace_root = self._workspace_root
974
+ _real_os = self._real_os
975
+
976
+ def _abspath(p: pathlib.Path) -> pathlib.Path:
977
+ """Normalize path without resolving symlinks/subst drives."""
978
+ return pathlib.Path(_real_os.path.abspath(str(p)))
979
+
980
+ # Resolve allowed paths to absolute (preserving symlinks)
981
+ resolved_writable = [
982
+ _abspath(workspace_root / p) for p in writable_paths
983
+ ]
984
+
985
+ # "*" means unrestricted reads
986
+ unrestricted_reads = "*" in readable_paths
987
+ resolved_readable = [
988
+ _abspath(workspace_root / p) for p in readable_paths if p != "*"
989
+ ]
990
+
991
+ # .pyddock/ is always excluded from writes (self-modification protection)
992
+ pyddock_dir = _abspath(workspace_root / ".pyddock")
993
+
994
+ # Resolve workspace module directories (write-protected)
995
+ workspace_imports = self._config.get("imports", {}).get("workspace", {})
996
+ workspace_module_dirs: list[pathlib.Path] = [
997
+ _abspath(workspace_root / rel_path)
998
+ for rel_path in workspace_imports.values()
999
+ ]
1000
+
1001
+ # Compute stdlib Lib directory path for write protection.
1002
+ # Uses sys.base_prefix (same logic as _build_trusted_prefixes) to handle
1003
+ # virtualenvs correctly — it points to the original Python installation.
1004
+ _stdlib_lib_candidate = _real_os.path.join(sys.base_prefix, "Lib")
1005
+ if not _real_os.path.isdir(_stdlib_lib_candidate):
1006
+ # Unix layout: lib/pythonX.Y/
1007
+ _stdlib_lib_candidate = _real_os.path.join(
1008
+ sys.base_prefix, "lib",
1009
+ f"python{sys.version_info.major}.{sys.version_info.minor}"
1010
+ )
1011
+ _stdlib_lib_path = pathlib.Path(_real_os.path.realpath(_stdlib_lib_candidate))
1012
+
1013
+ # Derive write-protected paths from shell policies
1014
+ shell_config = self._config.get("shell", {})
1015
+ shell_protected_dirs: list[pathlib.Path] = []
1016
+ for _name, policy in shell_config.items():
1017
+ cmd_regex = policy.get("command", "")
1018
+ # Heuristic: regex is path-like if it contains path separators or starts with \.
1019
+ if "/" in cmd_regex or "\\\\" in cmd_regex or cmd_regex.startswith("\\."):
1020
+ path_pattern = cmd_regex.lstrip("^").rstrip("$")
1021
+ if "/" in path_pattern:
1022
+ dir_part = path_pattern.rsplit("/", 1)[0]
1023
+ elif "\\\\" in path_pattern:
1024
+ dir_part = path_pattern.rsplit("\\\\", 1)[0]
1025
+ else:
1026
+ dir_part = path_pattern
1027
+ if dir_part:
1028
+ # Clean up regex escapes to get a usable filesystem path
1029
+ # Common regex escapes: \. → ., \/ → /, \\ → \
1030
+ clean_dir = dir_part.replace("\\.", ".").replace("\\/", "/")
1031
+ # Remove any remaining regex metacharacters that aren't path chars
1032
+ # (keep alphanumeric, /, \, ., -, _)
1033
+ shell_protected_dirs.append(
1034
+ _abspath(workspace_root / clean_dir)
1035
+ )
1036
+
1037
+ # Compile filesystem guards (regex → disposition, first match wins).
1038
+ # Guards apply to BOTH reads and writes.
1039
+ guards_config = fs_config.get("guards", [])
1040
+ compiled_guards: list[tuple[re.Pattern[str], str]] = []
1041
+ for guard in guards_config:
1042
+ pattern_str = guard.get("pattern", "") if isinstance(guard, dict) else ""
1043
+ disposition = guard.get("disposition", "deny") if isinstance(guard, dict) else "deny"
1044
+ try:
1045
+ compiled_guards.append((re.compile(pattern_str), disposition))
1046
+ except re.error:
1047
+ pass # Skip invalid patterns silently (logged at config load time)
1048
+
1049
+ _workspace_root_abs = _abspath(workspace_root)
1050
+ _guard_trusted_prefixes = self._trusted_prefixes
1051
+
1052
+ def _check_guard(path: pathlib.Path, operation: str) -> bool | None:
1053
+ """Check path against filesystem guards. Returns:
1054
+ - True if access is explicitly allowed
1055
+ - False (raises) if access is denied
1056
+ - None if no guard matched (fall through to normal logic)
1057
+
1058
+ Args:
1059
+ path: The resolved absolute path to check.
1060
+ operation: "read" or "write" (for error messages).
1061
+ """
1062
+ # Normalize to forward slashes for cross-platform regex matching
1063
+ path_str = str(path).replace("\\", "/")
1064
+
1065
+ for pattern, disposition in compiled_guards:
1066
+ if pattern.search(path_str):
1067
+ if disposition == "deny-agent":
1068
+ # "deny-agent" blocks agent code but allows trusted libraries
1069
+ # (site-packages, workspace modules) to access the path.
1070
+ if _guard_trusted_prefixes and _caller_is_trusted(_guard_trusted_prefixes):
1071
+ return True # trusted library — allow
1072
+ raise PermissionError(
1073
+ f"PermissionError: Cannot {operation} '{path}' — "
1074
+ f"path matches a filesystem guard (pattern: "
1075
+ f"'{pattern.pattern}', disposition: deny-agent). "
1076
+ f"This path is blocked for security."
1077
+ )
1078
+ elif disposition == "deny-all":
1079
+ # "deny-all" blocks everyone unconditionally — no
1080
+ # trusted caller bypass. Use for paths where no
1081
+ # legitimate library reader exists in this sandbox.
1082
+ raise PermissionError(
1083
+ f"PermissionError: Cannot {operation} '{path}' — "
1084
+ f"path matches a filesystem guard (pattern: "
1085
+ f"'{pattern.pattern}', disposition: deny-all). "
1086
+ f"This path is blocked for security."
1087
+ )
1088
+ elif disposition == "workspace":
1089
+ try:
1090
+ path.relative_to(_workspace_root_abs)
1091
+ return True # inside workspace — allowed
1092
+ except ValueError:
1093
+ raise PermissionError(
1094
+ f"PermissionError: Cannot {operation} '{path}' — "
1095
+ f"path matches a filesystem guard (pattern: "
1096
+ f"'{pattern.pattern}', disposition: workspace). "
1097
+ f"This path is only accessible inside the workspace."
1098
+ )
1099
+ elif disposition == "allow":
1100
+ return True # explicitly allowed
1101
+ return None # no guard matched
1102
+
1103
+ def _is_within(target: pathlib.Path, allowed_roots: list[pathlib.Path]) -> bool:
1104
+ """Check if target path is within any of the allowed roots."""
1105
+ resolved_target = _abspath(target)
1106
+ for root in allowed_roots:
1107
+ try:
1108
+ resolved_target.relative_to(root)
1109
+ return True
1110
+ except ValueError:
1111
+ continue
1112
+ return False
1113
+
1114
+ def _is_pyddock_path(target: pathlib.Path) -> bool:
1115
+ """Check if target path is inside .pyddock/ directory (excluding tmp/)."""
1116
+ try:
1117
+ rel = _abspath(target).relative_to(pyddock_dir)
1118
+ # Allow writes to .pyddock/tmp/ and anything inside it.
1119
+ # This is used by tempfile (NamedTemporaryFile passes the dir
1120
+ # path to _io.open with a custom opener).
1121
+ rel_str = str(rel)
1122
+ if rel_str.startswith("tmp"):
1123
+ return False
1124
+ return True
1125
+ except ValueError:
1126
+ return False
1127
+
1128
+ def _check_read(path: pathlib.Path) -> None:
1129
+ """Raise PermissionError if path is outside readable scope."""
1130
+ resolved = _abspath(path)
1131
+ # Check guards first (first match wins)
1132
+ guard_result = _check_guard(resolved, "read")
1133
+ if guard_result is True:
1134
+ return # explicitly allowed by guard
1135
+ # guard_result is None — no guard matched, fall through
1136
+ if unrestricted_reads:
1137
+ return
1138
+ if not _is_within(resolved, resolved_readable):
1139
+ paths_str = ", ".join(str(p) for p in resolved_readable)
1140
+ raise PermissionError(
1141
+ f"PermissionError: Cannot read '{path}' — reads are restricted "
1142
+ f"to the workspace directory. Please use a path within the "
1143
+ f"workspace instead."
1144
+ )
1145
+
1146
+ def _check_write(path: pathlib.Path) -> None:
1147
+ """Raise PermissionError if path is outside writable scope."""
1148
+ resolved = _abspath(path)
1149
+ # Check guards first (first match wins)
1150
+ guard_result = _check_guard(resolved, "write")
1151
+ # Even if guard says "allow", still enforce structural protections
1152
+ # (.pyddock/, pyddock source, stdlib, workspace modules, shell dirs).
1153
+ # Guards can only DENY or relax the writable_paths boundary — they
1154
+ # cannot override structural write protections.
1155
+
1156
+ if _is_pyddock_path(path):
1157
+ raise PermissionError(
1158
+ f"PermissionError: Cannot write to '{path}' — the .pyddock/ "
1159
+ f"directory is protected. Snippets cannot modify their own "
1160
+ f"configuration or environment."
1161
+ )
1162
+ # Protect pyddock's own source directory (enforcement code)
1163
+ try:
1164
+ resolved.relative_to(pathlib.Path(_PYDDOCK_DIR))
1165
+ raise PermissionError(
1166
+ f"PermissionError: Cannot write to '{path}' — the pyddock "
1167
+ f"source directory is protected."
1168
+ )
1169
+ except ValueError:
1170
+ pass
1171
+ # Protect the Python stdlib Lib directory
1172
+ try:
1173
+ resolved.relative_to(_stdlib_lib_path)
1174
+ raise PermissionError(
1175
+ f"PermissionError: Cannot write to '{path}' — the Python "
1176
+ f"standard library directory is protected."
1177
+ )
1178
+ except ValueError:
1179
+ pass
1180
+ # Check workspace module directory protection
1181
+ for ws_dir in workspace_module_dirs:
1182
+ try:
1183
+ resolved.relative_to(ws_dir)
1184
+ raise PermissionError(
1185
+ f"Cannot write to '{path}' — workspace module "
1186
+ f"directories are protected."
1187
+ )
1188
+ except ValueError:
1189
+ continue
1190
+ # Check shell write protection (prevent write-then-execute escalation)
1191
+ for protected_dir in shell_protected_dirs:
1192
+ try:
1193
+ resolved.relative_to(protected_dir)
1194
+ raise PermissionError(
1195
+ f"PermissionError: Cannot write to '{path}' — this path "
1196
+ f"is write-protected because it contains shell-executable "
1197
+ f"scripts. This prevents write-then-execute escalation."
1198
+ )
1199
+ except ValueError:
1200
+ continue
1201
+
1202
+ # If guard explicitly allowed, skip writable_paths boundary check
1203
+ if guard_result is True:
1204
+ return
1205
+
1206
+ if not _is_within(resolved, resolved_writable):
1207
+ paths_str = ", ".join(str(p) for p in resolved_writable)
1208
+ raise PermissionError(
1209
+ f"PermissionError: Cannot write '{path}' — writes are restricted "
1210
+ f"to the workspace directory. Please use a path within the "
1211
+ f"workspace instead."
1212
+ )
1213
+
1214
+ _WRITE_MODES = {"w", "a", "x", "r+", "w+", "a+", "x+",
1215
+ "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b",
1216
+ "rb+", "wb+", "ab+", "xb+",
1217
+ "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t",
1218
+ "rt+", "wt+", "at+", "xt+"}
1219
+
1220
+ def _is_write_mode(mode: str) -> bool:
1221
+ """Determine if a file mode implies writing."""
1222
+ # Any mode containing w, a, x, or + (except bare r) is a write mode
1223
+ return any(c in mode for c in "wax+")
1224
+
1225
+ # Patch builtins.open
1226
+ _ORIGINALS["builtins.open"] = builtins.open
1227
+
1228
+ def _patched_open(
1229
+ file: Any, mode: str = "r", *args: Any, **kwargs: Any
1230
+ ) -> Any:
1231
+ path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
1232
+ if _is_write_mode(mode):
1233
+ _check_write(path)
1234
+ else:
1235
+ _check_read(path)
1236
+ return _ORIGINALS["builtins.open"](file, mode, *args, **kwargs)
1237
+
1238
+ builtins.open = _patched_open
1239
+
1240
+ # Set tempfile to use the workspace-local temp directory.
1241
+ # The directory is created by the server at startup (server.py).
1242
+ _tempfile_module.tempdir = str(workspace_root / ".pyddock" / "tmp")
1243
+
1244
+ # Patch pathlib.Path methods
1245
+ _ORIGINALS["Path.write_text"] = pathlib.Path.write_text
1246
+ _ORIGINALS["Path.write_bytes"] = pathlib.Path.write_bytes
1247
+ _ORIGINALS["Path.read_text"] = pathlib.Path.read_text
1248
+ _ORIGINALS["Path.read_bytes"] = pathlib.Path.read_bytes
1249
+ _ORIGINALS["Path.open"] = pathlib.Path.open
1250
+
1251
+ def _patched_write_text(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1252
+ _check_write(self_path)
1253
+ return _ORIGINALS["Path.write_text"](self_path, *args, **kwargs)
1254
+
1255
+ def _patched_write_bytes(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1256
+ _check_write(self_path)
1257
+ return _ORIGINALS["Path.write_bytes"](self_path, *args, **kwargs)
1258
+
1259
+ def _patched_read_text(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1260
+ _check_read(self_path)
1261
+ return _ORIGINALS["Path.read_text"](self_path, *args, **kwargs)
1262
+
1263
+ def _patched_read_bytes(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1264
+ _check_read(self_path)
1265
+ return _ORIGINALS["Path.read_bytes"](self_path, *args, **kwargs)
1266
+
1267
+ def _patched_path_open(self_path: pathlib.Path, mode: str = "r", *args: Any, **kwargs: Any) -> Any:
1268
+ if _is_write_mode(mode):
1269
+ _check_write(self_path)
1270
+ else:
1271
+ _check_read(self_path)
1272
+ return _ORIGINALS["Path.open"](self_path, mode, *args, **kwargs)
1273
+
1274
+ pathlib.Path.write_text = _patched_write_text
1275
+ pathlib.Path.write_bytes = _patched_write_bytes
1276
+ pathlib.Path.read_text = _patched_read_text
1277
+ pathlib.Path.read_bytes = _patched_read_bytes
1278
+ pathlib.Path.open = _patched_path_open
1279
+
1280
+ # Patch Path.rename and Path.replace — both move files to a target path.
1281
+ # replace() atomically overwrites the target; rename() fails if target
1282
+ # exists on Windows. Both must check the destination against write guards.
1283
+ _ORIGINALS["Path.rename"] = pathlib.Path.rename
1284
+ _ORIGINALS["Path.replace"] = pathlib.Path.replace
1285
+
1286
+ def _patched_rename(self_path: pathlib.Path, target: Any, *args: Any, **kwargs: Any) -> Any:
1287
+ target_path = pathlib.Path(target) if not isinstance(target, pathlib.Path) else target
1288
+ _check_write(target_path)
1289
+ _check_write(self_path) # source is also "modified" (removed)
1290
+ return _ORIGINALS["Path.rename"](self_path, target, *args, **kwargs)
1291
+
1292
+ def _patched_replace(self_path: pathlib.Path, target: Any, *args: Any, **kwargs: Any) -> Any:
1293
+ target_path = pathlib.Path(target) if not isinstance(target, pathlib.Path) else target
1294
+ _check_write(target_path)
1295
+ _check_write(self_path) # source is also "modified" (removed)
1296
+ return _ORIGINALS["Path.replace"](self_path, target, *args, **kwargs)
1297
+
1298
+ pathlib.Path.rename = _patched_rename
1299
+ pathlib.Path.replace = _patched_replace
1300
+
1301
+ # Patch Path.unlink, rmdir, touch, mkdir — all modify the filesystem.
1302
+ _ORIGINALS["Path.unlink"] = pathlib.Path.unlink
1303
+ _ORIGINALS["Path.rmdir"] = pathlib.Path.rmdir
1304
+ _ORIGINALS["Path.touch"] = pathlib.Path.touch
1305
+ _ORIGINALS["Path.mkdir"] = pathlib.Path.mkdir
1306
+
1307
+ def _patched_unlink(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1308
+ _check_write(self_path)
1309
+ return _ORIGINALS["Path.unlink"](self_path, *args, **kwargs)
1310
+
1311
+ def _patched_rmdir(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1312
+ _check_write(self_path)
1313
+ return _ORIGINALS["Path.rmdir"](self_path, *args, **kwargs)
1314
+
1315
+ def _patched_touch(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1316
+ _check_write(self_path)
1317
+ return _ORIGINALS["Path.touch"](self_path, *args, **kwargs)
1318
+
1319
+ def _patched_mkdir(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
1320
+ _check_write(self_path)
1321
+ return _ORIGINALS["Path.mkdir"](self_path, *args, **kwargs)
1322
+
1323
+ pathlib.Path.unlink = _patched_unlink
1324
+ pathlib.Path.rmdir = _patched_rmdir
1325
+ pathlib.Path.touch = _patched_touch
1326
+ pathlib.Path.mkdir = _patched_mkdir
1327
+
1328
+ # Disable dangerous Path methods entirely — these enable bypass via
1329
+ # indirection (symlinks/hardlinks) or permission escalation.
1330
+ def _blocked_symlink_to(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> None:
1331
+ raise PermissionError(
1332
+ f"PermissionError: Path.symlink_to() is not permitted. "
1333
+ f"Symlink creation is disabled to prevent filesystem bypass."
1334
+ )
1335
+
1336
+ def _blocked_hardlink_to(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> None:
1337
+ raise PermissionError(
1338
+ f"PermissionError: Path.hardlink_to() is not permitted. "
1339
+ f"Hard link creation is disabled to prevent filesystem bypass."
1340
+ )
1341
+
1342
+ def _blocked_link_to(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> None:
1343
+ raise PermissionError(
1344
+ f"PermissionError: Path.link_to() is not permitted. "
1345
+ f"Hard link creation is disabled to prevent filesystem bypass."
1346
+ )
1347
+
1348
+ def _blocked_chmod(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> None:
1349
+ raise PermissionError(
1350
+ f"PermissionError: Path.chmod() is not permitted. "
1351
+ f"Permission changes are disabled."
1352
+ )
1353
+
1354
+ def _blocked_lchmod(self_path: pathlib.Path, *args: Any, **kwargs: Any) -> None:
1355
+ raise PermissionError(
1356
+ f"PermissionError: Path.lchmod() is not permitted. "
1357
+ f"Permission changes are disabled."
1358
+ )
1359
+
1360
+ pathlib.Path.symlink_to = _blocked_symlink_to
1361
+ pathlib.Path.hardlink_to = _blocked_hardlink_to
1362
+ if hasattr(pathlib.Path, "link_to"):
1363
+ pathlib.Path.link_to = _blocked_link_to
1364
+ pathlib.Path.chmod = _blocked_chmod
1365
+ if hasattr(pathlib.Path, "lchmod"):
1366
+ pathlib.Path.lchmod = _blocked_lchmod
1367
+
1368
+ # Patch io.open — it's a separate function from builtins.open
1369
+ # and can bypass filesystem scoping if not patched.
1370
+ _io_module = self._io_module
1371
+ _ORIGINALS["io.open"] = _io_module.open
1372
+
1373
+ def _patched_io_open(
1374
+ file: Any, mode: str = "r", *args: Any, **kwargs: Any
1375
+ ) -> Any:
1376
+ # Skip path checking for integer file descriptors (used internally by subprocess)
1377
+ if isinstance(file, int):
1378
+ return _ORIGINALS["io.open"](file, mode, *args, **kwargs)
1379
+ path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
1380
+ if _is_write_mode(mode):
1381
+ _check_write(path)
1382
+ else:
1383
+ _check_read(path)
1384
+ return _ORIGINALS["io.open"](file, mode, *args, **kwargs)
1385
+
1386
+ _io_module.open = _patched_io_open
1387
+
1388
+ # Also patch _io.open (C implementation) to prevent bypass of filesystem scoping
1389
+ _ORIGINALS["_io.open"] = _cio_module.open
1390
+
1391
+ def _patched_cio_open(
1392
+ file: Any, mode: str = "r", *args: Any, **kwargs: Any
1393
+ ) -> Any:
1394
+ # File descriptors (int) bypass path checks — they're already-open handles
1395
+ if isinstance(file, int):
1396
+ return _ORIGINALS["_io.open"](file, mode, *args, **kwargs)
1397
+ # Skip path checks when called from frozen import machinery
1398
+ # (loading .py/.pyc files). Only frozen code gets this bypass.
1399
+ caller = sys._getframe(1)
1400
+ if caller and caller.f_code.co_filename.startswith("<frozen"):
1401
+ return _ORIGINALS["_io.open"](file, mode, *args, **kwargs)
1402
+ path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
1403
+ if _is_write_mode(mode):
1404
+ _check_write(path)
1405
+ else:
1406
+ _check_read(path)
1407
+ return _ORIGINALS["_io.open"](file, mode, *args, **kwargs)
1408
+
1409
+ _cio_module.open = _patched_cio_open
1410
+
1411
+ # Patch io.FileIO — its constructor opens files directly without going
1412
+ # through builtins.open or io.open. Same for _io.FileIO (C implementation).
1413
+ _ORIGINALS["io.FileIO"] = _io_module.FileIO
1414
+ _ORIGINALS["_io.FileIO"] = _cio_module.FileIO
1415
+
1416
+ class _PatchedFileIO(_ORIGINALS["_io.FileIO"]):
1417
+ """FileIO subclass that enforces filesystem scoping on construction."""
1418
+
1419
+ def __init__(self, file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> None:
1420
+ if not isinstance(file, int):
1421
+ path = pathlib.Path(file) if not isinstance(file, pathlib.Path) else file
1422
+ if _is_write_mode(mode):
1423
+ _check_write(path)
1424
+ else:
1425
+ _check_read(path)
1426
+ super().__init__(file, mode, *args, **kwargs)
1427
+
1428
+ _io_module.FileIO = _PatchedFileIO
1429
+ _cio_module.FileIO = _PatchedFileIO
1430
+
1431
+ # Lock down tempfile.tempdir — prevent agent from redirecting temp file
1432
+ # creation outside the workspace by reassigning tempfile.tempdir.
1433
+ # We freeze it by replacing the tempfile module's __dict__ entry with a
1434
+ # property-like mechanism (module-level setattr override isn't possible,
1435
+ # so we delete the attribute and rely on the patched open() to enforce
1436
+ # path checks on any tempfile operations regardless of tempdir value).
1437
+ # Simpler approach: just remove tempdir setter by making tempfile use
1438
+ # a wrapper that ignores reassignment.
1439
+ _frozen_tempdir = _tempfile_module.tempdir
1440
+
1441
+ class _TempfileProxy:
1442
+ """Proxy that freezes tempdir and blocks mkstemp while forwarding everything else."""
1443
+
1444
+ # mkstemp returns a raw (fd, path) tuple that requires os.close/os.write
1445
+ # which aren't on the safe os proxy. Block it to avoid leaked fds.
1446
+ _BLOCKED = frozenset({"mkstemp", "mkdtemp"})
1447
+
1448
+ def __getattr__(self, name: str) -> Any:
1449
+ if name == "tempdir":
1450
+ return _frozen_tempdir
1451
+ if name in self._BLOCKED:
1452
+ def _blocked(*args: Any, **kwargs: Any) -> None:
1453
+ raise PermissionError(
1454
+ f"PermissionError: tempfile.{name}() is not permitted. "
1455
+ f"Use tempfile.NamedTemporaryFile() or tempfile.TemporaryFile() instead."
1456
+ )
1457
+ return _blocked
1458
+ return getattr(_tempfile_module, name)
1459
+
1460
+ def __setattr__(self, name: str, value: Any) -> None:
1461
+ if name == "tempdir":
1462
+ raise PermissionError(
1463
+ "PermissionError: Cannot reassign tempfile.tempdir. "
1464
+ "Temp files are restricted to the workspace .pyddock/tmp/ directory."
1465
+ )
1466
+ setattr(_tempfile_module, name, value)
1467
+
1468
+ sys.modules["tempfile"] = _TempfileProxy()
1469
+
1470
+ # Patch os.makedirs and os.mkdir on the safe os proxy to use _check_write.
1471
+ # This ensures .pyddock/, workspace module dirs, and other protected paths
1472
+ # are enforced (not just the workspace boundary check).
1473
+ _real_os = self._real_os
1474
+
1475
+ def _safe_makedirs(name: str, mode: int = 0o777, exist_ok: bool = False) -> None:
1476
+ _check_write(pathlib.Path(name))
1477
+ _real_os.makedirs(name, mode, exist_ok=exist_ok)
1478
+
1479
+ def _safe_mkdir(name: str, mode: int = 0o777) -> None:
1480
+ _check_write(pathlib.Path(name))
1481
+ _real_os.mkdir(name, mode)
1482
+
1483
+ if "os" in sys.modules:
1484
+ safe_os = sys.modules["os"]
1485
+ safe_os.makedirs = _safe_makedirs
1486
+ safe_os.mkdir = _safe_mkdir
1487
+
1488
+ def apply_restrictions(self) -> None:
1489
+ """Apply module-level and class-level restrictions.
1490
+
1491
+ For mode="deny":
1492
+ - module_allow: install a _CallerScopedModuleProxy (simple mode) that
1493
+ exposes only attributes matching allow patterns. The real module is
1494
+ NOT mutated.
1495
+ - class_allow: wrap allowed callable attrs with FactoryProxy and store
1496
+ them in custom_attrs on the proxy, so objects they return are
1497
+ restricted to class_allow patterns.
1498
+
1499
+ For mode="allow":
1500
+ - module_deny: block module-level attrs matching deny patterns
1501
+ - class_deny: patch methods matching deny patterns on all public classes
1502
+ """
1503
+ restrictions = self._config.get("restrictions", {})
1504
+ allowed_imports = set(self._config.get("imports", {}).get("allowed", []))
1505
+
1506
+ for module_name, restriction in restrictions.items():
1507
+ # Skip restrictions for modules that aren't in [imports] —
1508
+ # the agent can't import them anyway, and importing here can
1509
+ # trigger side effects (e.g. attrgetter guard conflicts).
1510
+ if module_name not in allowed_imports:
1511
+ continue
1512
+
1513
+ mode = restriction.get("mode", "allow")
1514
+ module_allow = restriction.get("module_allow", [])
1515
+ module_deny = restriction.get("module_deny", [])
1516
+ class_allow = restriction.get("class_allow", [])
1517
+ class_deny = restriction.get("class_deny", [])
1518
+
1519
+ try:
1520
+ module = importlib.import_module(module_name)
1521
+ except ImportError:
1522
+ continue
1523
+
1524
+ # --- Module-level enforcement ---
1525
+ if mode == "allow" and module_deny:
1526
+ # Block matching patterns on the module
1527
+ deny_compiled = [re.compile(p) for p in module_deny]
1528
+ for attr_name in list(dir(module)):
1529
+ if attr_name.startswith("_"):
1530
+ continue
1531
+ if any(p.match(attr_name) for p in deny_compiled):
1532
+ self._patch_module_function(module, attr_name, module_name)
1533
+ elif mode == "deny" and module_allow:
1534
+ # Install a simple-mode _CallerScopedModuleProxy.
1535
+ # The proxy exposes only attributes matching module_allow patterns.
1536
+ # The real module is NOT mutated — FactoryProxy instances (if any)
1537
+ # live in custom_attrs on the proxy.
1538
+ always_allowed = _expand_patterns(module_allow, module)
1539
+ custom_attrs: dict[str, Any] = {}
1540
+
1541
+ if class_allow:
1542
+ # For each allowed callable attr, wrap it in FactoryProxy
1543
+ # so objects it returns are restricted to class_allow patterns.
1544
+ compiled_class_patterns = [re.compile(p) for p in class_allow]
1545
+ for attr_name in always_allowed:
1546
+ attr = getattr(module, attr_name, None)
1547
+ if attr is not None and callable(attr) and not isinstance(attr, type):
1548
+ custom_attrs[attr_name] = FactoryProxy(
1549
+ attr, compiled_class_patterns
1550
+ )
1551
+
1552
+ proxy = _CallerScopedModuleProxy(
1553
+ module_name=module_name,
1554
+ real_module=module,
1555
+ always_allowed=always_allowed,
1556
+ always_blocked=frozenset(),
1557
+ trusted_prefixes=None, # simple mode
1558
+ custom_attrs=custom_attrs if custom_attrs else None,
1559
+ )
1560
+ sys.modules[module_name] = proxy
1561
+
1562
+ # --- Class-level enforcement ---
1563
+ if mode == "allow" and class_deny:
1564
+ # Patch methods on all public classes matching deny patterns
1565
+ deny_compiled = [re.compile(p) for p in class_deny]
1566
+ for cls_name in dir(module):
1567
+ if cls_name.startswith("_"):
1568
+ continue
1569
+ cls = getattr(module, cls_name, None)
1570
+ if cls is None or not isinstance(cls, type):
1571
+ continue
1572
+ for method_name in list(dir(cls)):
1573
+ if method_name.startswith("_"):
1574
+ continue
1575
+ if any(p.match(method_name) for p in deny_compiled):
1576
+ self._patch_class_method(cls, method_name, module_name)
1577
+
1578
+ @staticmethod
1579
+ def _patch_module_function(
1580
+ module: Any, func_name: str, module_name: str
1581
+ ) -> None:
1582
+ """Replace a module-level function with one that raises PermissionError."""
1583
+
1584
+ def _blocked(*args: Any, **kwargs: Any) -> None:
1585
+ raise PermissionError(
1586
+ f"PermissionError: '{func_name}' is not permitted on {module_name}. "
1587
+ f"Please rewrite your snippet to avoid this function."
1588
+ )
1589
+
1590
+ setattr(module, func_name, _blocked)
1591
+
1592
+ @staticmethod
1593
+ def _patch_class_method(
1594
+ cls: Any, method_name: str, module_name: str
1595
+ ) -> None:
1596
+ """Replace a class method with one that raises PermissionError."""
1597
+
1598
+ def _blocked(*args: Any, **kwargs: Any) -> None:
1599
+ raise PermissionError(
1600
+ f"PermissionError: '{method_name}' is not permitted on {module_name}. "
1601
+ f"Please rewrite your snippet to avoid this function."
1602
+ )
1603
+
1604
+ setattr(cls, method_name, _blocked)
1605
+
1606
+ def apply_subprocess_patch(self) -> None:
1607
+ """Replace subprocess with a safe proxy module and block os.system.
1608
+
1609
+ Instead of patching individual functions (whack-a-mole), we replace
1610
+ the entire subprocess module in sys.modules with a proxy that only
1611
+ exposes subprocess.run() and subprocess.Popen() — both validated
1612
+ against shell policies.
1613
+
1614
+ Exposed on the proxy:
1615
+ - subprocess.run() — validated against shell policies
1616
+ - subprocess.Popen() — validated proxy class (same policy checks at construction)
1617
+ - subprocess.PIPE, DEVNULL, STDOUT — constants for run()/Popen() calls
1618
+ - subprocess.CompletedProcess — return type
1619
+ - subprocess.CalledProcessError, TimeoutExpired, SubprocessError — exceptions
1620
+
1621
+ NOT exposed (no bypass surface):
1622
+ - call, check_call, check_output, getoutput, getstatusoutput
1623
+ """
1624
+ types = self._types_module
1625
+
1626
+ _real_os = self._real_os
1627
+ _resolve_cmd = self._resolve_command
1628
+ shell_policies = self._config.get("shell", {})
1629
+
1630
+ # Build example command for error messages
1631
+ if shell_policies:
1632
+ first_name = next(iter(shell_policies))
1633
+ first_policy = shell_policies[first_name]
1634
+ example_cmd = first_policy.get("command", first_name).lstrip("^").rstrip("$")
1635
+ allowed_commands_str = ", ".join(
1636
+ p.get("command", name) for name, p in shell_policies.items()
1637
+ )
1638
+ else:
1639
+ example_cmd = "command"
1640
+ allowed_commands_str = "(none configured)"
1641
+
1642
+ def _find_matching_policy(command: str) -> dict | None:
1643
+ """Find first matching shell policy for a command."""
1644
+ for _name, policy in shell_policies.items():
1645
+ if re.match(policy["command"], command):
1646
+ return policy
1647
+ return None
1648
+
1649
+ def _check_args_policy(policy: dict, cmd_args: list[str]) -> str | None:
1650
+ """Validate args against policy. Returns error message or None."""
1651
+ args_str = " ".join(cmd_args)
1652
+ mode = policy.get("mode", "deny")
1653
+
1654
+ if mode == "deny":
1655
+ allow_patterns = policy.get("allow", [])
1656
+ if not allow_patterns:
1657
+ return "No argument patterns are allowed for this command."
1658
+ if not any(re.match(p, args_str) for p in allow_patterns):
1659
+ allowed = ", ".join(allow_patterns)
1660
+ return (
1661
+ f"Arguments '{args_str}' not permitted. "
1662
+ f"Allowed patterns: {allowed}"
1663
+ )
1664
+ return None
1665
+ elif mode == "allow":
1666
+ deny_patterns = policy.get("deny", [])
1667
+ for pattern in deny_patterns:
1668
+ if re.match(pattern, args_str):
1669
+ return (
1670
+ f"Arguments '{args_str}' matched deny pattern '{pattern}'."
1671
+ )
1672
+ return None
1673
+ return None
1674
+
1675
+ # Pre-compute protected paths for arg scanning
1676
+ _ws_root = self._workspace_root
1677
+ _pyddock_dir = pathlib.Path(_real_os.path.abspath(str(_ws_root / ".pyddock")))
1678
+ _workspace_imports = self._config.get("imports", {}).get("workspace", {})
1679
+ _ws_module_dirs: list[tuple[str, pathlib.Path]] = [
1680
+ (mod_name, pathlib.Path(_real_os.path.abspath(str(_ws_root / rel_path))))
1681
+ for mod_name, rel_path in _workspace_imports.items()
1682
+ ]
1683
+ _shell_protected_dirs: list[tuple[str, pathlib.Path]] = []
1684
+ for _sp_name, _sp_policy in shell_policies.items():
1685
+ _sp_cmd = _sp_policy.get("command", "")
1686
+ if "/" in _sp_cmd or "\\\\" in _sp_cmd or _sp_cmd.startswith("\\."):
1687
+ _sp_pattern = _sp_cmd.lstrip("^").rstrip("$")
1688
+ if "/" in _sp_pattern:
1689
+ _sp_dir = _sp_pattern.rsplit("/", 1)[0]
1690
+ elif "\\\\" in _sp_pattern:
1691
+ _sp_dir = _sp_pattern.rsplit("\\\\", 1)[0]
1692
+ else:
1693
+ _sp_dir = _sp_pattern
1694
+ if _sp_dir:
1695
+ _sp_clean = _sp_dir.replace("\\.", ".").replace("\\/", "/")
1696
+ _shell_protected_dirs.append(
1697
+ (_sp_clean, pathlib.Path(_real_os.path.abspath(str(_ws_root / _sp_clean))))
1698
+ )
1699
+ _ws_root_abs = pathlib.Path(_real_os.path.abspath(str(_ws_root)))
1700
+
1701
+ _looks_like_path_rt = self._looks_like_path
1702
+ _extract_path_candidates_rt = self._extract_path_candidates
1703
+
1704
+ def _check_arg_paths(policy: dict, cmd_args: list[str]) -> str | None:
1705
+ """Scan args for path-like values and validate against arg_paths policy."""
1706
+ arg_paths_mode = policy.get("arg_paths", "workspace")
1707
+ if arg_paths_mode == "none":
1708
+ return None
1709
+
1710
+ for arg in cmd_args:
1711
+ # Extract all path candidates (raw arg + embedded --flag=value)
1712
+ candidates = _extract_path_candidates_rt(arg)
1713
+ if not candidates:
1714
+ continue
1715
+
1716
+ for candidate in candidates:
1717
+ resolved = pathlib.Path(_real_os.path.abspath(
1718
+ str(_ws_root / candidate)
1719
+ ))
1720
+
1721
+ # Check .pyddock/ (excluding .pyddock/tmp/)
1722
+ try:
1723
+ rel = resolved.relative_to(_pyddock_dir)
1724
+ if not str(rel).startswith("tmp"):
1725
+ return (
1726
+ f"Argument '{arg}' targets the protected .pyddock/ "
1727
+ f"directory. Shell commands cannot write to .pyddock/ "
1728
+ f"(self-modification protection)."
1729
+ )
1730
+ except ValueError:
1731
+ pass
1732
+
1733
+ # Check workspace module directories
1734
+ for mod_name, ws_dir in _ws_module_dirs:
1735
+ try:
1736
+ resolved.relative_to(ws_dir)
1737
+ return (
1738
+ f"Argument '{arg}' targets workspace module directory "
1739
+ f"'{mod_name}'. Shell commands cannot write to workspace "
1740
+ f"module directories."
1741
+ )
1742
+ except ValueError:
1743
+ continue
1744
+
1745
+ # Check shell script directories
1746
+ for dir_label, script_dir in _shell_protected_dirs:
1747
+ try:
1748
+ resolved.relative_to(script_dir)
1749
+ return (
1750
+ f"Argument '{arg}' targets a shell-executable script "
1751
+ f"directory ({dir_label}). Shell commands cannot write "
1752
+ f"to script directories (write-then-execute prevention)."
1753
+ )
1754
+ except ValueError:
1755
+ continue
1756
+
1757
+ # "workspace" mode: block paths outside the workspace
1758
+ if arg_paths_mode == "workspace":
1759
+ try:
1760
+ resolved.relative_to(_ws_root_abs)
1761
+ except ValueError:
1762
+ return (
1763
+ f"Argument '{arg}' resolves outside the workspace. "
1764
+ f"Shell commands are restricted to workspace-relative "
1765
+ f"paths (arg_paths = \"workspace\")."
1766
+ )
1767
+
1768
+ return None
1769
+
1770
+ def _validated_run(cmd: Any, *args: Any, **kwargs: Any) -> Any:
1771
+ """subprocess.run replacement that validates against shell policies."""
1772
+ # Reject shell=True
1773
+ if kwargs.get("shell", False):
1774
+ raise PermissionError(
1775
+ "PermissionError: shell=True is not permitted in subprocess.run(). "
1776
+ "Pass command as a list instead: "
1777
+ f"subprocess.run(['{example_cmd}', 'arg1', 'arg2'])"
1778
+ )
1779
+ # Reject string commands
1780
+ if isinstance(cmd, str):
1781
+ raise PermissionError(
1782
+ "PermissionError: String commands are not permitted in subprocess.run(). "
1783
+ "Pass command as a list instead: "
1784
+ f"subprocess.run(['{example_cmd}', 'arg1', 'arg2'])"
1785
+ )
1786
+ # If no shell policies configured, block entirely
1787
+ if not shell_policies:
1788
+ raise PermissionError(
1789
+ "PermissionError: No shell policies configured. "
1790
+ "Add [shell.*] sections to pyddock.toml to enable command execution, "
1791
+ "or use run_shell directly."
1792
+ )
1793
+ # Validate command against shell policy
1794
+ if not cmd:
1795
+ raise PermissionError(
1796
+ "PermissionError: Empty command list is not permitted."
1797
+ )
1798
+ command = str(cmd[0])
1799
+ cmd_args = [str(a) for a in cmd[1:]]
1800
+ policy = _find_matching_policy(command)
1801
+ if policy is None:
1802
+ raise PermissionError(
1803
+ f"PermissionError: Command '{command}' is not permitted. "
1804
+ f"No matching shell policy found. "
1805
+ f"Allowed commands: {allowed_commands_str}"
1806
+ )
1807
+ rejection = _check_args_policy(policy, cmd_args)
1808
+ if rejection is not None:
1809
+ raise PermissionError(f"PermissionError: {rejection}")
1810
+ # Check arg paths against protected directories
1811
+ path_rejection = _check_arg_paths(policy, cmd_args)
1812
+ if path_rejection is not None:
1813
+ raise PermissionError(f"PermissionError: {path_rejection}")
1814
+ # Apply interpreter mapping (same as run_shell) and execute
1815
+ resolved = _resolve_cmd(command)
1816
+ full_cmd = resolved + cmd_args
1817
+ kwargs["shell"] = False
1818
+ return _ORIGINALS["subprocess.run"](full_cmd, *args, **kwargs)
1819
+
1820
+ def _validate_command(cmd: Any, caller: str) -> tuple[list[str], list[str]]:
1821
+ """Shared validation for run() and Popen(). Returns (resolved_cmd, cmd_args).
1822
+
1823
+ Raises PermissionError if the command is not permitted.
1824
+ """
1825
+ # Reject shell=True handled by caller (kwargs not passed here)
1826
+ # Reject string commands
1827
+ if isinstance(cmd, str):
1828
+ raise PermissionError(
1829
+ f"PermissionError: String commands are not permitted in subprocess.{caller}(). "
1830
+ "Pass command as a list instead: "
1831
+ f"subprocess.{caller}(['{example_cmd}', 'arg1', 'arg2'])"
1832
+ )
1833
+ # If no shell policies configured, block entirely
1834
+ if not shell_policies:
1835
+ raise PermissionError(
1836
+ "PermissionError: No shell policies configured. "
1837
+ "Add [shell.*] sections to pyddock.toml to enable command execution, "
1838
+ "or use run_shell directly."
1839
+ )
1840
+ if not cmd:
1841
+ raise PermissionError(
1842
+ "PermissionError: Empty command list is not permitted."
1843
+ )
1844
+ command = str(cmd[0])
1845
+ cmd_args = [str(a) for a in cmd[1:]]
1846
+ policy = _find_matching_policy(command)
1847
+ if policy is None:
1848
+ raise PermissionError(
1849
+ f"PermissionError: Command '{command}' is not permitted. "
1850
+ f"No matching shell policy found. "
1851
+ f"Allowed commands: {allowed_commands_str}"
1852
+ )
1853
+ rejection = _check_args_policy(policy, cmd_args)
1854
+ if rejection is not None:
1855
+ raise PermissionError(f"PermissionError: {rejection}")
1856
+ path_rejection = _check_arg_paths(policy, cmd_args)
1857
+ if path_rejection is not None:
1858
+ raise PermissionError(f"PermissionError: {path_rejection}")
1859
+ resolved = _resolve_cmd(command)
1860
+ return resolved + cmd_args, cmd_args
1861
+
1862
+ class _SafePopen:
1863
+ """Proxy around subprocess.Popen that validates commands against shell policies.
1864
+
1865
+ Validates the command at construction time (same checks as subprocess.run),
1866
+ then delegates all safe operations to the real Popen instance.
1867
+ """
1868
+
1869
+ def __init__(self, cmd: Any, *args: Any, **kwargs: Any) -> None:
1870
+ if kwargs.get("shell", False):
1871
+ raise PermissionError(
1872
+ "PermissionError: shell=True is not permitted in subprocess.Popen(). "
1873
+ "Pass command as a list instead: "
1874
+ f"subprocess.Popen(['{example_cmd}', 'arg1', 'arg2'])"
1875
+ )
1876
+ full_cmd, _ = _validate_command(cmd, "Popen")
1877
+ kwargs["shell"] = False
1878
+ self._proc = _ORIGINALS["subprocess.Popen"](full_cmd, *args, **kwargs)
1879
+
1880
+ # --- Process control ---
1881
+ def communicate(self, *args: Any, **kwargs: Any) -> tuple:
1882
+ return self._proc.communicate(*args, **kwargs)
1883
+
1884
+ def wait(self, *args: Any, **kwargs: Any) -> int:
1885
+ return self._proc.wait(*args, **kwargs)
1886
+
1887
+ def poll(self) -> int | None:
1888
+ return self._proc.poll()
1889
+
1890
+ def terminate(self) -> None:
1891
+ return self._proc.terminate()
1892
+
1893
+ def kill(self) -> None:
1894
+ return self._proc.kill()
1895
+
1896
+ def send_signal(self, signal: int) -> None:
1897
+ return self._proc.send_signal(signal)
1898
+
1899
+ # --- Properties ---
1900
+ @property
1901
+ def stdout(self) -> Any:
1902
+ return self._proc.stdout
1903
+
1904
+ @property
1905
+ def stderr(self) -> Any:
1906
+ return self._proc.stderr
1907
+
1908
+ @property
1909
+ def stdin(self) -> Any:
1910
+ return self._proc.stdin
1911
+
1912
+ @property
1913
+ def pid(self) -> int:
1914
+ return self._proc.pid
1915
+
1916
+ @property
1917
+ def returncode(self) -> int | None:
1918
+ return self._proc.returncode
1919
+
1920
+ @property
1921
+ def args(self) -> Any:
1922
+ return self._proc.args
1923
+
1924
+ # --- Context manager ---
1925
+ def __enter__(self) -> "_SafePopen":
1926
+ return self
1927
+
1928
+ def __exit__(self, *args: Any) -> None:
1929
+ self._proc.__exit__(*args)
1930
+
1931
+ def __repr__(self) -> str:
1932
+ return f"<SafePopen pid={self.pid} returncode={self.returncode}>"
1933
+
1934
+ # Build the safe subprocess proxy
1935
+ _subprocess_module = self._subprocess_module
1936
+ if _subprocess_module is not None:
1937
+ _ORIGINALS["subprocess.run"] = _subprocess_module.run
1938
+ _ORIGINALS["subprocess.Popen"] = _subprocess_module.Popen
1939
+
1940
+ safe_subprocess = types.ModuleType("subprocess")
1941
+ safe_subprocess.__doc__ = "Safe subprocess proxy provided by pyddock. Only subprocess.run() and subprocess.Popen() are available, validated against shell policies."
1942
+
1943
+ # Allowed entry points
1944
+ safe_subprocess.run = _validated_run
1945
+ safe_subprocess.Popen = _SafePopen
1946
+
1947
+ # Constants needed for run()/Popen() calls
1948
+ safe_subprocess.PIPE = _subprocess_module.PIPE
1949
+ safe_subprocess.DEVNULL = _subprocess_module.DEVNULL
1950
+ safe_subprocess.STDOUT = _subprocess_module.STDOUT
1951
+
1952
+ # Types needed for return values and error handling
1953
+ safe_subprocess.CompletedProcess = _subprocess_module.CompletedProcess
1954
+ safe_subprocess.CalledProcessError = _subprocess_module.CalledProcessError
1955
+ safe_subprocess.TimeoutExpired = _subprocess_module.TimeoutExpired
1956
+ safe_subprocess.SubprocessError = _subprocess_module.SubprocessError
1957
+
1958
+ # Replace in sys.modules so 'import subprocess' finds the proxy
1959
+ sys.modules["subprocess"] = safe_subprocess
1960
+
1961
+ # Always patch os.system
1962
+ def _blocked_os_system(cmd: Any) -> None:
1963
+ raise PermissionError(
1964
+ "PermissionError: os.system() is not available. "
1965
+ f"Use subprocess.run(['{example_cmd}', 'arg1', 'arg2']) instead, "
1966
+ "which validates commands against the shell policy."
1967
+ )
1968
+
1969
+ # Patch os.system on the real os module
1970
+ _real_os.system = _blocked_os_system
1971
+
1972
+ # Also patch it on the safe os proxy if it exists in sys.modules
1973
+ if "os" in sys.modules:
1974
+ safe_os = sys.modules["os"]
1975
+ safe_os.system = _blocked_os_system