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.
- patchproof/__init__.py +44 -0
- patchproof/__main__.py +8 -0
- patchproof/benchmarks/__init__.py +17 -0
- patchproof/benchmarks/swe_bench.py +159 -0
- patchproof/cli.py +1254 -0
- patchproof/core/__init__.py +33 -0
- patchproof/core/agent_init.py +103 -0
- patchproof/core/anti_cheat.py +396 -0
- patchproof/core/applier.py +159 -0
- patchproof/core/ast_analyzer.py +254 -0
- patchproof/core/detector.py +78 -0
- patchproof/core/git_provider.py +298 -0
- patchproof/core/healer.py +104 -0
- patchproof/core/mutator.py +223 -0
- patchproof/core/normalizer.py +338 -0
- patchproof/core/polyglot_guard.py +167 -0
- patchproof/core/runtime_guard.py +188 -0
- patchproof/core/search_replace.py +222 -0
- patchproof/core/slicer.py +172 -0
- patchproof/core/sparse_tree.py +95 -0
- patchproof/docker/runner.Dockerfile +42 -0
- patchproof/exceptions.py +37 -0
- patchproof/factory/__init__.py +22 -0
- patchproof/factory/blast_radius.py +120 -0
- patchproof/factory/engine.py +134 -0
- patchproof/factory/models.py +75 -0
- patchproof/mcp.py +532 -0
- patchproof/models/__init__.py +57 -0
- patchproof/models/ast.py +78 -0
- patchproof/models/patch.py +106 -0
- patchproof/models/sandbox.py +417 -0
- patchproof/reporting/__init__.py +19 -0
- patchproof/reporting/asymmetric.py +88 -0
- patchproof/reporting/badge.py +86 -0
- patchproof/reporting/certificate.py +230 -0
- patchproof/reporting/diagnostic.py +330 -0
- patchproof/reporting/html_report.py +367 -0
- patchproof/reporting/in_toto.py +188 -0
- patchproof/reporting/markdown.py +179 -0
- patchproof/reporting/sbom.py +152 -0
- patchproof/sandbox/__init__.py +37 -0
- patchproof/sandbox/classifier.py +289 -0
- patchproof/sandbox/comparative.py +478 -0
- patchproof/sandbox/docker_cli.py +384 -0
- patchproof/sandbox/doctor.py +605 -0
- patchproof/sandbox/flakiness.py +87 -0
- patchproof/sandbox/network_bridge.py +145 -0
- patchproof/sandbox/parser.py +172 -0
- patchproof/sandbox/runner.py +424 -0
- patchproof/sandbox/setup_runner.py +261 -0
- patchproof_core-0.3.1.dist-info/METADATA +212 -0
- patchproof_core-0.3.1.dist-info/RECORD +56 -0
- patchproof_core-0.3.1.dist-info/WHEEL +5 -0
- patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
- patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
- patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Patch normalizer and analyzer core module."""
|
|
2
|
+
|
|
3
|
+
from patchproof.core.applier import apply_patch
|
|
4
|
+
from patchproof.core.ast_analyzer import (
|
|
5
|
+
analyze_patch_ast,
|
|
6
|
+
analyze_python_source,
|
|
7
|
+
extract_delta_line_ranges,
|
|
8
|
+
)
|
|
9
|
+
from patchproof.core.detector import ProjectKind, ProjectProfile, detect_project_stack
|
|
10
|
+
from patchproof.core.git_provider import (
|
|
11
|
+
get_head_diff,
|
|
12
|
+
get_uncommitted_diff,
|
|
13
|
+
install_pre_commit_hook,
|
|
14
|
+
is_git_repository,
|
|
15
|
+
)
|
|
16
|
+
from patchproof.core.normalizer import parse_patch
|
|
17
|
+
from patchproof.core.search_replace import parse_search_replace
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ProjectKind",
|
|
21
|
+
"ProjectProfile",
|
|
22
|
+
"analyze_patch_ast",
|
|
23
|
+
"analyze_python_source",
|
|
24
|
+
"apply_patch",
|
|
25
|
+
"detect_project_stack",
|
|
26
|
+
"extract_delta_line_ranges",
|
|
27
|
+
"get_head_diff",
|
|
28
|
+
"get_uncommitted_diff",
|
|
29
|
+
"install_pre_commit_hook",
|
|
30
|
+
"is_git_repository",
|
|
31
|
+
"parse_patch",
|
|
32
|
+
"parse_search_replace",
|
|
33
|
+
]
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Configuration initializers for AI coding agents (Aider, Cursor, Claude Code).
|
|
2
|
+
|
|
3
|
+
Enables one-command setup for agents to automatically use PatchProof.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import pathlib
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
AIDER_CONFIG_CONTENT = """# Aider configuration with PatchProof deterministic verification
|
|
15
|
+
test-cmd: "patchproof verify --git"
|
|
16
|
+
auto-test: true
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
CURSORRULES_CONTENT = """# PatchProof Invariant Rules for AI Assistance
|
|
20
|
+
Whenever modifying code or fixing bugs:
|
|
21
|
+
1. Always run `patchproof verify --git` or call the MCP tool `patchproof_verify_git`.
|
|
22
|
+
2. If verification returns REJECTED, inspect the `ai_feedback` diagnostics.
|
|
23
|
+
3. Fix the regression without modifying existing tests or weakening assertions.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
CLAUDE_MD_CONTENT = """# AI Assistant Engineering Rules
|
|
27
|
+
- **Patch Verification**: Before finalizing any code changes or bug fixes, always verify:
|
|
28
|
+
`patchproof verify --git`
|
|
29
|
+
- If verification fails with regressions, review diagnostic output and fix the root cause.
|
|
30
|
+
- Never weaken, comment out, or delete existing tests to force a pass.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _safe_write_file(path: pathlib.Path, content: str, force: bool = False) -> bool:
|
|
35
|
+
"""Safely write content to file, creating parent directories. Returns True if written."""
|
|
36
|
+
if path.is_file() and not force:
|
|
37
|
+
logger.info("File already exists, skipping: %s", path)
|
|
38
|
+
return False
|
|
39
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
path.write_text(content, encoding="utf-8")
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def init_aider_config(repo_path: pathlib.Path, force: bool = False) -> list[pathlib.Path]:
|
|
45
|
+
"""Generate .aider.conf.yml configured with PatchProof test runner."""
|
|
46
|
+
created: list[pathlib.Path] = []
|
|
47
|
+
config_file = repo_path / ".aider.conf.yml"
|
|
48
|
+
if _safe_write_file(config_file, AIDER_CONFIG_CONTENT, force=force):
|
|
49
|
+
created.append(config_file)
|
|
50
|
+
return created
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def init_cursor_config(repo_path: pathlib.Path, force: bool = False) -> list[pathlib.Path]:
|
|
54
|
+
"""Generate .cursor/mcp.json and .cursorrules for Cursor IDE."""
|
|
55
|
+
created: list[pathlib.Path] = []
|
|
56
|
+
mcp_file = repo_path / ".cursor" / "mcp.json"
|
|
57
|
+
mcp_data = {
|
|
58
|
+
"mcpServers": {
|
|
59
|
+
"patchproof": {
|
|
60
|
+
"command": "python",
|
|
61
|
+
"args": ["-m", "patchproof", "mcp"],
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if _safe_write_file(mcp_file, json.dumps(mcp_data, indent=2) + "\n", force=force):
|
|
66
|
+
created.append(mcp_file)
|
|
67
|
+
|
|
68
|
+
rules_file = repo_path / ".cursorrules"
|
|
69
|
+
if _safe_write_file(rules_file, CURSORRULES_CONTENT, force=force):
|
|
70
|
+
created.append(rules_file)
|
|
71
|
+
|
|
72
|
+
return created
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def init_claude_config(repo_path: pathlib.Path, force: bool = False) -> list[pathlib.Path]:
|
|
76
|
+
"""Generate .mcp.json and CLAUDE.md for Claude Code."""
|
|
77
|
+
created: list[pathlib.Path] = []
|
|
78
|
+
mcp_file = repo_path / ".mcp.json"
|
|
79
|
+
mcp_data = {
|
|
80
|
+
"mcpServers": {
|
|
81
|
+
"patchproof": {
|
|
82
|
+
"command": "python",
|
|
83
|
+
"args": ["-m", "patchproof", "mcp"],
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if _safe_write_file(mcp_file, json.dumps(mcp_data, indent=2) + "\n", force=force):
|
|
88
|
+
created.append(mcp_file)
|
|
89
|
+
|
|
90
|
+
claude_file = repo_path / "CLAUDE.md"
|
|
91
|
+
if _safe_write_file(claude_file, CLAUDE_MD_CONTENT, force=force):
|
|
92
|
+
created.append(claude_file)
|
|
93
|
+
|
|
94
|
+
return created
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def init_all_agents(repo_path: pathlib.Path, force: bool = False) -> list[pathlib.Path]:
|
|
98
|
+
"""Generate configuration for all supported AI agents (Aider, Cursor, Claude Code)."""
|
|
99
|
+
results: list[pathlib.Path] = []
|
|
100
|
+
results.extend(init_aider_config(repo_path, force=force))
|
|
101
|
+
results.extend(init_cursor_config(repo_path, force=force))
|
|
102
|
+
results.extend(init_claude_config(repo_path, force=force))
|
|
103
|
+
return results
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""Anti-Cheat test tampering guard and integrity verification engine.
|
|
2
|
+
|
|
3
|
+
Detects unauthorized modifications, assertion count reductions, test function deletions,
|
|
4
|
+
and skip/suppression injections executed by autonomous coding agents.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import pathlib
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
14
|
+
|
|
15
|
+
from patchproof.core.applier import apply_patch
|
|
16
|
+
from patchproof.models.patch import CanonicalPatch, ChangeType, FileDelta
|
|
17
|
+
|
|
18
|
+
TEST_DIR_PARTS = {"test", "tests", "__tests__"}
|
|
19
|
+
TEST_EXTENSIONS = {".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def is_test_file(path: str | pathlib.Path) -> bool:
|
|
23
|
+
"""Determine whether a canonical relative repository path represents a test file."""
|
|
24
|
+
p = pathlib.PurePosixPath(str(path).replace("\\", "/"))
|
|
25
|
+
parts_lower = {part.lower() for part in p.parts[:-1]}
|
|
26
|
+
filename_lower = p.name.lower()
|
|
27
|
+
|
|
28
|
+
if any(part in TEST_DIR_PARTS for part in parts_lower):
|
|
29
|
+
if p.suffix in TEST_EXTENSIONS:
|
|
30
|
+
return True
|
|
31
|
+
|
|
32
|
+
if filename_lower == "conftest.py":
|
|
33
|
+
return True
|
|
34
|
+
|
|
35
|
+
if filename_lower.startswith("test_") and p.suffix == ".py":
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
if filename_lower.endswith("_test.py"):
|
|
39
|
+
return True
|
|
40
|
+
|
|
41
|
+
if any(
|
|
42
|
+
filename_lower.endswith(ext)
|
|
43
|
+
for ext in (
|
|
44
|
+
".test.ts",
|
|
45
|
+
".spec.ts",
|
|
46
|
+
".test.tsx",
|
|
47
|
+
".spec.tsx",
|
|
48
|
+
".test.js",
|
|
49
|
+
".spec.js",
|
|
50
|
+
".test.jsx",
|
|
51
|
+
".spec.jsx",
|
|
52
|
+
)
|
|
53
|
+
):
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
CONFIG_FILES = {
|
|
60
|
+
"pyproject.toml",
|
|
61
|
+
"pytest.ini",
|
|
62
|
+
"setup.cfg",
|
|
63
|
+
"tox.ini",
|
|
64
|
+
"jest.config.js",
|
|
65
|
+
"jest.config.ts",
|
|
66
|
+
"jest.config.json",
|
|
67
|
+
"vitest.config.ts",
|
|
68
|
+
"vitest.config.js",
|
|
69
|
+
}
|
|
70
|
+
SUSPICIOUS_CONFIG_PATTERNS = (
|
|
71
|
+
"--ignore",
|
|
72
|
+
"--deselect",
|
|
73
|
+
"-k \"not",
|
|
74
|
+
"-k 'not",
|
|
75
|
+
"-k not",
|
|
76
|
+
"-m \"not",
|
|
77
|
+
"-m 'not",
|
|
78
|
+
"-m not",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_config_file(path: str | pathlib.Path) -> bool:
|
|
83
|
+
"""Determine whether path represents a test runner configuration file."""
|
|
84
|
+
p = pathlib.PurePosixPath(str(path).replace("\\", "/"))
|
|
85
|
+
return p.name.lower() in CONFIG_FILES
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TamperingViolationType(StrEnum):
|
|
89
|
+
"""Categorization of test tampering violations."""
|
|
90
|
+
|
|
91
|
+
TEST_FILE_DELETED = "test_file_deleted"
|
|
92
|
+
TEST_FUNCTION_DELETED = "test_function_deleted"
|
|
93
|
+
ASSERTION_COUNT_REDUCED = "assertion_count_reduced"
|
|
94
|
+
TEST_SUPPRESSION_INJECTED = "test_suppression_injected"
|
|
95
|
+
TEST_SYNTAX_ERROR = "test_syntax_error"
|
|
96
|
+
CONFIG_TAMPERING = "config_tampering"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class TamperingViolation(BaseModel):
|
|
100
|
+
"""Specific recorded violation of test integrity."""
|
|
101
|
+
|
|
102
|
+
model_config = ConfigDict(frozen=True)
|
|
103
|
+
|
|
104
|
+
violation_type: TamperingViolationType
|
|
105
|
+
file_path: str
|
|
106
|
+
target_name: str | None = None
|
|
107
|
+
details: str
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AntiCheatAuditReport(BaseModel):
|
|
111
|
+
"""Comprehensive integrity report resulting from patch tampering audit."""
|
|
112
|
+
|
|
113
|
+
model_config = ConfigDict(frozen=True)
|
|
114
|
+
|
|
115
|
+
tampering_detected: bool
|
|
116
|
+
violations: tuple[TamperingViolation, ...] = Field(default=())
|
|
117
|
+
summary: str
|
|
118
|
+
assertion_delta: int = 0
|
|
119
|
+
tests_deleted_count: int = 0
|
|
120
|
+
tests_suppressed_count: int = 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _TestFileAuditVisitor(ast.NodeVisitor):
|
|
124
|
+
"""AST visitor extracting test function signatures, assertion counts, and suppressions."""
|
|
125
|
+
|
|
126
|
+
def __init__(self) -> None:
|
|
127
|
+
self.test_functions: dict[str, list[str]] = {}
|
|
128
|
+
self.assert_count: int = 0
|
|
129
|
+
self.class_stack: list[str] = []
|
|
130
|
+
self.suppressions: set[str] = set()
|
|
131
|
+
|
|
132
|
+
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
|
133
|
+
self.class_stack.append(node.name)
|
|
134
|
+
self.generic_visit(node)
|
|
135
|
+
self.class_stack.pop()
|
|
136
|
+
|
|
137
|
+
def visit_Assert(self, node: ast.Assert) -> None:
|
|
138
|
+
self.assert_count += 1
|
|
139
|
+
self.generic_visit(node)
|
|
140
|
+
|
|
141
|
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
|
|
142
|
+
self._record_func(node)
|
|
143
|
+
|
|
144
|
+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
|
|
145
|
+
self._record_func(node)
|
|
146
|
+
|
|
147
|
+
def _record_func(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
148
|
+
is_test = node.name.startswith("test_")
|
|
149
|
+
if self.class_stack and self.class_stack[-1].startswith("Test"):
|
|
150
|
+
is_test = True
|
|
151
|
+
|
|
152
|
+
qualname = f"{self.class_stack[-1]}.{node.name}" if self.class_stack else node.name
|
|
153
|
+
|
|
154
|
+
# Detect decorator suppressions: @pytest.mark.skip, @pytest.mark.xfail, @unittest.skip
|
|
155
|
+
decorators: list[str] = []
|
|
156
|
+
for dec in node.decorator_list:
|
|
157
|
+
dec_repr = ast.unparse(dec) if hasattr(ast, "unparse") else ""
|
|
158
|
+
decorators.append(dec_repr)
|
|
159
|
+
if any(
|
|
160
|
+
s in dec_repr for s in ("pytest.mark.skip", "pytest.mark.xfail", "unittest.skip")
|
|
161
|
+
):
|
|
162
|
+
self.suppressions.add(f"{qualname} ({dec_repr})")
|
|
163
|
+
|
|
164
|
+
# Detect in-body calls to pytest.skip()
|
|
165
|
+
for sub in ast.walk(node):
|
|
166
|
+
if isinstance(sub, ast.Call):
|
|
167
|
+
func_repr = ast.unparse(sub.func) if hasattr(ast, "unparse") else ""
|
|
168
|
+
if "pytest.skip" in func_repr:
|
|
169
|
+
self.suppressions.add(f"{qualname} (pytest.skip)")
|
|
170
|
+
|
|
171
|
+
if is_test:
|
|
172
|
+
self.test_functions[qualname] = decorators
|
|
173
|
+
|
|
174
|
+
self.generic_visit(node)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _audit_single_test_delta(
|
|
178
|
+
delta: FileDelta,
|
|
179
|
+
original_text: str,
|
|
180
|
+
patched_text: str,
|
|
181
|
+
) -> tuple[list[TamperingViolation], int, int, int]:
|
|
182
|
+
"""Audit AST differences between baseline and patched content of a single test file."""
|
|
183
|
+
p_path = pathlib.PurePosixPath(delta.path)
|
|
184
|
+
if p_path.suffix.lower() in {".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"}:
|
|
185
|
+
from patchproof.core.polyglot_guard import audit_js_ts_test_content
|
|
186
|
+
return audit_js_ts_test_content(delta, original_text, patched_text)
|
|
187
|
+
|
|
188
|
+
violations: list[TamperingViolation] = []
|
|
189
|
+
tests_deleted = 0
|
|
190
|
+
tests_suppressed = 0
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
orig_tree = ast.parse(original_text, filename=delta.path)
|
|
194
|
+
except SyntaxError:
|
|
195
|
+
# If baseline had syntax error, we cannot cleanly compare AST
|
|
196
|
+
return (violations, 0, 0, 0)
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
patched_tree = ast.parse(patched_text, filename=delta.path)
|
|
200
|
+
except SyntaxError as exc:
|
|
201
|
+
violations.append(
|
|
202
|
+
TamperingViolation(
|
|
203
|
+
violation_type=TamperingViolationType.TEST_SYNTAX_ERROR,
|
|
204
|
+
file_path=delta.path,
|
|
205
|
+
details=f"Patched test file failed AST parsing: {exc.msg} (line {exc.lineno})",
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
return (violations, 0, 0, 0)
|
|
209
|
+
|
|
210
|
+
orig_visitor = _TestFileAuditVisitor()
|
|
211
|
+
orig_visitor.visit(orig_tree)
|
|
212
|
+
|
|
213
|
+
patched_visitor = _TestFileAuditVisitor()
|
|
214
|
+
patched_visitor.visit(patched_tree)
|
|
215
|
+
|
|
216
|
+
assertion_delta = patched_visitor.assert_count - orig_visitor.assert_count
|
|
217
|
+
if assertion_delta < 0:
|
|
218
|
+
violations.append(
|
|
219
|
+
TamperingViolation(
|
|
220
|
+
violation_type=TamperingViolationType.ASSERTION_COUNT_REDUCED,
|
|
221
|
+
file_path=delta.path,
|
|
222
|
+
details=(
|
|
223
|
+
f"Test assertion count decreased from {orig_visitor.assert_count} "
|
|
224
|
+
f"to {patched_visitor.assert_count} (delta: {assertion_delta})"
|
|
225
|
+
),
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# Check for deleted test functions
|
|
230
|
+
for orig_func in orig_visitor.test_functions:
|
|
231
|
+
if orig_func not in patched_visitor.test_functions:
|
|
232
|
+
tests_deleted += 1
|
|
233
|
+
violations.append(
|
|
234
|
+
TamperingViolation(
|
|
235
|
+
violation_type=TamperingViolationType.TEST_FUNCTION_DELETED,
|
|
236
|
+
file_path=delta.path,
|
|
237
|
+
target_name=orig_func,
|
|
238
|
+
details=f"Existing test function '{orig_func}' was deleted or renamed in patch",
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
# Check for newly injected suppressions
|
|
243
|
+
new_suppressions = patched_visitor.suppressions - orig_visitor.suppressions
|
|
244
|
+
for supp in sorted(new_suppressions):
|
|
245
|
+
tests_suppressed += 1
|
|
246
|
+
violations.append(
|
|
247
|
+
TamperingViolation(
|
|
248
|
+
violation_type=TamperingViolationType.TEST_SUPPRESSION_INJECTED,
|
|
249
|
+
file_path=delta.path,
|
|
250
|
+
target_name=supp.split(" ")[0],
|
|
251
|
+
details=f"Test suppression or skip marker injected: {supp}",
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return (violations, assertion_delta, tests_deleted, tests_suppressed)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def audit_patch_integrity(
|
|
259
|
+
patch: CanonicalPatch,
|
|
260
|
+
repo_root: pathlib.Path | str,
|
|
261
|
+
allow_test_edits: bool = False,
|
|
262
|
+
) -> AntiCheatAuditReport:
|
|
263
|
+
"""Audit patch for intentional weakening, deletion, or suppression of tests.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
patch: Canonical patch to inspect.
|
|
267
|
+
repo_root: Base repository root directory containing baseline files.
|
|
268
|
+
allow_test_edits: If True, test improvements and additions are permitted, but
|
|
269
|
+
deletions/reductions still trigger audit warnings.
|
|
270
|
+
"""
|
|
271
|
+
root_path = pathlib.Path(repo_root).resolve()
|
|
272
|
+
all_violations: list[TamperingViolation] = []
|
|
273
|
+
total_assertion_delta = 0
|
|
274
|
+
total_tests_deleted = 0
|
|
275
|
+
total_tests_suppressed = 0
|
|
276
|
+
|
|
277
|
+
for delta in patch.file_deltas:
|
|
278
|
+
if is_config_file(delta.path):
|
|
279
|
+
for hunk in delta.hunks:
|
|
280
|
+
for line in hunk.lines:
|
|
281
|
+
if line.startswith("+"):
|
|
282
|
+
line_lower = line[1:].strip().lower()
|
|
283
|
+
for pattern in SUSPICIOUS_CONFIG_PATTERNS:
|
|
284
|
+
if pattern in line_lower:
|
|
285
|
+
all_violations.append(
|
|
286
|
+
TamperingViolation(
|
|
287
|
+
violation_type=TamperingViolationType.CONFIG_TAMPERING,
|
|
288
|
+
file_path=delta.path,
|
|
289
|
+
details=(
|
|
290
|
+
f"Configuration tampering in '{delta.path}': "
|
|
291
|
+
f"test suppression flag '{pattern}' introduced: "
|
|
292
|
+
f"'{line.strip()}'"
|
|
293
|
+
),
|
|
294
|
+
)
|
|
295
|
+
)
|
|
296
|
+
continue
|
|
297
|
+
|
|
298
|
+
if not is_test_file(delta.path):
|
|
299
|
+
continue
|
|
300
|
+
|
|
301
|
+
# Check for whole test file deletion
|
|
302
|
+
if delta.change_type == ChangeType.DELETE:
|
|
303
|
+
total_tests_deleted += 1
|
|
304
|
+
all_violations.append(
|
|
305
|
+
TamperingViolation(
|
|
306
|
+
violation_type=TamperingViolationType.TEST_FILE_DELETED,
|
|
307
|
+
file_path=delta.path,
|
|
308
|
+
details=f"Test file '{delta.path}' was completely deleted in patch",
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
continue
|
|
312
|
+
|
|
313
|
+
# For modifications to existing test files
|
|
314
|
+
target_file = root_path / delta.path
|
|
315
|
+
if not target_file.is_file():
|
|
316
|
+
# If allow_test_edits is False and patch creates or edits test file, flag violation
|
|
317
|
+
if not allow_test_edits:
|
|
318
|
+
all_violations.append(
|
|
319
|
+
TamperingViolation(
|
|
320
|
+
violation_type=TamperingViolationType.TEST_SUPPRESSION_INJECTED,
|
|
321
|
+
file_path=delta.path,
|
|
322
|
+
details=f"Unpermitted test modification in patch: '{delta.path}'",
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
continue
|
|
326
|
+
|
|
327
|
+
try:
|
|
328
|
+
original_text = target_file.read_text(encoding="utf-8", errors="replace")
|
|
329
|
+
except OSError:
|
|
330
|
+
continue
|
|
331
|
+
|
|
332
|
+
# Apply hunks in-memory using an ephemeral directory
|
|
333
|
+
import tempfile
|
|
334
|
+
with tempfile.TemporaryDirectory(prefix="patchproof-anticheat-") as tmp_dir:
|
|
335
|
+
tmp_root = pathlib.Path(tmp_dir)
|
|
336
|
+
tmp_file = tmp_root / delta.path
|
|
337
|
+
tmp_file.parent.mkdir(parents=True, exist_ok=True)
|
|
338
|
+
tmp_file.write_text(original_text, encoding="utf-8")
|
|
339
|
+
|
|
340
|
+
single_file_patch = CanonicalPatch(
|
|
341
|
+
patch_type=patch.patch_type,
|
|
342
|
+
file_deltas=(delta,),
|
|
343
|
+
raw_diff=patch.raw_diff,
|
|
344
|
+
)
|
|
345
|
+
try:
|
|
346
|
+
apply_patch(single_file_patch, tmp_root)
|
|
347
|
+
patched_text = tmp_file.read_text(encoding="utf-8", errors="replace")
|
|
348
|
+
except Exception as app_exc:
|
|
349
|
+
all_violations.append(
|
|
350
|
+
TamperingViolation(
|
|
351
|
+
violation_type=TamperingViolationType.TEST_SYNTAX_ERROR,
|
|
352
|
+
file_path=delta.path,
|
|
353
|
+
details=f"Failed applying test patch in-memory for audit: {app_exc}",
|
|
354
|
+
)
|
|
355
|
+
)
|
|
356
|
+
continue
|
|
357
|
+
|
|
358
|
+
v_list, a_delta, t_del, t_supp = _audit_single_test_delta(
|
|
359
|
+
delta, original_text, patched_text
|
|
360
|
+
)
|
|
361
|
+
all_violations.extend(v_list)
|
|
362
|
+
total_assertion_delta += a_delta
|
|
363
|
+
total_tests_deleted += t_del
|
|
364
|
+
total_tests_suppressed += t_supp
|
|
365
|
+
|
|
366
|
+
if allow_test_edits:
|
|
367
|
+
# When allow_test_edits is True, only flag explicit deletions and suppressions
|
|
368
|
+
all_violations = [
|
|
369
|
+
v for v in all_violations
|
|
370
|
+
if v.violation_type in (
|
|
371
|
+
TamperingViolationType.TEST_FILE_DELETED,
|
|
372
|
+
TamperingViolationType.TEST_FUNCTION_DELETED,
|
|
373
|
+
TamperingViolationType.TEST_SUPPRESSION_INJECTED,
|
|
374
|
+
TamperingViolationType.ASSERTION_COUNT_REDUCED,
|
|
375
|
+
TamperingViolationType.CONFIG_TAMPERING,
|
|
376
|
+
)
|
|
377
|
+
]
|
|
378
|
+
|
|
379
|
+
tampering_detected = len(all_violations) > 0
|
|
380
|
+
if tampering_detected:
|
|
381
|
+
summary = (
|
|
382
|
+
f"Test tampering detected: {len(all_violations)} violation(s) found "
|
|
383
|
+
f"({total_tests_deleted} deleted, {total_tests_suppressed} suppressed, "
|
|
384
|
+
f"assertion delta: {total_assertion_delta})"
|
|
385
|
+
)
|
|
386
|
+
else:
|
|
387
|
+
summary = "Patch integrity verified clean: no test tampering detected"
|
|
388
|
+
|
|
389
|
+
return AntiCheatAuditReport(
|
|
390
|
+
tampering_detected=tampering_detected,
|
|
391
|
+
violations=tuple(all_violations),
|
|
392
|
+
summary=summary,
|
|
393
|
+
assertion_delta=total_assertion_delta,
|
|
394
|
+
tests_deleted_count=total_tests_deleted,
|
|
395
|
+
tests_suppressed_count=total_tests_suppressed,
|
|
396
|
+
)
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Safe, isolated application of canonical patches and diffs to staging workspaces."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pathlib
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
|
|
8
|
+
from patchproof.core.normalizer import parse_patch
|
|
9
|
+
from patchproof.core.search_replace import SEARCH_START, parse_search_replace
|
|
10
|
+
from patchproof.exceptions import (
|
|
11
|
+
InvalidPatchFormatError,
|
|
12
|
+
PatchApplicationError,
|
|
13
|
+
SandboxSecurityError,
|
|
14
|
+
)
|
|
15
|
+
from patchproof.models.patch import (
|
|
16
|
+
CanonicalPatch,
|
|
17
|
+
ChangeType,
|
|
18
|
+
PatchHunk,
|
|
19
|
+
PatchType,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _resolve_and_validate_path(target_base: pathlib.Path, rel_path: str) -> pathlib.Path:
|
|
24
|
+
"""Resolve file path within target_base, rejecting any directory traversal or symlinks."""
|
|
25
|
+
target_candidate = target_base / rel_path
|
|
26
|
+
if target_candidate.is_symlink():
|
|
27
|
+
raise SandboxSecurityError(f"Patch cannot target a symbolic link: {rel_path}")
|
|
28
|
+
|
|
29
|
+
resolved = target_candidate.resolve()
|
|
30
|
+
if resolved == target_base:
|
|
31
|
+
raise SandboxSecurityError(f"Patch target cannot be the workspace root: {rel_path}")
|
|
32
|
+
try:
|
|
33
|
+
resolved.relative_to(target_base)
|
|
34
|
+
except ValueError as err:
|
|
35
|
+
raise SandboxSecurityError(f"Patch path traversal attempted: {rel_path}") from err
|
|
36
|
+
return resolved
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _apply_hunks_to_lines(
|
|
40
|
+
lines: list[str], hunks: Sequence[PatchHunk], file_path: str
|
|
41
|
+
) -> list[str]:
|
|
42
|
+
"""Apply sorted unified diff hunks to a list of file lines."""
|
|
43
|
+
result = list(lines)
|
|
44
|
+
offset = 0
|
|
45
|
+
|
|
46
|
+
sorted_hunks = sorted(hunks, key=lambda h: h.old_start)
|
|
47
|
+
for hunk in sorted_hunks:
|
|
48
|
+
expected_start = max(0, hunk.old_start - 1 + offset)
|
|
49
|
+
expected_old = [
|
|
50
|
+
line_str[1:]
|
|
51
|
+
for line_str in hunk.lines
|
|
52
|
+
if line_str.startswith(" ") or line_str.startswith("-")
|
|
53
|
+
]
|
|
54
|
+
new_slice = [
|
|
55
|
+
line_str[1:]
|
|
56
|
+
for line_str in hunk.lines
|
|
57
|
+
if line_str.startswith(" ") or line_str.startswith("+")
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
actual_slice = result[expected_start : expected_start + len(expected_old)]
|
|
61
|
+
if actual_slice != expected_old:
|
|
62
|
+
raise PatchApplicationError(
|
|
63
|
+
f"Context mismatch in {file_path} at hunk starting at line {hunk.old_start}"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
result[expected_start : expected_start + len(expected_old)] = new_slice
|
|
67
|
+
offset += len(new_slice) - len(expected_old)
|
|
68
|
+
|
|
69
|
+
return result
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def apply_patch(
|
|
73
|
+
patch: CanonicalPatch | str,
|
|
74
|
+
target_dir: str | pathlib.Path,
|
|
75
|
+
) -> list[str]:
|
|
76
|
+
"""Apply a CanonicalPatch or raw diff string cleanly to an ephemeral staging workspace.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
List of relative repository paths modified, added, or deleted.
|
|
80
|
+
|
|
81
|
+
Raises:
|
|
82
|
+
PatchApplicationError: If patch formatting is invalid, context fails to match,
|
|
83
|
+
or files are missing/unexpectedly present.
|
|
84
|
+
SandboxSecurityError: If any path attempts to escape the staging workspace.
|
|
85
|
+
"""
|
|
86
|
+
target_base = pathlib.Path(target_dir).resolve()
|
|
87
|
+
if not target_base.exists() or not target_base.is_dir():
|
|
88
|
+
raise PatchApplicationError(
|
|
89
|
+
f"Staging directory does not exist or is not a directory: {target_dir}"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# Parse raw patch if supplied as string
|
|
93
|
+
canonical_patch: CanonicalPatch
|
|
94
|
+
if isinstance(patch, str):
|
|
95
|
+
try:
|
|
96
|
+
if SEARCH_START in patch:
|
|
97
|
+
canonical_patch = parse_search_replace(patch)
|
|
98
|
+
else:
|
|
99
|
+
canonical_patch = parse_patch(patch)
|
|
100
|
+
except InvalidPatchFormatError as err:
|
|
101
|
+
raise PatchApplicationError(f"Cannot apply invalid patch format: {err}") from err
|
|
102
|
+
else:
|
|
103
|
+
canonical_patch = patch
|
|
104
|
+
|
|
105
|
+
modified_paths: list[str] = []
|
|
106
|
+
|
|
107
|
+
for delta in canonical_patch.file_deltas:
|
|
108
|
+
target_file = _resolve_and_validate_path(target_base, delta.path)
|
|
109
|
+
|
|
110
|
+
if delta.change_type == ChangeType.ADD:
|
|
111
|
+
if target_file.exists():
|
|
112
|
+
raise PatchApplicationError(f"Cannot create file that already exists: {delta.path}")
|
|
113
|
+
target_file.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
added_lines = [
|
|
115
|
+
line[1:] for hunk in delta.hunks for line in hunk.lines if line.startswith("+")
|
|
116
|
+
]
|
|
117
|
+
content = "\n".join(added_lines) + ("\n" if added_lines else "")
|
|
118
|
+
target_file.write_text(content, encoding="utf-8")
|
|
119
|
+
modified_paths.append(delta.path)
|
|
120
|
+
|
|
121
|
+
elif delta.change_type == ChangeType.DELETE:
|
|
122
|
+
if not target_file.exists():
|
|
123
|
+
raise PatchApplicationError(f"Cannot delete non-existent file: {delta.path}")
|
|
124
|
+
target_file.unlink()
|
|
125
|
+
modified_paths.append(delta.path)
|
|
126
|
+
|
|
127
|
+
elif delta.change_type == ChangeType.MODIFY:
|
|
128
|
+
if not target_file.exists():
|
|
129
|
+
raise PatchApplicationError(f"File to modify does not exist: {delta.path}")
|
|
130
|
+
|
|
131
|
+
content = target_file.read_text(encoding="utf-8")
|
|
132
|
+
|
|
133
|
+
if canonical_patch.patch_type == PatchType.SEARCH_REPLACE:
|
|
134
|
+
for hunk in delta.hunks:
|
|
135
|
+
search_lines = [
|
|
136
|
+
line_str[1:] for line_str in hunk.lines if line_str.startswith("-")
|
|
137
|
+
]
|
|
138
|
+
replace_lines = [
|
|
139
|
+
line_str[1:] for line_str in hunk.lines if line_str.startswith("+")
|
|
140
|
+
]
|
|
141
|
+
search_text = "\n".join(search_lines)
|
|
142
|
+
replace_text = "\n".join(replace_lines)
|
|
143
|
+
|
|
144
|
+
if search_text not in content:
|
|
145
|
+
raise PatchApplicationError(
|
|
146
|
+
f"SEARCH block not found in {delta.path}: {search_text[:40]}..."
|
|
147
|
+
)
|
|
148
|
+
content = content.replace(search_text, replace_text, 1)
|
|
149
|
+
|
|
150
|
+
target_file.write_text(content, encoding="utf-8")
|
|
151
|
+
else:
|
|
152
|
+
lines = content.splitlines(keepends=False)
|
|
153
|
+
updated_lines = _apply_hunks_to_lines(lines, delta.hunks, delta.path)
|
|
154
|
+
new_content = "\n".join(updated_lines) + ("\n" if updated_lines else "")
|
|
155
|
+
target_file.write_text(new_content, encoding="utf-8")
|
|
156
|
+
|
|
157
|
+
modified_paths.append(delta.path)
|
|
158
|
+
|
|
159
|
+
return modified_paths
|