OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

        "injected_footer_leak_caught": True,
        "carveout_nested_object_rejected": carveout_nested_rejected,
        "probes": results,
    }


def _extract_manifest_inventory_paths(container: Any, label: str) -> list[str]:
    """Parse BOTH list (list[str] or list[{path/relpath,...}]) and dict manifest inventory representations."""
    paths: list[str] = []
    if isinstance(container, dict):
        paths = [str(k) for k in container.keys()]
    elif isinstance(container, list):
        for idx, entry in enumerate(container):
            if isinstance(entry, str):
                p = entry.strip()
            elif isinstance(entry, dict):
                raw_p = entry.get("path") if "path" in entry else entry.get("relpath")
                if type(raw_p) is not str or not raw_p.strip():
                    raise RuntimeError(f"Invalid manifest entry at {label}[{idx}]: missing string path/relpath")
                p = raw_p.strip()
            else:
                raise RuntimeError(f"Unsupported manifest entry type at {label}[{idx}]: {type(entry).__name__}")
            if not p:
                raise RuntimeError(f"Empty path at {label}[{idx}]")
            paths.append(p)
    else:
        raise RuntimeError(f"Manifest {label} must be a list or dict, got {type(container).__name__}")
    if len(paths) != len(set(paths)):
        raise RuntimeError(f"Duplicate paths detected in manifest {label}")
    return sorted(paths)


WAVE5_STRICT_IIP0042_PUBLIC_FILES: tuple[str, ...] = (
    "data/protocols/iip0042_portfolio_and_trackb_side_contract_v0.8.0.json",
    "docs/GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md",
    "scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py",
    "data/extracted/iip0042_master_multilayer_portfolio_crosswalk_v0.8.0.json",
)
WAVE5_STRICT_4CLASS_PUBLIC_FILES: tuple[str, ...] = (
    "data/constructs/islet1_abx_cd64t_il1rn_modeb_v0.8.0.fasta",
    "data/constructs/openislet_cleanroom_v1_3_all_leads.fasta",
    "data/constructs/islet_shield_comp2_comparators_v1_3.fasta",
    "data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json",
    "data/protocols/iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json",
    "data/extracted/iip0041_clinical_h1_cd64t_siglec_verification_v0.8.0.json",
    "data/extracted/iip0043_composite_release_evaluator_v0.8.0.json",
    "data/extracted/iip0043_wholegraft_gate0v_and_calibration_v0.8.0.json",
    "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json",
    "data/extracted/iip0044_foundry_v1_3_biologics_verification_v0.8.0.json",
    "docs/GATE-28-ABX-CD64T-IL1RN-AND-H1-PROTOCOL.md",
    "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md",
    "docs/FOUNDRY-V1-3-CLEANROOM-BIOLOGICS-PROTOCOL.md",
    "scripts/verify_iip0041_clinical_h1_cd64t_siglec.py",
    "scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py",
    "scripts/evaluate_gate0v_composite_release.py",
    "scripts/verify_iip0044_foundry_v1_3_biologics.py",
    "tests/test_iip0041_iip0042_iip0043_wave5_suite.py",
    "tests/test_iip0044_foundry_v1_3_biologics.py",
)
WAVE5_REQUIRED_DECISION_TREE_BLOCKS: tuple[tuple[str, str], ...] = (
    ("clinical_h1_abx_cd64t_il1rn_siglec_iip_0041", "COMMERCIAL_AI"),
    ("master_2pow20_portfolio_and_option1_trackb_contingency_iip_0042", "STRICT_IIP0042"),
    ("wholegraft_gate0v_composite_and_nw08_calibration_iip_0043", "COMMERCIAL_AI"),
    ("foundry_v1_3_cleanroom_biologics_registration_iip_0044", "COMMERCIAL_AI"),
)


_PUBLIC_BUNDLE_MARKER_BYTES = b"openislet_public_bundle_v0.8.0\n"
_INVENTORY_TRUST_BOUNDARY_NOTE = (
    "Verifies every manifest-declared public artifact's exact SHA-256 digest and byte size against manifest.json, "
    "enforces zero unmanifested extra files across the public bundle root (or across all allowlisted public paths "
    "in a local checkout), and independently verifies the 17 hardcoded pre-Wave-5 structure SHA-256 pins and 23 "
    "declared Wave-5 public files plus 4 DEC blocks; cryptographic authentication of the root manifest.json file "
    "itself depends on external release verification rather than self-reference."
)


