fix(integrity): enforce ledger provenance checks, delete fabricated data, and isolate forbidden hashes

This commit is contained in:
omkarande14
2026-09-28 17:13:24 +05:30
parent 3fca5e91e6
commit 3e1342fad0
8 changed files with 480 additions and 133 deletions
+4
View File
@@ -41,4 +41,8 @@ reports/*
# Snapshots of unredacted state # Snapshots of unredacted state
private_snapshots/ private_snapshots/
golden_outputs/
# Sensitive local config
config/forbidden_hashes.json
+48 -1
View File
@@ -10,7 +10,11 @@ Statistical Evaluator & Selection Decision Engine.
""" """
import math import math
import json
import hashlib
import time
import subprocess import subprocess
from pathlib import Path
from decimal import Decimal from decimal import Decimal
from typing import Dict, Any, List, Optional, Tuple, Set 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) c_cnt = candidate_selection.failure_breakdown.get(cat.value, 0)
failure_deltas[cat.value] = c_cnt - b_cnt 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( return DecisionRecord(
proposal_id=hypothesis.proposal_id, proposal_id=hypothesis.proposal_id,
area=hypothesis.area.value, area=hypothesis.area.value,
status=status, status=status,
process_outcome=process_outcome, process_outcome=process_outcome,
measurement_status="measured",
integrity_exempt=False,
baseline_accuracy=baseline_selection.macro_accuracy, baseline_accuracy=baseline_selection.macro_accuracy,
candidate_accuracy=candidate_selection.macro_accuracy, candidate_accuracy=candidate_selection.macro_accuracy,
delta_accuracy=round(delta_acc, 2), delta_accuracy=round(delta_acc, 2),
@@ -470,5 +511,11 @@ class StatisticalEvaluator:
rejection_reasons=rejection_reasons, rejection_reasons=rejection_reasons,
pruning_recommendations=[], pruning_recommendations=[],
failure_deltas=failure_deltas, 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
) )
+98 -28
View File
@@ -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 json
import hashlib
from pathlib import Path from pathlib import Path
from typing import Dict, Any, List, Optional from typing import Dict, Any, List, Optional
@@ -41,8 +35,72 @@ class ExperimentLedger:
with open(self.ledger_path, "w", encoding="utf-8") as f: with open(self.ledger_path, "w", encoding="utf-8") as f:
json.dump(self.records, f, indent=2) json.dump(self.records, f, indent=2)
def append(self, decision: DecisionRecord): def append(self, decision: DecisionRecord, results_dir: Optional[Path] = None):
"""Appends a new decision record to the auditable ledger.""" """
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.records.append(decision.to_dict())
self.save() self.save()
@@ -55,18 +113,29 @@ class ExperimentLedger:
def generate_markdown_summary(self, decision: DecisionRecord) -> str: def generate_markdown_summary(self, decision: DecisionRecord) -> str:
"""Generates a structured, auditable Markdown report for a candidate decision.""" """Generates a structured, auditable Markdown report for a candidate decision."""
status_badge = "[ACCEPTED]" if decision.status == ExperimentStatus.ACCEPTED else "[REJECTED]" status_val = decision.status.value if isinstance(decision.status, ExperimentStatus) else decision.status
delta_sign = "+" if decision.delta_accuracy > 0 else "" 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 = [ lines = [
f"### RRSI Evaluation Report: `{decision.proposal_id}` ({status_badge})", f"### RRSI Evaluation Report: `{decision.proposal_id}` ({status_badge})",
f"- **Target Area**: `{decision.area}`", f"- **Target Area**: `{decision.area}`",
f"- **Baseline Accuracy**: `{decision.baseline_accuracy:.2f}%`", f"- **Measurement Status**: `{decision.measurement_status}` (Integrity Exempt: {decision.integrity_exempt})",
f"- **Candidate Accuracy**: `{decision.candidate_accuracy:.2f}%` ({delta_sign}{decision.delta_accuracy:.2f}%)", f"- **Baseline Accuracy**: `{b_acc}`",
f"- **Statistical Noise Floor**: `+/-{decision.noise_floor:.2f}%`", f"- **Candidate Accuracy**: `{c_acc}`",
f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO (Indistinguishable from luck/noise)'}`", f"- **Statistically Significant**: `{'YES' if decision.is_statistically_significant else 'NO'}`",
f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED (Memorization/Cheating detected)'}`", f"- **Leakage Screen**: `{'PASSED' if decision.leakage_screen_passed else 'FAILED'}`",
f"- **Cost-Aware Acceptance**: `{'PASSED' if decision.cost_aware_accepted else 'FAILED (Latency/Cost budget exceeded)'}` (dt: {decision.latency_delta_seconds:+.2f}s)", 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(f"- [PRUNE] {pr}")
lines.append("") lines.append("")
lines.append("#### Failure Deltas by Error Category:") if decision.failure_deltas:
lines.append("| Error Category | Delta vs Baseline | Status |") lines.append("#### Failure Deltas by Error Category:")
lines.append("| :--- | :---: | :---: |") lines.append("| Error Category | Delta vs Baseline | Status |")
for cat, delta in decision.failure_deltas.items(): lines.append("| :--- | :---: | :---: |")
if delta < 0: for cat, delta in decision.failure_deltas.items():
icon = f"[REDUCED] by {abs(delta)}" if delta < 0:
elif delta > 0: icon = f"[REDUCED] by {abs(delta)}"
icon = f"[INCREASED] by {delta}" elif delta > 0:
else: icon = f"[INCREASED] by {delta}"
icon = "[UNCHANGED] (0)" else:
lines.append(f"| `{cat}` | {delta:+d} | {icon} |") icon = "[UNCHANGED] (0)"
lines.append(f"| `{cat}` | {delta:+d} | {icon} |")
return "\n".join(lines) return "\n".join(lines)
+8 -8
View File
@@ -39,14 +39,14 @@ class LeakageScreening:
@classmethod @classmethod
def _load_forbidden_hashes(cls) -> Tuple[str, set]: def _load_forbidden_hashes(cls) -> Tuple[str, set]:
cfg_path = Path("config/forbidden_hashes.json") for p in [Path("data_private/config/forbidden_hashes.json"), Path("config/forbidden_hashes.json")]:
if cfg_path.exists(): if p.exists():
try: try:
with open(cfg_path, "r", encoding="utf-8") as f: with open(p, "r", encoding="utf-8") as f:
data = json.load(f) data = json.load(f)
return data.get("salt", ""), set(data.get("hashes", [])) return data.get("salt", ""), set(data.get("hashes", []))
except Exception: except Exception:
pass pass
return "", set() return "", set()
@classmethod @classmethod
+27 -16
View File
@@ -263,25 +263,36 @@ class DecisionRecord:
area: str area: str
status: ExperimentStatus status: ExperimentStatus
process_outcome: ProcessOutcome process_outcome: ProcessOutcome
baseline_accuracy: float measurement_status: str = "measured" # "measured" | "not_measured"
candidate_accuracy: float integrity_exempt: bool = False # True for leak/overfit removals
delta_accuracy: float baseline_accuracy: Optional[float] = None
paired_ci_lower: float candidate_accuracy: Optional[float] = None
paired_ci_upper: float delta_accuracy: Optional[float] = None
is_statistically_significant: bool paired_ci_lower: Optional[float] = None
leakage_screen_passed: bool paired_ci_upper: Optional[float] = None
leakage_findings: List[str] is_statistically_significant: bool = False
cost_aware_accepted: bool leakage_screen_passed: bool = True
latency_delta_seconds: float leakage_findings: List[str] = field(default_factory=list)
vision_fallback_calls: int cost_aware_accepted: bool = False
case_regressions: List[str] latency_delta_seconds: Optional[float] = None
rejection_reasons: List[str] vision_fallback_calls: int = 0
pruning_recommendations: List[str] case_regressions: List[str] = field(default_factory=list)
failure_deltas: Dict[str, int] 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" 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_commit_hash: str = ""
git_diff_hash: str = "" git_diff_hash: str = ""
timestamp: float = field(default_factory=time.time) timestamp: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]: 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
+1 -33
View File
@@ -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
}
]
+125 -47
View File
@@ -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 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 2. Real PAN numbers matching \b[A-Z]{5}\d{4}[A-Z]\b
3. Indian phone numbers 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.) 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 import re
@@ -14,6 +16,7 @@ import subprocess
import sys import sys
import json import json
import hashlib import hashlib
import argparse
from pathlib import Path from pathlib import Path
# RegEx for sensitive identifiers # RegEx for sensitive identifiers
@@ -38,22 +41,68 @@ FORBIDDEN_PATH_SUBSTRINGS = [
"venv/", "venv/",
".venv/", ".venv/",
"scratch/", "scratch/",
"private_snapshots" "private_snapshots",
"golden_outputs"
] ]
def load_forbidden_hashes(): def load_forbidden_hashes():
cfg_path = Path("config/forbidden_hashes.json") # Priority: private config path, then legacy config path
if cfg_path.exists(): for p in [Path("data_private/config/forbidden_hashes.json"), Path("config/forbidden_hashes.json")]:
try: if p.exists():
with open(cfg_path, "r", encoding="utf-8") as f: try:
data = json.load(f) with open(p, "r", encoding="utf-8") as f:
return data.get("salt", ""), set(data.get("hashes", [])) data = json.load(f)
except Exception: return data.get("salt", ""), set(data.get("hashes", []))
pass except Exception:
pass
return "", set() 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]: 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) 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()] files = [f.strip() for f in res.stdout.splitlines() if f.strip()]
if not files: 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()] files = [f.strip() for f in res2.stdout.splitlines() if f.strip()]
return files return files
def check_hygiene() -> bool: def check_current_hygiene() -> bool:
run_synthetic_canary_test()
files = get_staged_or_tracked_files() files = get_staged_or_tracked_files()
violations = [] violations = []
salt, forbidden_hashes = load_forbidden_hashes() 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: for f_str in files:
p = Path(f_str) p = Path(f_str)
# Check path restrictions
norm_path = f_str.replace("\\", "/") norm_path = f_str.replace("\\", "/")
for forbidden in FORBIDDEN_PATH_SUBSTRINGS: for forbidden in FORBIDDEN_PATH_SUBSTRINGS:
if forbidden in norm_path: if forbidden in norm_path:
violations.append(f"FORBIDDEN FILE TRACKED: '{f_str}' is inside private/ignored directory '{forbidden}'.") 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"]: if f_str in ["scripts/check_git_hygiene.py", "config/forbidden_hashes.json"] or p.suffix.lower() in [".png", ".jpg", ".pdf", ".pyc", ".zip"]:
continue continue
if p.exists() and p.is_file(): if p.exists() and p.is_file():
try: try:
content = p.read_text(encoding="utf-8", errors="ignore") content = p.read_text(encoding="utf-8", errors="ignore")
violations.extend(scan_text_lines(content, f_str, salt, forbidden_hashes))
except Exception: except Exception:
continue 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: if violations:
print("[!] GIT HYGIENE CHECK FAILED:") print("[!] GIT HYGIENE CHECK FAILED:")
for v in violations: 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.") print("[+] Git hygiene check passed cleanly: No un-anonymized PII, real GSTINs, or private data tracked.")
return True 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 __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(1)
sys.exit(0) sys.exit(0)
+169
View File
@@ -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)