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,188 @@
|
|
|
1
|
+
"""in-toto v1.0 Attestation and SLSA Provenance generation for PatchProof.
|
|
2
|
+
|
|
3
|
+
Implements Dead Simple Signing Envelope (DSSE) and in-toto Statement v1
|
|
4
|
+
cryptographic attestations for enterprise software supply chain integrity.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import datetime
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from cryptography.exceptions import InvalidSignature
|
|
16
|
+
from cryptography.hazmat.primitives import serialization
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
18
|
+
|
|
19
|
+
from patchproof import __version__
|
|
20
|
+
from patchproof.models.sandbox import ComparativeExecutionResult
|
|
21
|
+
from patchproof.reporting.certificate import ProofCertificate
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def PAE(payload_type: str, payload_bytes: bytes) -> bytes:
|
|
25
|
+
"""Compute Pre-Authentication Encoding (PAE) for DSSE v1 spec.
|
|
26
|
+
|
|
27
|
+
Formula:
|
|
28
|
+
PAE(type, body) = "DSSEv1" + " " + len(type) + " " + type + " " + len(body) + " " + body
|
|
29
|
+
"""
|
|
30
|
+
type_bytes = payload_type.encode("utf-8")
|
|
31
|
+
return (
|
|
32
|
+
b"DSSEv1 "
|
|
33
|
+
+ str(len(type_bytes)).encode("ascii")
|
|
34
|
+
+ b" "
|
|
35
|
+
+ type_bytes
|
|
36
|
+
+ b" "
|
|
37
|
+
+ str(len(payload_bytes)).encode("ascii")
|
|
38
|
+
+ b" "
|
|
39
|
+
+ payload_bytes
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_slsa_provenance_predicate(
|
|
44
|
+
cert: ProofCertificate,
|
|
45
|
+
result: ComparativeExecutionResult,
|
|
46
|
+
builder_id: str = "https://patchproof.dev/engine/docker-sandbox",
|
|
47
|
+
dependencies: dict[str, str] | None = None,
|
|
48
|
+
) -> dict[str, Any]:
|
|
49
|
+
"""Generate SLSA Provenance v1.0 predicate dictionary."""
|
|
50
|
+
resolved_deps = [
|
|
51
|
+
{"uri": f"pkg:pypi/{pkg}@{ver}" if ver != "*" else f"pkg:pypi/{pkg}"}
|
|
52
|
+
for pkg, ver in sorted((dependencies or {}).items())
|
|
53
|
+
]
|
|
54
|
+
duration = max(result.patched_result.duration_seconds, 0.001)
|
|
55
|
+
finish_time = datetime.datetime.fromisoformat(cert.created_at_iso)
|
|
56
|
+
start_time = finish_time - datetime.timedelta(seconds=duration)
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
"buildDefinition": {
|
|
60
|
+
"buildType": "https://patchproof.dev/verifier/v0.3",
|
|
61
|
+
"externalParameters": {
|
|
62
|
+
"base_commit": cert.base_commit,
|
|
63
|
+
"patch_sha256": cert.patch_sha256,
|
|
64
|
+
"signer_identity": cert.signer_identity or "unspecified",
|
|
65
|
+
"signer_identity_is_placeholder": True,
|
|
66
|
+
},
|
|
67
|
+
"internalParameters": {
|
|
68
|
+
"sandbox_isolated": cert.sandbox_isolated,
|
|
69
|
+
"anti_cheat_passed": cert.anti_cheat_passed,
|
|
70
|
+
"algorithm": cert.algorithm,
|
|
71
|
+
},
|
|
72
|
+
"resolvedDependencies": resolved_deps,
|
|
73
|
+
},
|
|
74
|
+
"runDetails": {
|
|
75
|
+
"builder": {
|
|
76
|
+
"id": builder_id,
|
|
77
|
+
"version": {"patchproof": __version__},
|
|
78
|
+
},
|
|
79
|
+
"metadata": {
|
|
80
|
+
"invocationId": f"patchproof-{cert.patch_sha256[:16]}",
|
|
81
|
+
"startedOn": start_time.isoformat(),
|
|
82
|
+
"finishedOn": finish_time.isoformat(),
|
|
83
|
+
},
|
|
84
|
+
"byproducts": [
|
|
85
|
+
{
|
|
86
|
+
"name": "verification_verdict",
|
|
87
|
+
"verdict": cert.verdict,
|
|
88
|
+
"total_tests": cert.total_tests,
|
|
89
|
+
"passed_tests": cert.passed_tests,
|
|
90
|
+
"regressions": cert.introduced_regressions,
|
|
91
|
+
"assertion_baseline_count": cert.assertion_baseline_count,
|
|
92
|
+
"assertion_patched_count": cert.assertion_patched_count,
|
|
93
|
+
}
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def build_in_toto_statement(
|
|
100
|
+
cert: ProofCertificate,
|
|
101
|
+
result: ComparativeExecutionResult,
|
|
102
|
+
patch_content: str,
|
|
103
|
+
builder_id: str = "https://patchproof.dev/engine/docker-sandbox",
|
|
104
|
+
predicate_type: str = "https://slsa.dev/provenance/v1",
|
|
105
|
+
dependencies: dict[str, str] | None = None,
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
"""Build in-toto v1.0 Statement structure."""
|
|
108
|
+
patch_digest = hashlib.sha256(patch_content.encode("utf-8")).hexdigest()
|
|
109
|
+
predicate = build_slsa_provenance_predicate(
|
|
110
|
+
cert, result, builder_id=builder_id, dependencies=dependencies
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
"_type": "https://in-toto.io/Statement/v1",
|
|
115
|
+
"subject": [
|
|
116
|
+
{
|
|
117
|
+
"name": "patch.diff",
|
|
118
|
+
"digest": {
|
|
119
|
+
"sha256": patch_digest,
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
],
|
|
123
|
+
"predicateType": predicate_type,
|
|
124
|
+
"predicate": predicate,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_dsse_envelope(
|
|
129
|
+
statement: dict[str, Any],
|
|
130
|
+
private_key_pem: str,
|
|
131
|
+
key_id: str | None = None,
|
|
132
|
+
payload_type: str = "application/vnd.in-toto+json",
|
|
133
|
+
) -> dict[str, Any]:
|
|
134
|
+
"""Create and sign a Dead Simple Signing Envelope (DSSE) for an in-toto statement."""
|
|
135
|
+
statement_bytes = json.dumps(statement, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
|
136
|
+
pae_bytes = PAE(payload_type, statement_bytes)
|
|
137
|
+
|
|
138
|
+
priv_key = serialization.load_pem_private_key(
|
|
139
|
+
private_key_pem.encode("utf-8"),
|
|
140
|
+
password=None,
|
|
141
|
+
)
|
|
142
|
+
if not isinstance(priv_key, ed25519.Ed25519PrivateKey):
|
|
143
|
+
raise ValueError("Provided key is not an Ed25519 private key")
|
|
144
|
+
|
|
145
|
+
sig_bytes = priv_key.sign(pae_bytes)
|
|
146
|
+
sig_b64 = base64.b64encode(sig_bytes).decode("ascii")
|
|
147
|
+
|
|
148
|
+
envelope = {
|
|
149
|
+
"payloadType": payload_type,
|
|
150
|
+
"payload": base64.b64encode(statement_bytes).decode("ascii"),
|
|
151
|
+
"signatures": [
|
|
152
|
+
{
|
|
153
|
+
"keyid": key_id or "default",
|
|
154
|
+
"sig": sig_b64,
|
|
155
|
+
}
|
|
156
|
+
],
|
|
157
|
+
}
|
|
158
|
+
return envelope
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def verify_dsse_envelope(
|
|
162
|
+
envelope: dict[str, Any],
|
|
163
|
+
public_key_pem: str,
|
|
164
|
+
) -> bool:
|
|
165
|
+
"""Verify DSSE envelope signature against Ed25519 public key."""
|
|
166
|
+
try:
|
|
167
|
+
payload_type = envelope.get("payloadType", "")
|
|
168
|
+
payload_b64 = envelope.get("payload", "")
|
|
169
|
+
signatures = envelope.get("signatures", [])
|
|
170
|
+
if not payload_type or not payload_b64 or not signatures:
|
|
171
|
+
return False
|
|
172
|
+
|
|
173
|
+
payload_bytes = base64.b64decode(payload_b64.encode("ascii"))
|
|
174
|
+
pae_bytes = PAE(payload_type, payload_bytes)
|
|
175
|
+
|
|
176
|
+
pub_key = serialization.load_pem_public_key(
|
|
177
|
+
public_key_pem.encode("utf-8"),
|
|
178
|
+
)
|
|
179
|
+
if not isinstance(pub_key, ed25519.Ed25519PublicKey):
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
sig_b64 = signatures[0].get("sig", "")
|
|
183
|
+
sig_bytes = base64.b64decode(sig_b64.encode("ascii"))
|
|
184
|
+
|
|
185
|
+
pub_key.verify(sig_bytes, pae_bytes)
|
|
186
|
+
return True
|
|
187
|
+
except (InvalidSignature, ValueError, KeyError, Exception):
|
|
188
|
+
return False
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""GitHub PR comment and Step Summary Markdown generator.
|
|
2
|
+
|
|
3
|
+
Formats deterministic comparative execution results into rich, GitHub-native proof cards
|
|
4
|
+
including verdict badges, Anti-Cheat integrity audits, and cryptographic attestations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from patchproof.core.mutator import DifferentialMutationReport
|
|
12
|
+
from patchproof.models.sandbox import (
|
|
13
|
+
ComparativeExecutionResult,
|
|
14
|
+
PatchVerdict,
|
|
15
|
+
RegressionClassification,
|
|
16
|
+
)
|
|
17
|
+
from patchproof.reporting.certificate import ProofCertificate
|
|
18
|
+
from patchproof.reporting.sbom import DependencyDiff
|
|
19
|
+
|
|
20
|
+
MARKER_COMMENT = "<!-- patchproof-attestation-marker -->"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def generate_markdown_summary(
|
|
24
|
+
result: ComparativeExecutionResult,
|
|
25
|
+
cert: ProofCertificate | None = None,
|
|
26
|
+
patch_content: str | None = None,
|
|
27
|
+
in_toto_statement: dict[str, Any] | None = None,
|
|
28
|
+
sbom_diff: DependencyDiff | None = None,
|
|
29
|
+
mutation_report: DifferentialMutationReport | None = None,
|
|
30
|
+
) -> str:
|
|
31
|
+
"""Generate GitHub Flavored Markdown summary card for PR comments and CI summaries."""
|
|
32
|
+
lines: list[str] = [MARKER_COMMENT]
|
|
33
|
+
|
|
34
|
+
# 1. Header with Status Badge
|
|
35
|
+
verdict_str = result.verdict.value.upper()
|
|
36
|
+
if result.verdict == PatchVerdict.ACCEPTED:
|
|
37
|
+
badge_url = "https://img.shields.io/badge/PatchProof-VERIFIED-brightgreen?style=flat-square&logo=shield"
|
|
38
|
+
header_icon = "🛡️"
|
|
39
|
+
elif result.verdict == PatchVerdict.SUSPICIOUS:
|
|
40
|
+
badge_url = "https://img.shields.io/badge/PatchProof-SUSPICIOUS-yellow?style=flat-square&logo=shield"
|
|
41
|
+
header_icon = "⚠️"
|
|
42
|
+
elif result.verdict == PatchVerdict.REJECTED:
|
|
43
|
+
badge_url = "https://img.shields.io/badge/PatchProof-REJECTED-red?style=flat-square&logo=shield"
|
|
44
|
+
header_icon = "❌"
|
|
45
|
+
else:
|
|
46
|
+
badge_url = "https://img.shields.io/badge/PatchProof-INCONCLUSIVE-lightgrey?style=flat-square"
|
|
47
|
+
header_icon = "❓"
|
|
48
|
+
|
|
49
|
+
lines.append(f"## {header_icon} PatchProof Verification Report")
|
|
50
|
+
lines.append(f"[](https://github.com/ArnavSingha/Patchproof)\n")
|
|
51
|
+
lines.append(f"> **Summary:** {result.summary}\n")
|
|
52
|
+
|
|
53
|
+
# 2. Key Metrics Table
|
|
54
|
+
clean_count = sum(
|
|
55
|
+
1
|
|
56
|
+
for t in result.test_comparisons
|
|
57
|
+
if t.classification == RegressionClassification.CLEAN_PRESERVATION
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
anti_cheat_status = (
|
|
61
|
+
"🚨 **TAMPERING DETECTED**"
|
|
62
|
+
if result.test_tampering_detected
|
|
63
|
+
else "✅ **PASSED** (Untampered)"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
lines.append("### Verification Metrics")
|
|
67
|
+
lines.append("| Metric | Measurement | Status |")
|
|
68
|
+
lines.append("| :--- | :--- | :--- |")
|
|
69
|
+
reg_icon = "❌" if result.introduced_regressions_count > 0 else "✅"
|
|
70
|
+
tamper_icon = "🚨" if result.test_tampering_detected else "✅"
|
|
71
|
+
lines.append(f"| **Verdict** | `{verdict_str}` | {header_icon} |")
|
|
72
|
+
lines.append(f"| **Preserved Tests** | `{clean_count}` test(s) preserved clean | ✅ |")
|
|
73
|
+
lines.append(
|
|
74
|
+
f"| **Resolved Defects** | `{result.resolved_defects_count}` bug(s) resolved | 🎯 |"
|
|
75
|
+
)
|
|
76
|
+
lines.append(
|
|
77
|
+
f"| **Introduced Regressions** | `{result.introduced_regressions_count}` regression(s) | "
|
|
78
|
+
f"{reg_icon} |"
|
|
79
|
+
)
|
|
80
|
+
lines.append(f"| **Anti-Cheat Integrity** | {anti_cheat_status} | {tamper_icon} |")
|
|
81
|
+
removed_cnt = int(getattr(result, "removed_tests_count", 0) or 0)
|
|
82
|
+
suppressed_cnt = int(getattr(result, "suppressed_tests_count", 0) or 0)
|
|
83
|
+
lines.append(
|
|
84
|
+
f"| **Removed / Skipped Tests** | `{removed_cnt}` removed, `{suppressed_cnt}` suppressed | "
|
|
85
|
+
f"{'⚠️' if (removed_cnt + suppressed_cnt) > 0 else '✅'} |"
|
|
86
|
+
)
|
|
87
|
+
lines.append("| **Isolation Sandbox** | Docker (`--network none`, read-only root) | 🔒 |")
|
|
88
|
+
|
|
89
|
+
if cert is not None:
|
|
90
|
+
lines.append(
|
|
91
|
+
f"| **Proof Attestation** | {cert.algorithm}: `{cert.signature[:16]}...` | 📜 |"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
if in_toto_statement is not None:
|
|
95
|
+
lines.append(
|
|
96
|
+
"| **in-toto & SLSA v1.0** | Predicate: `https://slsa.dev/provenance/v1` | 🛡️ |"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
if mutation_report is not None:
|
|
100
|
+
score_val = f"{mutation_report.mutation_score:.1f}%"
|
|
101
|
+
kill_info = f"{mutation_report.killed_mutants}/{mutation_report.total_mutants} killed"
|
|
102
|
+
lines.append(f"| **Differential Mutation** | Score: `{score_val}` ({kill_info}) | 🧬 |")
|
|
103
|
+
|
|
104
|
+
lines.append("")
|
|
105
|
+
|
|
106
|
+
# 3. Supply-Chain SBOM Drift (if any)
|
|
107
|
+
if sbom_diff is not None and sbom_diff.has_modifications:
|
|
108
|
+
lines.append(
|
|
109
|
+
"<details open><summary>📦 <b>Supply-Chain Dependency Drift Detected</b></summary>\n"
|
|
110
|
+
)
|
|
111
|
+
if sbom_diff.added:
|
|
112
|
+
lines.append(f"- **Added Packages:** {', '.join(f'`{p}`' for p in sbom_diff.added)}")
|
|
113
|
+
if sbom_diff.removed:
|
|
114
|
+
rem_list = ", ".join(f"`{p}`" for p in sbom_diff.removed)
|
|
115
|
+
lines.append(f"- **Removed Packages:** {rem_list}")
|
|
116
|
+
if sbom_diff.modified:
|
|
117
|
+
mod_strs = [
|
|
118
|
+
f"`{m.package}` ({m.old_spec} -> {m.new_spec})" for m in sbom_diff.modified
|
|
119
|
+
]
|
|
120
|
+
lines.append(f"- **Modified Versions:** {', '.join(mod_strs)}")
|
|
121
|
+
lines.append("</details>\n")
|
|
122
|
+
|
|
123
|
+
# 4. Anti-Cheat Violations Section (if any)
|
|
124
|
+
if result.test_tampering_detected and result.tampering_details:
|
|
125
|
+
lines.append("<details open><summary>🚨 <b>Anti-Cheat Tampering Violations</b></summary>\n")
|
|
126
|
+
lines.append(
|
|
127
|
+
"> The candidate patch modified existing tests in a manner that weakens "
|
|
128
|
+
"regression guarantees:\n"
|
|
129
|
+
)
|
|
130
|
+
for detail in result.tampering_details:
|
|
131
|
+
lines.append(f"- ⚠️ **[VIOLATION]** {detail}")
|
|
132
|
+
lines.append("</details>\n")
|
|
133
|
+
|
|
134
|
+
# 4. Critical Test Transitions Section
|
|
135
|
+
critical_transitions = [
|
|
136
|
+
tc
|
|
137
|
+
for tc in result.test_comparisons
|
|
138
|
+
if tc.classification
|
|
139
|
+
in (
|
|
140
|
+
RegressionClassification.INTRODUCED_REGRESSION,
|
|
141
|
+
RegressionClassification.RESOLVED_DEFECT,
|
|
142
|
+
RegressionClassification.SUPPRESSION_ALERT,
|
|
143
|
+
RegressionClassification.REMOVED_TEST,
|
|
144
|
+
)
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
if critical_transitions:
|
|
148
|
+
lines.append("<details open><summary>🔍 <b>Critical Test Transitions</b></summary>\n")
|
|
149
|
+
lines.append("| Classification | Test Identifier | Shift | Message |")
|
|
150
|
+
lines.append("| :--- | :--- | :--- | :--- |")
|
|
151
|
+
for tc in critical_transitions:
|
|
152
|
+
b_val = tc.baseline_outcome.value.upper() if tc.baseline_outcome else "NONE"
|
|
153
|
+
p_val = tc.patched_outcome.value.upper() if tc.patched_outcome else "NONE"
|
|
154
|
+
msg = tc.message or "-"
|
|
155
|
+
lines.append(
|
|
156
|
+
f"| `{tc.classification.value}` | `{tc.test_name}` | `{b_val} -> {p_val}` | {msg} |"
|
|
157
|
+
)
|
|
158
|
+
lines.append("</details>\n")
|
|
159
|
+
|
|
160
|
+
# 5. Diagnostic Output (Stderr) on failure
|
|
161
|
+
err_text = result.patched_result.stderr.strip()
|
|
162
|
+
if err_text and result.verdict in (PatchVerdict.REJECTED, PatchVerdict.INFRASTRUCTURE_FAILURE):
|
|
163
|
+
lines.append("<details><summary>📋 <b>Test Execution Diagnostics (Stderr)</b></summary>\n")
|
|
164
|
+
lines.append("```text")
|
|
165
|
+
for err_line in err_text.splitlines()[:15]:
|
|
166
|
+
lines.append(err_line)
|
|
167
|
+
if len(err_text.splitlines()) > 15:
|
|
168
|
+
lines.append("... [truncated in summary, see artifact or full log]")
|
|
169
|
+
lines.append("```")
|
|
170
|
+
lines.append("</details>\n")
|
|
171
|
+
|
|
172
|
+
# 6. Footer
|
|
173
|
+
lines.append("---")
|
|
174
|
+
lines.append(
|
|
175
|
+
"*Evaluated deterministically by [PatchProof](https://github.com/ArnavSingha/Patchproof) "
|
|
176
|
+
"in zero-network container isolation.*"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""SBOM Dependency Diffing and Supply-Chain Drift Detection Subsystem.
|
|
2
|
+
|
|
3
|
+
Inspects manifests across Python (requirements.txt, pyproject.toml) and Node (package.json)
|
|
4
|
+
to detect unauthorized third-party package injections and version changes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import pathlib
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class DependencyModification:
|
|
21
|
+
"""Represents a changed dependency version specification."""
|
|
22
|
+
|
|
23
|
+
package: str
|
|
24
|
+
old_spec: str
|
|
25
|
+
new_spec: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class DependencyDiff:
|
|
30
|
+
"""Summary of dependency changes between baseline and patched workspaces."""
|
|
31
|
+
|
|
32
|
+
added: list[str] = field(default_factory=list)
|
|
33
|
+
removed: list[str] = field(default_factory=list)
|
|
34
|
+
modified: list[DependencyModification] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def has_modifications(self) -> bool:
|
|
38
|
+
"""True if any dependencies were added, removed, or modified."""
|
|
39
|
+
return bool(self.added or self.removed or self.modified)
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, Any]:
|
|
42
|
+
"""Convert diff to dictionary."""
|
|
43
|
+
return {
|
|
44
|
+
"has_modifications": self.has_modifications,
|
|
45
|
+
"added": self.added,
|
|
46
|
+
"removed": self.removed,
|
|
47
|
+
"modified": [
|
|
48
|
+
{"package": m.package, "old_spec": m.old_spec, "new_spec": m.new_spec}
|
|
49
|
+
for m in self.modified
|
|
50
|
+
],
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _parse_requirements_txt(content: str) -> dict[str, str]:
|
|
55
|
+
"""Extract package names and versions from requirements.txt."""
|
|
56
|
+
deps: dict[str, str] = {}
|
|
57
|
+
for raw_line in content.splitlines():
|
|
58
|
+
line = raw_line.strip()
|
|
59
|
+
if not line or line.startswith("#") or line.startswith("-"):
|
|
60
|
+
continue
|
|
61
|
+
parts = line.split()
|
|
62
|
+
pkg_spec = parts[0]
|
|
63
|
+
hashes = [p for p in parts[1:] if p.startswith("--hash=")]
|
|
64
|
+
match = re.match(r"^([a-zA-Z0-9_\-\.]+)(?:([=><~!].+))?$", pkg_spec)
|
|
65
|
+
if match:
|
|
66
|
+
pkg = match.group(1).lower().replace("_", "-")
|
|
67
|
+
spec = match.group(2) or "*"
|
|
68
|
+
if spec.startswith("=="):
|
|
69
|
+
spec = spec[2:]
|
|
70
|
+
if hashes:
|
|
71
|
+
spec = f"{spec} {' '.join(hashes)}"
|
|
72
|
+
deps[pkg] = spec
|
|
73
|
+
return deps
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _parse_pyproject_toml(content: str) -> dict[str, str]:
|
|
77
|
+
"""Simple parser for pyproject.toml dependencies without full toml parser dependency."""
|
|
78
|
+
deps: dict[str, str] = {}
|
|
79
|
+
in_deps_section = False
|
|
80
|
+
for line in content.splitlines():
|
|
81
|
+
stripped = line.strip()
|
|
82
|
+
if stripped in ("[project]", "dependencies = ["):
|
|
83
|
+
in_deps_section = True
|
|
84
|
+
continue
|
|
85
|
+
if in_deps_section:
|
|
86
|
+
if stripped == "]":
|
|
87
|
+
in_deps_section = False
|
|
88
|
+
continue
|
|
89
|
+
match = re.match(r'^"([a-zA-Z0-9_\-\.]+)(?:([=><~!].+))?",?$', stripped)
|
|
90
|
+
if match:
|
|
91
|
+
pkg = match.group(1).lower().replace("_", "-")
|
|
92
|
+
spec = match.group(2) or "*"
|
|
93
|
+
deps[pkg] = spec
|
|
94
|
+
return deps
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _parse_package_json(content: str) -> dict[str, str]:
|
|
98
|
+
"""Parse Node package.json dependencies."""
|
|
99
|
+
deps: dict[str, str] = {}
|
|
100
|
+
try:
|
|
101
|
+
data = json.loads(content)
|
|
102
|
+
for dep_key in ("dependencies", "devDependencies"):
|
|
103
|
+
if isinstance(data.get(dep_key), dict):
|
|
104
|
+
for pkg, spec in data[dep_key].items():
|
|
105
|
+
deps[pkg.lower()] = str(spec)
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
return deps
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def extract_dependencies_from_dir(directory: pathlib.Path) -> dict[str, str]:
|
|
112
|
+
"""Extract declared package dependencies from all manifest files in directory."""
|
|
113
|
+
deps: dict[str, str] = {}
|
|
114
|
+
|
|
115
|
+
reqs_path = directory / "requirements.txt"
|
|
116
|
+
if reqs_path.is_file():
|
|
117
|
+
deps.update(_parse_requirements_txt(reqs_path.read_text(encoding="utf-8", errors="ignore")))
|
|
118
|
+
|
|
119
|
+
pyproj_path = directory / "pyproject.toml"
|
|
120
|
+
if pyproj_path.is_file():
|
|
121
|
+
deps.update(_parse_pyproject_toml(pyproj_path.read_text(encoding="utf-8", errors="ignore")))
|
|
122
|
+
|
|
123
|
+
pkg_json_path = directory / "package.json"
|
|
124
|
+
if pkg_json_path.is_file():
|
|
125
|
+
deps.update(_parse_package_json(pkg_json_path.read_text(encoding="utf-8", errors="ignore")))
|
|
126
|
+
|
|
127
|
+
return deps
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def diff_declared_dependencies(
|
|
131
|
+
baseline_dir: pathlib.Path,
|
|
132
|
+
patched_dir: pathlib.Path,
|
|
133
|
+
) -> DependencyDiff:
|
|
134
|
+
"""Compare manifests between baseline and patched workspace directories."""
|
|
135
|
+
base_deps = extract_dependencies_from_dir(baseline_dir)
|
|
136
|
+
patched_deps = extract_dependencies_from_dir(patched_dir)
|
|
137
|
+
|
|
138
|
+
added = sorted([pkg for pkg in patched_deps if pkg not in base_deps])
|
|
139
|
+
removed = sorted([pkg for pkg in base_deps if pkg not in patched_deps])
|
|
140
|
+
modified: list[DependencyModification] = []
|
|
141
|
+
|
|
142
|
+
for pkg in sorted(base_deps.keys()):
|
|
143
|
+
if pkg in patched_deps and base_deps[pkg] != patched_deps[pkg]:
|
|
144
|
+
modified.append(
|
|
145
|
+
DependencyModification(
|
|
146
|
+
package=pkg,
|
|
147
|
+
old_spec=base_deps[pkg],
|
|
148
|
+
new_spec=patched_deps[pkg],
|
|
149
|
+
)
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
return DependencyDiff(added=added, removed=removed, modified=modified)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Sandbox isolation and execution subsystem for PatchProof."""
|
|
2
|
+
|
|
3
|
+
from patchproof.sandbox.classifier import RegressionClassifier
|
|
4
|
+
from patchproof.sandbox.comparative import ComparativeRunner
|
|
5
|
+
from patchproof.sandbox.docker_cli import (
|
|
6
|
+
DockerCommandBuilder,
|
|
7
|
+
DockerPreflight,
|
|
8
|
+
DockerPreflightResult,
|
|
9
|
+
EnvironmentSanitizer,
|
|
10
|
+
parse_test_command,
|
|
11
|
+
)
|
|
12
|
+
from patchproof.sandbox.doctor import DoctorCheckResult, SystemDoctor
|
|
13
|
+
from patchproof.sandbox.parser import PytestOutputParser
|
|
14
|
+
from patchproof.sandbox.runner import (
|
|
15
|
+
ContainerRunner,
|
|
16
|
+
OrphanSweeper,
|
|
17
|
+
is_docker_available,
|
|
18
|
+
)
|
|
19
|
+
from patchproof.sandbox.setup_runner import DEFAULT_RUNNER_TAG, build_runner_image
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DEFAULT_RUNNER_TAG",
|
|
23
|
+
"ComparativeRunner",
|
|
24
|
+
"ContainerRunner",
|
|
25
|
+
"DockerCommandBuilder",
|
|
26
|
+
"DockerPreflight",
|
|
27
|
+
"DockerPreflightResult",
|
|
28
|
+
"DoctorCheckResult",
|
|
29
|
+
"EnvironmentSanitizer",
|
|
30
|
+
"OrphanSweeper",
|
|
31
|
+
"PytestOutputParser",
|
|
32
|
+
"RegressionClassifier",
|
|
33
|
+
"SystemDoctor",
|
|
34
|
+
"build_runner_image",
|
|
35
|
+
"is_docker_available",
|
|
36
|
+
"parse_test_command",
|
|
37
|
+
]
|