From 3e1342fad00784b1d9bb4fdffd8db3eac51cd013 Mon Sep 17 00:00:00 2001 From: omkarande14 <284905859+omkarande14@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:13:24 +0530 Subject: [PATCH] fix(integrity): enforce ledger provenance checks, delete fabricated data, and isolate forbidden hashes --- .gitignore | 4 + app/rrsi/evaluator.py | 49 ++++++++- app/rrsi/ledger.py | 126 +++++++++++++++++----- app/rrsi/screening.py | 16 +-- app/rrsi/taxonomy.py | 43 +++++--- data/rrsi/experiment_ledger.json | 34 +----- scripts/check_git_hygiene.py | 172 ++++++++++++++++++++++--------- tests/test_ledger_provenance.py | 169 ++++++++++++++++++++++++++++++ 8 files changed, 480 insertions(+), 133 deletions(-) create mode 100644 tests/test_ledger_provenance.py diff --git a/.gitignore b/.gitignore index 0a016ee..5ff8139 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,8 @@ reports/* # Snapshots of unredacted state private_snapshots/ +golden_outputs/ + +# Sensitive local config +config/forbidden_hashes.json diff --git a/app/rrsi/evaluator.py b/app/rrsi/evaluator.py index 7708b3f..3fe756c 100644 --- a/app/rrsi/evaluator.py +++ b/app/rrsi/evaluator.py @@ -10,7 +10,11 @@ Statistical Evaluator & Selection Decision Engine. """ import math +import json +import hashlib +import time import subprocess +from pathlib import Path from decimal import Decimal from typing import Dict, Any, List, Optional, Tuple, Set @@ -450,11 +454,48 @@ class StatisticalEvaluator: c_cnt = candidate_selection.failure_breakdown.get(cat.value, 0) failure_deltas[cat.value] = c_cnt - b_cnt + # 6. Provenance & Artifact Generation + b_commit = git_base_ref or "HEAD~1" + c_commit = "HEAD" + diff_hash = "no_diff_clean" + try: + res_c = subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True) + if res_c.returncode == 0 and res_c.stdout.strip(): + c_commit = res_c.stdout.strip() + res_diff = subprocess.run(["git", "diff", b_commit], capture_output=True, text=True) + if res_diff.stdout: + diff_hash = hashlib.sha256(res_diff.stdout.encode("utf-8")).hexdigest()[:16] + else: + diff_hash = hashlib.sha256(hypothesis.proposal_id.encode("utf-8")).hexdigest()[:16] + except Exception: + diff_hash = hashlib.sha256(hypothesis.proposal_id.encode("utf-8")).hexdigest()[:16] + + run_id = f"eval_{hypothesis.proposal_id}_{int(time.time())}" + eval_payload = { + "eval_run_id": run_id, + "proposal_id": hypothesis.proposal_id, + "timestamp": time.time(), + "baseline_commit": b_commit, + "candidate_commit": c_commit, + "git_diff_hash": diff_hash, + "doc_results": {d: res.to_dict() for d, res in candidate_selection.doc_results.items()}, + "per_field_metrics": {f: m.to_dict() for f, m in candidate_selection.per_field_metrics.items()} + } + eval_bytes = json.dumps(eval_payload, indent=2).encode("utf-8") + eval_sha = hashlib.sha256(eval_bytes).hexdigest() + + eval_dir = Path("reports/evaluations") + eval_dir.mkdir(parents=True, exist_ok=True) + results_file = eval_dir / f"{run_id}.json" + results_file.write_bytes(eval_bytes) + return DecisionRecord( proposal_id=hypothesis.proposal_id, area=hypothesis.area.value, status=status, process_outcome=process_outcome, + measurement_status="measured", + integrity_exempt=False, baseline_accuracy=baseline_selection.macro_accuracy, candidate_accuracy=candidate_selection.macro_accuracy, delta_accuracy=round(delta_acc, 2), @@ -470,5 +511,11 @@ class StatisticalEvaluator: rejection_reasons=rejection_reasons, pruning_recommendations=[], failure_deltas=failure_deltas, - provenance=hypothesis.provenance + provenance=hypothesis.provenance, + eval_run_id=str(results_file.as_posix()), + eval_results_sha256=eval_sha, + baseline_commit=b_commit, + candidate_commit=c_commit, + git_commit_hash=c_commit, + git_diff_hash=diff_hash ) diff --git a/app/rrsi/ledger.py b/app/rrsi/ledger.py index 9dbb142..b6362c3 100644 --- a/app/rrsi/ledger.py +++ b/app/rrsi/ledger.py @@ -1,11 +1,5 @@ -# app/rrsi/ledger.py -""" -Auditable Experiment Ledger. -Persists all RRSI experiment decisions, error breakdowns, and metric deltas to data/rrsi/experiment_ledger.json. -Provides human-readable summaries and regression tracking. -""" - import json +import hashlib from pathlib import Path from typing import Dict, Any, List, Optional @@ -41,8 +35,72 @@ class ExperimentLedger: with open(self.ledger_path, "w", encoding="utf-8") as f: json.dump(self.records, f, indent=2) - def append(self, decision: DecisionRecord): - """Appends a new decision record to the auditable ledger.""" + def append(self, decision: DecisionRecord, results_dir: Optional[Path] = None): + """ + Appends a new decision record to the auditable ledger. + Enforces strict cryptographic and empirical provenance: + - Hand-supplied numeric metric numbers without a verified evaluation run file are rejected. + - Measured runs require eval_run_id pointing to a valid results file whose sha256 matches eval_results_sha256, + plus baseline_commit, candidate_commit, and git_diff_hash. + - not_measured runs must have integrity_exempt=True and all numeric metrics set to None. + """ + if decision.measurement_status == "not_measured": + if not decision.integrity_exempt: + raise ValueError("Unmeasured decision records must have integrity_exempt=True.") + numeric_fields = [ + decision.baseline_accuracy, decision.candidate_accuracy, + decision.delta_accuracy, decision.paired_ci_lower, + decision.paired_ci_upper, decision.latency_delta_seconds + ] + if any(f is not None for f in numeric_fields): + raise ValueError("Unmeasured decision records cannot contain hand-supplied numeric metrics. All numeric metrics must be None.") + elif decision.measurement_status == "measured": + if not decision.eval_run_id: + raise ValueError("Measured decision record requires a valid eval_run_id pointing to saved evaluation results.") + if not decision.eval_results_sha256: + raise ValueError("Measured decision record requires eval_results_sha256.") + if not decision.baseline_commit: + raise ValueError("Measured decision record requires baseline_commit.") + if not decision.candidate_commit: + raise ValueError("Measured decision record requires candidate_commit.") + if not decision.git_diff_hash: + raise ValueError("Measured decision record requires a non-empty git_diff_hash.") + + # Validate results file path and checksum + results_path = Path(decision.eval_run_id) + if not results_path.exists() and results_dir: + results_path = results_dir / decision.eval_run_id + if not results_path.exists() and not results_path.is_absolute(): + for search_dir in [Path("data_private/evaluations"), Path("reports/evaluations")]: + cand = search_dir / decision.eval_run_id + if cand.exists(): + results_path = cand + break + if cand.with_suffix(".json").exists(): + results_path = cand.with_suffix(".json") + break + + if not results_path.exists(): + raise FileNotFoundError(f"Evaluation results file '{decision.eval_run_id}' not found.") + + content_bytes = results_path.read_bytes() + computed_sha = hashlib.sha256(content_bytes).hexdigest() + if computed_sha.lower() != decision.eval_results_sha256.lower(): + raise ValueError( + f"Integrity violation: eval_results_sha256 mismatch for '{decision.eval_run_id}'. " + f"Expected {decision.eval_results_sha256}, got {computed_sha}." + ) + + # Ensure the results file actually contains per-doc / per-field outcomes structure + try: + run_data = json.loads(content_bytes.decode("utf-8")) + if not (isinstance(run_data, dict) and any(k in run_data for k in ["doc_results", "field_outcomes", "per_field_metrics", "invoices"])): + raise ValueError(f"Evaluation results file '{decision.eval_run_id}' missing per-doc / per-field outcomes structure.") + except json.JSONDecodeError: + raise ValueError(f"Evaluation results file '{decision.eval_run_id}' is not valid JSON.") + else: + raise ValueError(f"Unknown measurement_status '{decision.measurement_status}'. Must be 'measured' or 'not_measured'.") + self.records.append(decision.to_dict()) self.save() @@ -55,18 +113,29 @@ class ExperimentLedger: def generate_markdown_summary(self, decision: DecisionRecord) -> str: """Generates a structured, auditable Markdown report for a candidate decision.""" - status_badge = "[ACCEPTED]" if decision.status == ExperimentStatus.ACCEPTED else "[REJECTED]" - delta_sign = "+" if decision.delta_accuracy > 0 else "" + status_val = decision.status.value if isinstance(decision.status, ExperimentStatus) else decision.status + status_badge = "[ACCEPTED]" if status_val == ExperimentStatus.ACCEPTED.value else "[REJECTED]" + + if decision.measurement_status == "not_measured": + b_acc = "Not Measured (Integrity Exempt)" + c_acc = "Not Measured (Integrity Exempt)" + dt_str = "N/A" + else: + delta_val = decision.delta_accuracy if decision.delta_accuracy is not None else 0.0 + delta_sign = "+" if delta_val > 0 else "" + b_acc = f"{decision.baseline_accuracy:.2f}%" if decision.baseline_accuracy is not None else "N/A" + c_acc = f"{decision.candidate_accuracy:.2f}% ({delta_sign}{delta_val:.2f}%)" if decision.candidate_accuracy is not None else "N/A" + dt_str = f"{decision.latency_delta_seconds:+.2f}s" if decision.latency_delta_seconds is not None else "N/A" lines = [ f"### RRSI Evaluation Report: `{decision.proposal_id}` ({status_badge})", f"- **Target Area**: `{decision.area}`", - f"- **Baseline Accuracy**: `{decision.baseline_accuracy:.2f}%`", - f"- **Candidate Accuracy**: `{decision.candidate_accuracy:.2f}%` ({delta_sign}{decision.delta_accuracy:.2f}%)", - f"- **Statistical Noise Floor**: `+/-{decision.noise_floor:.2f}%`", - f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO (Indistinguishable from luck/noise)'}`", - f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED (Memorization/Cheating detected)'}`", - f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED (Latency/Cost budget exceeded)'}` (dt: {decision.latency_delta_seconds:+.2f}s)", + f"- **Measurement Status**: `{decision.measurement_status}` (Integrity Exempt: {decision.integrity_exempt})", + f"- **Baseline Accuracy**: `{b_acc}`", + f"- **Candidate Accuracy**: `{c_acc}`", + f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`", + f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED'}`", + f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED'}` (dt: {dt_str})", "" ] @@ -88,16 +157,17 @@ class ExperimentLedger: lines.append(f"- [PRUNE] {pr}") lines.append("") - lines.append("#### Failure Deltas by Error Category:") - lines.append("| Error Category | Delta vs Baseline | Status |") - lines.append("| :--- | :---: | :---: |") - for cat, delta in decision.failure_deltas.items(): - if delta < 0: - icon = f"[REDUCED] by {abs(delta)}" - elif delta > 0: - icon = f"[INCREASED] by {delta}" - else: - icon = "[UNCHANGED] (0)" - lines.append(f"| `{cat}` | {delta:+d} | {icon} |") + if decision.failure_deltas: + lines.append("#### Failure Deltas by Error Category:") + lines.append("| Error Category | Delta vs Baseline | Status |") + lines.append("| :--- | :---: | :---: |") + for cat, delta in decision.failure_deltas.items(): + if delta < 0: + icon = f"[REDUCED] by {abs(delta)}" + elif delta > 0: + icon = f"[INCREASED] by {delta}" + else: + icon = "[UNCHANGED] (0)" + lines.append(f"| `{cat}` | {delta:+d} | {icon} |") return "\n".join(lines) diff --git a/app/rrsi/screening.py b/app/rrsi/screening.py index ebf99e2..73922c9 100644 --- a/app/rrsi/screening.py +++ b/app/rrsi/screening.py @@ -39,14 +39,14 @@ class LeakageScreening: @classmethod def _load_forbidden_hashes(cls) -> Tuple[str, set]: - cfg_path = Path("config/forbidden_hashes.json") - if cfg_path.exists(): - try: - with open(cfg_path, "r", encoding="utf-8") as f: - data = json.load(f) - return data.get("salt", ""), set(data.get("hashes", [])) - except Exception: - pass + for p in [Path("data_private/config/forbidden_hashes.json"), Path("config/forbidden_hashes.json")]: + if p.exists(): + try: + with open(p, "r", encoding="utf-8") as f: + data = json.load(f) + return data.get("salt", ""), set(data.get("hashes", [])) + except Exception: + pass return "", set() @classmethod diff --git a/app/rrsi/taxonomy.py b/app/rrsi/taxonomy.py index 552bff1..4045d9d 100644 --- a/app/rrsi/taxonomy.py +++ b/app/rrsi/taxonomy.py @@ -263,25 +263,36 @@ class DecisionRecord: area: str status: ExperimentStatus process_outcome: ProcessOutcome - baseline_accuracy: float - candidate_accuracy: float - delta_accuracy: float - paired_ci_lower: float - paired_ci_upper: float - is_statistically_significant: bool - leakage_screen_passed: bool - leakage_findings: List[str] - cost_aware_accepted: bool - latency_delta_seconds: float - vision_fallback_calls: int - case_regressions: List[str] - rejection_reasons: List[str] - pruning_recommendations: List[str] - failure_deltas: Dict[str, int] + measurement_status: str = "measured" # "measured" | "not_measured" + integrity_exempt: bool = False # True for leak/overfit removals + baseline_accuracy: Optional[float] = None + candidate_accuracy: Optional[float] = None + delta_accuracy: Optional[float] = None + paired_ci_lower: Optional[float] = None + paired_ci_upper: Optional[float] = None + is_statistically_significant: bool = False + leakage_screen_passed: bool = True + leakage_findings: List[str] = field(default_factory=list) + cost_aware_accepted: bool = False + latency_delta_seconds: Optional[float] = None + vision_fallback_calls: int = 0 + case_regressions: List[str] = field(default_factory=list) + rejection_reasons: List[str] = field(default_factory=list) + pruning_recommendations: List[str] = field(default_factory=list) + failure_deltas: Dict[str, int] = field(default_factory=dict) provenance: str = "real" + eval_run_id: Optional[str] = None + eval_results_sha256: Optional[str] = None + baseline_commit: Optional[str] = None + candidate_commit: Optional[str] = None git_commit_hash: str = "" git_diff_hash: str = "" timestamp: float = field(default_factory=time.time) def to_dict(self) -> Dict[str, Any]: - return asdict(self) + res = asdict(self) + if isinstance(self.status, ExperimentStatus): + res["status"] = self.status.value + if isinstance(self.process_outcome, ProcessOutcome): + res["process_outcome"] = self.process_outcome.value + return res diff --git a/data/rrsi/experiment_ledger.json b/data/rrsi/experiment_ledger.json index dd7b93a..0637a08 100644 --- a/data/rrsi/experiment_ledger.json +++ b/data/rrsi/experiment_ledger.json @@ -1,33 +1 @@ -[ - { - "proposal_id": "REMOVE-HARDCODES", - "area": "entity_extraction", - "status": "accepted", - "process_outcome": "accepted", - "baseline_accuracy": 95.0, - "candidate_accuracy": 95.0, - "delta_accuracy": 0.0, - "paired_ci_lower": 0.0, - "paired_ci_upper": 0.0, - "is_statistically_significant": false, - "leakage_screen_passed": true, - "leakage_findings": [], - "cost_aware_accepted": true, - "latency_delta_seconds": -0.5, - "vision_fallback_calls": 0, - "case_regressions": [], - "rejection_reasons": [], - "pruning_recommendations": [ - "Pruned hardcoded static PAN, hardcoded hospital name overrides, and static pixel thresholds (550, 300, 220.0, 350.0) in favor of dynamic relative layout geometry." - ], - "failure_deltas": { - "amount_parse": 0, - "totals_arithmetic": 0, - "hallucination": 0 - }, - "provenance": "real", - "git_commit_hash": "aff9aad", - "git_diff_hash": "", - "timestamp": 1790594845.2201421 - } -] \ No newline at end of file +[] \ No newline at end of file diff --git a/scripts/check_git_hygiene.py b/scripts/check_git_hygiene.py index 329dc3c..d7c94cc 100644 --- a/scripts/check_git_hygiene.py +++ b/scripts/check_git_hygiene.py @@ -5,8 +5,10 @@ Fails on: 1. Real GSTINs matching \b\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]\b 2. Real PAN numbers matching \b[A-Z]{5}\d{4}[A-Z]\b 3. Indian phone numbers -4. Salted hashes of sensitive vendor and buyer names (from config/forbidden_hashes.json) +4. Salted hashes of sensitive vendor and buyer names (when data_private/config/forbidden_hashes.json exists) 5. Tracked private data paths (data_private/, data/deskewed/, venv/, .venv/, etc.) +Supports: +--history : Scans all historical commit messages and blob objects across repository history. """ import re @@ -14,6 +16,7 @@ import subprocess import sys import json import hashlib +import argparse from pathlib import Path # RegEx for sensitive identifiers @@ -38,22 +41,68 @@ FORBIDDEN_PATH_SUBSTRINGS = [ "venv/", ".venv/", "scratch/", - "private_snapshots" + "private_snapshots", + "golden_outputs" ] def load_forbidden_hashes(): - cfg_path = Path("config/forbidden_hashes.json") - if cfg_path.exists(): - try: - with open(cfg_path, "r", encoding="utf-8") as f: - data = json.load(f) - return data.get("salt", ""), set(data.get("hashes", [])) - except Exception: - pass + # Priority: private config path, then legacy config path + for p in [Path("data_private/config/forbidden_hashes.json"), Path("config/forbidden_hashes.json")]: + if p.exists(): + try: + with open(p, "r", encoding="utf-8") as f: + data = json.load(f) + return data.get("salt", ""), set(data.get("hashes", [])) + except Exception: + pass return "", set() +def run_synthetic_canary_test() -> bool: + """Verifies that the regex checkers are functional and catch synthetic leaks.""" + fake_gstin = "27ABCDE1234F1Z5" + fake_pan = "ABCDE1234F" + fake_phone = "9822012345" + + assert bool(GSTIN_REGEX.search(fake_gstin)), "Canary failed: GSTIN regex broken" + assert bool(PAN_REGEX.search(fake_pan)), "Canary failed: PAN regex broken" + assert bool(PHONE_REGEX.search(fake_phone)), "Canary failed: PHONE regex broken" + assert fake_gstin not in SYNTHETIC_WHITELIST, "Canary failed: Whitelist collision" + return True + +def scan_text_lines(text: str, source_label: str, salt: str, forbidden_hashes: set) -> list[str]: + violations = [] + lines = text.splitlines() + for line_no, line in enumerate(lines, 1): + if "re.compile" in line or "REGEX" in line or "pattern" in line or "SYNTHETIC_WHITELIST" in line: + continue + + for match in GSTIN_REGEX.findall(line): + if match not in SYNTHETIC_WHITELIST: + violations.append(f"PII LEAK (GSTIN): Found '{match}' in {source_label}:{line_no}") + + for match in PAN_REGEX.findall(line): + if match not in SYNTHETIC_WHITELIST: + violations.append(f"PII LEAK (PAN): Found '{match}' in {source_label}:{line_no}") + + for match in PHONE_REGEX.findall(line): + if match not in SYNTHETIC_WHITELIST: + violations.append(f"PII LEAK (PHONE): Found '{match}' in {source_label}:{line_no}") + + if salt and forbidden_hashes: + tokens = [t.lower().strip(" \t\r\n'\",;:.()[]{}") for t in line.split() if len(t.strip()) >= 4] + for token in tokens: + thash = hashlib.sha256((salt + token).encode("utf-8")).hexdigest() + if thash in forbidden_hashes: + violations.append(f"FORBIDDEN ENTITY (Salted Hash): '{token}' in {source_label}:{line_no}") + for i in range(len(tokens) - 1): + bigram = f"{tokens[i]} {tokens[i+1]}" + bhash = hashlib.sha256((salt + bigram).encode("utf-8")).hexdigest() + if bhash in forbidden_hashes: + violations.append(f"FORBIDDEN ENTITY (Salted Hash): '{bigram}' in {source_label}:{line_no}") + + return violations + def get_staged_or_tracked_files() -> list[str]: - # Check staged files if any, else check tracked files res = subprocess.run(["git", "diff", "--cached", "--name-only"], capture_output=True, text=True) files = [f.strip() for f in res.stdout.splitlines() if f.strip()] if not files: @@ -61,61 +110,32 @@ def get_staged_or_tracked_files() -> list[str]: files = [f.strip() for f in res2.stdout.splitlines() if f.strip()] return files -def check_hygiene() -> bool: +def check_current_hygiene() -> bool: + run_synthetic_canary_test() files = get_staged_or_tracked_files() violations = [] salt, forbidden_hashes = load_forbidden_hashes() + if not forbidden_hashes: + print("[*] Running in Public/CI mode: Regex + Synthetic Canaries active (private hash list omitted).") + for f_str in files: p = Path(f_str) - # Check path restrictions norm_path = f_str.replace("\\", "/") for forbidden in FORBIDDEN_PATH_SUBSTRINGS: if forbidden in norm_path: violations.append(f"FORBIDDEN FILE TRACKED: '{f_str}' is inside private/ignored directory '{forbidden}'.") - # Skip binary files, gitignore, forbidden hash file, and this hygiene checker itself if f_str in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"] or p.suffix.lower() in [".png", ".jpg", ".pdf", ".pyc", ".zip"]: continue if p.exists() and p.is_file(): try: content = p.read_text(encoding="utf-8", errors="ignore") + violations.extend(scan_text_lines(content, f_str, salt, forbidden_hashes)) except Exception: continue - lines = content.splitlines() - for line_no, line in enumerate(lines, 1): - # Ignore lines defining regexes - if "re.compile" in line or "REGEX" in line or "pattern" in line: - continue - - for match in GSTIN_REGEX.findall(line): - if match not in SYNTHETIC_WHITELIST: - violations.append(f"PII LEAK (GSTIN): Found '{match}' in {f_str}:{line_no}") - - for match in PAN_REGEX.findall(line): - if match not in SYNTHETIC_WHITELIST: - violations.append(f"PII LEAK (PAN): Found '{match}' in {f_str}:{line_no}") - - for match in PHONE_REGEX.findall(line): - if match not in SYNTHETIC_WHITELIST: - violations.append(f"PII LEAK (PHONE): Found '{match}' in {f_str}:{line_no}") - - # Salted hash name check (single tokens and bigrams) - if salt and forbidden_hashes: - tokens = [t.lower().strip(" \t\r\n'\",;:.()[]{}") for t in line.split() if len(t.strip()) >= 4] - for token in tokens: - thash = hashlib.sha256((salt + token).encode("utf-8")).hexdigest() - if thash in forbidden_hashes: - violations.append(f"FORBIDDEN ENTITY NAME (Salted Hash Match): '{token}' in {f_str}:{line_no}") - # Check bigrams - for i in range(len(tokens) - 1): - bigram = f"{tokens[i]} {tokens[i+1]}" - bhash = hashlib.sha256((salt + bigram).encode("utf-8")).hexdigest() - if bhash in forbidden_hashes: - violations.append(f"FORBIDDEN ENTITY NAME (Salted Hash Match): '{bigram}' in {f_str}:{line_no}") - if violations: print("[!] GIT HYGIENE CHECK FAILED:") for v in violations: @@ -125,7 +145,65 @@ def check_hygiene() -> bool: print("[+] Git hygiene check passed cleanly: No un-anonymized PII, real GSTINs, or private data tracked.") return True +def scan_full_history() -> bool: + print("[*] Performing full git history scan across all commits and blobs...") + run_synthetic_canary_test() + salt, forbidden_hashes = load_forbidden_hashes() + violations = [] + + res_commits = subprocess.run(["git", "log", "--all", "--format=%H"], capture_output=True, text=True) + commits = [c.strip() for c in res_commits.stdout.splitlines() if c.strip()] + + print(f" Scanning {len(commits)} commits for commit message and file blob leaks...") + scanned_blobs = set() + + for commit in commits: + # Check commit message + res_msg = subprocess.run(["git", "log", "-1", "--format=%B", commit], capture_output=True, text=True) + msg_violations = scan_text_lines(res_msg.stdout, f"commit {commit[:7]} message", salt, forbidden_hashes) + violations.extend(msg_violations) + + # Check all blobs in commit + res_tree = subprocess.run(["git", "ls-tree", "-r", commit], capture_output=True, text=True) + for line in res_tree.stdout.splitlines(): + parts = line.split() + if len(parts) >= 4 and parts[1] == "blob": + blob_hash = parts[2] + file_path = line.split(maxsplit=3)[3].strip() + + norm_path = file_path.replace("\\", "/") + for forbidden in FORBIDDEN_PATH_SUBSTRINGS: + if forbidden in norm_path: + violations.append(f"HISTORICAL FORBIDDEN FILE: '{file_path}' in commit {commit[:7]}") + + if blob_hash in scanned_blobs: + continue + scanned_blobs.add(blob_hash) + + if any(file_path.endswith(ext) for ext in [".png", ".jpg", ".pdf", ".pyc", ".zip"]): + continue + if file_path in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"]: + continue + + res_blob = subprocess.run(["git", "cat-file", "-p", blob_hash], capture_output=True, text=True, errors="ignore") + blob_violations = scan_text_lines(res_blob.stdout, f"blob {blob_hash[:7]} ({file_path}) in {commit[:7]}", salt, forbidden_hashes) + violations.extend(blob_violations) + + if violations: + print("[!] FULL GIT HISTORY AUDIT FAILED:") + for v in violations: + print(f" - {v}") + return False + + print(f"[+] Full git history audit PASSED cleanly: {len(commits)} commits and {len(scanned_blobs)} blobs verified zero-leak.") + return True + if __name__ == "__main__": - if not check_hygiene(): + parser = argparse.ArgumentParser(description="Git Hygiene and PII Leakage Auditor") + parser.add_argument("--history", action="store_true", help="Scan entire repository commit history and blob tree") + args = parser.parse_args() + + success = scan_full_history() if args.history else check_current_hygiene() + if not success: sys.exit(1) sys.exit(0) diff --git a/tests/test_ledger_provenance.py b/tests/test_ledger_provenance.py new file mode 100644 index 0000000..15e91be --- /dev/null +++ b/tests/test_ledger_provenance.py @@ -0,0 +1,169 @@ +import json +import hashlib +import pytest +from pathlib import Path + +from app.rrsi.ledger import ExperimentLedger +from app.rrsi.taxonomy import DecisionRecord, ExperimentStatus, ProcessOutcome + + +@pytest.fixture +def temp_ledger(tmp_path): + ledger_file = tmp_path / "test_ledger.json" + return ExperimentLedger(ledger_path=ledger_file) + + +@pytest.fixture +def dummy_results_file(tmp_path): + res_path = tmp_path / "run_20260928_eval.json" + data = { + "run_id": "run_20260928_eval", + "doc_results": { + "INV_001": {"accuracy": 1.0, "field_outcomes": {"vendor_name": True}} + }, + "per_field_metrics": { + "vendor_name": {"precision": 1.0, "recall": 1.0} + } + } + content_bytes = json.dumps(data, indent=2).encode("utf-8") + res_path.write_bytes(content_bytes) + sha256 = hashlib.sha256(content_bytes).hexdigest() + return res_path, sha256 + + +def test_ledger_rejects_hand_supplied_metrics_without_eval_run(temp_ledger): + record = DecisionRecord( + proposal_id="PROP-HAND-TYPED", + area="table_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="measured", + baseline_accuracy=95.0, + candidate_accuracy=96.0, + delta_accuracy=1.0, + eval_run_id=None, + eval_results_sha256=None, + baseline_commit=None, + candidate_commit=None, + git_diff_hash=None + ) + with pytest.raises(ValueError, match="requires a valid eval_run_id"): + temp_ledger.append(record) + + +def test_ledger_rejects_mismatched_sha256(temp_ledger, dummy_results_file): + res_path, true_sha = dummy_results_file + record = DecisionRecord( + proposal_id="PROP-BAD-SHA", + area="table_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="measured", + baseline_accuracy=95.0, + candidate_accuracy=96.0, + delta_accuracy=1.0, + eval_run_id=str(res_path), + eval_results_sha256="0000000000000000000000000000000000000000000000000000000000000000", + baseline_commit="8c9c281", + candidate_commit="aff9aad", + git_diff_hash="abcdef123456" + ) + with pytest.raises(ValueError, match="eval_results_sha256 mismatch"): + temp_ledger.append(record) + + +def test_ledger_rejects_missing_commit_hashes(temp_ledger, dummy_results_file): + res_path, true_sha = dummy_results_file + record = DecisionRecord( + proposal_id="PROP-NO-COMMIT", + area="table_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="measured", + baseline_accuracy=95.0, + candidate_accuracy=96.0, + delta_accuracy=1.0, + eval_run_id=str(res_path), + eval_results_sha256=true_sha, + baseline_commit="", + candidate_commit="", + git_diff_hash="" + ) + with pytest.raises(ValueError, match="baseline_commit"): + temp_ledger.append(record) + + +def test_ledger_accepts_verified_measured_entry(temp_ledger, dummy_results_file): + res_path, true_sha = dummy_results_file + record = DecisionRecord( + proposal_id="PROP-VERIFIED", + area="table_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="measured", + baseline_accuracy=95.0, + candidate_accuracy=96.0, + delta_accuracy=1.0, + eval_run_id=str(res_path), + eval_results_sha256=true_sha, + baseline_commit="8c9c281", + candidate_commit="aff9aad", + git_diff_hash="d3b07384d113edec49eaa6238ad5ff00" + ) + temp_ledger.append(record) + assert len(temp_ledger.records) == 1 + assert temp_ledger.records[0]["proposal_id"] == "PROP-VERIFIED" + + +def test_ledger_accepts_not_measured_integrity_exempt_entry(temp_ledger): + record = DecisionRecord( + proposal_id="REMOVE-HARDCODES", + area="entity_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="not_measured", + integrity_exempt=True, + baseline_accuracy=None, + candidate_accuracy=None, + delta_accuracy=None, + paired_ci_lower=None, + paired_ci_upper=None, + latency_delta_seconds=None, + pruning_recommendations=["Pruned static hardcoded coordinates and specific entity regexes."] + ) + temp_ledger.append(record) + assert len(temp_ledger.records) == 1 + rec = temp_ledger.records[0] + assert rec["measurement_status"] == "not_measured" + assert rec["integrity_exempt"] is True + assert rec["baseline_accuracy"] is None + + +def test_ledger_rejects_not_measured_with_numeric_metrics(temp_ledger): + record = DecisionRecord( + proposal_id="REMOVE-HARDCODES", + area="entity_extraction", + status=ExperimentStatus.ACCEPTED, + process_outcome=ProcessOutcome.ACCEPTED, + measurement_status="not_measured", + integrity_exempt=True, + baseline_accuracy=95.0, # Fabricated numeric value! Must be rejected + candidate_accuracy=None, + delta_accuracy=None + ) + with pytest.raises(ValueError, match="cannot contain hand-supplied numeric metrics"): + temp_ledger.append(record) + + +def test_ledger_rejects_not_measured_without_integrity_exempt(temp_ledger): + record = DecisionRecord( + proposal_id="RANDOM-UNMEASURED", + area="entity_extraction", + status=ExperimentStatus.REJECTED, + process_outcome=ProcessOutcome.INSIGNIFICANT, + measurement_status="not_measured", + integrity_exempt=False, + baseline_accuracy=None + ) + with pytest.raises(ValueError, match="must have integrity_exempt=True"): + temp_ledger.append(record)