scripts/evaluate_gate0v_composite_release.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/evaluate_gate0v_composite_release.py · SHA-256: 2be0252340222fe4…
if isinstance(obj, (list, tuple)):
for item in obj:
ok, err = _check_json_structure_v2_round8(item, depth + 1)
if not ok:
return False, err
return True, None
return False, f"UNSUPPORTED_JSON_TYPE:{type(obj).__name__}"
def _safe_canonical_sha256_v2_round8(obj: Any) -> str | None:
ok, _err = _check_json_structure_v2_round8(obj, 0)
if not ok:
return None
try:
canon = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
return hashlib.sha256(canon.encode("utf-8")).hexdigest()
except (TypeError, ValueError, OverflowError, RecursionError):
return None
def _canonical_sha256_v2_round5(obj: Any) -> str:
digest = _safe_canonical_sha256_v2_round8(obj)
if digest is None:
raise ValueError("Cannot compute canonical SHA-256 for malformed/non-finite/non-JSON object")
return digest
def _unfreeze_owner_obj_v2_round7(obj: Any) -> Any:
if isinstance(obj, _AbcMapping):
return {k: _unfreeze_owner_obj_v2_round7(v) for k, v in obj.items()}
if isinstance(obj, (tuple, list)):
return [_unfreeze_owner_obj_v2_round7(v) for v in obj]
return obj
def _strict_no_dup_pairs_v2_round8(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
out: Dict[str, Any] = {}
for k, v in pairs:
if k in out:
raise ValueError(f"Duplicate JSON key: {k!r}")
out[k] = v
return out
def _reject_json_constant_v2_round8(tok: str) -> Any:
raise ValueError(f"Non-finite JSON constant forbidden: {tok!r}")
def _safe_load_governed_json_v2_round8(path: Path) -> Tuple[Any, str | None]:
"""Load an immutable on-disk governed JSON file cleanly without symlinks, duplicate keys, or uncaught exceptions."""
try:
if path.is_symlink():
return None, "SYMLINK_FORBIDDEN"
if not path.is_file():
return None, "FILE_NOT_FOUND"
raw_text = path.read_text(encoding="utf-8")
obj = json.loads(
raw_text,
object_pairs_hook=_strict_no_dup_pairs_v2_round8,
parse_constant=_reject_json_constant_v2_round8,
)
ok, err = _check_json_structure_v2_round8(obj, 0)
if not ok:
return None, err or "MALFORMED_JSON_STRUCTURE"
return obj, None
except (OSError, UnicodeDecodeError, ValueError, TypeError, OverflowError, RecursionError) as exc:
return None, f"MALFORMED_JSON:{type(exc).__name__}"
def _safe_validate_5_lineages_v2_round8(lineages: Any) -> Tuple[bool, str | None, bool]:
"""Return (ok, error_code, is_malformed_type). Never calls set() on unhashable nested dicts/lists."""
if not isinstance(lineages, list):
return False, f"LINEAGES_NOT_LIST:{type(lineages).__name__}", True
for item in lineages:
if not isinstance(item, str):
return False, f"LINEAGES_NON_STRING_ENTRY:{type(item).__name__}", True
if len(lineages) != len(set(lineages)) or set(lineages) != _GY030_REQUIRED_5_LINEAGES:
return False, "DOSSIER_5_LINEAGES_INCOMPLETE", False
return True, None, False
def _seal_gate0v_receipt_v2_round5(body: Dict[str, Any]) -> Dict[str, Any]:
rec = copy.deepcopy({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
return rec
def seal_owner_physical_dossier_record_v2_round7(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
"""Seal an owner-governed physical Gate 0V wet-lab dossier with its immutable archive_sha256."""
rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
return rec
def seal_owner_qa_signoff_record_v2_round7(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
"""Seal an independent QA sign-off record bound to an archived physical Gate 0V dossier."""
rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
return rec
def seal_owner_qa_issuer_registry_v2_round8(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
"""Seal an independent QA issuer authority registry with its immutable registry_sha256."""
rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k != "registry_sha256"})
rec["registry_sha256"] = _canonical_sha256_v2_round5(rec)
return rec
def write_governed_gate0v_store_v2_round8(
store_root: Path | str,
*,
qa_issuer_registry: _AbcMapping[str, Any] | None = None,
dossiers: _AbcSequence[_AbcMapping[str, Any]] = (),
qa_signoffs: _AbcSequence[_AbcMapping[str, Any]] = (),
) -> Path:
"""Populate a separately governed on-disk Gate 0V evidence store layout:
<root>/qa_issuer_registry.json
<root>/physical_dossiers/<dossier_id>.json
<root>/qa_signoffs/<qa_signoff_id>.json
<root>/issued_receipts/ (single canonical key <archive_sha256>.json written ONLY on PASS)"""
root = Path(store_root)
d_dir = root / "physical_dossiers"
q_dir = root / "qa_signoffs"
i_dir = root / "issued_receipts"
d_dir.mkdir(parents=True, exist_ok=True)
q_dir.mkdir(parents=True, exist_ok=True)
i_dir.mkdir(parents=True, exist_ok=True)
if qa_issuer_registry is not None:
reg_plain = _unfreeze_owner_obj_v2_round7(qa_issuer_registry)
(root / "qa_issuer_registry.json").write_text(
json.dumps(reg_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
encoding="utf-8",
)
for raw_d in dossiers:
d_plain = _unfreeze_owner_obj_v2_round7(raw_d)
did = d_plain.get("dossier_id")
if not _is_safe_store_id_v2_round8(did):
raise ValueError(f"Unsafe dossier_id for governed store write: {did!r}")
(d_dir / f"{did}.json").write_text(
json.dumps(d_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
encoding="utf-8",
)
for raw_q in qa_signoffs:
q_plain = _unfreeze_owner_obj_v2_round7(raw_q)
qid = q_plain.get("qa_signoff_id")
if not _is_safe_store_id_v2_round8(qid):
raise ValueError(f"Unsafe qa_signoff_id for governed store write: {qid!r}")
(q_dir / f"{qid}.json").write_text(
json.dumps(q_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
encoding="utf-8",
)
return root
def build_gate0v_installation_identity_v2_round10(
*,
installation_id: str,
authorized_qa_issuer_registry_sha256: str,
provenance_mode: str = "OWNER_PROVISIONED_PRODUCTION_INSTALLATION",
owner_authority_id: str = _GATE0V_INSTALLATION_IDENTITY_AUTHORITY_ID_V2_ROUND10,
) -> Dict[str, Any]:
"""Audit R9-03: Build separate installation identity record binding an authorized OpenIslet
checkout independently of artifact relative paths."""
body: Dict[str, Any] = {
"schema_version": _GATE0V_INSTALLATION_IDENTITY_SCHEMA_V2_ROUND10,
"installation_id": str(installation_id),
"owner_authority_id": str(owner_authority_id),
"provenance_mode": str(provenance_mode),
"authorized_qa_issuer_registry_sha256": str(authorized_qa_issuer_registry_sha256),
}
body["installation_identity_sha256"] = _canonical_sha256_v2_round5(body)
return body
def build_gate0v_governed_trust_config_v2_round9(
*,
qa_issuer_registry_sha256: str,
canonical_arm_manifest_sha256: str,
installation_id: str,
installation_identity_sha256: str,
installation_identity_path: str = "data/protocols/gate0v_installation_identity.json",
provenance_mode: str = "OWNER_PROVISIONED_PRODUCTION",
authorized_store_root: str = "data/governed_gate0v_store",
canonical_arm_manifest_path: str = "data/protocols/wave6_canonical_arm_manifest.json",
) -> Dict[str, Any]:
"""Audit R8-03 & Audit R9-03: Build owner-configured Gate 0V trust anchor using strictly repo-relative
paths and pinning qa_issuer_registry.json, wave6_canonical_arm_manifest.json, AND separate
gate0v_installation_identity.json raw SHA-256 + installation_id."""
body: Dict[str, Any] = {
"schema_version": _GATE0V_TRUST_CONFIG_SCHEMA_V2_ROUND9,
"owner_authority_id": _GATE0V_TRUST_CONFIG_AUTHORITY_ID_V2_ROUND9,
"provenance_mode": str(provenance_mode),
"installation_id": str(installation_id),
"installation_identity_path": str(installation_identity_path),
"installation_identity_sha256": str(installation_identity_sha256),
"authorized_store_root": str(authorized_store_root),
"canonical_arm_manifest_path": str(canonical_arm_manifest_path),
"qa_issuer_registry_sha256": str(qa_issuer_registry_sha256),
"canonical_arm_manifest_sha256": str(canonical_arm_manifest_sha256),
}
body["trust_config_sha256"] = _canonical_sha256_v2_round5(body)
return body
def _is_safe_repo_rel_path_v2_round9(rel_str: Any) -> bool:
if not isinstance(rel_str, str) or not rel_str.strip() or rel_str != rel_str.strip():
return False
p = Path(rel_str)
if p.is_absolute() or ".." in p.parts:
return False
return True
def _load_and_verify_owner_trust_config_v2_round9(
resolved_root: Path,
) -> Tuple[Dict[str, Any] | None, str | None]:
"""Audit R8-03 & Audit R9-03: Verify BOTH owner-configured `<repo_root>/data/protocols/gate0v_governed_trust_config.json`
against `_PINNED_GATE0V_TRUST_CONFIG_SHA256` AND separate `<repo_root>/data/protocols/gate0v_installation_identity.json`
against `_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256`, binding installation_id and authorized QA issuer registry."""
if not _is_safe_sha256_v2_round8(_PINNED_GATE0V_TRUST_CONFIG_SHA256):
return None, "TRUST_CONFIG_OWNER_PIN_NOT_CONFIGURED"
if not _is_safe_sha256_v2_round8(_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256):
return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_OWNER_PIN_NOT_CONFIGURED"
cfg_path = resolved_root / _GATE0V_TRUST_CONFIG_REL_PATH_V2_ROUND9
if cfg_path.is_symlink():
return None, "TRUST_CONFIG_SYMLINK_FORBIDDEN"
if not cfg_path.is_file():
return None, "MISSING_OWNER_TRUST_CONFIG"
try:
raw_bytes = cfg_path.read_bytes()
except OSError as exc:
return None, f"TRUST_CONFIG_READ_ERROR:{type(exc).__name__}"
raw_sha = hashlib.sha256(raw_bytes).hexdigest()
if raw_sha != _PINNED_GATE0V_TRUST_CONFIG_SHA256:
return None, f"TRUST_CONFIG_OWNER_PIN_MISMATCH:{raw_sha}!={_PINNED_GATE0V_TRUST_CONFIG_SHA256}"
try:
cfg_obj = json.loads(
raw_bytes.decode("utf-8"),
object_pairs_hook=_strict_no_dup_pairs_v2_round8,
parse_constant=_reject_json_constant_v2_round8,
)
except (UnicodeDecodeError, ValueError, TypeError) as exc:
return None, f"TRUST_CONFIG_MALFORMED_JSON:{type(exc).__name__}"
if not isinstance(cfg_obj, dict):
return None, "TRUST_CONFIG_NOT_MAPPING"
if cfg_obj.get("schema_version") != _GATE0V_TRUST_CONFIG_SCHEMA_V2_ROUND9:
return None, "TRUST_CONFIG_SCHEMA_INVALID"
if cfg_obj.get("owner_authority_id") != _GATE0V_TRUST_CONFIG_AUTHORITY_ID_V2_ROUND9:
return None, "TRUST_CONFIG_AUTHORITY_INVALID"