From 26b6174510c54ccaa0e3dcf87e03d21b7cd21ab6 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:35:45 +0100 Subject: [PATCH] feat(valid-detection-benchmark): integrate reviewed label blind manifest --- .../specs/valid-detection-benchmark/tasks.md | 3 +- benchmarks/valid/population_label_blind.py | 247 +++++++++++++++ .../valid/population_label_blind_contract.py | 178 +++++++++++ ...st_valid_benchmark_label_blind_manifest.py | 295 ++++++++++++++++++ 4 files changed, 722 insertions(+), 1 deletion(-) create mode 100644 benchmarks/valid/population_label_blind.py create mode 100644 benchmarks/valid/population_label_blind_contract.py create mode 100644 tests/test_valid_benchmark_label_blind_manifest.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 99c0bbfb..8db931b4 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -119,7 +119,7 @@ - Done when public serialization contains no private bytes, labels, credentials, or local paths and every opaque reference resolves only through the authorized custodian boundary. - _Requirements: 5.1, 5.3, 7.1, 7.6, 10.3_ - _Boundary: Population Freezer_ -- [ ] 4.4 Integrate the independently reviewed label-blind population manifest +- [x] 4.4 Integrate the independently reviewed label-blind population manifest - Construct only counts, exact scopes, canonical input identities, and digests needed by later plan composition, with no label-bearing field. - Require an independent manifest review with policy satisfaction and conflict disclosure. - Bind immutable population, freeze, census, scope, review, and input-set identities before any arm plan or label access. @@ -424,3 +424,4 @@ - Task 4.1 deterministically draws at least twenty same-network first-parent ordinary pushes per accepted positive, globally excludes every accepted fix revision, stores shared pushes once, and routes reviewed contamination to exclusion or terminal retirement according to freeze timing. - Task 4.2 classifies and freezes only exact reviewed authorities against the Reservation Authority's current census snapshot; admission requires at least forty positives across Python and JavaScript and two families, while stale censuses, split networks, and insufficient scope remain non-authorizing. - Task 4.3 separates metadata-only public manifests from typed content-addressed public source objects: source literals are never interpreted as operational paths, while manifests expose only closed license metadata, digests, lengths, canonical exclusion projections, and opaque private references; private source and sealed labels retain exact custodian-bound access. +- Task 4.4 derives the exact label-blind input set from the frozen positive and ordinary-selection authorities, uses detection-core V3's canonical input-set identity, and accepts review only through a rederived independence policy plus resolvable conflict-disclosure evidence. diff --git a/benchmarks/valid/population_label_blind.py b/benchmarks/valid/population_label_blind.py new file mode 100644 index 00000000..cdbcdcc1 --- /dev/null +++ b/benchmarks/valid/population_label_blind.py @@ -0,0 +1,247 @@ +"""Build and validate independently reviewed label-blind population manifests.""" + +from __future__ import annotations + +import re +from dataclasses import replace + +from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1, ordinary_selection_bytes +from benchmarks.valid.population_freeze_contract import PopulationFreezeV3, population_freeze_bytes +from benchmarks.valid.population_label_blind_contract import ( + LabelBlindManifestConflict, + LabelBlindManifestError, + LabelBlindPopulationDraftV3, + LabelBlindPopulationManifestV3, + _draft_value, + _manifest_value, + label_blind_population_draft_bytes, + label_blind_population_manifest_bytes, +) +from benchmarks.valid.population_material_contract import PopulationMaterialPartitionV1 +from benchmarks.valid.population_materials import material_artifact_bytes, public_manifest_bytes +from openultrasast.core import canonical +from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest +from openultrasast.core.factpack import ( + FactPackValidationError, + IndependenceAttestation, + ReviewIndependencePolicy, + derive_independence_attestation_digest, + derive_review_independence_policy_digest, +) + +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +def _digest(value: object, field: str) -> str: + if not isinstance(value, str) or _DIGEST.fullmatch(value) is None: + raise LabelBlindManifestError(f"{field} must be a full lowercase SHA-256 digest") + return value + + +def _validated_inputs(selection: OrdinarySelectionV1, freeze: PopulationFreezeV3) -> tuple[str, ...]: + if type(selection) is not OrdinarySelectionV1: + raise LabelBlindManifestError("input authority must use exact OrdinarySelectionV1") + try: + content = ordinary_selection_bytes(selection) + except (TypeError, ValueError) as error: + raise LabelBlindManifestError("ordinary selection authority is invalid") from error + if not content: + raise LabelBlindManifestError("ordinary selection authority is unreadable or empty") + if selection.selection_digest != freeze.ordinary_selection_digest: + raise LabelBlindManifestError("ordinary selection does not match the frozen authority") + if selection.positive_change_digests != freeze.positive_change_digests: + raise LabelBlindManifestError("ordinary selection does not bind the exact frozen positives") + identities = (*freeze.positive_change_digests, *(push.push_digest for push in selection.pushes)) + if len(set(identities)) != len(identities): + raise LabelBlindManifestError("positive and ordinary input identities must be unique") + return tuple(sorted(identities)) + + +def _validated_sources( + freeze: PopulationFreezeV3, + partition: PopulationMaterialPartitionV1, +) -> tuple[str, str]: + if type(freeze) is not PopulationFreezeV3 or type(partition) is not PopulationMaterialPartitionV1: + raise LabelBlindManifestError("label-blind manifest requires exact replacement V3 authorities") + try: + freeze_content = population_freeze_bytes(freeze) + manifest_content = public_manifest_bytes(partition) + artifacts = material_artifact_bytes(partition) + except (TypeError, ValueError) as error: + raise LabelBlindManifestError("label-blind source authority is invalid") from error + if not freeze_content or not manifest_content or any(not item for item in artifacts): + raise LabelBlindManifestError("label-blind source authority is unreadable or empty") + manifest = partition.manifest + if (manifest.population_digest, manifest.freeze_digest) != (freeze.population_digest, freeze.freeze_digest): + raise LabelBlindManifestError("material partition does not bind the exact replacement freeze") + artifact_set = canonical.content_digest({"artifact_digests": tuple(canonical.bytes_digest(item) for item in artifacts)}) + return manifest.manifest_digest, artifact_set + + +def build_label_blind_population_draft( + freeze: PopulationFreezeV3, + partition: PopulationMaterialPartitionV1, + ordinary_selection: OrdinarySelectionV1, +) -> LabelBlindPopulationDraftV3: + """Derive label-blind census metadata from exact frozen authorities.""" + public_manifest_digest, artifact_set_digest = _validated_sources(freeze, partition) + inputs = _validated_inputs(ordinary_selection, freeze) + if not freeze.scope_census: + raise LabelBlindManifestError("label-blind population requires exact scope counts") + draft = LabelBlindPopulationDraftV3( + freeze.population_digest, + freeze.freeze_digest, + freeze.reservation_census_digest, + freeze.review_set_digest, + freeze.ordinary_selection_digest, + public_manifest_digest, + artifact_set_digest, + freeze.scope_census, + inputs, + freeze.positive_count, + len(inputs), + derive_evaluation_input_set_digest(inputs), + "", + ) + result = replace(draft, draft_digest=canonical.content_digest(_draft_value(draft, include_digest=False))) + label_blind_population_draft_bytes(result) + return result + + +def _validated_policy(policy: ReviewIndependencePolicy) -> ReviewIndependencePolicy: + if type(policy) is not ReviewIndependencePolicy: + raise LabelBlindManifestError("review policy must use exact ReviewIndependencePolicy") + try: + policy.__post_init__() + expected = derive_review_independence_policy_digest( + policy.reviewed_reviewer_digests, + policy.forbidden_identity_pairs, + policy.trusted_store_identities, + policy.maximum_evidence_bytes, + ) + except (FactPackValidationError, TypeError, ValueError) as error: + raise LabelBlindManifestError("review independence policy is invalid") from error + if policy.policy_digest != expected: + raise LabelBlindManifestError("review independence policy digest cannot be re-derived") + return policy + + +def _validated_review( + draft: LabelBlindPopulationDraftV3, + review: IndependenceAttestation, + policy: ReviewIndependencePolicy, + resolver: canonical.ContentResolver, +) -> str: + label_blind_population_draft_bytes(draft) + policy = _validated_policy(policy) + if type(review) is not IndependenceAttestation or type(review.conflict_disclosure) is not canonical.ContentRef: + raise LabelBlindManifestError("review must use exact detection-core independence contracts") + try: + review.__post_init__() + review.conflict_disclosure.__post_init__() + except (FactPackValidationError, TypeError, ValueError) as error: + raise LabelBlindManifestError("review attestation is invalid") from error + if review.subject_digest != draft.draft_digest: + raise LabelBlindManifestError("label-blind manifest review is stale") + if review.producer_identity == review.reviewer_identity: + raise LabelBlindManifestError("label-blind manifest review must be independent") + if review.reviewer_identity not in policy.reviewed_reviewer_digests: + raise LabelBlindManifestError("manifest reviewer is not admitted by policy") + if (review.producer_identity, review.reviewer_identity) in policy.forbidden_identity_pairs: + raise LabelBlindManifestError("manifest producer/reviewer pair is forbidden") + if review.attestation_digest != derive_independence_attestation_digest(review): + raise LabelBlindManifestError("review attestation digest cannot be re-derived") + try: + disclosure = canonical.resolve_content( + review.conflict_disclosure, + resolver, + trusted_store_identities=policy.trusted_store_identities, + maximum_bytes=policy.maximum_evidence_bytes, + ) + except (AttributeError, TypeError, ValueError, LookupError) as error: + raise LabelBlindManifestError("review conflict disclosure cannot be resolved") from error + if not disclosure: + raise LabelBlindManifestError("review conflict disclosure must be nonempty") + return review.attestation_digest + + +def _reviewed_manifest(draft: LabelBlindPopulationDraftV3, review_digest: str) -> LabelBlindPopulationManifestV3: + manifest = LabelBlindPopulationManifestV3( + draft.population_digest, + draft.freeze_digest, + draft.reservation_census_digest, + draft.review_set_digest, + draft.ordinary_selection_digest, + draft.public_material_manifest_digest, + draft.material_artifact_set_digest, + draft.scope_census, + draft.input_digests, + draft.positive_count, + draft.input_count, + draft.input_set_digest, + draft.draft_digest, + review_digest, + "", + ) + result = replace(manifest, manifest_digest=canonical.content_digest(_manifest_value(manifest, include_digest=False))) + label_blind_population_manifest_bytes(result) + return result + + +def review_label_blind_population_manifest( + draft: LabelBlindPopulationDraftV3, + review: IndependenceAttestation, + policy: ReviewIndependencePolicy, + resolver: canonical.ContentResolver, +) -> LabelBlindPopulationManifestV3: + """Accept an externally supplied core review of one exact draft.""" + return _reviewed_manifest(draft, _validated_review(draft, review, policy, resolver)) + + +def validate_label_blind_population_manifest( + manifest: LabelBlindPopulationManifestV3, + freeze: PopulationFreezeV3, + partition: PopulationMaterialPartitionV1, + ordinary_selection: OrdinarySelectionV1, + review: IndependenceAttestation, + policy: ReviewIndependencePolicy, + resolver: canonical.ContentResolver, +) -> bytes: + """Rebuild all label-blind authorities before accepting manifest bytes.""" + draft = build_label_blind_population_draft(freeze, partition, ordinary_selection) + expected = review_label_blind_population_manifest(draft, review, policy, resolver) + if manifest != expected: + raise LabelBlindManifestError("reviewed label-blind manifest does not replay from exact authorities") + return label_blind_population_manifest_bytes(manifest) + + +def accept_label_blind_population_manifest( + manifest: LabelBlindPopulationManifestV3, + freeze: PopulationFreezeV3, + partition: PopulationMaterialPartitionV1, + ordinary_selection: OrdinarySelectionV1, + review: IndependenceAttestation, + policy: ReviewIndependencePolicy, + resolver: canonical.ContentResolver, + *, + existing_content: bytes | None = None, +) -> bytes: + content = validate_label_blind_population_manifest(manifest, freeze, partition, ordinary_selection, review, policy, resolver) + if existing_content is not None and existing_content != content: + raise LabelBlindManifestConflict("same label-blind manifest identity resolves to different bytes") + return content + + +__all__ = [ + "IndependenceAttestation", + "LabelBlindManifestConflict", + "LabelBlindManifestError", + "LabelBlindPopulationDraftV3", + "LabelBlindPopulationManifestV3", + "ReviewIndependencePolicy", + "accept_label_blind_population_manifest", + "build_label_blind_population_draft", + "label_blind_population_manifest_bytes", + "review_label_blind_population_manifest", + "validate_label_blind_population_manifest", +] diff --git a/benchmarks/valid/population_label_blind_contract.py b/benchmarks/valid/population_label_blind_contract.py new file mode 100644 index 00000000..561113b7 --- /dev/null +++ b/benchmarks/valid/population_label_blind_contract.py @@ -0,0 +1,178 @@ +"""Canonical contracts for the reviewed label-blind population manifest.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +from benchmarks.valid.population_freeze_contract import PopulationScopeCountV1 +from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest +from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest + +LABEL_BLIND_DRAFT_SCHEMA = "openultrasast.valid-detection-benchmark.label-blind-population-draft.v3" +LABEL_BLIND_MANIFEST_SCHEMA = "openultrasast.valid-detection-benchmark.label-blind-population-manifest.v3" +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +class LabelBlindManifestError(ValueError): + """A label-blind manifest or its review violates the canonical contract.""" + + +class LabelBlindManifestConflict(LabelBlindManifestError): + """One accepted manifest identity resolves to different bytes.""" + + +@dataclass(frozen=True) +class LabelBlindPopulationDraftV3: + population_digest: str + freeze_digest: str + reservation_census_digest: str + review_set_digest: str + ordinary_selection_digest: str + public_material_manifest_digest: str + material_artifact_set_digest: str + scope_census: tuple[PopulationScopeCountV1, ...] + input_digests: tuple[str, ...] + positive_count: int + input_count: int + input_set_digest: str + draft_digest: str + + +@dataclass(frozen=True) +class LabelBlindPopulationManifestV3: + population_digest: str + freeze_digest: str + reservation_census_digest: str + review_set_digest: str + ordinary_selection_digest: str + public_material_manifest_digest: str + material_artifact_set_digest: str + scope_census: tuple[PopulationScopeCountV1, ...] + input_digests: tuple[str, ...] + positive_count: int + input_count: int + input_set_digest: str + draft_digest: str + review_digest: str + manifest_digest: str + + +def _digest(value: object, field: str) -> str: + if not isinstance(value, str) or _DIGEST.fullmatch(value) is None: + raise LabelBlindManifestError(f"{field} must be a full lowercase SHA-256 digest") + return value + + +def _count(value: object, field: str, *, positive: bool = False) -> int: + minimum = 1 if positive else 0 + if type(value) is not int or value < minimum: + qualifier = "positive" if positive else "nonnegative" + raise LabelBlindManifestError(f"{field} must be a {qualifier} integer") + return value + + +def _scope_value(row: PopulationScopeCountV1) -> dict[str, JsonValue]: + if type(row) is not PopulationScopeCountV1: + raise LabelBlindManifestError("scope census must contain exact PopulationScopeCountV1 rows") + return { + "vulnerability_family": row.vulnerability_family, + "ecosystem": row.ecosystem.value, + "count": _count(row.count, "scope count", positive=True), + } + + +def _validate_draft_shape(draft: LabelBlindPopulationDraftV3) -> None: + if type(draft) is not LabelBlindPopulationDraftV3: + raise LabelBlindManifestError("label-blind draft must use the exact V3 contract") + if draft.scope_census != tuple(sorted(set(draft.scope_census))) or not draft.scope_census: + raise LabelBlindManifestError("scope census must be nonempty and canonical") + if draft.input_digests != tuple(sorted(set(draft.input_digests))) or not draft.input_digests: + raise LabelBlindManifestError("input identities must be nonempty and canonical") + for item in draft.input_digests: + _digest(item, "input identity") + positive_count = _count(draft.positive_count, "positive count", positive=True) + input_count = _count(draft.input_count, "input count", positive=True) + if input_count != len(draft.input_digests) or positive_count > input_count: + raise LabelBlindManifestError("manifest counts do not match exact input identities") + if any(row.count > positive_count for row in draft.scope_census): + raise LabelBlindManifestError("scope census count exceeds the positive population") + if draft.input_set_digest != derive_evaluation_input_set_digest(draft.input_digests): + raise LabelBlindManifestError("input-set digest does not match canonical input identities") + + +def _draft_value(draft: LabelBlindPopulationDraftV3, *, include_digest: bool) -> dict[str, JsonValue]: + _validate_draft_shape(draft) + value: dict[str, JsonValue] = { + "schema_version": LABEL_BLIND_DRAFT_SCHEMA, + "population_digest": _digest(draft.population_digest, "population"), + "freeze_digest": _digest(draft.freeze_digest, "freeze"), + "reservation_census_digest": _digest(draft.reservation_census_digest, "reservation census"), + "review_set_digest": _digest(draft.review_set_digest, "review set"), + "ordinary_selection_digest": _digest(draft.ordinary_selection_digest, "ordinary selection"), + "public_material_manifest_digest": _digest(draft.public_material_manifest_digest, "public material manifest"), + "material_artifact_set_digest": _digest(draft.material_artifact_set_digest, "material artifact set"), + "scope_census": tuple(_scope_value(row) for row in draft.scope_census), + "input_digests": draft.input_digests, + "positive_count": draft.positive_count, + "input_count": draft.input_count, + "input_set_digest": _digest(draft.input_set_digest, "input set"), + } + if include_digest: + value["draft_digest"] = _digest(draft.draft_digest, "label-blind draft") + return value + + +def label_blind_population_draft_bytes(draft: LabelBlindPopulationDraftV3) -> bytes: + value = _draft_value(draft, include_digest=False) + if content_digest(value) != draft.draft_digest: + raise LabelBlindManifestError("label-blind draft digest does not match") + return canonical_bytes(_draft_value(draft, include_digest=True)) + + +def _manifest_draft(manifest: LabelBlindPopulationManifestV3) -> LabelBlindPopulationDraftV3: + return LabelBlindPopulationDraftV3( + manifest.population_digest, + manifest.freeze_digest, + manifest.reservation_census_digest, + manifest.review_set_digest, + manifest.ordinary_selection_digest, + manifest.public_material_manifest_digest, + manifest.material_artifact_set_digest, + manifest.scope_census, + manifest.input_digests, + manifest.positive_count, + manifest.input_count, + manifest.input_set_digest, + manifest.draft_digest, + ) + + +def _manifest_value(manifest: LabelBlindPopulationManifestV3, *, include_digest: bool) -> dict[str, JsonValue]: + if type(manifest) is not LabelBlindPopulationManifestV3: + raise LabelBlindManifestError("label-blind manifest must use the exact V3 contract") + draft = _manifest_draft(manifest) + label_blind_population_draft_bytes(draft) + value = _draft_value(draft, include_digest=True) + value["schema_version"] = LABEL_BLIND_MANIFEST_SCHEMA + value["review_digest"] = _digest(manifest.review_digest, "label-blind manifest review") + if include_digest: + value["manifest_digest"] = _digest(manifest.manifest_digest, "label-blind manifest") + return value + + +def label_blind_population_manifest_bytes(manifest: LabelBlindPopulationManifestV3) -> bytes: + value = _manifest_value(manifest, include_digest=False) + if content_digest(value) != manifest.manifest_digest: + raise LabelBlindManifestError("label-blind manifest digest does not match") + return canonical_bytes(_manifest_value(manifest, include_digest=True)) + + +__all__ = [ + "LabelBlindManifestConflict", + "LabelBlindManifestError", + "LabelBlindPopulationDraftV3", + "LabelBlindPopulationManifestV3", + "label_blind_population_draft_bytes", + "label_blind_population_manifest_bytes", +] diff --git a/tests/test_valid_benchmark_label_blind_manifest.py b/tests/test_valid_benchmark_label_blind_manifest.py new file mode 100644 index 00000000..407138b1 --- /dev/null +++ b/tests/test_valid_benchmark_label_blind_manifest.py @@ -0,0 +1,295 @@ +"""Reviewed label-blind replacement population manifest tests.""" + +from __future__ import annotations + +import json +import sys +from dataclasses import replace +from functools import lru_cache +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from detection_core_fixtures import InMemoryContentResolver, stored_artifact # noqa: E402 +from test_core_evaluation_plan import _configuration # noqa: E402 +from test_valid_benchmark_population_freeze import ( # noqa: E402 + _freeze as _reviewed_freeze, +) +from test_valid_benchmark_population_freeze import ( + _positives, + _selection, +) +from test_valid_benchmark_population_materials import _digest, _Validator # noqa: E402 + +from benchmarks.valid import population_label_blind as label_blind # noqa: E402 +from benchmarks.valid import population_materials as materials # noqa: E402 +from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1 # noqa: E402 +from benchmarks.valid.population_freeze_contract import PopulationFreezeV3 # noqa: E402 +from openultrasast.core import canonical # noqa: E402 +from openultrasast.core.evaluation_plan import ( # noqa: E402 + create_evaluation_plan_declaration, + derive_evaluation_input_set_digest, +) +from openultrasast.core.factpack import ( # noqa: E402 + IndependenceAttestation, + ReviewIndependencePolicy, + derive_independence_attestation_digest, + derive_review_independence_policy_digest, +) + + +def _policy( + reviewer: str, + forbidden: tuple[tuple[str, str], ...] = (), + *, + stores: tuple[str, ...] = ("trusted-store",), + maximum_bytes: int = 4096, +) -> ReviewIndependencePolicy: + digest = derive_review_independence_policy_digest((reviewer,), forbidden, stores, maximum_bytes) + return ReviewIndependencePolicy((reviewer,), forbidden, stores, maximum_bytes, digest) + + +def _attestation( + subject: str, + disclosure: canonical.ContentRef, + *, + producer: str | None = None, + reviewer: str | None = None, +) -> IndependenceAttestation: + draft = IndependenceAttestation( + subject, + producer or _digest("manifest-producer"), + reviewer or _digest("manifest-reviewer"), + disclosure, + "0" * 64, + ) + return replace(draft, attestation_digest=derive_independence_attestation_digest(draft)) + + +@lru_cache(maxsize=1) +def _sources() -> tuple[ + PopulationFreezeV3, + OrdinarySelectionV1, + materials.PopulationMaterialPartitionV1, +]: + positives = _positives() + selection = _selection(positives) + freeze = _reviewed_freeze(positives) + material_inputs = tuple( + materials.PopulationMaterialInputV1( + change, + materials.LicenseClass.PERMISSIVE, + "Apache-2.0", + f"public source {index}".encode(), + f"sealed label {index}".encode(), + f"sealed review {index}".encode(), + True, + ) + for index, change in enumerate(freeze.positive_change_digests) + ) + partition = materials.build_population_material_partition( + freeze, + material_inputs, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + return freeze, selection, partition + + +def _reviewed() -> tuple[ + PopulationFreezeV3, + OrdinarySelectionV1, + materials.PopulationMaterialPartitionV1, + ReviewIndependencePolicy, + InMemoryContentResolver, + IndependenceAttestation, + label_blind.LabelBlindPopulationManifestV3, +]: + freeze, selection, partition = _sources() + draft = label_blind.build_label_blind_population_draft(freeze, partition, selection) + disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="label-blind-conflicts") + review = _attestation(draft.draft_digest, disclosure) + policy = _policy(review.reviewer_identity) + manifest = label_blind.review_label_blind_population_manifest(draft, review, policy, resolver) + return freeze, selection, partition, policy, resolver, review, manifest + + +def _validate( + case: tuple[ + PopulationFreezeV3, + OrdinarySelectionV1, + materials.PopulationMaterialPartitionV1, + ReviewIndependencePolicy, + InMemoryContentResolver, + IndependenceAttestation, + label_blind.LabelBlindPopulationManifestV3, + ], +) -> bytes: + freeze, selection, partition, policy, resolver, review, manifest = case + return label_blind.validate_label_blind_population_manifest(manifest, freeze, partition, selection, review, policy, resolver) + + +def test_reviewed_manifest_replays_core_v3_input_identity_and_exact_census() -> None: + case = _reviewed() + content = _validate(case) + manifest = case[-1] + decoded = json.loads(content) + + assert decoded["input_digests"] == list(manifest.input_digests) + assert decoded["input_count"] == len(manifest.input_digests) + assert manifest.input_set_digest == derive_evaluation_input_set_digest(manifest.input_digests) + declaration = create_evaluation_plan_declaration( + population_digest=manifest.population_digest, + freeze_digest=manifest.freeze_digest, + input_set_digest=manifest.input_set_digest, + arm_configurations=(_configuration("compatibility-arm"),), + input_identity_digests=manifest.input_digests, + ) + assert declaration.input_set_digest == manifest.input_set_digest + assert decoded["scope_census"] + assert decoded["review_digest"] == case[-2].attestation_digest + + +def test_inputs_are_frozen_positives_plus_unique_underlying_pushes_once() -> None: + freeze, selection, *_ = _reviewed() + manifest = _reviewed()[-1] + expected = tuple(sorted((*freeze.positive_change_digests, *(push.push_digest for push in selection.pushes)))) + + assert manifest.input_digests == expected + assert manifest.input_count == freeze.positive_count + len(selection.pushes) + assert len(manifest.input_digests) < len(selection.assignments) + freeze.positive_count + + +def test_manifest_contains_only_census_and_digest_metadata() -> None: + _, _, partition, _, _, review, manifest = _reviewed() + content = label_blind.label_blind_population_manifest_bytes(manifest) + decoded = json.loads(content) + + for forbidden in (b"sealed label", b"sealed review", b"public source", b"content_base64", b"/home/", b"password="): + assert forbidden not in content + assert partition.manifest.private_object_digest.encode() not in content + assert partition.manifest.sealed_label_digest.encode() not in content + assert review.producer_identity.encode() not in content + assert review.reviewer_identity.encode() not in content + assert set(decoded) == { + "draft_digest", + "freeze_digest", + "input_count", + "input_digests", + "input_set_digest", + "manifest_digest", + "material_artifact_set_digest", + "ordinary_selection_digest", + "population_digest", + "positive_count", + "public_material_manifest_digest", + "reservation_census_digest", + "review_digest", + "review_set_digest", + "schema_version", + "scope_census", + } + + +@pytest.mark.parametrize("mutation", ("extra", "missing", "digest", "positives", "malformed")) +def test_changed_or_malformed_ordinary_selection_is_refused(mutation: str) -> None: + freeze, selection, partition = _sources() + changed = selection + if mutation == "extra": + extra = replace(selection.pushes[-1], push_digest=_digest("arbitrary-extra-push")) + changed = replace(selection, pushes=tuple(sorted((*selection.pushes, extra)))) + elif mutation == "missing": + changed = replace(selection, pushes=selection.pushes[:-1]) + elif mutation == "digest": + changed = replace(selection, selection_digest=_digest("wrong-selection")) + elif mutation == "positives": + changed = replace(selection, positive_change_digests=selection.positive_change_digests[:-1]) + else: + changed_push = replace(selection.pushes[0], change_byte_length=0) + changed = replace(selection, pushes=(changed_push, *selection.pushes[1:])) + + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.build_label_blind_population_draft(freeze, partition, changed) + + +def test_review_requires_exact_core_independence_authority() -> None: + freeze, selection, partition = _sources() + draft = label_blind.build_label_blind_population_draft(freeze, partition, selection) + disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="review-policy-cases") + producer = _digest("manifest-producer") + reviewer = _digest("manifest-reviewer") + accepted = _attestation(draft.draft_digest, disclosure, producer=producer, reviewer=reviewer) + + cases = ( + (_attestation(draft.draft_digest, disclosure, reviewer=_digest("unregistered")), _policy(reviewer), resolver), + (accepted, _policy(reviewer, ((producer, reviewer),)), resolver), + (accepted, replace(_policy(reviewer), policy_digest=_digest("wrong-policy")), resolver), + (_attestation(_digest("wrong-subject"), disclosure, producer=producer, reviewer=reviewer), _policy(reviewer), resolver), + (replace(accepted, attestation_digest=_digest("wrong-attestation")), _policy(reviewer), resolver), + (_attestation(draft.draft_digest, disclosure, producer=reviewer, reviewer=reviewer), _policy(reviewer), resolver), + ) + for review, policy, selected_resolver in cases: + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.review_label_blind_population_manifest(draft, review, policy, selected_resolver) + + +@pytest.mark.parametrize("failure", ("missing", "wrong_store", "oversized", "empty")) +def test_conflict_disclosure_must_resolve_nonempty_under_policy(failure: str) -> None: + freeze, selection, partition = _sources() + draft = label_blind.build_label_blind_population_draft(freeze, partition, selection) + content = b'{"conflicts":[]}' if failure != "empty" else b"" + store = "wrong-store" if failure == "wrong_store" else "trusted-store" + disclosure, resolver = stored_artifact(content, artifact_id=f"disclosure-{failure}", store_identity=store) + if failure == "missing": + resolver = InMemoryContentResolver({}) + review = _attestation(draft.draft_digest, disclosure) + maximum = max(1, disclosure.byte_length - 1) if failure == "oversized" else 4096 + + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.review_label_blind_population_manifest( + draft, review, _policy(review.reviewer_identity, maximum_bytes=maximum), resolver + ) + + +def test_stale_population_material_scope_and_review_are_refused() -> None: + freeze, selection, partition, policy, resolver, review, manifest = _reviewed() + changed_freeze = replace(freeze, population_digest=_digest("changed-population")) + changed_partition = replace(partition, manifest=replace(partition.manifest, manifest_digest=_digest("changed-material"))) + + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.validate_label_blind_population_manifest(manifest, changed_freeze, partition, selection, review, policy, resolver) + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.validate_label_blind_population_manifest(manifest, freeze, changed_partition, selection, review, policy, resolver) + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.validate_label_blind_population_manifest( + replace(manifest, scope_census=()), freeze, partition, selection, review, policy, resolver + ) + with pytest.raises(label_blind.LabelBlindManifestError): + label_blind.validate_label_blind_population_manifest( + replace(manifest, input_set_digest=_digest("wrong-input-set")), + freeze, + partition, + selection, + review, + policy, + resolver, + ) + + +def test_same_identity_different_bytes_conflicts() -> None: + case = _reviewed() + content = _validate(case) + freeze, selection, partition, policy, resolver, review, manifest = case + + assert ( + label_blind.accept_label_blind_population_manifest( + manifest, freeze, partition, selection, review, policy, resolver, existing_content=content + ) + == content + ) + with pytest.raises(label_blind.LabelBlindManifestConflict): + label_blind.accept_label_blind_population_manifest( + manifest, freeze, partition, selection, review, policy, resolver, existing_content=content + b"\n" + )