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,88 @@
1
+ """Asymmetric Ed25519 cryptographic signing and verification subsystem.
2
+
3
+ Provides tamper-evident digital signatures for Proof-of-Patch certificates
4
+ enabling offline verification in CI/CD without shared secrets.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import logging
11
+
12
+ from cryptography.exceptions import InvalidSignature
13
+ from cryptography.hazmat.primitives import serialization
14
+ from cryptography.hazmat.primitives.asymmetric import ed25519
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def generate_ed25519_keypair() -> tuple[str, str]:
20
+ """Generate a new Ed25519 keypair formatted as PEM strings.
21
+
22
+ Returns:
23
+ tuple[str, str]: (private_key_pem, public_key_pem)
24
+ """
25
+ private_key = ed25519.Ed25519PrivateKey.generate()
26
+ public_key = private_key.public_key()
27
+
28
+ priv_pem = private_key.private_bytes(
29
+ encoding=serialization.Encoding.PEM,
30
+ format=serialization.PrivateFormat.PKCS8,
31
+ encryption_algorithm=serialization.NoEncryption(),
32
+ ).decode("utf-8")
33
+
34
+ pub_pem = public_key.public_bytes(
35
+ encoding=serialization.Encoding.PEM,
36
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
37
+ ).decode("utf-8")
38
+
39
+ return priv_pem, pub_pem
40
+
41
+
42
+ def sign_payload_ed25519(payload: bytes, private_key_pem: str) -> str:
43
+ """Sign payload with Ed25519 private key and return base64-encoded signature.
44
+
45
+ Args:
46
+ payload: Canonical byte sequence to sign.
47
+ private_key_pem: PEM-encoded Ed25519 private key.
48
+
49
+ Returns:
50
+ str: Base64-encoded signature.
51
+ """
52
+ priv_key = serialization.load_pem_private_key(
53
+ private_key_pem.encode("utf-8"),
54
+ password=None,
55
+ )
56
+ if not isinstance(priv_key, ed25519.Ed25519PrivateKey):
57
+ raise ValueError("Provided key is not an Ed25519 private key")
58
+
59
+ signature = priv_key.sign(payload)
60
+ return base64.b64encode(signature).decode("ascii")
61
+
62
+
63
+ def verify_payload_ed25519(
64
+ payload: bytes,
65
+ signature_base64: str,
66
+ public_key_pem: str,
67
+ ) -> bool:
68
+ """Verify Ed25519 signature against payload using public key.
69
+
70
+ Args:
71
+ payload: Canonical byte sequence.
72
+ signature_base64: Base64-encoded signature string.
73
+ public_key_pem: PEM-encoded Ed25519 public key.
74
+
75
+ Returns:
76
+ bool: True if signature is cryptographically valid, False otherwise.
77
+ """
78
+ try:
79
+ pub_key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
80
+ if not isinstance(pub_key, ed25519.Ed25519PublicKey):
81
+ return False
82
+
83
+ sig_bytes = base64.b64decode(signature_base64)
84
+ pub_key.verify(sig_bytes, payload)
85
+ return True
86
+ except (InvalidSignature, ValueError, TypeError) as err:
87
+ logger.debug("Ed25519 verification failed: %s", err)
88
+ return False
@@ -0,0 +1,86 @@
1
+ """Dynamic SVG badge generator for PatchProof verification attestation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import NamedTuple
6
+
7
+ from patchproof.models.sandbox import (
8
+ ComparativeExecutionResult,
9
+ PatchVerdict,
10
+ )
11
+
12
+
13
+ class BadgeStyle(NamedTuple):
14
+ """Visual style attributes for an SVG badge."""
15
+
16
+ status_text: str
17
+ bg_color: str
18
+ right_width: int
19
+
20
+
21
+ VERDICT_BADGE_CONFIG: dict[PatchVerdict, BadgeStyle] = {
22
+ PatchVerdict.ACCEPTED: BadgeStyle("verified", "#2ea44f", 64),
23
+ PatchVerdict.REJECTED: BadgeStyle("rejected", "#cb2431", 64),
24
+ PatchVerdict.SUSPICIOUS: BadgeStyle("suspicious", "#dfb317", 74),
25
+ PatchVerdict.INFRASTRUCTURE_FAILURE: BadgeStyle("infra failure", "#959da5", 84),
26
+ }
27
+
28
+
29
+ def generate_svg_badge(result: ComparativeExecutionResult) -> str:
30
+ """Render a standalone, GitHub-compatible SVG badge reflecting verification verdict."""
31
+ style = VERDICT_BADGE_CONFIG.get(
32
+ result.verdict,
33
+ BadgeStyle(result.verdict.value, "#959da5", 64),
34
+ )
35
+
36
+ left_label = "patchproof"
37
+ left_width = 72
38
+ right_width = style.right_width
39
+ total_width = left_width + right_width
40
+ height = 20
41
+
42
+ label_x = left_width / 2.0
43
+ status_x = left_width + (right_width / 2.0)
44
+ text_y = 14
45
+ bg_color = style.bg_color
46
+ status_text = style.status_text
47
+
48
+ font_family = "Verdana,Geneva,DejaVu Sans,sans-serif"
49
+ header = (
50
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{total_width}" height="{height}" '
51
+ f'role="img" aria-label="{left_label}: {status_text}">'
52
+ )
53
+ group_text = (
54
+ f' <g fill="#fff" text-anchor="middle" font-family="{font_family}" '
55
+ 'text-rendering="geometricPrecision" font-size="11">'
56
+ )
57
+ left_shadow = (
58
+ f' <text aria-hidden="true" x="{label_x}" y="{text_y + 1}" '
59
+ f'fill="#010101" fill-opacity=".3">{left_label}</text>'
60
+ )
61
+ right_shadow = (
62
+ f' <text aria-hidden="true" x="{status_x}" y="{text_y + 1}" '
63
+ f'fill="#010101" fill-opacity=".3">{status_text}</text>'
64
+ )
65
+
66
+ return f"""{header}
67
+ <title>{left_label}: {status_text}</title>
68
+ <linearGradient id="s" x2="0" y2="100%">
69
+ <stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
70
+ <stop offset="1" stop-opacity=".1"/>
71
+ </linearGradient>
72
+ <clipPath id="r">
73
+ <rect width="{total_width}" height="{height}" rx="3" fill="#fff"/>
74
+ </clipPath>
75
+ <g clip-path="url(#r)">
76
+ <rect width="{left_width}" height="{height}" fill="#555"/>
77
+ <rect x="{left_width}" width="{right_width}" height="{height}" fill="{bg_color}"/>
78
+ <rect width="{total_width}" height="{height}" fill="url(#s)"/>
79
+ </g>
80
+ {group_text}
81
+ {left_shadow}
82
+ <text x="{label_x}" y="{text_y}">{left_label}</text>
83
+ {right_shadow}
84
+ <text x="{status_x}" y="{text_y}">{status_text}</text>
85
+ </g>
86
+ </svg>"""
@@ -0,0 +1,230 @@
1
+ """Cryptographic Proof-of-Patch Attestation Engine.
2
+
3
+ Generates and validates tamper-proof signed verification certificates proving
4
+ that code patches were evaluated in an isolated zero-network sandbox without regressions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import pathlib
14
+ from dataclasses import asdict, dataclass
15
+ from typing import Any
16
+
17
+ from cryptography.hazmat.primitives import serialization
18
+ from cryptography.hazmat.primitives.asymmetric import ed25519
19
+
20
+ from patchproof.core.runtime_guard import extract_runtime_profile
21
+ from patchproof.models.sandbox import ComparativeExecutionResult
22
+ from patchproof.reporting.asymmetric import (
23
+ sign_payload_ed25519,
24
+ verify_payload_ed25519,
25
+ )
26
+
27
+ DEFAULT_HMAC_SECRET = "patchproof-attestation-v1"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ProofCertificate:
32
+ """Tamper-evident certificate of sandboxed patch verification."""
33
+
34
+ version: str
35
+ patch_sha256: str
36
+ base_commit: str | None
37
+ verdict: str
38
+ total_tests: int
39
+ passed_tests: int
40
+ introduced_regressions: int
41
+ sandbox_isolated: bool
42
+ created_at_iso: str
43
+ signature: str
44
+ anti_cheat_passed: bool = True
45
+ algorithm: str = "HMAC-SHA256"
46
+ public_key_pem: str | None = None
47
+ signer_identity: str | None = None
48
+ assertion_baseline_count: int | None = None
49
+ assertion_patched_count: int | None = None
50
+
51
+ def to_dict(self) -> dict[str, Any]:
52
+ """Convert certificate to serializable dictionary."""
53
+ return asdict(self)
54
+
55
+
56
+ def _compute_digest_payload(
57
+ version: str,
58
+ patch_sha256: str,
59
+ base_commit: str | None,
60
+ verdict: str,
61
+ total_tests: int,
62
+ passed_tests: int,
63
+ introduced_regressions: int,
64
+ sandbox_isolated: bool,
65
+ anti_cheat_passed: bool,
66
+ created_at_iso: str,
67
+ algorithm: str = "HMAC-SHA256",
68
+ signer_identity: str | None = None,
69
+ assertion_baseline_count: int | None = None,
70
+ assertion_patched_count: int | None = None,
71
+ ) -> bytes:
72
+ """Generate canonical byte string for signature computation."""
73
+ canonical_str = (
74
+ f"v={version}|patch={patch_sha256}|commit={base_commit or ''}|"
75
+ f"verdict={verdict}|total={total_tests}|passed={passed_tests}|"
76
+ f"regressions={introduced_regressions}|isolated={sandbox_isolated}|"
77
+ f"anticheat={anti_cheat_passed}|algo={algorithm}|"
78
+ f"signer={signer_identity or ''}|"
79
+ f"base_asserts={assertion_baseline_count or ''}|"
80
+ f"patch_asserts={assertion_patched_count or ''}|"
81
+ f"created={created_at_iso}"
82
+ )
83
+ return canonical_str.encode("utf-8")
84
+
85
+
86
+ def _compute_signature(payload: bytes, secret_key: str) -> str:
87
+ """Compute HMAC-SHA256 signature for the given payload."""
88
+ return hmac.new(secret_key.encode("utf-8"), payload, hashlib.sha256).hexdigest()
89
+
90
+
91
+ def generate_certificate(
92
+ result: ComparativeExecutionResult,
93
+ patch_content: str,
94
+ base_commit: str | None = None,
95
+ secret_key: str | None = None,
96
+ private_key_pem: str | None = None,
97
+ signer_identity: str | None = None,
98
+ created_at: datetime.datetime | None = None,
99
+ ) -> ProofCertificate:
100
+ """Generate signed Proof-of-Patch certificate for a comparative execution result."""
101
+ now = created_at or datetime.datetime.now(datetime.UTC)
102
+ created_iso = now.isoformat()
103
+
104
+ patch_hash = hashlib.sha256(patch_content.encode("utf-8")).hexdigest()
105
+ total_tests = len(result.test_comparisons)
106
+ passed_tests = (
107
+ result.patched_result.test_report.passed_count if result.patched_result.test_report else 0
108
+ )
109
+ anti_cheat_passed = (
110
+ not result.test_tampering_detected
111
+ and result.removed_tests_count == 0
112
+ )
113
+
114
+ base_prof = extract_runtime_profile(result.baseline_result.stdout)
115
+ patch_prof = extract_runtime_profile(result.patched_result.stdout)
116
+ assert_base = base_prof.executed_assertions if base_prof else None
117
+ assert_patch = patch_prof.executed_assertions if patch_prof else None
118
+
119
+ if private_key_pem:
120
+ algorithm = "Ed25519"
121
+ priv_key = serialization.load_pem_private_key(
122
+ private_key_pem.encode("utf-8"),
123
+ password=None,
124
+ )
125
+ if not isinstance(priv_key, ed25519.Ed25519PrivateKey):
126
+ raise ValueError("Provided key is not an Ed25519 private key")
127
+ pub_pem = priv_key.public_key().public_bytes(
128
+ encoding=serialization.Encoding.PEM,
129
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
130
+ ).decode("utf-8")
131
+
132
+ payload = _compute_digest_payload(
133
+ version="2.0",
134
+ patch_sha256=patch_hash,
135
+ base_commit=base_commit,
136
+ verdict=result.verdict.value,
137
+ total_tests=total_tests,
138
+ passed_tests=passed_tests,
139
+ introduced_regressions=result.introduced_regressions_count,
140
+ sandbox_isolated=True,
141
+ anti_cheat_passed=anti_cheat_passed,
142
+ created_at_iso=created_iso,
143
+ algorithm=algorithm,
144
+ signer_identity=signer_identity,
145
+ assertion_baseline_count=assert_base,
146
+ assertion_patched_count=assert_patch,
147
+ )
148
+ sig = sign_payload_ed25519(payload, private_key_pem)
149
+ version = "2.0"
150
+ else:
151
+ algorithm = "HMAC-SHA256"
152
+ secret = secret_key or DEFAULT_HMAC_SECRET
153
+ pub_pem = None
154
+ version = "1.0"
155
+ payload = _compute_digest_payload(
156
+ version=version,
157
+ patch_sha256=patch_hash,
158
+ base_commit=base_commit,
159
+ verdict=result.verdict.value,
160
+ total_tests=total_tests,
161
+ passed_tests=passed_tests,
162
+ introduced_regressions=result.introduced_regressions_count,
163
+ sandbox_isolated=True,
164
+ anti_cheat_passed=anti_cheat_passed,
165
+ created_at_iso=created_iso,
166
+ algorithm=algorithm,
167
+ signer_identity=signer_identity,
168
+ assertion_baseline_count=assert_base,
169
+ assertion_patched_count=assert_patch,
170
+ )
171
+ sig = _compute_signature(payload, secret)
172
+
173
+ return ProofCertificate(
174
+ version=version,
175
+ patch_sha256=patch_hash,
176
+ base_commit=base_commit,
177
+ verdict=result.verdict.value,
178
+ total_tests=total_tests,
179
+ passed_tests=passed_tests,
180
+ introduced_regressions=result.introduced_regressions_count,
181
+ sandbox_isolated=True,
182
+ anti_cheat_passed=anti_cheat_passed,
183
+ created_at_iso=created_iso,
184
+ signature=sig,
185
+ algorithm=algorithm,
186
+ public_key_pem=pub_pem,
187
+ signer_identity=signer_identity,
188
+ assertion_baseline_count=assert_base,
189
+ assertion_patched_count=assert_patch,
190
+ )
191
+
192
+
193
+ def verify_certificate(
194
+ cert: ProofCertificate,
195
+ secret_key: str | None = None,
196
+ public_key_pem: str | None = None,
197
+ ) -> bool:
198
+ """Verify that the certificate signature matches its payload and was not tampered with."""
199
+ payload = _compute_digest_payload(
200
+ version=cert.version,
201
+ patch_sha256=cert.patch_sha256,
202
+ base_commit=cert.base_commit,
203
+ verdict=cert.verdict,
204
+ total_tests=cert.total_tests,
205
+ passed_tests=cert.passed_tests,
206
+ introduced_regressions=cert.introduced_regressions,
207
+ sandbox_isolated=cert.sandbox_isolated,
208
+ anti_cheat_passed=cert.anti_cheat_passed,
209
+ created_at_iso=cert.created_at_iso,
210
+ algorithm=cert.algorithm,
211
+ signer_identity=cert.signer_identity,
212
+ assertion_baseline_count=cert.assertion_baseline_count,
213
+ assertion_patched_count=cert.assertion_patched_count,
214
+ )
215
+
216
+ if cert.algorithm == "Ed25519":
217
+ target_pub = public_key_pem or cert.public_key_pem
218
+ if not target_pub:
219
+ return False
220
+ return verify_payload_ed25519(payload, cert.signature, target_pub)
221
+
222
+ secret = secret_key or DEFAULT_HMAC_SECRET
223
+ expected_sig = _compute_signature(payload, secret)
224
+ return hmac.compare_digest(cert.signature, expected_sig)
225
+
226
+
227
+ def export_certificate(cert: ProofCertificate, output_path: pathlib.Path) -> None:
228
+ """Write ProofCertificate to disk in pretty-printed JSON format."""
229
+ output_path.parent.mkdir(parents=True, exist_ok=True)
230
+ output_path.write_text(json.dumps(cert.to_dict(), indent=2) + "\n", encoding="utf-8")