def verify_gate30_tos_quarantine_full_inventory(
    openislet_root: Path,
    *,
    extra_wave5_texts: dict[str, str] | None = None,
    require_manifest: bool = True,
) -> dict[str, Any]:
    """Execute fail-closed Gate 30-TOS-QUARANTINE enforcement aligned 1-to-1 with Protocol §2.4:
      1. Directly parses manifest.json (BOTH list and dict forms of public_export_file_inventory
         and artifacts; never falls back silently; fails closed if manifest or ANY manifest-declared
         public artifact is missing from disk), verifies EVERY manifest-listed public file's exact
         SHA-256 digest and byte count against manifest.json['artifacts'], verifies exact public
         disk membership confirming ZERO unmanifested extra files (across the entire public bundle
         root when .openislet_public_bundle is present, or across all allowlisted public paths in a
         local research checkout), independently verifies all 17/17 hardcoded pre-Wave-5 structure
         SHA-256 pins, and scans EVERY allowlisted public file for:
         - local home paths (raw + decoded JSON strings),
         - hosted Tier-2 tokens/numerics (with strict pre-masking scalar-schema validation on the
           5-item IIP-0044 summary carve-out),
         - coordinate rows (raw + recursively decoded JSON strings) strictly prohibited outside the
           EXACT SHA-256-pinned 17-file pre-Wave-5 data/structures/ origin allowlist.
      2. Scans ALL 23 published Wave-5 public files (failing closed if any declared file is missing)
         plus ALL 4 Wave-5 decision-tree blocks (DEC-120..DEC-123 extracted from
         stage0_decision_tree_v1.json, failing closed if stage0_decision_tree_v1.json or any block
         is missing) and extra_wave5_texts for ALL 4 prohibited classes.
      3. Discloses explicitly that cryptographic authentication of the root manifest.json file
         itself depends on external release verification rather than self-reference.
    """
    neg_self_tests = run_gate30_tos_quarantine_negative_self_tests()

    manifest_path = openislet_root / "manifest.json"
    public_inventory_scanned = 0
    manifest_sha256_verified_count = 0
    authorized_coord_files_verified: list[str] = []
    manifest_mode = "NO_MANIFEST_IN_ROOT"
    inventory_source = "no_manifest"
    manifest_file_sha256: str | None = None
    declared_manifest_verified = False
    exact_disk_membership_verified = False
    public_disk_membership_scope = "NONE"

    if not manifest_path.is_file():
        if require_manifest:
            raise FileNotFoundError(
                f"Gate 30-TOS-QUARANTINE fail-closed: required manifest.json missing in {openislet_root.name}"
            )
    else:
        manifest_bytes = manifest_path.read_bytes()
        manifest_file_sha256 = hashlib.sha256(manifest_bytes).hexdigest()
        mf = load_strict_json_text(manifest_bytes.decode("utf-8"), "manifest.json")
        if not isinstance(mf, dict):
            raise RuntimeError("manifest.json must decode to a JSON object")
        artifacts_obj = mf.get("artifacts")
        if not isinstance(artifacts_obj, dict) or not artifacts_obj:
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: manifest.json missing non-empty 'artifacts' digest map"
            )
        if "public_export_file_inventory" in mf:
            pub_rels = _extract_manifest_inventory_paths(
                mf["public_export_file_inventory"], "public_export_file_inventory"
            )
            manifest_mode = "PUBLIC_EXPORT_BUNDLE_MANIFEST"
            inventory_source = "public_bundle_manifest_json"
        else:
            all_rels = _extract_manifest_inventory_paths(artifacts_obj, "artifacts")
            spec = mf.get("public_redistribution_allowlist_spec")
            if isinstance(spec, dict) and spec.get("public_package_included_paths"):
                inc = spec.get("public_package_included_paths", [])
                exc = spec.get("local_research_cache_excluded_from_public_bundle", [])
                pub_rels = [
                    rel
                    for rel in all_rels
                    if not any(fnmatch.fnmatch(rel, pat) for pat in exc)
                    and any(fnmatch.fnmatch(rel, pat) for pat in inc)
                ]
            else:
                pub_rels = all_rels
            manifest_mode = "REPO_PUBLIC_ALLOWLIST_MANIFEST"
            inventory_source = "manifest_json"

        if not pub_rels:
            raise RuntimeError(f"Gate 30-TOS-QUARANTINE fail-closed: manifest {inventory_source} yielded 0 public files")

        # 1.0 Symmetric public-bundle marker enforcement BEFORE artifact loop (R10 B4):
        # Whenever manifest.json declares public_export_file_inventory (OR .openislet_public_bundle exists/is symlink),
        # require BOTH public_export_file_inventory AND a valid regular single-hardlink .openislet_public_bundle marker
        # (matching generate_release_manifest.py --verify-public-bundle 'invalid-public-marker' fail-closed!).
        marker_path = openislet_root / ".openislet_public_bundle"
        is_public_bundle_mode = (
            manifest_mode == "PUBLIC_EXPORT_BUNDLE_MANIFEST"
            or marker_path.exists()
            or marker_path.is_symlink()
        )
        if is_public_bundle_mode:
            if manifest_mode != "PUBLIC_EXPORT_BUNDLE_MANIFEST":
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-inventory "
                    "(.openislet_public_bundle marker present without manifest.json['public_export_file_inventory'])"
                )
            if manifest_path.is_symlink():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:manifest.json symlink prohibited inside public bundle"
                )
            mf_st = manifest_path.lstat()
            if not stat.S_ISREG(mf_st.st_mode) or mf_st.st_nlink != 1:
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:manifest.json must be a regular single-hardlink file inside public bundle"
                )
            if marker_path.is_symlink() or not marker_path.is_file():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-marker "
                    "(missing or non-regular .openislet_public_bundle marker required when manifest.json declares public_export_file_inventory)"
                )
            marker_st = marker_path.lstat()
            if (
                not stat.S_ISREG(marker_st.st_mode)
                or marker_st.st_nlink != 1
                or marker_path.read_bytes() != _PUBLIC_BUNDLE_MARKER_BYTES
            ):
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-marker "
                    "(invalid .openislet_public_bundle marker bytes or file metadata)"
                )

        # 1a. Verify EVERY listed manifest artifact exists on disk, matches manifest.json SHA-256 & byte size,
        #     satisfies hardcoded 17-structure SHA-256 pins, and passes hygiene/coordinate scans!
        for rel in pub_rels:
            fp = openislet_root / rel
            if not fp.is_file():
                raise FileNotFoundError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest-declared public artifact missing from disk: {rel}"
                )
            pin = artifacts_obj.get(rel)
            if (
                not isinstance(pin, dict)
                or type(pin.get("sha256")) is not str
                or not _RE_SHA256_HEX.match(pin["sha256"])
                or type(pin.get("bytes")) is not int
                or pin["bytes"] < 0
            ):
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest.json['artifacts'] missing valid sha256/bytes pin for {rel}"
                )
            raw_b = fp.read_bytes()
            actual_sha = hashlib.sha256(raw_b).hexdigest()

            # Check structure extension provenance: NO .cif/.mmcif/.pdb outside exact SHA-256-pinned pre-Wave-5 allowlist
            is_coord_ext = fp.suffix.lower() in (".cif", ".mmcif", ".pdb")
            expected_coord_sha = AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_SHA256.get(rel)
            is_auth_coord = expected_coord_sha is not None
            if is_coord_ext and not is_auth_coord:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE: unauthorized coordinate structure file in public manifest: {rel}"
                )
            if is_auth_coord and actual_sha != expected_coord_sha:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: SHA-256 mismatch on pre-Wave-5 coordinate file {rel}: "
                    f"got {actual_sha}, expected {expected_coord_sha}"
                )

            # Verify EVERY manifest-listed public file's SHA-256 digest & byte size against manifest.json!
            if actual_sha != pin["sha256"] or len(raw_b) != pin["bytes"]:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest.json SHA-256/bytes mismatch on public file {rel}: "
                    f"disk=({actual_sha}, {len(raw_b)} B) vs manifest=({pin['sha256']}, {pin['bytes']} B)"
                )
            manifest_sha256_verified_count += 1

            try:
                raw_txt = raw_b.decode("utf-8")
            except UnicodeDecodeError:
                if _T2_TAG.encode("ascii") in raw_b.lower() or ("sab_" + "pred_").encode("ascii") in raw_b.lower():
                    raise RuntimeError(f"Gate 30-TOS-QUARANTINE: Tier-2 marker in binary public file: {rel}")
                public_inventory_scanned += 1