patchproof-core 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. patchproof/__init__.py +44 -0
  2. patchproof/__main__.py +8 -0
  3. patchproof/benchmarks/__init__.py +17 -0
  4. patchproof/benchmarks/swe_bench.py +159 -0
  5. patchproof/cli.py +1254 -0
  6. patchproof/core/__init__.py +33 -0
  7. patchproof/core/agent_init.py +103 -0
  8. patchproof/core/anti_cheat.py +396 -0
  9. patchproof/core/applier.py +159 -0
  10. patchproof/core/ast_analyzer.py +254 -0
  11. patchproof/core/detector.py +78 -0
  12. patchproof/core/git_provider.py +298 -0
  13. patchproof/core/healer.py +104 -0
  14. patchproof/core/mutator.py +223 -0
  15. patchproof/core/normalizer.py +338 -0
  16. patchproof/core/polyglot_guard.py +167 -0
  17. patchproof/core/runtime_guard.py +188 -0
  18. patchproof/core/search_replace.py +222 -0
  19. patchproof/core/slicer.py +172 -0
  20. patchproof/core/sparse_tree.py +95 -0
  21. patchproof/docker/runner.Dockerfile +42 -0
  22. patchproof/exceptions.py +37 -0
  23. patchproof/factory/__init__.py +22 -0
  24. patchproof/factory/blast_radius.py +120 -0
  25. patchproof/factory/engine.py +134 -0
  26. patchproof/factory/models.py +75 -0
  27. patchproof/mcp.py +532 -0
  28. patchproof/models/__init__.py +57 -0
  29. patchproof/models/ast.py +78 -0
  30. patchproof/models/patch.py +106 -0
  31. patchproof/models/sandbox.py +417 -0
  32. patchproof/reporting/__init__.py +19 -0
  33. patchproof/reporting/asymmetric.py +88 -0
  34. patchproof/reporting/badge.py +86 -0
  35. patchproof/reporting/certificate.py +230 -0
  36. patchproof/reporting/diagnostic.py +330 -0
  37. patchproof/reporting/html_report.py +367 -0
  38. patchproof/reporting/in_toto.py +188 -0
  39. patchproof/reporting/markdown.py +179 -0
  40. patchproof/reporting/sbom.py +152 -0
  41. patchproof/sandbox/__init__.py +37 -0
  42. patchproof/sandbox/classifier.py +289 -0
  43. patchproof/sandbox/comparative.py +478 -0
  44. patchproof/sandbox/docker_cli.py +384 -0
  45. patchproof/sandbox/doctor.py +605 -0
  46. patchproof/sandbox/flakiness.py +87 -0
  47. patchproof/sandbox/network_bridge.py +145 -0
  48. patchproof/sandbox/parser.py +172 -0
  49. patchproof/sandbox/runner.py +424 -0
  50. patchproof/sandbox/setup_runner.py +261 -0
  51. patchproof_core-0.3.1.dist-info/METADATA +212 -0
  52. patchproof_core-0.3.1.dist-info/RECORD +56 -0
  53. patchproof_core-0.3.1.dist-info/WHEEL +5 -0
  54. patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
  55. patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
  56. patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,384 @@
