pyddock 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {pyddock-0.2.0 → pyddock-0.2.2}/PKG-INFO +1 -1
  2. {pyddock-0.2.0 → pyddock-0.2.2}/publish-to-pypi.ps1 +2 -1
  3. {pyddock-0.2.0 → pyddock-0.2.2}/pyproject.toml +1 -1
  4. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/_runtime.py +137 -22
  5. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/ast_validator.py +4 -1
  6. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/config.py +60 -3
  7. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/default_config.toml +31 -2
  8. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/executor.py +4 -0
  9. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/shell_executor.py +21 -7
  10. pyddock-0.2.2/tests/test_deny_messages.py +206 -0
  11. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_filesystem_guards.py +1 -1
  12. {pyddock-0.2.0 → pyddock-0.2.2}/uv.lock +1 -1
  13. {pyddock-0.2.0 → pyddock-0.2.2}/.gitignore +0 -0
  14. {pyddock-0.2.0 → pyddock-0.2.2}/LICENSE +0 -0
  15. {pyddock-0.2.0 → pyddock-0.2.2}/README.md +0 -0
  16. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/__init__.py +0 -0
  17. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/_process_utils.py +0 -0
  18. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/cli.py +0 -0
  19. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/script_registry.py +0 -0
  20. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/server.py +0 -0
  21. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/__init__.py +0 -0
  22. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/fs_append.py +0 -0
  23. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/fs_delete.py +0 -0
  24. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/read_file.py +0 -0
  25. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/stat_file.py +0 -0
  26. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/tools/str_replace.py +0 -0
  27. {pyddock-0.2.0 → pyddock-0.2.2}/src/pyddock/venv_manager.py +0 -0
  28. {pyddock-0.2.0 → pyddock-0.2.2}/tests/__init__.py +0 -0
  29. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_ast_properties.py +0 -0
  30. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_chmod_integration.py +0 -0
  31. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_config.py +0 -0
  32. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_executor.py +0 -0
  33. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_file_tools.py +0 -0
  34. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_proxy_properties.py +0 -0
  35. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_realistic.py +0 -0
  36. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_runtime.py +0 -0
  37. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_security_guards.py +0 -0
  38. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_server.py +0 -0
  39. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_shell_arg_paths.py +0 -0
  40. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_shell_executor.py +0 -0
  41. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_shell_properties.py +0 -0
  42. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_subprocess_enforcement.py +0 -0
  43. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_subprocess_properties.py +0 -0
  44. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_subst_trusted_path.py +0 -0
  45. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_venv_stamp.py +0 -0
  46. {pyddock-0.2.0 → pyddock-0.2.2}/tests/test_workspace_imports.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyddock
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: MCP server that gives AI agents pre-approved Python, shell, and file I/O tools with declarative policy controls
5
5
  Project-URL: Homepage, https://github.com/portablestew/pyddock
6
6
  Project-URL: Repository, https://github.com/portablestew/pyddock
