Download research/harden.py from Helinity/python-security-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/harden.py
- Command line
-
hf download hf://datasets/Helinity/python-security-benchmark/research/harden.py
-
curl -L -o harden.py https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/harden.py
7.32 kB
| """Produce versioned Phase 3B evidence and conservative scoring eligibility.""" | |
| import argparse | |
| from collections import Counter | |
| from hashlib import sha256 | |
| import json | |
| from pathlib import Path | |
| from .build import OUTPUT, json_bytes, jsonl_bytes, release, compare_release | |
| from .catalog import validate_rows | |
| from .leakage import similarity, validate_split_boundaries | |
| from .verify import run_verification | |
| DESTINATION = OUTPUT / "v3b2" | |
| MOCK_PATTERNS = { | |
| "workspace-export-capability", "project-archive-permission", | |
| "handoff-cookie-transport-policy", "secure-browser-policy-cookie", | |
| "billing-https-context-verification", "mail-relay-tls-trust-source", | |
| "tls-guard-at-connector", "download-grant-random-token", | |
| "device-pairing-random-code", "worker-tool-registry", | |
| "internal-shell-status", "local-value-roundtrip", | |
| } | |
| # These outcomes are direct local observations of the named property. | |
| RUNTIME_PATTERNS = { | |
| "moderation-note-log-framing", "sync-result-log-event-catalog", | |
| "thumbnail-filesystem-error", "ledger-database-error", | |
| "reset-token-log-minimization", "gateway-header-log-allowlist", | |
| "profile-bearer-request-location", "account-recovery-post-body", | |
| "dashboard-session-cookie-transport", | |
| "outbound-metrics-credential-source", "inbound-hook-shared-secret-source", | |
| "billing-rollup-capability", "support-ticket-audit", | |
| "fulfillment-diagnostics", "approved-dashboard-sort", "opaque-help-asset", | |
| "audit-selection-before-serialize", "exception-observer", | |
| "reproducible-layout-jitter", | |
| } | |
| def build(): | |
| from .critical import run | |
| critical = run() | |
| evidence = run_verification() | |
| recorded = json.loads((OUTPUT / "evidence.json").read_bytes()) | |
| if evidence != recorded: | |
| raise ValueError("Phase 3A evidence differs from a fresh execution") | |
| expected, _ = release(evidence) | |
| compare_release(expected) | |
| rows = [ | |
| json.loads(line) | |
| for split in ("train", "validation", "test") | |
| for line in (OUTPUT / "corpus" / f"{split}.jsonl").read_bytes().splitlines() | |
| ] | |
| validate_rows(rows, evidence) | |
| report = similarity(rows) | |
| validate_split_boundaries(rows, report) | |
| annotations = [] | |
| for row in sorted(rows, key=lambda item: item["sample_id"]): | |
| pattern = row["pattern"] | |
| levels = ["syntax_verified"] | |
| critical_case = critical["cases"].get(pattern) | |
| if row["verification_status"] == "behavior_verified": | |
| if pattern in MOCK_PATTERNS: | |
| levels.append("mock_boundary_behavior_verified") | |
| elif pattern in RUNTIME_PATTERNS: | |
| levels.append("isolated_runtime_behavior_verified") | |
| else: | |
| levels.append("parser_output_behavior_verified") | |
| if critical_case: | |
| levels.append("isolated_runtime_behavior_verified") | |
| eligible = "isolated_runtime_behavior_verified" in levels | |
| annotations.append({ | |
| "sample_id": row["sample_id"], | |
| "pair_id": row["pair_id"], | |
| "split": row["split"], | |
| "cwe_id": row["cwe_id"], | |
| "legacy_status": row["verification_status"], | |
| "current_status": "behavior_verified" if critical_case else row["verification_status"], | |
| "evidence_levels": levels, | |
| "score_eligible": eligible, | |
| "independent_review": None, | |
| "source_review": "AI-assisted source reassessment; not independent validation", | |
| "source_review_note": row["review_note"], | |
| "evidence_reference": ( | |
| f"data/research/v3b2/critical-runtime.json::cases/{pattern}" | |
| if critical_case else row["evidence_reference"] | |
| ), | |
| "scope": evidence["cases"].get(pattern, {}).get("method"), | |
| "record_sha256": sha256(json_bytes(row)).hexdigest(), | |
| }) | |
| by_id = {row["sample_id"]: row for row in rows} | |
| dispositions = [] | |
| for edge in report["near_matches"]: | |
| left, right = by_id[edge["left"]], by_id[edge["right"]] | |
| intentional = left["pair_id"] is not None and left["pair_id"] == right["pair_id"] | |
| dispositions.append({ | |
| **edge, | |
| "left_pattern": left["pattern"], "right_pattern": right["pattern"], | |
| "disposition": "intentional_secure_insecure_pair" if intentional else "semantic_variant", | |
| "same_split": left["split"] == right["split"], | |
| "reason": "The compared implementations share structure; differing controls or use contexts are retained for paired or false-positive analysis.", | |
| }) | |
| summary = { | |
| "samples": len(rows), | |
| "new_behavior_verified": 16, | |
| "evidence_level_counts": dict(Counter(level for row in annotations for level in row["evidence_levels"])), | |
| "eligible_samples": sum(row["score_eligible"] for row in annotations), | |
| "previous_status_counts": dict(Counter(row["legacy_status"] for row in annotations)), | |
| "critical_positive_verification_blocker": None, | |
| "human_reviews": 0, | |
| } | |
| artifacts = { | |
| "critical-runtime.json": json_bytes(critical), | |
| "annotations.json": json_bytes(annotations), | |
| "near_duplicate_dispositions.json": json_bytes(dispositions), | |
| "summary.json": json_bytes(summary), | |
| } | |
| accepted = {item["sample_id"] for item in annotations if item["score_eligible"]} | |
| for split in ("train", "validation", "test"): | |
| selected = sorted( | |
| (row for row in rows if row["split"] == split and row["sample_id"] in accepted), | |
| key=lambda row: row["sample_id"], | |
| ) | |
| for index, row in enumerate(selected): | |
| if row["pattern"] in critical["cases"]: | |
| row = row.copy() | |
| row["verification_status"] = "behavior_verified" | |
| row["verification_method"] = "isolated_linux_runtime" | |
| row["evidence_reference"] = f"data/research/v3b2/critical-runtime.json::cases/{row['pattern']}" | |
| selected[index] = row | |
| members = Counter(row["pair_id"] for row in selected if row["pair_id"]) | |
| if any(count != 2 for count in members.values()): | |
| raise ValueError("Official subset contains an incomplete pair") | |
| artifacts[f"official/{split}.jsonl"] = jsonl_bytes(selected) | |
| return artifacts | |
| def official_data(split): | |
| artifacts = build() | |
| for name, content in artifacts.items(): | |
| path = DESTINATION / name | |
| if not path.exists() or path.read_bytes() != content: | |
| raise ValueError(f"Stale official eligibility artifact: {name}") | |
| return artifacts[f"official/{split}.jsonl"], sha256(artifacts["annotations.json"]).hexdigest() | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--check", action="store_true") | |
| args = parser.parse_args() | |
| artifacts = build() | |
| for name, data in artifacts.items(): | |
| path = DESTINATION / name | |
| if args.check: | |
| if not path.exists() or path.read_bytes() != data: | |
| raise ValueError(f"Stale Phase 3B artifact: {name}") | |
| else: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_bytes(data) | |
| print("Phase 3B annotations and duplicate dispositions verified.") | |
| if __name__ == "__main__": | |
| main() | |