1
+ """Docker CLI command builder, environment sanitizer, and preflight verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pathlib
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+ from patchproof.exceptions import (
13
+ DockerUnavailableError,
14
+ SandboxSecurityError,
15
+ UnsupportedDockerEngineError,
16
+ )
17
+ from patchproof.models.sandbox import (
18
+ ALLOWLISTED_EXACT_VARS,
19
+ ALLOWLISTED_PREFIXES,
20
+ BROAD_ROOT_PATHS,
21
+ DISALLOWED_ENV_PATTERNS,
22
+ FORBIDDEN_HOST_PATHS,
23
+ ContainerConfig,
24
+ ContainerEnvironment,
25
+ NetworkMode,
26
+ )
27
+
28
+ DEFAULT_SAFE_ENV: dict[str, str] = {
29
+ "PATH": "/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin",
30
+ "LANG": "C.UTF-8",
31
+ "LC_ALL": "C.UTF-8",
32
+ "PYTHONUNBUFFERED": "1",
33
+ "PYTHONDONTWRITEBYTECODE": "1",
34
+ "PYTHONPATH": "/workspace",
35
+ }
36
+
37
+
38
+ class DockerPreflightResult(BaseModel):
39
+ """Result of Docker preflight health and engine mode verification."""
40
+
41
+ model_config = ConfigDict(frozen=True)
42
+
43
+ is_available: bool = Field(description="True if Docker daemon is active and responsive")
44
+ os_type: str = Field(description="Docker daemon operating system type (must be 'linux')")
45
+ binary_path: str = Field(description="Resolved path to docker CLI executable")
46
+
47
+
48
+ class EnvironmentSanitizer:
49
+ """Sanitizes environment variables to prevent host credential leakage."""
50
+
51
+ def __init__(self) -> None:
52
+ pass
53
+
54
+ def validate_env_pair(self, key: str, val: str) -> None:
55
+ """Validate an individual environment variable key-value pair.
56
+
57
+ Raises:
58
+ SandboxSecurityError: If key matches any sensitive pattern or is not allowlisted.
59
+ """
60
+ key_upper = key.upper()
61
+ for pattern in DISALLOWED_ENV_PATTERNS:
62
+ if pattern in key_upper:
63
+ raise SandboxSecurityError(
64
+ f"Environment variable '{key}' violates credential isolation policy"
65
+ )
66
+
67
+ if key not in ALLOWLISTED_EXACT_VARS and not any(
68
+ key.startswith(p) for p in ALLOWLISTED_PREFIXES
69
+ ):
70
+ raise SandboxSecurityError(
71
+ f"Environment variable '{key}' violates credential isolation policy "
72
+ "(not in allowlist)"
73
+ )
74
+
75
+ def sanitize(self, custom_env: ContainerEnvironment | None = None) -> dict[str, str]:
76
+ """Construct an isolated environment dictionary from default safe variables.
77
+
78
+ Never inherits host os.environ.
79
+ """
80
+ env = dict(DEFAULT_SAFE_ENV)
81
+ if custom_env is not None:
82
+ for k, v in custom_env.env_vars:
83
+ self.validate_env_pair(k, v)
84
+ env[k] = v
85
+ return env
86
+
87
+
88
+ class DockerCommandBuilder:
89
+ """Deterministically builds and verifies hardened docker run argument vectors."""
90
+
91
+ def __init__(self, config: ContainerConfig) -> None:
92
+ self.config = config
93
+ self.sanitizer = EnvironmentSanitizer()
94
+
95
+ def canonicalize_host_path(self, path_str: str) -> str:
96
+ """Resolve and canonicalize host repository path, enforcing security boundaries."""
97
+ p = pathlib.Path(path_str).resolve()
98
+ if not p.exists() or not p.is_dir():
99
+ raise SandboxSecurityError(
100
+ f"Host repository path does not exist or is not a directory: {path_str}"
101
+ )
102
+
103
+ normalized = str(p).replace("\\", "/").lower().rstrip("/")
104
+ if normalized in BROAD_ROOT_PATHS:
105
+ raise SandboxSecurityError(f"Broad root host path prohibited from mount: {path_str}")
106
+
107
+ for forbidden in FORBIDDEN_HOST_PATHS:
108
+ if forbidden in normalized:
109
+ raise SandboxSecurityError(f"Sensitive host path prohibited from mount: {path_str}")
110
+
111
+ return str(p)
112
+
113
+ def build(
114
+ self,
115
+ container_name: str | None = None,
116
+ execution_id: str | None = None,
117
+ auto_remove: bool = True,
118
+ extra_labels: dict[str, str] | None = None,
119
+ ) -> list[str]:
120
+ """Construct the complete docker run argument list."""
121
+ canonical_host_path = self.canonicalize_host_path(self.config.host_repo_path)
122
+ sanitized_env = self.sanitizer.sanitize(self.config.environment)
123
+
124
+ workspace = self.config.container_workspace_path
125
+
126
+ # Check if canonical_host_path is an ephemeral staging directory
127
+ is_staging = False
128
+ try:
129
+ resolved_host = pathlib.Path(canonical_host_path).resolve()
130
+ temp_root = pathlib.Path(tempfile.gettempdir()).resolve()
131
+ is_staging = resolved_host.is_relative_to(temp_root) and resolved_host.name.startswith(
132
+ "patchproof-staging-"
133
+ )
134
+ except (ValueError, OSError):
135
+ is_staging = False
136
+
137
+ bind_readonly = ",readonly=true" if not is_staging else ""
138
+
139
+ cmd: list[str] = [
140
+ "docker",
141
+ "run",
142
+ ]
143
+ if auto_remove:
144
+ cmd.append("--rm")
145
+
146
+ if container_name:
147
+ cmd.extend(["--name", container_name])
148
+
149
+ if self.config.security.network_mode == NetworkMode.INTERNAL_BRIDGE:
150
+ net_name = self.config.security.network_name or self.config.network.network_name
151
+ if not net_name or not net_name.startswith("patchproof-net-"):
152
+ raise SandboxSecurityError(
153
+ "NetworkMode.INTERNAL_BRIDGE requires a verified "
154
+ "'patchproof-net-*' network name"
155
+ )
156
+ network_arg = net_name
157
+ else:
158
+ network_arg = NetworkMode.NONE.value
159
+
160
+ git_host_path = pathlib.Path(canonical_host_path) / ".git"
161
+ if self.config.security.mask_git_dir:
162
+ if not is_staging:
163
+ if git_host_path.is_file():
164
+ raise SandboxSecurityError(
165
+ f"Git worktree pointer file ({git_host_path}) detected. "
166
+ "Direct container mount of git worktree files is prohibited for security; "
167
+ "use an isolated clone or ephemeral staging."
168
+ )
169
+ if not git_host_path.is_dir():
170
+ raise SandboxSecurityError(
171
+ f"Direct read-only container mount requires a valid repository with a "
172
+ f"'.git' directory for git credential masking ({canonical_host_path}). "
173
+ "Use ephemeral staging or set mask_git_dir=False."
174
+ )
175
+
176
+ cmd.extend(
177
+ [
178
+ "--network",
179
+ network_arg,
180
+ "--user",
181
+ self.config.security.user,
182
+ "--cap-drop",
183
+ "ALL",
184
+ "--security-opt",
185
+ "no-new-privileges",
186
+ "--read-only",
187
+ "--cpus",
188
+ str(self.config.resources.cpu_count),
189
+ "--memory",
190
+ f"{self.config.resources.memory_limit_mb}m",
191
+ "--memory-swap",
192
+ f"{self.config.resources.memory_limit_mb}m",
193
+ "--pids-limit",
194
+ str(self.config.resources.pids_limit),
195
+ "--mount",
196
+ f"type=bind,source={canonical_host_path},target={workspace}{bind_readonly}",
197
+ ]
198
+ )
199
+
200
+ if self.config.security.mask_git_dir:
201
+ cmd.extend(
202
+ [
203
+ "--mount",
204
+ f"type=tmpfs,destination={workspace}/.git,tmpfs-size=1k,tmpfs-mode=000",
205
+ ]
206
+ )
207
+
208
+ cmd.extend(
209
+ [
210
+ "--mount",
211
+ "type=tmpfs,destination=/tmp,tmpfs-size=64m,tmpfs-mode=1777",
212
+ ]
213
+ )
214
+
215
+ for k, v in sorted(sanitized_env.items()):
216
+ cmd.extend(["-e", f"{k}={v}"])
217
+
218
+ cmd.extend(["-w", workspace, "--label", "patchproof.managed=true"])
219
+
220
+ if execution_id:
221
+ cmd.extend(["--label", f"patchproof.execution_id={execution_id}"])
222
+
223
+ if extra_labels:
224
+ for lk, lv in sorted(extra_labels.items()):
225
+ cmd.extend(["--label", f"{lk}={lv}"])
226
+
227
+ cmd.extend(
228
+ [
229
+ self.config.image,
230
+ *self.config.entrypoint_command,
231
+ ]
232
+ )
233
+
234
+ self.verify_command_security(cmd)
235
+ return cmd
236
+
237
+ def verify_command_security(self, cmd: list[str]) -> bool:
238
+ """Verify that all required security flags are present in the argument vector."""
239
+ if not (len(cmd) >= 3 and cmd[0] == "docker" and cmd[1] == "run"):
240
+ raise SandboxSecurityError("Command must start with 'docker run'")
241
+
242
+ required_flags = [
243
+ "--network",
244
+ "--user",
245
+ "--cap-drop",
246
+ "--security-opt",
247
+ "--read-only",
248
+ "--cpus",
249
+ "--memory",
250
+ "--memory-swap",
251
+ "--pids-limit",
252
+ ]
253
+ for flag in required_flags:
254
+ if flag not in cmd:
255
+ raise SandboxSecurityError(f"Missing required security flag: {flag}")
256
+
257
+ net_idx = cmd.index("--network")
258
+ if net_idx + 1 >= len(cmd):
259
+ raise SandboxSecurityError("Missing argument for --network")
260
+ net_arg = cmd[net_idx + 1]
261
+ if net_arg != NetworkMode.NONE.value and not net_arg.startswith("patchproof-net-"):
262
+ raise SandboxSecurityError(
263
+ f"Invalid network mode '{net_arg}' in command: violates sandbox isolation policy. "
264
+ "Only 'none' or 'patchproof-net-*' internal networks are permitted."
265
+ )
266
+
267
+ user_idx = cmd.index("--user")
268
+ if user_idx + 1 >= len(cmd):
269
+ raise SandboxSecurityError("Missing user value in command")
270
+ user_val = cmd[user_idx + 1].split(":", 1)[0].strip()
271
+ if user_val == "root" or (user_val.isdigit() and int(user_val) == 0):
272
+ raise SandboxSecurityError("Root user specified in command")
273
+
274
+ cap_idx = cmd.index("--cap-drop")
275
+ if cap_idx + 1 >= len(cmd) or cmd[cap_idx + 1] != "ALL":
276
+ raise SandboxSecurityError("Invalid cap-drop in command: must be 'ALL'")
277
+
278
+ sec_idx = cmd.index("--security-opt")
279
+ if sec_idx + 1 >= len(cmd) or cmd[sec_idx + 1] != "no-new-privileges":
280
+ raise SandboxSecurityError("Missing 'no-new-privileges' security option")
281
+
282
+ if self.config.security.mask_git_dir:
283
+ if not any("/.git" in arg and "type=tmpfs" in arg for arg in cmd):
284
+ raise SandboxSecurityError("Missing git credential mask tmpfs mount")
285
+
286
+ if not any("patchproof.managed=true" in arg for arg in cmd):
287
+ raise SandboxSecurityError("Missing required label 'patchproof.managed=true'")
288
+
289
+ return True
290
+
291
+
292
+ class DockerPreflight:
293
+ """Pre-flight verification for Docker daemon availability and engine mode."""
294
+
295
+ def __init__(self, timeout_seconds: float = 2.0) -> None:
296
+ self.timeout_seconds = timeout_seconds
297
+
298
+ def check(self) -> DockerPreflightResult:
299
+ """Verify Docker is available, responsive, and operating in Linux Containers mode.
300
+
301
+ Raises:
302
+ DockerUnavailableError: If Docker binary is missing, unresponsive, or timed out.
303
+ UnsupportedDockerEngineError: If Docker is in Windows Containers mode.
304
+ """
305
+ which_path = shutil.which("docker")
306
+ if not which_path:
307
+ raise DockerUnavailableError("Docker binary not found in system PATH")
308
+
309
+ try:
310
+ res = subprocess.run(
311
+ ["docker", "info", "--format", "{{.OSType}}"],
312
+ capture_output=True,
313
+ text=True,
314
+ timeout=self.timeout_seconds,
315
+ shell=False,
316
+ close_fds=True,
317
+ )
318
+ except FileNotFoundError as err:
319
+ raise DockerUnavailableError(f"Docker binary execution failed: {err}") from err
320
+ except subprocess.TimeoutExpired as err:
321
+ raise DockerUnavailableError(
322
+ f"Docker daemon probe timed out after {self.timeout_seconds}s"
323
+ ) from err
324
+
325
+ if res.returncode != 0:
326
+ err_msg = res.stderr.strip() or f"exit code {res.returncode}"
327
+ raise DockerUnavailableError(f"Docker daemon is not responsive: {err_msg}")
328
+
329
+ os_type = res.stdout.strip().lower()
330
+ if os_type != "linux":
331
+ raise UnsupportedDockerEngineError(
332
+ f"Docker Desktop must be running in Linux Containers mode (WSL2 backend), "
333
+ f"got '{os_type}'"
334
+ )
335
+
336
+ return DockerPreflightResult(
337
+ is_available=True,
338
+ os_type=os_type,
339
+ binary_path=which_path,
340
+ )
341
+
342
+
343
+ PROHIBITED_COMMAND_METASYMBOLS = (
344
+ ";",
345
+ "&",
346
+ "|",
347
+ "`",
348
+ "$",
349
+ ">",
350
+ "<",
351
+ "\n",
352
+ "\r",
353
+ )
354
+
355
+
356
+ def parse_test_command(cmd_str: str) -> tuple[str, ...]:
357
+ """Parse and validate a custom test command string into an argv tuple.
358
+
359
+ Enforces security boundary checks against shell injection.
360
+
361
+ Raises:
362
+ SandboxSecurityError: If command is empty, contains shell metacharacters, or is malformed.
363
+ """
364
+ import shlex
365
+
366
+ trimmed = cmd_str.strip()
367
+ if not trimmed:
368
+ raise SandboxSecurityError("Custom test command cannot be empty")
369
+
370
+ for symbol in PROHIBITED_COMMAND_METASYMBOLS:
371
+ if symbol in trimmed:
372
+ raise SandboxSecurityError(
373
+ f"Custom test command contains prohibited character '{symbol}'"
374
+ )
375
+
376
+ try:
377
+ parts = shlex.split(trimmed)
378
+ except ValueError as err:
379
+ raise SandboxSecurityError(f"Invalid shell quoting in test command: {err}") from err
380
+
381
+ if not parts:
382
+ raise SandboxSecurityError("Custom test command cannot be empty")
383
+
384
+ return tuple(parts)