pyddock 0.2.2__tar.gz → 0.2.3__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.
- {pyddock-0.2.2 → pyddock-0.2.3}/PKG-INFO +1 -1
- {pyddock-0.2.2 → pyddock-0.2.3}/publish-to-pypi.ps1 +5 -1
- {pyddock-0.2.2 → pyddock-0.2.3}/pyproject.toml +1 -1
- pyddock-0.2.3/src/pyddock/_base.py +45 -0
- pyddock-0.2.3/src/pyddock/_enforcement.py +584 -0
- pyddock-0.2.3/src/pyddock/_fs_enforcement.py +589 -0
- pyddock-0.2.3/src/pyddock/_import_hook.py +161 -0
- pyddock-0.2.3/src/pyddock/_prewarm.py +69 -0
- pyddock-0.2.3/src/pyddock/_process_utils.py +199 -0
- pyddock-0.2.3/src/pyddock/_proxies.py +526 -0
- pyddock-0.2.3/src/pyddock/_runtime.py +39 -0
- pyddock-0.2.3/src/pyddock/_subprocess_patch.py +430 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/default_config.toml +4 -3
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_proxy_properties.py +6 -6
- {pyddock-0.2.2 → pyddock-0.2.3}/uv.lock +1 -1
- pyddock-0.2.2/src/pyddock/_process_utils.py +0 -88
- pyddock-0.2.2/src/pyddock/_runtime.py +0 -2124
- {pyddock-0.2.2 → pyddock-0.2.3}/.gitignore +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/LICENSE +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/README.md +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/__init__.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/ast_validator.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/cli.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/config.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/executor.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/script_registry.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/server.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/shell_executor.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/__init__.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/fs_append.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/fs_delete.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/read_file.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/stat_file.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/tools/str_replace.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/src/pyddock/venv_manager.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/__init__.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_ast_properties.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_chmod_integration.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_config.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_deny_messages.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_executor.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_file_tools.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_filesystem_guards.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_realistic.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_runtime.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_security_guards.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_server.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_shell_arg_paths.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_shell_executor.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_shell_properties.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_subprocess_enforcement.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_subprocess_properties.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_subst_trusted_path.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_venv_stamp.py +0 -0
- {pyddock-0.2.2 → pyddock-0.2.3}/tests/test_workspace_imports.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyddock
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
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
|
|
@@ -16,8 +16,12 @@ Write-Host "> uvx twine upload --repository testpypi dist/*"
|
|
|
16
16
|
uvx twine upload --repository testpypi dist/*
|
|
17
17
|
if ($LASTEXITCODE -ne 0) { throw "testpypi upload failed" }
|
|
18
18
|
|
|
19
|
+
# Hint for testing
|
|
20
|
+
Write-Host "`nTo test from testpypi:"
|
|
21
|
+
Write-Host " uvx --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ pyddock"
|
|
22
|
+
|
|
19
23
|
# Pause for confirmation
|
|
20
|
-
$response = Read-Host "`
|
|
24
|
+
$response = Read-Host "`nType 'y' to upload to pypi (anything else aborts)"
|
|
21
25
|
if ($response -ne 'y') { Write-Host "Aborted."; exit 0 }
|
|
22
26
|
|
|
23
27
|
# Upload to pypi
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Shared constants and utilities for pyddock runtime enforcement.
|
|
2
|
+
|
|
3
|
+
This is the leaf module in the dependency graph — it has NO imports from
|
|
4
|
+
other pyddock modules. All other _runtime split modules import from here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
# Filename used for compile() when executing agent snippets.
|
|
14
|
+
# Defined here so the sandbox subprocess doesn't need to import the
|
|
15
|
+
# pyddock package (which would trigger importlib.metadata).
|
|
16
|
+
SNIPPET_FILENAME = "<snippet>"
|
|
17
|
+
|
|
18
|
+
# Resolved at module load time (before the import hook activates).
|
|
19
|
+
# Used by _caller_is_trusted to skip pyddock's own frames.
|
|
20
|
+
import os as _os_for_path
|
|
21
|
+
_PYDDOCK_DIR = _os_for_path.path.dirname(_os_for_path.path.abspath(__file__))
|
|
22
|
+
# Cache path helpers for _caller_is_trusted (avoids repeated attribute lookups).
|
|
23
|
+
_normcase = _os_for_path.path.normcase
|
|
24
|
+
_realpath = _os_for_path.path.realpath
|
|
25
|
+
del _os_for_path
|
|
26
|
+
|
|
27
|
+
# Module-level dict for storing original (unpatched) function references.
|
|
28
|
+
# Security-critical wrappers look up originals here instead of capturing them
|
|
29
|
+
# in closure cells. This prevents agent code from extracting originals via
|
|
30
|
+
# function.__closure__[N].cell_contents or descriptor-protocol introspection.
|
|
31
|
+
# Since pyddock._* modules are not importable by agent code, this dict is inaccessible.
|
|
32
|
+
_ORIGINALS: dict[str, Any] = {}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _find_deny_hint(attempted: str, deny_messages: list[tuple[re.Pattern[str], str]]) -> str | None:
|
|
36
|
+
"""Return the first matching deny hint for the attempted action, or None.
|
|
37
|
+
|
|
38
|
+
This is the subprocess-side equivalent of config.find_deny_hint().
|
|
39
|
+
It operates on pre-compiled (pattern, message) tuples reconstructed
|
|
40
|
+
from the serialized config dict.
|
|
41
|
+
"""
|
|
42
|
+
for pattern, message in deny_messages:
|
|
43
|
+
if pattern.search(attempted):
|
|
44
|
+
return message
|
|
45
|
+
return None
|
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
"""RuntimeEnforcement orchestrator.
|
|
2
|
+
|
|
3
|
+
This module contains the RuntimeEnforcement class which coordinates all
|
|
4
|
+
sandbox enforcement mechanisms. It delegates filesystem scoping and
|
|
5
|
+
subprocess patching to their respective standalone modules while keeping
|
|
6
|
+
the remaining enforcement logic (import hooks, module proxies, attribute
|
|
7
|
+
guards, and restriction application) in-class.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import builtins
|
|
12
|
+
import importlib
|
|
13
|
+
import pathlib
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
import types
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from pyddock._base import SNIPPET_FILENAME, _ORIGINALS, _find_deny_hint
|
|
20
|
+
from pyddock._import_hook import _ImportBlocker, _caller_is_trusted
|
|
21
|
+
from pyddock._proxies import (
|
|
22
|
+
MethodFilterProxy, FactoryProxy, _CallerScopedModuleProxy,
|
|
23
|
+
_expand_patterns, _build_trusted_prefixes, _proxy_module_universal,
|
|
24
|
+
)
|
|
25
|
+
from pyddock._fs_enforcement import apply_filesystem_scoping
|
|
26
|
+
from pyddock._subprocess_patch import apply_subprocess_patch
|
|
27
|
+
from pyddock._prewarm import run_all as _run_prewarms
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RuntimeEnforcement:
|
|
31
|
+
"""Applies runtime enforcement inside the subprocess.
|
|
32
|
+
|
|
33
|
+
Constructor accepts:
|
|
34
|
+
config: dict — serialized PyddockConfig (plain dict from executor)
|
|
35
|
+
workspace_root: str — absolute path to the workspace directory
|
|
36
|
+
|
|
37
|
+
Call apply_all() to install all enforcement hooks in order.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, config: dict, workspace_root: str) -> None:
|
|
41
|
+
self._config = config
|
|
42
|
+
# Use abspath (not resolve) to preserve symlinks/subst drives
|
|
43
|
+
import os as _os_init
|
|
44
|
+
self._workspace_root = pathlib.Path(_os_init.path.abspath(workspace_root))
|
|
45
|
+
# Pre-compile deny_messages patterns from serialized config
|
|
46
|
+
self._deny_messages: list[tuple[re.Pattern[str], str]] = []
|
|
47
|
+
for entry in config.get("deny_messages", []):
|
|
48
|
+
try:
|
|
49
|
+
pattern = re.compile(entry["pattern"])
|
|
50
|
+
self._deny_messages.append((pattern, entry["message"]))
|
|
51
|
+
except (re.error, KeyError, TypeError):
|
|
52
|
+
pass # Skip malformed entries silently in subprocess
|
|
53
|
+
|
|
54
|
+
def apply_all(self) -> None:
|
|
55
|
+
"""Apply all enforcement in order: import hook, filesystem, proxies, patches, subprocess."""
|
|
56
|
+
# Save references to modules before safe proxies replace them in sys.modules
|
|
57
|
+
import os as _real_os
|
|
58
|
+
self._real_os = _real_os
|
|
59
|
+
import sys as _real_sys
|
|
60
|
+
self._real_sys = _real_sys
|
|
61
|
+
try:
|
|
62
|
+
import subprocess as _subprocess_module
|
|
63
|
+
self._subprocess_module = _subprocess_module
|
|
64
|
+
except ImportError:
|
|
65
|
+
self._subprocess_module = None
|
|
66
|
+
|
|
67
|
+
# Import resolve_command before the hook blocks pyddock
|
|
68
|
+
from pyddock.shell_executor import resolve_command, _looks_like_path, _extract_path_candidates
|
|
69
|
+
self._resolve_command = resolve_command
|
|
70
|
+
self._looks_like_path = _looks_like_path
|
|
71
|
+
self._extract_path_candidates = _extract_path_candidates
|
|
72
|
+
|
|
73
|
+
# Pre-import modules needed by enforcement methods before the hook activates.
|
|
74
|
+
# These are runtime-internal dependencies, not user-facing.
|
|
75
|
+
import operator as _operator_module
|
|
76
|
+
self._operator_module = _operator_module
|
|
77
|
+
import types as _types_module
|
|
78
|
+
self._types_module = _types_module
|
|
79
|
+
import io as _io_module
|
|
80
|
+
self._io_module = _io_module
|
|
81
|
+
import traceback as _traceback_module
|
|
82
|
+
self._traceback_module = _traceback_module
|
|
83
|
+
|
|
84
|
+
self.install_import_hook()
|
|
85
|
+
self.apply_attrgetter_guard()
|
|
86
|
+
apply_filesystem_scoping(
|
|
87
|
+
config=self._config,
|
|
88
|
+
workspace_root=self._workspace_root,
|
|
89
|
+
real_os=self._real_os,
|
|
90
|
+
trusted_prefixes=self._trusted_prefixes,
|
|
91
|
+
io_module=self._io_module,
|
|
92
|
+
)
|
|
93
|
+
self.apply_restrictions()
|
|
94
|
+
apply_subprocess_patch(
|
|
95
|
+
config=self._config,
|
|
96
|
+
workspace_root=self._workspace_root,
|
|
97
|
+
real_os=self._real_os,
|
|
98
|
+
subprocess_module=self._subprocess_module,
|
|
99
|
+
types_module=self._types_module,
|
|
100
|
+
resolve_command=self._resolve_command,
|
|
101
|
+
looks_like_path=self._looks_like_path,
|
|
102
|
+
extract_path_candidates=self._extract_path_candidates,
|
|
103
|
+
deny_messages=self._deny_messages,
|
|
104
|
+
)
|
|
105
|
+
self.install_module_proxies()
|
|
106
|
+
|
|
107
|
+
def apply_attrgetter_guard(self) -> None:
|
|
108
|
+
"""Patch operator.attrgetter and builtins.getattr to reject blocked attribute names.
|
|
109
|
+
|
|
110
|
+
This closes bypasses where attrgetter('__globals__') or
|
|
111
|
+
getattr(obj, '__globals__') is used to access dangerous attributes
|
|
112
|
+
at runtime, bypassing AST-level attribute checks.
|
|
113
|
+
"""
|
|
114
|
+
operator = self._operator_module
|
|
115
|
+
|
|
116
|
+
blocked_attrs = set(
|
|
117
|
+
self._config.get("ast", {}).get("block_attributes", [])
|
|
118
|
+
)
|
|
119
|
+
_ORIGINALS["attrgetter"] = operator.attrgetter
|
|
120
|
+
_ORIGINALS["getattr"] = builtins.getattr
|
|
121
|
+
|
|
122
|
+
def _safe_attrgetter(*names: str) -> Any:
|
|
123
|
+
for name in names:
|
|
124
|
+
# Check each dotted component (attrgetter supports 'a.b.c')
|
|
125
|
+
for part in name.split("."):
|
|
126
|
+
if part in blocked_attrs:
|
|
127
|
+
raise PermissionError(
|
|
128
|
+
f"PermissionError: attrgetter access to '{part}' is "
|
|
129
|
+
f"not permitted. Please rewrite your snippet to avoid "
|
|
130
|
+
f"this attribute."
|
|
131
|
+
)
|
|
132
|
+
return _ORIGINALS["attrgetter"](*names)
|
|
133
|
+
|
|
134
|
+
def _safe_getattr(obj: Any, name: str, *default: Any) -> Any:
|
|
135
|
+
if isinstance(name, str) and name in blocked_attrs:
|
|
136
|
+
raise PermissionError(
|
|
137
|
+
f"PermissionError: getattr access to '{name}' is "
|
|
138
|
+
f"not permitted. Please rewrite your snippet to avoid "
|
|
139
|
+
f"this attribute."
|
|
140
|
+
)
|
|
141
|
+
return _ORIGINALS["getattr"](obj, name, *default)
|
|
142
|
+
|
|
143
|
+
operator.attrgetter = _safe_attrgetter
|
|
144
|
+
builtins.getattr = _safe_getattr
|
|
145
|
+
|
|
146
|
+
def install_import_hook(self) -> None:
|
|
147
|
+
"""Install a pure-allowlist import hook with stack-aware bypass.
|
|
148
|
+
|
|
149
|
+
Pre-imports all allowed modules first so their transitive dependencies
|
|
150
|
+
are cached in sys.modules before the hook is active. Then installs
|
|
151
|
+
two enforcement points:
|
|
152
|
+
1. _ImportBlocker on sys.meta_path (fires for uncached modules)
|
|
153
|
+
2. _guarded_import on builtins.__import__ (fires for ALL imports)
|
|
154
|
+
|
|
155
|
+
Both use the same logic: top-level module in allowlist → allow,
|
|
156
|
+
caller is inside a trusted path (workspace module or site-packages) → allow,
|
|
157
|
+
else → block.
|
|
158
|
+
|
|
159
|
+
Trusted paths include:
|
|
160
|
+
- Workspace module directories (editable installs)
|
|
161
|
+
- The venv's site-packages (transitive dependencies)
|
|
162
|
+
"""
|
|
163
|
+
allowed = self._config.get("imports", {}).get("allowed", [])
|
|
164
|
+
allowed_set = set(allowed)
|
|
165
|
+
workspace_imports = self._config.get("imports", {}).get("workspace", {})
|
|
166
|
+
|
|
167
|
+
# Pre-import allowed modules so their transitive dependencies
|
|
168
|
+
# are in sys.modules before the hook activates
|
|
169
|
+
for module_name in allowed:
|
|
170
|
+
try:
|
|
171
|
+
importlib.import_module(module_name)
|
|
172
|
+
except ImportError:
|
|
173
|
+
# Module not installed yet — that's fine, skip it
|
|
174
|
+
pass
|
|
175
|
+
|
|
176
|
+
# Build trusted path prefixes for stack-aware bypass.
|
|
177
|
+
# These are directories where code is allowed to import freely.
|
|
178
|
+
# Includes workspace module dirs, venv site-packages, and stdlib Lib.
|
|
179
|
+
venv_path = self._workspace_root / ".pyddock" / "venv"
|
|
180
|
+
trusted_prefixes_tuple = _build_trusted_prefixes(
|
|
181
|
+
workspace_root=self._workspace_root,
|
|
182
|
+
workspace_imports=workspace_imports,
|
|
183
|
+
venv_path=venv_path if venv_path.is_dir() else None,
|
|
184
|
+
real_os=self._real_os,
|
|
185
|
+
)
|
|
186
|
+
self._trusted_prefixes = trusted_prefixes_tuple
|
|
187
|
+
|
|
188
|
+
# Pre-warmed stdlib internals that are allowed to be re-imported from
|
|
189
|
+
# sys.modules cache. These are lazily imported by frozen stdlib modules
|
|
190
|
+
# (e.g. _strptime by datetime.strptime) and would be blocked by the
|
|
191
|
+
# trusted-caller check due to frozen frame chain issues in Python 3.12+.
|
|
192
|
+
_prewarmed_internals = _run_prewarms()
|
|
193
|
+
|
|
194
|
+
blocker = _ImportBlocker(allowed, trusted_prefixes_tuple, self._deny_messages)
|
|
195
|
+
# Insert at the beginning so it's checked first
|
|
196
|
+
sys.meta_path.insert(0, blocker)
|
|
197
|
+
|
|
198
|
+
# Patch builtins.__import__ to enforce the allowlist directly.
|
|
199
|
+
# This closes the bypass where attacker accesses __import__ from
|
|
200
|
+
# a function's __globals__['__builtins__'] dict.
|
|
201
|
+
_ORIGINALS["import"] = builtins.__import__
|
|
202
|
+
_trusted = trusted_prefixes_tuple
|
|
203
|
+
_loading_depth = [0] # reentrant counter: >0 while loading an allowed module
|
|
204
|
+
# Modules that must NOT be wrapped by _proxy_module_universal:
|
|
205
|
+
# os: plain types.ModuleType with safe attrs only (not a _CallerScopedModuleProxy)
|
|
206
|
+
# sys: specialized caller-scoped proxy with custom_attrs
|
|
207
|
+
# threading: _shutdown() called from C/frozen frames during interpreter exit
|
|
208
|
+
# Restriction modules are NOT skipped — mode="deny" modules already have a
|
|
209
|
+
# _CallerScopedModuleProxy (isinstance early-return), and mode="allow" modules
|
|
210
|
+
# need caller-scoped proxying to block ModuleType attr leakage (e.g. polars.os).
|
|
211
|
+
_skip_proxy = frozenset({"os", "sys", "threading"})
|
|
212
|
+
_ws_module_names = frozenset(workspace_imports.keys())
|
|
213
|
+
_deny_msgs = self._deny_messages
|
|
214
|
+
|
|
215
|
+
def _guarded_import(name: str, *args: Any, **kwargs: Any) -> Any:
|
|
216
|
+
# For relative imports (level > 0), the name is relative to the
|
|
217
|
+
# calling package which is already allowed. Let them through.
|
|
218
|
+
# args[3] is 'level' in the __import__ signature:
|
|
219
|
+
# __import__(name, globals, locals, fromlist, level)
|
|
220
|
+
level = args[3] if len(args) > 3 else kwargs.get("level", 0)
|
|
221
|
+
if level and level > 0:
|
|
222
|
+
return _ORIGINALS["import"](name, *args, **kwargs)
|
|
223
|
+
top_level = name.split(".")[0]
|
|
224
|
+
if top_level in allowed_set:
|
|
225
|
+
# Track that we're loading an allowed module — imports
|
|
226
|
+
# triggered by frozen import machinery during this load
|
|
227
|
+
# are allowed (e.g. _io for .pyc cache writing).
|
|
228
|
+
_loading_depth[0] += 1
|
|
229
|
+
try:
|
|
230
|
+
result = _ORIGINALS["import"](name, *args, **kwargs)
|
|
231
|
+
finally:
|
|
232
|
+
_loading_depth[0] -= 1
|
|
233
|
+
# Proxy ANY submodule import so agent code can't access
|
|
234
|
+
# leaked imports (e.g. pathlib.os, tempfile.os, json.decoder.os).
|
|
235
|
+
if "." in name:
|
|
236
|
+
_proxy_module_universal(name, _trusted, _skip_proxy, _ws_module_names)
|
|
237
|
+
return result
|
|
238
|
+
# If the module was explicitly pre-warmed as a stdlib internal
|
|
239
|
+
# (e.g. _strptime), allow re-import from cache. These are lazily
|
|
240
|
+
# imported by frozen stdlib modules and would be blocked by the
|
|
241
|
+
# trusted-caller check due to frozen frame chain issues.
|
|
242
|
+
if name in _prewarmed_internals and name in sys.modules:
|
|
243
|
+
return _ORIGINALS["import"](name, *args, **kwargs)
|
|
244
|
+
# If we're inside the loading of an allowed module AND the
|
|
245
|
+
# immediate caller is frozen import machinery, permit the import.
|
|
246
|
+
# This narrowly handles internal machinery needs (codec loading,
|
|
247
|
+
# .pyc writing) without opening a general bypass.
|
|
248
|
+
if _loading_depth[0] > 0:
|
|
249
|
+
caller = sys._getframe(1)
|
|
250
|
+
if caller and caller.f_code.co_filename.startswith("<frozen"):
|
|
251
|
+
return _ORIGINALS["import"](name, *args, **kwargs)
|
|
252
|
+
# Stack-aware bypass: allow imports from trusted code paths
|
|
253
|
+
# (workspace modules, their transitive deps in site-packages).
|
|
254
|
+
if _trusted and _caller_is_trusted(_trusted):
|
|
255
|
+
return _ORIGINALS["import"](name, *args, **kwargs)
|
|
256
|
+
allowed_list = ", ".join(sorted(allowed_set))
|
|
257
|
+
msg = (
|
|
258
|
+
f"ImportError: '{name}' is not an allowed import. "
|
|
259
|
+
f"Please use one of the following allowed imports "
|
|
260
|
+
f"instead: {allowed_list}"
|
|
261
|
+
)
|
|
262
|
+
hint = _find_deny_hint(name, _deny_msgs)
|
|
263
|
+
if hint:
|
|
264
|
+
msg += f"\n[{hint}]"
|
|
265
|
+
raise ImportError(msg)
|
|
266
|
+
|
|
267
|
+
builtins.__import__ = _guarded_import
|
|
268
|
+
|
|
269
|
+
# Install a safe sys proxy if 'sys' is in the allowlist.
|
|
270
|
+
# This gives user code access to sys.argv, sys.platform, etc.
|
|
271
|
+
# without exposing sys.modules, sys.meta_path, or other dangerous attrs.
|
|
272
|
+
# Trusted code (workspace modules, site-packages) gets full sys access.
|
|
273
|
+
if "sys" in allowed_set:
|
|
274
|
+
self._install_safe_sys(trusted_prefixes_tuple)
|
|
275
|
+
|
|
276
|
+
# Install a safe os proxy if 'os' is in the allowlist.
|
|
277
|
+
# Exposes os.environ, os.getcwd(), os.name, os.sep, os.path, etc.
|
|
278
|
+
# without exposing os.system, os.popen, os.exec*, os.spawn*, etc.
|
|
279
|
+
if "os" in allowed_set:
|
|
280
|
+
self._install_safe_os()
|
|
281
|
+
|
|
282
|
+
# Install module proxies on ALL allowed modules to prevent attribute
|
|
283
|
+
# leakage. This blocks agent code from accessing imported modules via
|
|
284
|
+
# e.g. pathlib.os, tempfile.os, workspace_pkg.sys, etc.
|
|
285
|
+
# Skip: os/sys (have specialized proxies), restriction modules (handled
|
|
286
|
+
# by apply_restrictions()), and anything already proxied.
|
|
287
|
+
# NOTE: This is called later by install_module_proxies() after all
|
|
288
|
+
# patches are applied, so proxies capture the patched versions.
|
|
289
|
+
self._allowed_set = allowed_set
|
|
290
|
+
|
|
291
|
+
def install_module_proxies(self) -> None:
|
|
292
|
+
"""Wrap ALL allowed modules in caller-scoped proxies.
|
|
293
|
+
|
|
294
|
+
Replaces the old implementation that only proxied workspace modules
|
|
295
|
+
and patched os references on stdlib modules.
|
|
296
|
+
|
|
297
|
+
Called LAST in apply_all() so that all runtime patches are applied first.
|
|
298
|
+
The proxies then pre-cache the patched versions of attributes.
|
|
299
|
+
|
|
300
|
+
This blocks agent code from accessing imported modules via e.g.
|
|
301
|
+
pathlib.os, tempfile.os, workspace_pkg.sys, etc.
|
|
302
|
+
"""
|
|
303
|
+
# Build the skip set: only os/sys/threading need skipping.
|
|
304
|
+
# subprocess and tempfile are NOT skipped — they are patched on the real module
|
|
305
|
+
# before proxying, and the proxy pre-caches the patched versions (since
|
|
306
|
+
# install_module_proxies runs last). threading IS skipped because _shutdown()
|
|
307
|
+
# is called during interpreter exit from C code / frozen frames, not from
|
|
308
|
+
# stdlib code with a file path — so _caller_is_trusted() would return False.
|
|
309
|
+
# Restriction modules are NOT skipped:
|
|
310
|
+
# - mode="deny" (boto3): already a _CallerScopedModuleProxy → isinstance early-return
|
|
311
|
+
# - mode="allow" (polars): real module with _blocked stubs → gets caller-scoped
|
|
312
|
+
# proxy to block ModuleType attr leakage (e.g. polars.os)
|
|
313
|
+
skip_modules = frozenset({"os", "sys", "threading"})
|
|
314
|
+
|
|
315
|
+
# Identify workspace module names for stricter class filtering.
|
|
316
|
+
workspace_imports = self._config.get("imports", {}).get("workspace", {})
|
|
317
|
+
workspace_module_names = frozenset(workspace_imports.keys())
|
|
318
|
+
|
|
319
|
+
for mod_name in list(sys.modules.keys()):
|
|
320
|
+
top = mod_name.split(".")[0]
|
|
321
|
+
if top not in self._allowed_set:
|
|
322
|
+
continue
|
|
323
|
+
_proxy_module_universal(
|
|
324
|
+
mod_name, self._trusted_prefixes, skip_modules, workspace_module_names
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
def _install_safe_sys(self, trusted_prefixes: tuple[str, ...]) -> None:
|
|
328
|
+
"""Replace sys in sys.modules with a caller-scoped proxy.
|
|
329
|
+
|
|
330
|
+
The proxy has three access tiers:
|
|
331
|
+
1. SAFE_ATTRS: Always accessible by anyone (argv, platform, stdout, etc.)
|
|
332
|
+
2. BLOCKED_ATTRS: Always blocked for everyone (meta_path, _getframe —
|
|
333
|
+
these would allow sandbox escape even from trusted code)
|
|
334
|
+
3. Everything else: Accessible only to trusted callers (workspace modules,
|
|
335
|
+
site-packages). Agent snippet code gets AttributeError.
|
|
336
|
+
|
|
337
|
+
This allows libraries like pywin32 (running from site-packages) to access
|
|
338
|
+
sys.modules, sys.path, etc. during their bootstrap, while preventing agent
|
|
339
|
+
code from using those attributes to escape the sandbox.
|
|
340
|
+
"""
|
|
341
|
+
_real_sys = sys
|
|
342
|
+
_traceback_mod = self._traceback_module
|
|
343
|
+
|
|
344
|
+
# Attributes always safe for anyone (read-only values, streams, etc.)
|
|
345
|
+
_SAFE_ATTRS = frozenset({
|
|
346
|
+
"argv", "platform", "version", "version_info", "maxsize",
|
|
347
|
+
"byteorder", "executable", "prefix", "exec_prefix",
|
|
348
|
+
"stdout", "stderr", "stdin",
|
|
349
|
+
"float_info", "int_info", "hash_info",
|
|
350
|
+
"getdefaultencoding", "getfilesystemencoding",
|
|
351
|
+
"getrecursionlimit",
|
|
352
|
+
"path", # frozen tuple copy for agent code (read-only)
|
|
353
|
+
"exit",
|
|
354
|
+
"exc_info",
|
|
355
|
+
"_pyddock_format_tb",
|
|
356
|
+
# Module metadata attrs Python expects on all modules
|
|
357
|
+
"__name__", "__doc__", "__loader__", "__spec__",
|
|
358
|
+
"__package__", "__path__",
|
|
359
|
+
})
|
|
360
|
+
|
|
361
|
+
# Attributes NEVER exposed — even trusted code shouldn't remove
|
|
362
|
+
# the import hook or inspect frames through the proxy.
|
|
363
|
+
_BLOCKED_ATTRS = frozenset({
|
|
364
|
+
"meta_path", # removing import blocker = sandbox escape
|
|
365
|
+
"path_hooks", # manipulating import machinery
|
|
366
|
+
"path_importer_cache",
|
|
367
|
+
"_getframe", # frame access = globals access = sandbox escape
|
|
368
|
+
"_current_frames",
|
|
369
|
+
})
|
|
370
|
+
|
|
371
|
+
# Build custom_attrs dict with sys-specific custom implementations.
|
|
372
|
+
|
|
373
|
+
# sys.exit — harmless in subprocess (raises SystemExit)
|
|
374
|
+
def _safe_exit(code: int = 0) -> None:
|
|
375
|
+
raise SystemExit(code)
|
|
376
|
+
|
|
377
|
+
# sys.exc_info() — strip traceback to prevent frame access
|
|
378
|
+
def _safe_exc_info() -> tuple:
|
|
379
|
+
typ, val, _tb = _real_sys.exc_info()
|
|
380
|
+
return (typ, val, None)
|
|
381
|
+
|
|
382
|
+
# sys._pyddock_format_tb() — safe traceback alternative
|
|
383
|
+
def _safe_format_tb() -> list[tuple[str, int, str, str | None]]:
|
|
384
|
+
_typ, _val, tb = _real_sys.exc_info()
|
|
385
|
+
if tb is None:
|
|
386
|
+
return []
|
|
387
|
+
entries = _traceback_mod.extract_tb(tb)
|
|
388
|
+
return [(e.filename, e.lineno, e.name, e.line) for e in entries]
|
|
389
|
+
|
|
390
|
+
custom_attrs = {
|
|
391
|
+
"exit": _safe_exit,
|
|
392
|
+
"exc_info": _safe_exc_info,
|
|
393
|
+
"path": tuple(_real_sys.path),
|
|
394
|
+
"_pyddock_format_tb": _safe_format_tb,
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
# Instantiate the unified caller-scoped proxy for sys
|
|
398
|
+
proxy = _CallerScopedModuleProxy(
|
|
399
|
+
module_name="sys",
|
|
400
|
+
real_module=_real_sys,
|
|
401
|
+
always_allowed=_SAFE_ATTRS,
|
|
402
|
+
always_blocked=_BLOCKED_ATTRS,
|
|
403
|
+
trusted_prefixes=tuple(trusted_prefixes),
|
|
404
|
+
custom_attrs=custom_attrs,
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
# Put the caller-scoped proxy where 'import sys' will find it
|
|
408
|
+
_real_sys.modules["sys"] = proxy
|
|
409
|
+
|
|
410
|
+
def _install_safe_os(self) -> None:
|
|
411
|
+
"""Replace os in sys.modules with a safe proxy exposing only benign attrs."""
|
|
412
|
+
_real_os = self._real_os
|
|
413
|
+
types = self._types_module
|
|
414
|
+
|
|
415
|
+
safe_os = types.ModuleType("os")
|
|
416
|
+
safe_os.__doc__ = "Safe os proxy provided by pyddock."
|
|
417
|
+
safe_os._pyddock_safe = True
|
|
418
|
+
|
|
419
|
+
# Safe constants and attributes
|
|
420
|
+
_safe_attrs = [
|
|
421
|
+
"name", "sep", "altsep", "extsep", "pathsep", "linesep",
|
|
422
|
+
"curdir", "pardir", "devnull",
|
|
423
|
+
"cpu_count", "PathLike", "fspath",
|
|
424
|
+
]
|
|
425
|
+
for attr in _safe_attrs:
|
|
426
|
+
if hasattr(_real_os, attr):
|
|
427
|
+
setattr(safe_os, attr, getattr(_real_os, attr))
|
|
428
|
+
|
|
429
|
+
# Safe functions (read-only operations)
|
|
430
|
+
_safe_funcs = [
|
|
431
|
+
"getcwd", "getpid", "getlogin",
|
|
432
|
+
"getenv",
|
|
433
|
+
"listdir", "scandir", "walk",
|
|
434
|
+
"stat", "lstat", "fstat",
|
|
435
|
+
"path", # os.path submodule (pure path manipulation)
|
|
436
|
+
]
|
|
437
|
+
for attr in _safe_funcs:
|
|
438
|
+
if hasattr(_real_os, attr):
|
|
439
|
+
setattr(safe_os, attr, getattr(_real_os, attr))
|
|
440
|
+
|
|
441
|
+
# os.environ — expose as read-only (MappingProxyType)
|
|
442
|
+
MappingProxyType = self._types_module.MappingProxyType
|
|
443
|
+
safe_os.environ = MappingProxyType(dict(_real_os.environ))
|
|
444
|
+
|
|
445
|
+
# Workspace-scoped directory operations are patched in apply_filesystem_scoping()
|
|
446
|
+
# where the full _check_write logic (including .pyddock/ and workspace module
|
|
447
|
+
# protection) is available. Here we just expose stubs that will be replaced.
|
|
448
|
+
|
|
449
|
+
# Put the safe proxy where 'import os' will find it
|
|
450
|
+
sys.modules["os"] = safe_os
|
|
451
|
+
# Also update os.path reference to use the real os.path
|
|
452
|
+
sys.modules["os.path"] = _real_os.path
|
|
453
|
+
|
|
454
|
+
def apply_restrictions(self) -> None:
|
|
455
|
+
"""Apply module-level and class-level restrictions.
|
|
456
|
+
|
|
457
|
+
For mode="deny":
|
|
458
|
+
- module_allow: install a _CallerScopedModuleProxy (simple mode) that
|
|
459
|
+
exposes only attributes matching allow patterns. The real module is
|
|
460
|
+
NOT mutated.
|
|
461
|
+
- class_allow: wrap allowed callable attrs with FactoryProxy and store
|
|
462
|
+
them in custom_attrs on the proxy, so objects they return are
|
|
463
|
+
restricted to class_allow patterns.
|
|
464
|
+
|
|
465
|
+
For mode="allow":
|
|
466
|
+
- module_deny: block module-level attrs matching deny patterns
|
|
467
|
+
- class_deny: patch methods matching deny patterns on all public classes
|
|
468
|
+
"""
|
|
469
|
+
restrictions = self._config.get("restrictions", {})
|
|
470
|
+
allowed_imports = set(self._config.get("imports", {}).get("allowed", []))
|
|
471
|
+
|
|
472
|
+
for module_name, restriction in restrictions.items():
|
|
473
|
+
# Skip restrictions for modules that aren't in [imports] —
|
|
474
|
+
# the agent can't import them anyway, and importing here can
|
|
475
|
+
# trigger side effects (e.g. attrgetter guard conflicts).
|
|
476
|
+
if module_name not in allowed_imports:
|
|
477
|
+
continue
|
|
478
|
+
|
|
479
|
+
mode = restriction.get("mode", "allow")
|
|
480
|
+
module_allow = restriction.get("module_allow", [])
|
|
481
|
+
module_deny = restriction.get("module_deny", [])
|
|
482
|
+
class_allow = restriction.get("class_allow", [])
|
|
483
|
+
class_deny = restriction.get("class_deny", [])
|
|
484
|
+
|
|
485
|
+
try:
|
|
486
|
+
module = importlib.import_module(module_name)
|
|
487
|
+
except ImportError:
|
|
488
|
+
continue
|
|
489
|
+
|
|
490
|
+
# --- Module-level enforcement ---
|
|
491
|
+
if mode == "allow" and module_deny:
|
|
492
|
+
# Block matching patterns on the module
|
|
493
|
+
deny_compiled = [re.compile(p) for p in module_deny]
|
|
494
|
+
for attr_name in list(dir(module)):
|
|
495
|
+
if attr_name.startswith("_"):
|
|
496
|
+
continue
|
|
497
|
+
if any(p.match(attr_name) for p in deny_compiled):
|
|
498
|
+
self._patch_module_function(module, attr_name, module_name)
|
|
499
|
+
elif mode == "deny" and module_allow:
|
|
500
|
+
# Install a simple-mode _CallerScopedModuleProxy.
|
|
501
|
+
# The proxy exposes only attributes matching module_allow patterns.
|
|
502
|
+
# The real module is NOT mutated — FactoryProxy instances (if any)
|
|
503
|
+
# live in custom_attrs on the proxy.
|
|
504
|
+
always_allowed = _expand_patterns(module_allow, module)
|
|
505
|
+
custom_attrs: dict[str, Any] = {}
|
|
506
|
+
|
|
507
|
+
if class_allow:
|
|
508
|
+
# For each allowed callable attr, wrap it in FactoryProxy
|
|
509
|
+
# so objects it returns are restricted to class_allow patterns.
|
|
510
|
+
# Classes are wrapped too (they're callable constructors),
|
|
511
|
+
# except BaseException subclasses which are never factories.
|
|
512
|
+
compiled_class_patterns = [re.compile(p) for p in class_allow]
|
|
513
|
+
for attr_name in always_allowed:
|
|
514
|
+
attr = getattr(module, attr_name, None)
|
|
515
|
+
if attr is None or not callable(attr):
|
|
516
|
+
continue
|
|
517
|
+
if isinstance(attr, type) and issubclass(attr, BaseException):
|
|
518
|
+
continue
|
|
519
|
+
custom_attrs[attr_name] = FactoryProxy(
|
|
520
|
+
attr, compiled_class_patterns,
|
|
521
|
+
self._deny_messages, module_name,
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
proxy = _CallerScopedModuleProxy(
|
|
525
|
+
module_name=module_name,
|
|
526
|
+
real_module=module,
|
|
527
|
+
always_allowed=always_allowed,
|
|
528
|
+
always_blocked=frozenset(),
|
|
529
|
+
trusted_prefixes=None, # simple mode
|
|
530
|
+
custom_attrs=custom_attrs if custom_attrs else None,
|
|
531
|
+
)
|
|
532
|
+
sys.modules[module_name] = proxy
|
|
533
|
+
|
|
534
|
+
# --- Class-level enforcement ---
|
|
535
|
+
if mode == "allow" and class_deny:
|
|
536
|
+
# Patch methods on all public classes matching deny patterns
|
|
537
|
+
deny_compiled = [re.compile(p) for p in class_deny]
|
|
538
|
+
for cls_name in dir(module):
|
|
539
|
+
if cls_name.startswith("_"):
|
|
540
|
+
continue
|
|
541
|
+
cls = getattr(module, cls_name, None)
|
|
542
|
+
if cls is None or not isinstance(cls, type):
|
|
543
|
+
continue
|
|
544
|
+
for method_name in list(dir(cls)):
|
|
545
|
+
if method_name.startswith("_"):
|
|
546
|
+
continue
|
|
547
|
+
if any(p.match(method_name) for p in deny_compiled):
|
|
548
|
+
self._patch_class_method(cls, method_name, module_name)
|
|
549
|
+
|
|
550
|
+
def _patch_module_function(
|
|
551
|
+
self, module: Any, func_name: str, module_name: str
|
|
552
|
+
) -> None:
|
|
553
|
+
"""Replace a module-level function with one that raises PermissionError."""
|
|
554
|
+
deny_messages = self._deny_messages
|
|
555
|
+
|
|
556
|
+
def _blocked(*args: Any, **kwargs: Any) -> None:
|
|
557
|
+
msg = (
|
|
558
|
+
f"PermissionError: '{func_name}' is not permitted on {module_name}. "
|
|
559
|
+
f"Please rewrite your snippet to avoid this function."
|
|
560
|
+
)
|
|
561
|
+
hint = _find_deny_hint(f"{module_name}.{func_name}", deny_messages)
|
|
562
|
+
if hint:
|
|
563
|
+
msg += f"\n[{hint}]"
|
|
564
|
+
raise PermissionError(msg)
|
|
565
|
+
|
|
566
|
+
setattr(module, func_name, _blocked)
|
|
567
|
+
|
|
568
|
+
def _patch_class_method(
|
|
569
|
+
self, cls: Any, method_name: str, module_name: str
|
|
570
|
+
) -> None:
|
|
571
|
+
"""Replace a class method with one that raises PermissionError."""
|
|
572
|
+
deny_messages = self._deny_messages
|
|
573
|
+
|
|
574
|
+
def _blocked(*args: Any, **kwargs: Any) -> None:
|
|
575
|
+
msg = (
|
|
576
|
+
f"PermissionError: '{method_name}' is not permitted on {module_name}. "
|
|
577
|
+
f"Please rewrite your snippet to avoid this function."
|
|
578
|
+
)
|
|
579
|
+
hint = _find_deny_hint(f"{module_name}.{method_name}", deny_messages)
|
|
580
|
+
if hint:
|
|
581
|
+
msg += f"\n[{hint}]"
|
|
582
|
+
raise PermissionError(msg)
|
|
583
|
+
|
|
584
|
+
setattr(cls, method_name, _blocked)
|