| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Deterministic defender-side deduplication for Anneal red-teaming.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import re | |
| from typing import Any, Iterable | |
| _KIND_PREFIX = { | |
| "PROOF_HACK": "PH", | |
| "SPEC_PREFLIGHT_HACK": "SP", | |
| "THEORY_AUDIT_HACK": "TA", | |
| } | |
| ALLOWED_STANDARD_AXIOMS = frozenset({"propext", "Classical.choice", "Quot.sound"}) | |
| BASELINE_DEFERRED = frozenset({ | |
| "complete review-surface reporting", | |
| "source-to-deployed-binary correspondence", | |
| }) | |
| # Prose briefs and advisory metadata never alter witness fingerprints. | |
| _IGNORE_WITNESS_PATHS = frozenset({"explanation.md", "manifest.json"}) | |
| _WITNESS_TOKEN_RE = re.compile(r'"(?:\\.|[^"\\])*"|--[^\n]*|\s+') | |
| def _normalize_witness_text(text: str) -> str: | |
| return _WITNESS_TOKEN_RE.sub( | |
| lambda m: " " if m.group(0)[0].isspace() else m.group(0), text | |
| ).strip() | |
| def compute_witness_hash(submission_files: dict[str, bytes]) -> str: | |
| """Compute SHA-256 over whitespace-normalized code and proof files.""" | |
| parts = [ | |
| f"{rel}:{_normalize_witness_text(submission_files[rel].decode('utf-8', errors='replace'))}" | |
| for rel in sorted(submission_files) | |
| if rel not in _IGNORE_WITNESS_PATHS | |
| ] | |
| return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() | |
| def _str_list(obj: dict[str, Any], key: str) -> list[str]: | |
| val = obj.get(key) | |
| return [x for x in val if isinstance(x, str)] if isinstance(val, list) else [] | |
| def _normalize_olean_tag(violation: str) -> str: | |
| """Strip attacker-chosen symbol names so renames share one bug ID.""" | |
| if violation.startswith("audit_bypass:"): | |
| parts = violation.split(":", 2) | |
| return f"{parts[0]}:{parts[1]}" if len(parts) > 1 else violation | |
| kind, sep, rest = violation.partition(":") | |
| if sep and kind in ( | |
| "forbidden_import", | |
| "forbidden_const_ref", | |
| "forbidden_env_ref", | |
| "transitive_forbidden_ref", | |
| "transitive_forbidden_const", | |
| "forbidden_alias_target", | |
| ): | |
| if ":" in rest: | |
| _, _, target = rest.rpartition(":") | |
| return f"{kind}:{target}" | |
| if kind == "transitive_forbidden_ref": | |
| root = rest.removeprefix("_private.").partition(".")[0] | |
| return kind if root in ("Anneal", "Spec", "Proof") else f"{kind}:{rest}" | |
| return kind | |
| def extract_receipt_anomalies( | |
| receipt: dict[str, Any] | None, | |
| *, | |
| inspect_report: dict[str, Any] | None = None, | |
| audit_report: dict[str, Any] | None = None, | |
| olean_violations: Iterable[str] = (), | |
| extra_anomalies: Iterable[str] = (), | |
| allowed_axioms: frozenset[str] = ALLOWED_STANDARD_AXIOMS, | |
| ) -> list[str]: | |
| """Extract sorted defender-observed Receipt v3, inspect, and audit tags.""" | |
| anomalies: set[str] = set() | |
| if isinstance(receipt, dict): | |
| st = receipt.get("status") | |
| if isinstance(st, str) and st.startswith("tainted_"): | |
| anomalies.add(f"status:{st}") | |
| if receipt.get("elaboration_sandbox") == "none": | |
| anomalies.add("sandbox:none") | |
| audit = receipt.get("audit") | |
| if isinstance(audit, dict): | |
| anomalies.update( | |
| f"unexpected_axiom:{ax}" | |
| for ax in _str_list(audit, "axioms") | |
| if ax not in allowed_axioms | |
| ) | |
| if audit.get("replay") is not True: | |
| anomalies.add("audit:replay_false") | |
| if audit.get("exactType") is not True: | |
| anomalies.add("audit:exact_type_false") | |
| cap = audit.get("checkedAlternateProofs") | |
| if type(cap) is not int or cap != 0: | |
| anomalies.add(f"audit:checked_alternate_proofs:{cap}") | |
| if audit.get("sorryDeclarations"): | |
| anomalies.add("audit:sorry_declared") | |
| anomalies.update(f"sorry_decl:{d}" for d in _str_list(receipt, "sorry_declarations")) | |
| anomalies.update(f"taint:{t}" for t in _str_list(receipt, "taint_reasons")) | |
| anomalies.update( | |
| f"deferred:{d}" | |
| for d in _str_list(receipt, "deferred") | |
| if d not in BASELINE_DEFERRED | |
| ) | |
| if isinstance(inspect_report, dict): | |
| if inspect_report.get("tainted") is not False: | |
| anomalies.add(f"inspect:tainted:{inspect_report.get('tainted')!r}") | |
| for key in ( | |
| "policy_violations", | |
| "invariant_violations", | |
| "unrecognized_fields", | |
| ): | |
| anomalies.update( | |
| f"inspect:{key}:{e}" for e in _str_list(inspect_report, key) | |
| ) | |
| art = inspect_report.get("artifact_verification") | |
| if not isinstance(art, dict) or art.get("exact_match") is not True: | |
| anomalies.add("inspect:artifact_exact_match_false") | |
| if isinstance(audit_report, dict): | |
| if audit_report.get("replay") is False: | |
| anomalies.add("repo_audit:replay_false") | |
| anomalies.update( | |
| f"unexpected_axiom:{ax}" | |
| for ax in _str_list(audit_report, "axioms") | |
| if ax not in allowed_axioms | |
| ) | |
| anomalies.update( | |
| f"olean:{_normalize_olean_tag(v)}" | |
| for v in olean_violations | |
| if isinstance(v, str) and v | |
| ) | |
| anomalies.update(a for a in extra_anomalies if isinstance(a, str) and a) | |
| return sorted(anomalies) | |
| def compute_dedup_metadata( | |
| *, | |
| scenario_id: str, | |
| scenario_kind: str, | |
| submission_files: dict[str, bytes], | |
| receipt: dict[str, Any] | None = None, | |
| inspect_report: dict[str, Any] | None = None, | |
| audit_report: dict[str, Any] | None = None, | |
| olean_violations: Iterable[str] = (), | |
| extra_anomalies: Iterable[str] = (), | |
| compromise_detected: bool = False, | |
| compromise_phase: str | None = None, | |
| tampered_paths: list[str] | tuple[str, ...] = (), | |
| ) -> dict[str, Any]: | |
| """Compute defender-only `dedup` metadata for a winning submission.""" | |
| anomalies = extract_receipt_anomalies( | |
| receipt, | |
| inspect_report=inspect_report, | |
| audit_report=audit_report, | |
| olean_violations=olean_violations, | |
| extra_anomalies=extra_anomalies, | |
| ) | |
| witness_hash = compute_witness_hash(submission_files) | |
| if compromise_detected: | |
| tampered = sorted(set(tampered_paths)) | |
| phase = compromise_phase or "unknown" | |
| payload: dict[str, Any] = { | |
| "kind": scenario_kind, | |
| "mechanism": "harness_compromise", | |
| "compromise_phase": phase, | |
| "tampered_paths": tampered, | |
| "receipt_anomalies": anomalies, | |
| } | |
| features = ["mechanism:harness_compromise", f"phase:{phase}", f"check:{scenario_id}", *(f"tampered:{p}" for p in tampered), *anomalies] | |
| kind_code = "ESC" | |
| summary = f"harness_compromise ({phase}) in {scenario_kind} ({scenario_id}); tampered={','.join(tampered) or 'unknown'}" | |
| else: | |
| payload = {"kind": scenario_kind, "check_or_fault": scenario_id, "receipt_anomalies": anomalies} | |
| if not anomalies: | |
| payload["witness_hash"] = witness_hash | |
| kind_code = _KIND_PREFIX.get(scenario_kind, "UNK") | |
| features = [f"check:{scenario_id}", *(anomalies or [f"witness:{witness_hash[:12]}"])] | |
| summary = f"{scenario_kind} ({scenario_id}); anomalies={','.join(anomalies) or 'none'}" | |
| canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")) | |
| digest12 = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12] | |
| return { | |
| "bug_id": f"RT-{kind_code}-{digest12}", | |
| "witness_hash": witness_hash, | |
| "mechanism_summary": summary, | |
| "features": sorted(set(features)), | |
| } |