@@ -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. Press Enter to upload to pypi (Ctrl+C to abort)"
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/*"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyddock"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "MCP server that gives AI agents pre-approved Python, shell, and file I/O tools with declarative policy controls"
5
5
  requires-python = ">=3.11"
6
6
  license = "MIT"
@@ -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__(self, allowed: list[str], trusted_prefixes: list[str]) -> None:
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
- raise ImportError(
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
- raise ImportError(
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__(self, wrapped: Any, allow_patterns: list[re.Pattern[str]]) -> None:
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
- raise PermissionError(
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, original_factory: Any, allow_patterns: list[re.Pattern[str]]
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(obj, self._allow_patterns)
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
- raise ImportError(
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
 
@@ -1089,6 +1152,16 @@ class RuntimeEnforcement:
1089
1152
  f"'{pattern.pattern}', disposition: deny-all). "
1090
1153
  f"This path is blocked for security."
1091
1154
  )
1155
+ elif disposition == "read-only":
1156
+ # "read-only" allows reads but blocks writes.
1157
+ if operation == "read":
1158
+ return True # reads permitted
1159
+ raise PermissionError(
1160
+ f"PermissionError: Cannot {operation} '{path}' — "
1161
+ f"path matches a filesystem guard (pattern: "
1162
+ f"'{pattern.pattern}', disposition: read-only). "
1163
+ f"This path is read-only."
1164
+ )
1092
1165
  elif disposition == "workspace":
1093
1166
  try:
1094
1167
  path.relative_to(_workspace_root_abs)
@@ -1580,7 +1653,8 @@ class RuntimeEnforcement:
1580
1653
  attr = getattr(module, attr_name, None)
1581
1654
  if attr is not None and callable(attr) and not isinstance(attr, type):
1582
1655
  custom_attrs[attr_name] = FactoryProxy(
1583
- attr, compiled_class_patterns
1656
+ attr, compiled_class_patterns,
1657
+ self._deny_messages, module_name,
1584
1658
  )
1585
1659
 
1586
1660
  proxy = _CallerScopedModuleProxy(
@@ -1609,31 +1683,39 @@ class RuntimeEnforcement:
1609
1683
  if any(p.match(method_name) for p in deny_compiled):
1610
1684
  self._patch_class_method(cls, method_name, module_name)
1611
1685
 
1612
- @staticmethod
1613
1686
  def _patch_module_function(
1614
- module: Any, func_name: str, module_name: str
1687
+ self, module: Any, func_name: str, module_name: str
1615
1688
  ) -> None:
1616
1689
  """Replace a module-level function with one that raises PermissionError."""
1690
+ deny_messages = self._deny_messages
1617
1691
 
1618
1692
  def _blocked(*args: Any, **kwargs: Any) -> None:
1619
- raise PermissionError(
1693
+ msg = (
1620
1694
  f"PermissionError: '{func_name}' is not permitted on {module_name}. "
1621
1695
  f"Please rewrite your snippet to avoid this function."
1622
1696
  )
1697
+ hint = _find_deny_hint(f"{module_name}.{func_name}", deny_messages)
1698
+ if hint:
1699
+ msg += f"\n[{hint}]"
1700
+ raise PermissionError(msg)
1623
1701
 
1624
1702
  setattr(module, func_name, _blocked)
1625
1703
 
1626
- @staticmethod
1627
1704
  def _patch_class_method(
1628
- cls: Any, method_name: str, module_name: str
1705
+ self, cls: Any, method_name: str, module_name: str
1629
1706
  ) -> None:
1630
1707
  """Replace a class method with one that raises PermissionError."""
1708
+ deny_messages = self._deny_messages
1631
1709
 
1632
1710
  def _blocked(*args: Any, **kwargs: Any) -> None:
1633
- raise PermissionError(
1711
+ msg = (
1634
1712
  f"PermissionError: '{method_name}' is not permitted on {module_name}. "
1635
1713
  f"Please rewrite your snippet to avoid this function."
1636
1714
  )
1715
+ hint = _find_deny_hint(f"{module_name}.{method_name}", deny_messages)
1716
+ if hint:
1717
+ msg += f"\n[{hint}]"
1718
+ raise PermissionError(msg)
1637
1719
 
1638
1720
  setattr(cls, method_name, _blocked)
1639
1721
 
@@ -1660,6 +1742,7 @@ class RuntimeEnforcement:
1660
1742
  _real_os = self._real_os
1661
1743
  _resolve_cmd = self._resolve_command
1662
1744
  shell_policies = self._config.get("shell", {})
1745
+ _deny_msgs_sp = self._deny_messages
1663
1746
 
1664
1747
  # Build example command for error messages
1665
1748
  if shell_policies:
@@ -1833,18 +1916,34 @@ class RuntimeEnforcement:
1833
1916
  cmd_args = [str(a) for a in cmd[1:]]
1834
1917
  policy = _find_matching_policy(command)
1835
1918
  if policy is None:
1836
- raise PermissionError(
1919
+ msg = (
1837
1920
  f"PermissionError: Command '{command}' is not permitted. "
1838
1921
  f"No matching shell policy found. "
1839
1922
  f"Allowed commands: {allowed_commands_str}"
1840
1923
  )
1924
+ hint = _find_deny_hint(command, _deny_msgs_sp)
1925
+ if hint:
1926
+ msg += f"\n[{hint}]"
1927
+ raise PermissionError(msg)
1841
1928
  rejection = _check_args_policy(policy, cmd_args)
1842
1929
  if rejection is not None:
1843
- raise PermissionError(f"PermissionError: {rejection}")
1930
+ msg = f"PermissionError: {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)
1844
1937
  # Check arg paths against protected directories
1845
1938
  path_rejection = _check_arg_paths(policy, cmd_args)
1846
1939
  if path_rejection is not None:
1847
- raise PermissionError(f"PermissionError: {path_rejection}")
1940
+ msg = f"PermissionError: {path_rejection}"
1941
+ hint = _find_deny_hint(
1942
+ f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
1943
+ )
1944
+ if hint:
1945
+ msg += f"\n[{hint}]"
1946
+ raise PermissionError(msg)
1848
1947
  # Apply interpreter mapping (same as run_shell) and execute
1849
1948
  resolved = _resolve_cmd(command)
1850
1949
  full_cmd = resolved + cmd_args
@@ -1879,17 +1978,33 @@ class RuntimeEnforcement:
1879
1978
  cmd_args = [str(a) for a in cmd[1:]]
1880
1979
  policy = _find_matching_policy(command)
1881
1980
  if policy is None:
1882
- raise PermissionError(
1981
+ msg = (
1883
1982
  f"PermissionError: Command '{command}' is not permitted. "
1884
1983
  f"No matching shell policy found. "
1885
1984
  f"Allowed commands: {allowed_commands_str}"
1886
1985
  )
1986
+ hint = _find_deny_hint(command, _deny_msgs_sp)
1987
+ if hint:
1988
+ msg += f"\n[{hint}]"
1989
+ raise PermissionError(msg)
1887
1990
  rejection = _check_args_policy(policy, cmd_args)
1888
1991
  if rejection is not None:
1889
- raise PermissionError(f"PermissionError: {rejection}")
1992
+ msg = f"PermissionError: {rejection}"
1993
+ hint = _find_deny_hint(
1994
+ f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
1995
+ )
1996
+ if hint:
1997
+ msg += f"\n[{hint}]"
1998
+ raise PermissionError(msg)
1890
1999
  path_rejection = _check_arg_paths(policy, cmd_args)
1891
2000
  if path_rejection is not None:
1892
- raise PermissionError(f"PermissionError: {path_rejection}")
2001
+ msg = f"PermissionError: {path_rejection}"
2002
+ hint = _find_deny_hint(
2003
+ f"{command} {' '.join(cmd_args)}", _deny_msgs_sp
2004
+ )
2005
+ if hint:
2006
+ msg += f"\n[{hint}]"
2007
+ raise PermissionError(msg)
1893
2008
  resolved = _resolve_cmd(command)
1894
2009
  return resolved + cmd_args, cmd_args
1895
2010
 
@@ -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:
@@ -170,16 +197,16 @@ def _parse_filesystem(data: dict) -> FilesystemConfig:
170
197
  if not isinstance(guards_section, dict):
171
198
  raise ConfigError("[filesystem.guards] must be a table")
172
199
  guards: list[GuardRule] = []
173
- _valid_dispositions = ("deny-agent", "deny-all", "workspace", "allow")
200
+ _valid_dispositions = ("deny-agent", "deny-all", "read-only", "workspace", "allow")
174
201
  for pattern, disposition in guards_section.items():
175
202
  if not isinstance(disposition, str):
176
203
  raise ConfigError(
177
204
  f"[filesystem.guards].'{pattern}' must be a string "
178
- f"('deny-agent', 'deny-all', 'workspace', or 'allow'), got {type(disposition).__name__}"
205
+ f"('deny-agent', 'deny-all', 'read-only', 'workspace', or 'allow'), got {type(disposition).__name__}"
179
206
  )
180
207
  if disposition not in _valid_dispositions:
181
208
  raise ConfigError(
182
- f"[filesystem.guards].'{pattern}' must be 'deny-agent', 'deny-all', 'workspace', "
209
+ f"[filesystem.guards].'{pattern}' must be 'deny-agent', 'deny-all', 'read-only', 'workspace', "
183
210
  f"or 'allow', got '{disposition}'"
184
211
  )
185
212
  guards.append(GuardRule(pattern=pattern, disposition=disposition))
@@ -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
- #git = "GitPython" # Enable for Git (shell policy enforces command restrictions via Popen)
65
+ git = "GitPython" # Shell policy enforces command restrictions via Popen
66
66
  polars = true
67
- #P4 = "p4python" # Enable for Perforce (restricted to non-submit operations)
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).
@@ -83,6 +83,7 @@ readable_paths = ["*"]
83
83
  # Dispositions:
84
84
  # "deny-agent" — block agent code; trusted libraries (site-packages) can still access
85
85
  # "deny-all" — block unconditionally, no caller bypass
86
+ # "read-only" — allow reads, block writes unconditionally
86
87
  # "workspace" — allow only if the path is inside the workspace
87
88
  # "allow" — permit unconditionally (override for specific paths)
88
89
  [filesystem.guards]
@@ -96,6 +97,9 @@ readable_paths = ["*"]
96
97
  '/\.pypirc$' = "deny-all" # PyPI registry tokens — no library reader in sandbox
97
98
  '/\.git-credentials$' = "deny-all" # Git plaintext passwords — no library reader in sandbox
98
99
  '/\.env(\.[^/]*)?$' = "workspace" # .env files — workspace only
100
+ '/\.kiro/agent' = "read-only" # Kiro agent config — prevent self-modification
101
+ '/\.kiro/settings' = "read-only" # Kiro settings — prevent self-modification
102
+ '/\.claude/settings' = "read-only" # Claude settings — prevent self-modification
99
103
 
100
104
  # AST-level static analysis — blocks dangerous constructs before execution.
101
105
  # These prevent trivial jailbreaks (e.g. eval("__import__('os').system(...)")).
@@ -217,3 +221,28 @@ allow = [
217
221
  #mode = "allow"
218
222
  #deny = []
219
223
  #arg_paths = "workspace"
224
+
225
+ # Custom denial hints — appended to rejection messages when the pattern matches
226
+ # the attempted action. These do NOT define new deny rules; they only provide
227
+ # better guidance after a rejection has already occurred.
228
+ #
229
+ # Match targets by rejection type:
230
+ # Shell command rejection → command string (e.g. "aws", "aws.exe", "curl")
231
+ # Shell args rejection → "command args..." (e.g. "git push origin main")
232
+ # Import rejection → full module name (e.g. "requests", "paramiko.client")
233
+ # Restriction rejection → "module.attribute" (e.g. "boto3.resource", "polars.write_csv")
234
+ #
235
+ # Regex uses re.search() against the attempted value. First match wins.
236
+ [deny_messages]
237
+ "^aws(\\.exe)?$" = "AWS CLI is not allowed. Use `import boto3` in run_python instead (client factory with read-only restrictions)."
238
+ "^git push" = "git push is not allowed. Stage changes locally and leave pushing for human review."
239
+ "^git remote" = "git remote is not allowed. Remote configuration cannot be modified from the sandbox."
240
+ "^git " = "This git operation is not in the allowed list. Operations should be limited to side effects within the local workspace."
241
+ "^p4 submit" = "p4 submit is not allowed. Use `p4 shelve` to stage changes for human review."
242
+ "^p4 " = "This p4 operation is not in the allowed list. Operations should be limited to side effects within the local workspace."
243
+ "^requests(\\.|$)" = "Open network access is not permitted in pyddock. Use a different tool if available (e.g. web_fetch)."
244
+ "^paramiko(\\.|$)" = "SSH access is not permitted in pyddock. Use a different tool for remote operations."
245
+ "^boto3\\.(resource|Resource)" = "Only boto3.client() is allowed (not resource/Session). Use boto3.client('<service>') to create service clients."
246
+ "^polars\\.(write_|sink_)" = "Polars write/sink operations are blocked. Write output files using Python builtins (open/pathlib) in run_python instead."
247
+ "^(bash|sh)(\\.exe)?$" = "Shell interpreters are not allowed. Write your logic directly in run_python, or use run_shell with an approved command."
248
+ "^(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
@@ -59,7 +59,7 @@ class TestGuardConfigParsing:
59
59
  "[filesystem.guards]\n"
60
60
  "'/\\.ssh/' = 'block'\n"
61
61
  ))
62
- with pytest.raises(ConfigError, match="'deny-agent', 'deny-all', 'workspace', or 'allow'"):
62
+ with pytest.raises(ConfigError, match="'deny-agent', 'deny-all', 'read-only', 'workspace', or 'allow'"):
63
63
  load_config(tmp_path)
64
64
 
65
65
 
@@ -480,7 +480,7 @@ wheels = [
480
480
 
481
481
  [[package]]
482
482
  name = "pyddock"
483
- version = "0.2.0"
483
+ version = "0.2.1"
484
484
  source = { editable = "." }
485
485
  dependencies = [
486
486
  { name = "mcp" },
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