pyddock 0.2.0__tar.gz → 0.2.1__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.0 → pyddock-0.2.1}/PKG-INFO +1 -1
- {pyddock-0.2.0 → pyddock-0.2.1}/publish-to-pypi.ps1 +2 -1
- {pyddock-0.2.0 → pyddock-0.2.1}/pyproject.toml +1 -1
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/_runtime.py +127 -22
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/ast_validator.py +4 -1
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/config.py +57 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/default_config.toml +30 -2
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/executor.py +4 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/shell_executor.py +21 -7
- pyddock-0.2.1/tests/test_deny_messages.py +206 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/uv.lock +1 -1
- {pyddock-0.2.0 → pyddock-0.2.1}/.gitignore +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/LICENSE +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/README.md +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/__init__.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/_process_utils.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/cli.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/script_registry.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/server.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/__init__.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/fs_append.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/fs_delete.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/read_file.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/stat_file.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/tools/str_replace.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/src/pyddock/venv_manager.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/__init__.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_ast_properties.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_chmod_integration.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_config.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_executor.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_file_tools.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_filesystem_guards.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_proxy_properties.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_realistic.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_runtime.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_security_guards.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_server.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_shell_arg_paths.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_shell_executor.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_shell_properties.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_subprocess_enforcement.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_subprocess_properties.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_subst_trusted_path.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/tests/test_venv_stamp.py +0 -0
- {pyddock-0.2.0 → pyddock-0.2.1}/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.1
|
|
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
|
|
@@ -17,7 +17,8 @@ uvx twine upload --repository testpypi dist/*
|
|
|
17
17
|
if ($LASTEXITCODE -ne 0) { throw "testpypi upload failed" }
|
|
18
18
|
|
|
19
19
|
# Pause for confirmation
|
|
20
|
-
Read-Host "`nUploaded to testpypi.
|
|
20
|
+
$response = Read-Host "`nUploaded to testpypi. Type 'y' to upload to pypi (else abort)"
|
|
21
|
+
if ($response -ne 'y') { Write-Host "Aborted."; exit 0 }
|
|
21
22
|
|
|
22
23
|
# Upload to pypi
|
|
23
24
|
Write-Host "> uvx twine upload --repository pyddock dist/*"
|
|
@@ -44,6 +44,19 @@ del _os_for_path
|
|
|
44
44
|
_ORIGINALS: dict[str, Any] = {}
|
|
45
45
|
|
|
46
46
|
|
|
47
|
+
def _find_deny_hint(attempted: str, deny_messages: list[tuple[re.Pattern[str], str]]) -> str | None:
|
|
48
|
+
"""Return the first matching deny hint for the attempted action, or None.
|
|
49
|
+
|
|
50
|
+
This is the subprocess-side equivalent of config.find_deny_hint().
|
|
51
|
+
It operates on pre-compiled (pattern, message) tuples reconstructed
|
|
52
|
+
from the serialized config dict.
|
|
53
|
+
"""
|
|
54
|
+
for pattern, message in deny_messages:
|
|
55
|
+
if pattern.search(attempted):
|
|
56
|
+
return message
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
47
60
|
def _is_infra_frame(filename: str) -> bool:
|
|
48
61
|
"""Return True if the frame belongs to import infrastructure or pyddock itself.
|
|
49
62
|
|
|
@@ -104,9 +117,15 @@ class _ImportBlocker:
|
|
|
104
117
|
trusted path (workspace module or its transitive dependency in site-packages).
|
|
105
118
|
"""
|
|
106
119
|
|
|
107
|
-
def __init__(
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
allowed: list[str],
|
|
123
|
+
trusted_prefixes: list[str],
|
|
124
|
+
deny_messages: list[tuple[re.Pattern[str], str]] | None = None,
|
|
125
|
+
) -> None:
|
|
108
126
|
self._allowed = set(allowed)
|
|
109
127
|
self._trusted_prefixes = tuple(trusted_prefixes)
|
|
128
|
+
self._deny_messages = deny_messages or []
|
|
110
129
|
|
|
111
130
|
def find_module(self, fullname: str, path: Any = None) -> _ImportBlocker | None:
|
|
112
131
|
"""Legacy import hook interface for compatibility."""
|
|
@@ -117,10 +136,14 @@ class _ImportBlocker:
|
|
|
117
136
|
def load_module(self, fullname: str) -> None:
|
|
118
137
|
"""Raise ImportError for blocked modules (legacy interface)."""
|
|
119
138
|
allowed_list = ", ".join(sorted(self._allowed))
|
|
120
|
-
|
|
139
|
+
msg = (
|
|
121
140
|
f"ImportError: '{fullname}' is not an allowed import. "
|
|
122
141
|
f"Please use one of the following allowed imports instead: {allowed_list}"
|
|
123
142
|
)
|
|
143
|
+
hint = _find_deny_hint(fullname, self._deny_messages)
|
|
144
|
+
if hint:
|
|
145
|
+
msg += f"\n[{hint}]"
|
|
146
|
+
raise ImportError(msg)
|
|
124
147
|
|
|
125
148
|
def find_spec(
|
|
126
149
|
self, fullname: str, path: Any = None, target: Any = None
|
|
@@ -132,11 +155,15 @@ class _ImportBlocker:
|
|
|
132
155
|
"""
|
|
133
156
|
if self._should_block(fullname):
|
|
134
157
|
allowed_list = ", ".join(sorted(self._allowed))
|
|
135
|
-
|
|
158
|
+
msg = (
|
|
136
159
|
f"ImportError: '{fullname}' is not an allowed import. "
|
|
137
160
|
f"Please use one of the following allowed imports instead: "
|
|
138
161
|
f"{allowed_list}"
|
|
139
162
|
)
|
|
163
|
+
hint = _find_deny_hint(fullname, self._deny_messages)
|
|
164
|
+
if hint:
|
|
165
|
+
msg += f"\n[{hint}]"
|
|
166
|
+
raise ImportError(msg)
|
|
140
167
|
return None
|
|
141
168
|
|
|
142
169
|
def _should_block(self, fullname: str) -> bool:
|
|
@@ -157,9 +184,17 @@ class MethodFilterProxy:
|
|
|
157
184
|
Only methods matching at least one allow pattern are permitted.
|
|
158
185
|
"""
|
|
159
186
|
|
|
160
|
-
def __init__(
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
wrapped: Any,
|
|
190
|
+
allow_patterns: list[re.Pattern[str]],
|
|
191
|
+
deny_messages: list[tuple[re.Pattern[str], str]] | None = None,
|
|
192
|
+
module_name: str = "",
|
|
193
|
+
) -> None:
|
|
161
194
|
object.__setattr__(self, "_wrapped", wrapped)
|
|
162
195
|
object.__setattr__(self, "_allow_patterns", allow_patterns)
|
|
196
|
+
object.__setattr__(self, "_deny_messages", deny_messages or [])
|
|
197
|
+
object.__setattr__(self, "_module_name", module_name)
|
|
163
198
|
|
|
164
199
|
def __getattr__(self, name: str) -> Any:
|
|
165
200
|
allow_patterns = object.__getattribute__(self, "_allow_patterns")
|
|
@@ -171,11 +206,18 @@ class MethodFilterProxy:
|
|
|
171
206
|
|
|
172
207
|
if not any(p.match(name) for p in allow_patterns):
|
|
173
208
|
patterns_str = ", ".join(p.pattern for p in allow_patterns)
|
|
174
|
-
|
|
209
|
+
msg = (
|
|
175
210
|
f"PermissionError: '{name}' is not permitted. "
|
|
176
211
|
f"Allowed method patterns: {patterns_str}. "
|
|
177
212
|
f"Please use one of the allowed methods instead."
|
|
178
213
|
)
|
|
214
|
+
deny_messages = object.__getattribute__(self, "_deny_messages")
|
|
215
|
+
module_name = object.__getattribute__(self, "_module_name")
|
|
216
|
+
attempted = f"{module_name}.{name}" if module_name else name
|
|
217
|
+
hint = _find_deny_hint(attempted, deny_messages)
|
|
218
|
+
if hint:
|
|
219
|
+
msg += f"\n[{hint}]"
|
|
220
|
+
raise PermissionError(msg)
|
|
179
221
|
return getattr(wrapped, name)
|
|
180
222
|
|
|
181
223
|
|
|
@@ -187,14 +229,22 @@ class FactoryProxy:
|
|
|
187
229
|
"""
|
|
188
230
|
|
|
189
231
|
def __init__(
|
|
190
|
-
self,
|
|
232
|
+
self,
|
|
233
|
+
original_factory: Any,
|
|
234
|
+
allow_patterns: list[re.Pattern[str]],
|
|
235
|
+
deny_messages: list[tuple[re.Pattern[str], str]] | None = None,
|
|
236
|
+
module_name: str = "",
|
|
191
237
|
) -> None:
|
|
192
238
|
self._original = original_factory
|
|
193
239
|
self._allow_patterns = allow_patterns
|
|
240
|
+
self._deny_messages = deny_messages or []
|
|
241
|
+
self._module_name = module_name
|
|
194
242
|
|
|
195
243
|
def __call__(self, *args: Any, **kwargs: Any) -> MethodFilterProxy:
|
|
196
244
|
obj = self._original(*args, **kwargs)
|
|
197
|
-
return MethodFilterProxy(
|
|
245
|
+
return MethodFilterProxy(
|
|
246
|
+
obj, self._allow_patterns, self._deny_messages, self._module_name
|
|
247
|
+
)
|
|
198
248
|
|
|
199
249
|
|
|
200
250
|
def _expand_patterns(
|
|
@@ -581,6 +631,14 @@ class RuntimeEnforcement:
|
|
|
581
631
|
# Use abspath (not resolve) to preserve symlinks/subst drives
|
|
582
632
|
import os as _os_init
|
|
583
633
|
self._workspace_root = pathlib.Path(_os_init.path.abspath(workspace_root))
|
|
634
|
+
# Pre-compile deny_messages patterns from serialized config
|
|
635
|
+
self._deny_messages: list[tuple[re.Pattern[str], str]] = []
|
|
636
|
+
for entry in config.get("deny_messages", []):
|
|
637
|
+
try:
|
|
638
|
+
pattern = re.compile(entry["pattern"])
|
|
639
|
+
self._deny_messages.append((pattern, entry["message"]))
|
|
640
|
+
except (re.error, KeyError, TypeError):
|
|
641
|
+
pass # Skip malformed entries silently in subprocess
|
|
584
642
|
|
|
585
643
|
def apply_all(self) -> None:
|
|
586
644
|
"""Apply all enforcement in order: import hook, filesystem, proxies, patches, subprocess."""
|
|
@@ -714,7 +772,7 @@ class RuntimeEnforcement:
|
|
|
714
772
|
except ImportError:
|
|
715
773
|
pass
|
|
716
774
|
|
|
717
|
-
blocker = _ImportBlocker(allowed, trusted_prefixes_tuple)
|
|
775
|
+
blocker = _ImportBlocker(allowed, trusted_prefixes_tuple, self._deny_messages)
|
|
718
776
|
# Insert at the beginning so it's checked first
|
|
719
777
|
sys.meta_path.insert(0, blocker)
|
|
720
778
|
|
|
@@ -733,6 +791,7 @@ class RuntimeEnforcement:
|
|
|
733
791
|
# need caller-scoped proxying to block ModuleType attr leakage (e.g. polars.os).
|
|
734
792
|
_skip_proxy = frozenset({"os", "sys", "threading"})
|
|
735
793
|
_ws_module_names = frozenset(workspace_imports.keys())
|
|
794
|
+
_deny_msgs = self._deny_messages
|
|
736
795
|
|
|
737
796
|
def _guarded_import(name: str, *args: Any, **kwargs: Any) -> Any:
|
|
738
797
|
# For relative imports (level > 0), the name is relative to the
|
|
@@ -770,11 +829,15 @@ class RuntimeEnforcement:
|
|
|
770
829
|
if _trusted and _caller_is_trusted(_trusted):
|
|
771
830
|
return _ORIGINALS["import"](name, *args, **kwargs)
|
|
772
831
|
allowed_list = ", ".join(sorted(allowed_set))
|
|
773
|
-
|
|
832
|
+
msg = (
|
|
774
833
|
f"ImportError: '{name}' is not an allowed import. "
|
|
775
834
|
f"Please use one of the following allowed imports "
|
|
776
835
|
f"instead: {allowed_list}"
|
|
777
836
|
)
|
|
837
|
+
hint = _find_deny_hint(name, _deny_msgs)
|
|
838
|
+
if hint:
|
|
839
|
+
msg += f"\n[{hint}]"
|
|
840
|
+
raise ImportError(msg)
|
|
778
841
|
|
|
779
842
|
builtins.__import__ = _guarded_import
|
|
780
843
|
|
|
@@ -1580,7 +1643,8 @@ class RuntimeEnforcement:
|
|
|
1580
1643
|
attr = getattr(module, attr_name, None)
|
|
1581
1644
|
if attr is not None and callable(attr) and not isinstance(attr, type):
|
|
1582
1645
|
custom_attrs[attr_name] = FactoryProxy(
|
|
1583
|
-
attr, compiled_class_patterns
|
|
1646
|
+
attr, compiled_class_patterns,
|
|
1647
|
+
self._deny_messages, module_name,
|
|
1584
1648
|
)
|
|
1585
1649
|
|
|
1586
1650
|
proxy = _CallerScopedModuleProxy(
|
|
@@ -1609,31 +1673,39 @@ class RuntimeEnforcement:
|
|
|
1609
1673
|
if any(p.match(method_name) for p in deny_compiled):
|
|
1610
1674
|
self._patch_class_method(cls, method_name, module_name)
|
|
1611
1675
|
|
|
1612
|
-
@staticmethod
|
|
1613
1676
|
def _patch_module_function(
|
|
1614
|
-
module: Any, func_name: str, module_name: str
|
|
1677
|
+
self, module: Any, func_name: str, module_name: str
|
|
1615
1678
|
) -> None:
|
|
1616
1679
|
"""Replace a module-level function with one that raises PermissionError."""
|
|
1680
|
+
deny_messages = self._deny_messages
|
|
1617
1681
|
|
|
1618
1682
|
def _blocked(*args: Any, **kwargs: Any) -> None:
|
|
1619
|
-
|
|
1683
|
+
msg = (
|
|
1620
1684
|
f"PermissionError: '{func_name}' is not permitted on {module_name}. "
|
|
1621
1685
|
f"Please rewrite your snippet to avoid this function."
|
|
1622
1686
|
)
|
|
1687
|
+
hint = _find_deny_hint(f"{module_name}.{func_name}", deny_messages)
|
|
1688
|
+
if hint:
|
|
1689
|
+
msg += f"\n[{hint}]"
|
|
1690
|
+
raise PermissionError(msg)
|
|
1623
1691
|
|
|
1624
1692
|
setattr(module, func_name, _blocked)
|
|
1625
1693
|
|
|
1626
|
-
@staticmethod
|
|
1627
1694
|
def _patch_class_method(
|
|
1628
|
-
cls: Any, method_name: str, module_name: str
|
|
1695
|
+
self, cls: Any, method_name: str, module_name: str
|
|
1629
1696
|
) -> None:
|
|
1630
1697
|
"""Replace a class method with one that raises PermissionError."""
|
|
1698
|
+
deny_messages = self._deny_messages
|
|
1631
1699
|
|
|
1632
1700
|
def _blocked(*args: Any, **kwargs: Any) -> None:
|
|
1633
|
-
|
|
1701
|
+
msg = (
|
|
1634
1702
|
f"PermissionError: '{method_name}' is not permitted on {module_name}. "
|
|
1635
1703
|
f"Please rewrite your snippet to avoid this function."
|
|
1636
1704
|
)
|
|
1705
|
+
hint = _find_deny_hint(f"{module_name}.{method_name}", deny_messages)
|
|
1706
|
+
if hint:
|
|
1707
|
+
msg += f"\n[{hint}]"
|
|
1708
|
+
raise PermissionError(msg)
|
|
1637
1709
|
|
|
1638
1710
|
setattr(cls, method_name, _blocked)
|
|
1639
1711
|
|
|
@@ -1660,6 +1732,7 @@ class RuntimeEnforcement:
|
|
|
1660
1732
|
_real_os = self._real_os
|
|
1661
1733
|
_resolve_cmd = self._resolve_command
|
|
1662
1734
|
shell_policies = self._config.get("shell", {})
|
|
1735
|
+
_deny_msgs_sp = self._deny_messages
|
|
1663
1736
|
|
|
1664
1737
|
# Build example command for error messages
|
|
1665
1738
|
if shell_policies:
|
|
@@ -1833,18 +1906,34 @@ class RuntimeEnforcement:
|
|
|
1833
1906
|
cmd_args = [str(a) for a in cmd[1:]]
|
|
1834
1907
|
policy = _find_matching_policy(command)
|
|
1835
1908
|
if policy is None:
|
|
1836
|
-
|
|
1909
|
+
msg = (
|
|
1837
1910
|
f"PermissionError: Command '{command}' is not permitted. "
|
|
1838
1911
|
f"No matching shell policy found. "
|
|
1839
1912
|
f"Allowed commands: {allowed_commands_str}"
|
|
1840
1913
|
)
|
|
1914
|
+
hint = _find_deny_hint(command, _deny_msgs_sp)
|
|
1915
|
+
if hint:
|
|
1916
|
+
msg += f"\n[{hint}]"
|
|
1917
|
+
raise PermissionError(msg)
|
|
1841
1918
|
rejection = _check_args_policy(policy, cmd_args)
|
|
1842
1919
|
if rejection is not None:
|
|
1843
|
-
|
|
1920
|
+
msg = f"PermissionError: {rejection}"
|
|
1921
|
+
hint = _find_deny_hint(
|
|
1922
|
+
f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
|
|
1923
|
+
)
|
|
1924
|
+
if hint:
|
|
1925
|
+
msg += f"\n[{hint}]"
|
|
1926
|
+
raise PermissionError(msg)
|
|
1844
1927
|
# Check arg paths against protected directories
|
|
1845
1928
|
path_rejection = _check_arg_paths(policy, cmd_args)
|
|
1846
1929
|
if path_rejection is not None:
|
|
1847
|
-
|
|
1930
|
+
msg = f"PermissionError: {path_rejection}"
|
|
1931
|
+
hint = _find_deny_hint(
|
|
1932
|
+
f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
|
|
1933
|
+
)
|
|
1934
|
+
if hint:
|
|
1935
|
+
msg += f"\n[{hint}]"
|
|
1936
|
+
raise PermissionError(msg)
|
|
1848
1937
|
# Apply interpreter mapping (same as run_shell) and execute
|
|
1849
1938
|
resolved = _resolve_cmd(command)
|
|
1850
1939
|
full_cmd = resolved + cmd_args
|
|
@@ -1879,17 +1968,33 @@ class RuntimeEnforcement:
|
|
|
1879
1968
|
cmd_args = [str(a) for a in cmd[1:]]
|
|
1880
1969
|
policy = _find_matching_policy(command)
|
|
1881
1970
|
if policy is None:
|
|
1882
|
-
|
|
1971
|
+
msg = (
|
|
1883
1972
|
f"PermissionError: Command '{command}' is not permitted. "
|
|
1884
1973
|
f"No matching shell policy found. "
|
|
1885
1974
|
f"Allowed commands: {allowed_commands_str}"
|
|
1886
1975
|
)
|
|
1976
|
+
hint = _find_deny_hint(command, _deny_msgs_sp)
|
|
1977
|
+
if hint:
|
|
1978
|
+
msg += f"\n[{hint}]"
|
|
1979
|
+
raise PermissionError(msg)
|
|
1887
1980
|
rejection = _check_args_policy(policy, cmd_args)
|
|
1888
1981
|
if rejection is not None:
|
|
1889
|
-
|
|
1982
|
+
msg = f"PermissionError: {rejection}"
|
|
1983
|
+
hint = _find_deny_hint(
|
|
1984
|
+
f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
|
|
1985
|
+
)
|
|
1986
|
+
if hint:
|
|
1987
|
+
msg += f"\n[{hint}]"
|
|
1988
|
+
raise PermissionError(msg)
|
|
1890
1989
|
path_rejection = _check_arg_paths(policy, cmd_args)
|
|
1891
1990
|
if path_rejection is not None:
|
|
1892
|
-
|
|
1991
|
+
msg = f"PermissionError: {path_rejection}"
|
|
1992
|
+
hint = _find_deny_hint(
|
|
1993
|
+
f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
|
|
1994
|
+
)
|
|
1995
|
+
if hint:
|
|
1996
|
+
msg += f"\n[{hint}]"
|
|
1997
|
+
raise PermissionError(msg)
|
|
1893
1998
|
resolved = _resolve_cmd(command)
|
|
1894
1999
|
return resolved + cmd_args, cmd_args
|
|
1895
2000
|
|
|
@@ -9,7 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import ast
|
|
10
10
|
from dataclasses import dataclass
|
|
11
11
|
|
|
12
|
-
from pyddock.config import PyddockConfig
|
|
12
|
+
from pyddock.config import PyddockConfig, find_deny_hint
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
@dataclass
|
|
@@ -125,6 +125,9 @@ class ASTValidator:
|
|
|
125
125
|
f"ImportError: '{module_name}' is not an allowed import. "
|
|
126
126
|
f"Please use one of the following allowed imports instead: {allowed_str}"
|
|
127
127
|
)
|
|
128
|
+
hint = find_deny_hint(module_name, self._config.deny_messages)
|
|
129
|
+
if hint:
|
|
130
|
+
message += f"\n[{hint}]"
|
|
128
131
|
return ASTViolation(
|
|
129
132
|
kind="blocked_import",
|
|
130
133
|
name=module_name,
|
|
@@ -8,6 +8,7 @@ Resolution order:
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
10
|
import logging
|
|
11
|
+
import re
|
|
11
12
|
import tomllib
|
|
12
13
|
from dataclasses import dataclass, field
|
|
13
14
|
from importlib import resources
|
|
@@ -87,6 +88,31 @@ class ShellPolicyConfig:
|
|
|
87
88
|
arg_paths: str = "workspace" # "workspace" | "protected" | "none"
|
|
88
89
|
|
|
89
90
|
|
|
91
|
+
@dataclass
|
|
92
|
+
class DenyMessageRule:
|
|
93
|
+
"""A single deny_messages rule (compiled regex → hint text)."""
|
|
94
|
+
|
|
95
|
+
pattern: re.Pattern[str]
|
|
96
|
+
message: str
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def find_deny_hint(attempted: str, deny_messages: list[DenyMessageRule]) -> str | None:
|
|
100
|
+
"""Return the first matching deny hint for the attempted action, or None.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
attempted: The attempted action string (command, module name, or
|
|
104
|
+
module.attribute depending on rejection type).
|
|
105
|
+
deny_messages: The parsed deny_messages rules from config.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
The hint message string if a pattern matches, else None.
|
|
109
|
+
"""
|
|
110
|
+
for rule in deny_messages:
|
|
111
|
+
if rule.pattern.search(attempted):
|
|
112
|
+
return rule.message
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
90
116
|
@dataclass
|
|
91
117
|
class PyddockConfig:
|
|
92
118
|
"""Top-level pyddock configuration."""
|
|
@@ -97,6 +123,7 @@ class PyddockConfig:
|
|
|
97
123
|
ast: ASTConfig
|
|
98
124
|
restrictions: dict[str, RestrictionConfig] = field(default_factory=dict)
|
|
99
125
|
shell: dict[str, ShellPolicyConfig] = field(default_factory=dict)
|
|
126
|
+
deny_messages: list[DenyMessageRule] = field(default_factory=list)
|
|
100
127
|
|
|
101
128
|
|
|
102
129
|
def _parse_execution(data: dict) -> ExecutionConfig:
|
|
@@ -319,6 +346,35 @@ def _parse_shell(data: dict) -> dict[str, ShellPolicyConfig]:
|
|
|
319
346
|
return shell
|
|
320
347
|
|
|
321
348
|
|
|
349
|
+
def _parse_deny_messages(data: dict) -> list[DenyMessageRule]:
|
|
350
|
+
"""Parse the [deny_messages] section (table of regex → message strings).
|
|
351
|
+
|
|
352
|
+
Each key is a regex pattern matched against the attempted action
|
|
353
|
+
(command string, module name, or module.attribute). Each value is the
|
|
354
|
+
hint message appended to the rejection error. First match wins at runtime.
|
|
355
|
+
"""
|
|
356
|
+
section = data.get("deny_messages", {})
|
|
357
|
+
if not isinstance(section, dict):
|
|
358
|
+
raise ConfigError("[deny_messages] must be a table")
|
|
359
|
+
|
|
360
|
+
rules: list[DenyMessageRule] = []
|
|
361
|
+
for pattern_str, message in section.items():
|
|
362
|
+
if not isinstance(message, str):
|
|
363
|
+
raise ConfigError(
|
|
364
|
+
f"[deny_messages].'{pattern_str}' must be a string, "
|
|
365
|
+
f"got {type(message).__name__}"
|
|
366
|
+
)
|
|
367
|
+
try:
|
|
368
|
+
compiled = re.compile(pattern_str)
|
|
369
|
+
except re.error as e:
|
|
370
|
+
raise ConfigError(
|
|
371
|
+
f"[deny_messages].'{pattern_str}' is not a valid regex: {e}"
|
|
372
|
+
)
|
|
373
|
+
rules.append(DenyMessageRule(pattern=compiled, message=message))
|
|
374
|
+
|
|
375
|
+
return rules
|
|
376
|
+
|
|
377
|
+
|
|
322
378
|
def _deep_merge(base: dict, overlay: dict) -> dict:
|
|
323
379
|
"""Recursively merge *overlay* on top of *base* (neither is mutated).
|
|
324
380
|
|
|
@@ -344,6 +400,7 @@ def _parse_config(data: dict) -> PyddockConfig:
|
|
|
344
400
|
ast=_parse_ast(data),
|
|
345
401
|
restrictions=_parse_restrictions(data),
|
|
346
402
|
shell=_parse_shell(data),
|
|
403
|
+
deny_messages=_parse_deny_messages(data),
|
|
347
404
|
)
|
|
348
405
|
|
|
349
406
|
|
|
@@ -62,9 +62,9 @@ tempfile = true
|
|
|
62
62
|
# Third-party — controlled via [restrictions] sections below
|
|
63
63
|
#boto3 = true # Enable for AWS (opens network access vectors, when with reasonable restrictions)
|
|
64
64
|
dateutil = "python-dateutil"
|
|
65
|
-
|
|
65
|
+
git = "GitPython" # Shell policy enforces command restrictions via Popen
|
|
66
66
|
polars = true
|
|
67
|
-
|
|
67
|
+
P4 = "p4python" # Restricted to non-submit operations
|
|
68
68
|
|
|
69
69
|
# Filesystem scoping for run_python.
|
|
70
70
|
# Paths are relative to the workspace root (the --workspace directory or CWD).
|
|
@@ -96,6 +96,9 @@ readable_paths = ["*"]
|
|
|
96
96
|
'/\.pypirc$' = "deny-all" # PyPI registry tokens — no library reader in sandbox
|
|
97
97
|
'/\.git-credentials$' = "deny-all" # Git plaintext passwords — no library reader in sandbox
|
|
98
98
|
'/\.env(\.[^/]*)?$' = "workspace" # .env files — workspace only
|
|
99
|
+
'/\.kiro/agent' = "deny-all" # Kiro agent config — prevent self-modification
|
|
100
|
+
'/\.kiro/settings' = "deny-all" # Kiro settings — prevent self-modification
|
|
101
|
+
'/\.claude/settings' = "deny-all" # Claude settings — prevent self-modification
|
|
99
102
|
|
|
100
103
|
# AST-level static analysis — blocks dangerous constructs before execution.
|
|
101
104
|
# These prevent trivial jailbreaks (e.g. eval("__import__('os').system(...)")).
|
|
@@ -217,3 +220,28 @@ allow = [
|
|
|
217
220
|
#mode = "allow"
|
|
218
221
|
#deny = []
|
|
219
222
|
#arg_paths = "workspace"
|
|
223
|
+
|
|
224
|
+
# Custom denial hints — appended to rejection messages when the pattern matches
|
|
225
|
+
# the attempted action. These do NOT define new deny rules; they only provide
|
|
226
|
+
# better guidance after a rejection has already occurred.
|
|
227
|
+
#
|
|
228
|
+
# Match targets by rejection type:
|
|
229
|
+
# Shell command rejection → command string (e.g. "aws", "aws.exe", "curl")
|
|
230
|
+
# Shell args rejection → "command args..." (e.g. "git push origin main")
|
|
231
|
+
# Import rejection → full module name (e.g. "requests", "paramiko.client")
|
|
232
|
+
# Restriction rejection → "module.attribute" (e.g. "boto3.resource", "polars.write_csv")
|
|
233
|
+
#
|
|
234
|
+
# Regex uses re.search() against the attempted value. First match wins.
|
|
235
|
+
[deny_messages]
|
|
236
|
+
"^aws(\\.exe)?$" = "AWS CLI is not allowed. Use `import boto3` in run_python instead (client factory with read-only restrictions)."
|
|
237
|
+
"^git push" = "git push is not allowed. Stage changes locally and leave pushing for human review."
|
|
238
|
+
"^git remote" = "git remote is not allowed. Remote configuration cannot be modified from the sandbox."
|
|
239
|
+
"^git " = "This git operation is not in the allowed list. Operations should be limited to side effects within the local workspace."
|
|
240
|
+
"^p4 submit" = "p4 submit is not allowed. Use `p4 shelve` to stage changes for human review."
|
|
241
|
+
"^p4 " = "This p4 operation is not in the allowed list. Operations should be limited to side effects within the local workspace."
|
|
242
|
+
"^requests(\\.|$)" = "Open network access is not permitted in pyddock. Use a different tool if available (e.g. web_fetch)."
|
|
243
|
+
"^paramiko(\\.|$)" = "SSH access is not permitted in pyddock. Use a different tool for remote operations."
|
|
244
|
+
"^boto3\\.(resource|Resource)" = "Only boto3.client() is allowed (not resource/Session). Use boto3.client('<service>') to create service clients."
|
|
245
|
+
"^polars\\.(write_|sink_)" = "Polars write/sink operations are blocked. Write output files using Python builtins (open/pathlib) in run_python instead."
|
|
246
|
+
"^(bash|sh)(\\.exe)?$" = "Shell interpreters are not allowed. Write your logic directly in run_python, or use run_shell with an approved command."
|
|
247
|
+
"^(powershell|pwsh)(\\.exe)?$" = "PowerShell is not allowed. Write your logic directly in run_python, or use run_shell with an approved command."
|
|
@@ -243,6 +243,10 @@ class SubprocessExecutor:
|
|
|
243
243
|
}
|
|
244
244
|
for name, s in self._config.shell.items()
|
|
245
245
|
},
|
|
246
|
+
"deny_messages": [
|
|
247
|
+
{"pattern": rule.pattern.pattern, "message": rule.message}
|
|
248
|
+
for rule in self._config.deny_messages
|
|
249
|
+
],
|
|
246
250
|
}
|
|
247
251
|
|
|
248
252
|
@staticmethod
|
|
@@ -13,7 +13,7 @@ import subprocess
|
|
|
13
13
|
from dataclasses import dataclass
|
|
14
14
|
from pathlib import Path
|
|
15
15
|
|
|
16
|
-
from pyddock.config import PyddockConfig, ShellPolicyConfig
|
|
16
|
+
from pyddock.config import PyddockConfig, ShellPolicyConfig, find_deny_hint
|
|
17
17
|
from pyddock._process_utils import get_startupinfo, kill_and_drain, make_child_env, truncate_output
|
|
18
18
|
|
|
19
19
|
import shutil
|
|
@@ -139,25 +139,39 @@ class ShellExecutor:
|
|
|
139
139
|
configured = ", ".join(
|
|
140
140
|
p.command for p in self._config.shell.values()
|
|
141
141
|
)
|
|
142
|
+
msg = (
|
|
143
|
+
f"Command '{command}' is not allowed. "
|
|
144
|
+
f"No matching [shell.*] policy found.\n"
|
|
145
|
+
f"Configured command patterns: {configured}\n"
|
|
146
|
+
f"Tip: Use run_python for complex workflows."
|
|
147
|
+
)
|
|
148
|
+
hint = find_deny_hint(command, self._config.deny_messages)
|
|
149
|
+
if hint:
|
|
150
|
+
msg += f"\n[{hint}]"
|
|
142
151
|
return RunShellOutput(
|
|
143
152
|
stdout="",
|
|
144
|
-
stderr=
|
|
145
|
-
f"Command '{command}' is not allowed. "
|
|
146
|
-
f"No matching [shell.*] policy found.\n"
|
|
147
|
-
f"Configured command patterns: {configured}\n"
|
|
148
|
-
f"Tip: Use run_python for complex workflows."
|
|
149
|
-
),
|
|
153
|
+
stderr=msg,
|
|
150
154
|
exit_code=1,
|
|
151
155
|
)
|
|
152
156
|
|
|
153
157
|
# Step 2: Check args against policy
|
|
154
158
|
rejection = self._check_args_policy(policy, args)
|
|
155
159
|
if rejection is not None:
|
|
160
|
+
hint = find_deny_hint(
|
|
161
|
+
f"{command} {' '.join(args)}", self._config.deny_messages
|
|
162
|
+
)
|
|
163
|
+
if hint:
|
|
164
|
+
rejection += f"\n[{hint}]"
|
|
156
165
|
return RunShellOutput(stdout="", stderr=rejection, exit_code=1)
|
|
157
166
|
|
|
158
167
|
# Step 3: Check args for path-like values targeting protected dirs
|
|
159
168
|
path_rejection = self._check_arg_paths(policy, args)
|
|
160
169
|
if path_rejection is not None:
|
|
170
|
+
hint = find_deny_hint(
|
|
171
|
+
f"{command} {' '.join(args)}", self._config.deny_messages
|
|
172
|
+
)
|
|
173
|
+
if hint:
|
|
174
|
+
path_rejection += f"\n[{hint}]"
|
|
161
175
|
return RunShellOutput(stdout="", stderr=path_rejection, exit_code=1)
|
|
162
176
|
|
|
163
177
|
# Step 4: Resolve interpreter prefix
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Unit tests for deny_messages feature — config parsing, hint lookup, and integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from pyddock.config import (
|
|
10
|
+
ASTConfig,
|
|
11
|
+
ConfigError,
|
|
12
|
+
DenyMessageRule,
|
|
13
|
+
ExecutionConfig,
|
|
14
|
+
FilesystemConfig,
|
|
15
|
+
ImportsConfig,
|
|
16
|
+
PyddockConfig,
|
|
17
|
+
ShellPolicyConfig,
|
|
18
|
+
find_deny_hint,
|
|
19
|
+
load_config,
|
|
20
|
+
)
|
|
21
|
+
from pyddock.shell_executor import ShellExecutor
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _make_config(
|
|
25
|
+
shell: dict[str, ShellPolicyConfig] | None = None,
|
|
26
|
+
deny_messages: list[DenyMessageRule] | None = None,
|
|
27
|
+
) -> PyddockConfig:
|
|
28
|
+
"""Create a config with sensible defaults for testing."""
|
|
29
|
+
import re
|
|
30
|
+
return PyddockConfig(
|
|
31
|
+
execution=ExecutionConfig(timeout=30.0),
|
|
32
|
+
imports=ImportsConfig(allowed=["json", "os"]),
|
|
33
|
+
filesystem=FilesystemConfig(writable_paths=["."], readable_paths=["*"]),
|
|
34
|
+
ast=ASTConfig(block_calls=[], block_attributes=[]),
|
|
35
|
+
shell=shell or {},
|
|
36
|
+
deny_messages=deny_messages or [],
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TestFindDenyHint:
|
|
41
|
+
"""Tests for find_deny_hint() matching logic."""
|
|
42
|
+
|
|
43
|
+
def test_first_match_wins(self) -> None:
|
|
44
|
+
"""When multiple patterns match, the first one wins."""
|
|
45
|
+
import re
|
|
46
|
+
rules = [
|
|
47
|
+
DenyMessageRule(pattern=re.compile("git push"), message="specific push hint"),
|
|
48
|
+
DenyMessageRule(pattern=re.compile("^git "), message="generic git hint"),
|
|
49
|
+
]
|
|
50
|
+
assert find_deny_hint("git push origin", rules) == "specific push hint"
|
|
51
|
+
|
|
52
|
+
def test_no_match_returns_none(self) -> None:
|
|
53
|
+
"""When no pattern matches, returns None."""
|
|
54
|
+
import re
|
|
55
|
+
rules = [
|
|
56
|
+
DenyMessageRule(pattern=re.compile("aws"), message="aws hint"),
|
|
57
|
+
]
|
|
58
|
+
assert find_deny_hint("git status", rules) is None
|
|
59
|
+
|
|
60
|
+
def test_search_not_match(self) -> None:
|
|
61
|
+
"""Pattern uses re.search, not re.match — matches anywhere in string."""
|
|
62
|
+
import re
|
|
63
|
+
rules = [
|
|
64
|
+
DenyMessageRule(pattern=re.compile("push"), message="push hint"),
|
|
65
|
+
]
|
|
66
|
+
assert find_deny_hint("git push origin", rules) == "push hint"
|
|
67
|
+
|
|
68
|
+
def test_empty_rules_returns_none(self) -> None:
|
|
69
|
+
"""Empty rules list always returns None."""
|
|
70
|
+
assert find_deny_hint("anything", []) is None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class TestDenyMessagesConfigParsing:
|
|
74
|
+
"""Tests for [deny_messages] config section parsing."""
|
|
75
|
+
|
|
76
|
+
def test_valid_section_parsed(self, tmp_path: Path) -> None:
|
|
77
|
+
"""Valid [deny_messages] section is parsed into DenyMessageRule list."""
|
|
78
|
+
workspace_cfg = tmp_path / ".pyddock" / "pyddock.toml"
|
|
79
|
+
workspace_cfg.parent.mkdir(parents=True)
|
|
80
|
+
workspace_cfg.write_text(
|
|
81
|
+
"[execution]\ntimeout = 30\n\n[imports]\njson = true\n\n"
|
|
82
|
+
"[filesystem]\nwritable_paths = ['.']\nreadable_paths = ['.']\n\n"
|
|
83
|
+
"[ast]\nblock_calls = []\nblock_attributes = []\n\n[restrictions]\n\n"
|
|
84
|
+
'[deny_messages]\n'
|
|
85
|
+
'"aws" = "Use boto3 instead."\n'
|
|
86
|
+
'"git push" = "Push is not allowed."\n'
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
config = load_config(tmp_path)
|
|
90
|
+
assert len(config.deny_messages) == 2
|
|
91
|
+
assert config.deny_messages[0].message == "Use boto3 instead."
|
|
92
|
+
assert config.deny_messages[1].message == "Push is not allowed."
|
|
93
|
+
|
|
94
|
+
def test_invalid_regex_raises(self, tmp_path: Path) -> None:
|
|
95
|
+
"""Invalid regex pattern in deny_messages raises ConfigError."""
|
|
96
|
+
workspace_cfg = tmp_path / ".pyddock" / "pyddock.toml"
|
|
97
|
+
workspace_cfg.parent.mkdir(parents=True)
|
|
98
|
+
workspace_cfg.write_text(
|
|
99
|
+
"[execution]\ntimeout = 30\n\n[imports]\njson = true\n\n"
|
|
100
|
+
"[filesystem]\nwritable_paths = ['.']\nreadable_paths = ['.']\n\n"
|
|
101
|
+
"[ast]\nblock_calls = []\nblock_attributes = []\n\n[restrictions]\n\n"
|
|
102
|
+
'[deny_messages]\n'
|
|
103
|
+
'"(unclosed" = "bad regex"\n'
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
with pytest.raises(ConfigError, match="not a valid regex"):
|
|
107
|
+
load_config(tmp_path)
|
|
108
|
+
|
|
109
|
+
def test_non_string_value_raises(self, tmp_path: Path) -> None:
|
|
110
|
+
"""Non-string value in deny_messages raises ConfigError."""
|
|
111
|
+
workspace_cfg = tmp_path / ".pyddock" / "pyddock.toml"
|
|
112
|
+
workspace_cfg.parent.mkdir(parents=True)
|
|
113
|
+
workspace_cfg.write_text(
|
|
114
|
+
"[execution]\ntimeout = 30\n\n[imports]\njson = true\n\n"
|
|
115
|
+
"[filesystem]\nwritable_paths = ['.']\nreadable_paths = ['.']\n\n"
|
|
116
|
+
"[ast]\nblock_calls = []\nblock_attributes = []\n\n[restrictions]\n\n"
|
|
117
|
+
'[deny_messages]\n'
|
|
118
|
+
'"aws" = 42\n'
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
with pytest.raises(ConfigError, match="must be a string"):
|
|
122
|
+
load_config(tmp_path)
|
|
123
|
+
|
|
124
|
+
def test_empty_section_produces_empty_list(self, tmp_path: Path) -> None:
|
|
125
|
+
"""Empty [deny_messages] section produces empty list."""
|
|
126
|
+
workspace_cfg = tmp_path / ".pyddock" / "pyddock.toml"
|
|
127
|
+
workspace_cfg.parent.mkdir(parents=True)
|
|
128
|
+
workspace_cfg.write_text(
|
|
129
|
+
"[execution]\ntimeout = 30\n\n[imports]\njson = true\n\n"
|
|
130
|
+
"[filesystem]\nwritable_paths = ['.']\nreadable_paths = ['.']\n\n"
|
|
131
|
+
"[ast]\nblock_calls = []\nblock_attributes = []\n\n[restrictions]\n\n"
|
|
132
|
+
"[deny_messages]\n"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
config = load_config(tmp_path)
|
|
136
|
+
assert config.deny_messages == []
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class TestShellExecutorDenyHints:
|
|
140
|
+
"""Tests for deny hints appended to shell rejection messages."""
|
|
141
|
+
|
|
142
|
+
def test_command_rejection_includes_hint(self, tmp_path: Path) -> None:
|
|
143
|
+
"""Rejected command includes the matching deny hint in stderr."""
|
|
144
|
+
import re
|
|
145
|
+
config = _make_config(
|
|
146
|
+
shell={"git": ShellPolicyConfig(command="^git$", mode="deny", allow=["status.*"])},
|
|
147
|
+
deny_messages=[DenyMessageRule(pattern=re.compile(r"aws"), message="Use boto3.")],
|
|
148
|
+
)
|
|
149
|
+
executor = ShellExecutor(config, tmp_path)
|
|
150
|
+
result = executor.execute("aws", ["s3", "ls"], 30)
|
|
151
|
+
assert result.exit_code == 1
|
|
152
|
+
assert "[Use boto3.]" in result.stderr
|
|
153
|
+
|
|
154
|
+
def test_args_rejection_includes_hint(self, tmp_path: Path) -> None:
|
|
155
|
+
"""Rejected args include the matching deny hint in stderr."""
|
|
156
|
+
import re
|
|
157
|
+
config = _make_config(
|
|
158
|
+
shell={"git": ShellPolicyConfig(command="^git$", mode="deny", allow=["status.*"])},
|
|
159
|
+
deny_messages=[DenyMessageRule(pattern=re.compile(r"git push"), message="No pushing.")],
|
|
160
|
+
)
|
|
161
|
+
executor = ShellExecutor(config, tmp_path)
|
|
162
|
+
result = executor.execute("git", ["push", "origin"], 30)
|
|
163
|
+
assert result.exit_code == 1
|
|
164
|
+
assert "[No pushing.]" in result.stderr
|
|
165
|
+
|
|
166
|
+
def test_no_hint_when_no_match(self, tmp_path: Path) -> None:
|
|
167
|
+
"""When no deny_messages pattern matches, no hint is appended."""
|
|
168
|
+
import re
|
|
169
|
+
config = _make_config(
|
|
170
|
+
shell={"git": ShellPolicyConfig(command="^git$", mode="deny", allow=["status.*"])},
|
|
171
|
+
deny_messages=[DenyMessageRule(pattern=re.compile(r"aws"), message="Use boto3.")],
|
|
172
|
+
)
|
|
173
|
+
executor = ShellExecutor(config, tmp_path)
|
|
174
|
+
result = executor.execute("git", ["push", "origin"], 30)
|
|
175
|
+
assert result.exit_code == 1
|
|
176
|
+
assert "[" not in result.stderr
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class TestASTValidatorDenyHints:
|
|
180
|
+
"""Tests for deny hints in AST validator import rejections."""
|
|
181
|
+
|
|
182
|
+
def test_import_rejection_includes_hint(self) -> None:
|
|
183
|
+
"""AST validator appends deny hint to blocked import message."""
|
|
184
|
+
import re
|
|
185
|
+
from pyddock.ast_validator import ASTValidator
|
|
186
|
+
|
|
187
|
+
config = _make_config(
|
|
188
|
+
deny_messages=[DenyMessageRule(pattern=re.compile(r"requests"), message="Use web_fetch.")],
|
|
189
|
+
)
|
|
190
|
+
validator = ASTValidator(config)
|
|
191
|
+
violations = validator.validate("import requests")
|
|
192
|
+
assert len(violations) == 1
|
|
193
|
+
assert "[Use web_fetch.]" in violations[0].message
|
|
194
|
+
|
|
195
|
+
def test_import_rejection_no_hint_when_no_match(self) -> None:
|
|
196
|
+
"""AST validator does not append hint when no pattern matches."""
|
|
197
|
+
import re
|
|
198
|
+
from pyddock.ast_validator import ASTValidator
|
|
199
|
+
|
|
200
|
+
config = _make_config(
|
|
201
|
+
deny_messages=[DenyMessageRule(pattern=re.compile(r"aws"), message="Use boto3.")],
|
|
202
|
+
)
|
|
203
|
+
validator = ASTValidator(config)
|
|
204
|
+
violations = validator.validate("import requests")
|
|
205
|
+
assert len(violations) == 1
|
|
206
|
+
assert "[" not in violations[0].message
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|