diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 087e256f..99c0bbfb 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -112,14 +112,13 @@ - Done when only a freeze with at least forty accepted positives across Python and JavaScript/TypeScript and at least two families can be admission class, while unchanged material reproduces its identity and conflicting bytes are refused. - _Requirements: 1.1, 1.2, 1.3, 1.4, 1.6, 1.7, 3.2, 7.1, 7.2, 7.3_ - _Boundary: Population Freezer_ -- [ ] 4.3 Separate public material, private material, and sealed labels +- [x] 4.3 Separate public material, private material, and sealed labels - Publish only permissively licensed source material and represent uncertain or non-permissive content through opaque digest-bound private references. - Keep label bytes and review judgments in private sealed objects unavailable to detector arms and presenters. - Bind public manifest, private-object digest, sealed-label digest, license partitions, and exclusion counts without exposing private paths or payloads. - 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_ - - _Blocked: two debug rounds plus five user-authorized extra repair/review cycles are exhausted — prior embedded-source forms and caps are fixed, but rooted paths after newline/comment/list boundaries remain public while complete standalone Unicode escapes are falsely classified private._ - [ ] 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. @@ -424,4 +423,4 @@ - Task 3.3 revalidates exact candidate and ecosystem authorities, derives accepted/excluded ground truth from explicit independent human judgments, keeps model assistance non-authoritative, and projects each change once while preserving all verified exact scopes. - 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 remains blocked after two debug rounds and five user-authorized extra cycles: 91 material and 322 benchmark tests and all caps are green; independent probes still expose newline/CRLF/comment/list-prefixed rooted paths and false-positive complete Unicode escapes, indicating the inline-source path-filter boundary needs an explicit architectural decision. +- 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. diff --git a/benchmarks/valid/population_material_contract.py b/benchmarks/valid/population_material_contract.py new file mode 100644 index 00000000..adb6c2a2 --- /dev/null +++ b/benchmarks/valid/population_material_contract.py @@ -0,0 +1,366 @@ +"""Canonical contracts for public, private, and sealed population material.""" + +from __future__ import annotations + +import base64 +import re +from dataclasses import dataclass +from enum import StrEnum + +from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes, content_digest + +PUBLIC_MANIFEST_SCHEMA = "openultrasast.valid-detection-benchmark.public-material-manifest.v1" +PUBLIC_SOURCE_OBJECT_SCHEMA = "openultrasast.valid-detection-benchmark.public-source-object.v1" +PRIVATE_OBJECT_SCHEMA = "openultrasast.valid-detection-benchmark.private-material-object.v1" +SEALED_LABEL_SCHEMA = "openultrasast.valid-detection-benchmark.sealed-label-object.v1" +MATERIAL_AUTHORITY_SCHEMA = "openultrasast.valid-detection-benchmark.material-access-authority.v1" +_DIGEST = re.compile(r"[0-9a-f]{64}") +PERMISSIVE_PUBLIC_LICENSES = frozenset( + {"0BSD", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "CC0-1.0", "ISC", "MIT", "Python-2.0", "Unlicense"} +) + + +class PopulationMaterialError(ValueError): + """Population material violates its access or identity contract.""" + + +class PopulationMaterialConflict(PopulationMaterialError): + """An existing material identity resolves to different bytes.""" + + +class LicenseClass(StrEnum): + PERMISSIVE = "permissive" + NON_PERMISSIVE = "non_permissive" + UNCERTAIN = "uncertain" + + +class MaterialActorRole(StrEnum): + CUSTODIAN = "custodian" + DETECTOR = "detector" + PRESENTER = "presenter" + OPERATOR = "operator" + + +class MaterialPermission(StrEnum): + PRIVATE_SOURCE = "private_source" + SEALED_LABELS = "sealed_labels" + + +@dataclass(frozen=True) +class PopulationMaterialInputV1: + change_digest: str + license_class: LicenseClass + license_expression: str + source_content: bytes + label_content: bytes + review_judgment_content: bytes + public_distribution_approved: bool + + +@dataclass(frozen=True, order=True) +class PublicSourceRecordV1: + change_digest: str + license_class: LicenseClass + license_expression: str + source_digest: str + byte_length: int + object_digest: str + + +@dataclass(frozen=True, order=True) +class PublicSourceObjectV1: + change_digest: str + source_digest: str + source_content: bytes + + +@dataclass(frozen=True, order=True) +class OpaquePrivateMaterialRefV1: + change_digest: str + license_class: LicenseClass + source_digest: str + byte_length: int + + +@dataclass(frozen=True, order=True) +class PrivateSourceRecordV1: + change_digest: str + source_digest: str + source_content: bytes + + +@dataclass(frozen=True, order=True) +class SealedLabelRecordV1: + change_digest: str + label_digest: str + judgment_digest: str + label_content: bytes + judgment_content: bytes + + +@dataclass(frozen=True) +class PublicPopulationMaterialManifestV1: + population_digest: str + freeze_digest: str + positive_change_digests: tuple[str, ...] + public_sources: tuple[PublicSourceRecordV1, ...] + private_refs: tuple[OpaquePrivateMaterialRefV1, ...] + private_object_digest: str + sealed_label_digest: str + license_partitions: tuple[tuple[LicenseClass, int], ...] + exclusion_counts: tuple[tuple[str, int], ...] + public_count: int + private_count: int + partition_policy_digest: str + manifest_digest: str + + +@dataclass(frozen=True) +class PopulationMaterialPartitionV1: + manifest: PublicPopulationMaterialManifestV1 + public_source_objects: tuple[PublicSourceObjectV1, ...] + private_records: tuple[PrivateSourceRecordV1, ...] + sealed_label_records: tuple[SealedLabelRecordV1, ...] + + +@dataclass(frozen=True) +class MaterialAccessAuthorityV1: + population_digest: str + freeze_digest: str + manifest_digest: str + partition_policy_digest: str + private_object_digest: str + sealed_label_digest: str + actor_role: MaterialActorRole + permissions: tuple[MaterialPermission, ...] + policy_digest: str + authority_digest: str + + +def _digest(value: object, field: str) -> str: + if not isinstance(value, str) or _DIGEST.fullmatch(value) is None: + raise PopulationMaterialError(f"{field} must be a full lowercase SHA-256 digest") + return value + + +def _text(value: object, field: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise PopulationMaterialError(f"{field} must be nonempty text") + return value.strip() + + +def _nonempty_bytes(value: object, field: str) -> bytes: + if not isinstance(value, bytes) or not value: + raise PopulationMaterialError(f"{field} bytes must be nonempty") + return value + + +def _positive_length(value: object, field: str) -> int: + if type(value) is not int or value <= 0: + raise PopulationMaterialError(f"{field} byte length must be positive") + return value + + +def _public_value(record: PublicSourceRecordV1) -> dict[str, JsonValue]: + if LicenseClass(record.license_class) is not LicenseClass.PERMISSIVE: + raise PopulationMaterialError("public source must be permissively licensed") + expression = _text(record.license_expression, "license expression") + if expression not in PERMISSIVE_PUBLIC_LICENSES: + raise PopulationMaterialError("public source license is outside the closed permissive policy") + return { + "change_digest": _digest(record.change_digest, "public change"), + "license_class": LicenseClass.PERMISSIVE.value, + "license_expression": expression, + "source_digest": _digest(record.source_digest, "public source"), + "byte_length": _positive_length(record.byte_length, "public source"), + "object_digest": _digest(record.object_digest, "public source object"), + } + + +def _public_object_value(record: PublicSourceObjectV1) -> dict[str, JsonValue]: + content = _nonempty_bytes(record.source_content, "public source") + if bytes_digest(content) != _digest(record.source_digest, "public source"): + raise PopulationMaterialError("public source digest does not match bytes") + return { + "schema_version": PUBLIC_SOURCE_OBJECT_SCHEMA, + "change_digest": _digest(record.change_digest, "public change"), + "source_digest": record.source_digest, + "byte_length": len(content), + "content_base64": base64.b64encode(content).decode("ascii"), + } + + +def public_source_record_bytes(record: PublicSourceObjectV1) -> bytes: + """Serialize one typed public source object independently of its manifest.""" + return canonical_bytes(_public_object_value(record)) + + +def _private_ref_value(record: OpaquePrivateMaterialRefV1) -> dict[str, JsonValue]: + return { + "change_digest": _digest(record.change_digest, "private change"), + "license_class": LicenseClass(record.license_class).value, + "source_digest": _digest(record.source_digest, "private source"), + "byte_length": _positive_length(record.byte_length, "private source"), + } + + +def _private_record_value(record: PrivateSourceRecordV1) -> dict[str, JsonValue]: + content = _nonempty_bytes(record.source_content, "private source") + if bytes_digest(content) != _digest(record.source_digest, "private source"): + raise PopulationMaterialError("private source digest does not match bytes") + return { + "change_digest": _digest(record.change_digest, "private change"), + "source_digest": record.source_digest, + "byte_length": len(content), + "content_base64": base64.b64encode(content).decode("ascii"), + } + + +def _label_record_value(record: SealedLabelRecordV1) -> dict[str, JsonValue]: + label = _nonempty_bytes(record.label_content, "label") + judgment = _nonempty_bytes(record.judgment_content, "review judgment") + if bytes_digest(label) != _digest(record.label_digest, "label"): + raise PopulationMaterialError("label digest does not match bytes") + if bytes_digest(judgment) != _digest(record.judgment_digest, "review judgment"): + raise PopulationMaterialError("review judgment digest does not match bytes") + return { + "change_digest": _digest(record.change_digest, "sealed change"), + "label_digest": record.label_digest, + "judgment_digest": record.judgment_digest, + "label_base64": base64.b64encode(label).decode("ascii"), + "judgment_base64": base64.b64encode(judgment).decode("ascii"), + } + + +def private_object_bytes(partition: PopulationMaterialPartitionV1) -> bytes: + if partition.private_records != tuple(sorted(set(partition.private_records))): + raise PopulationMaterialError("private records are not canonical") + records = tuple(_private_record_value(record) for record in partition.private_records) + return canonical_bytes({"schema_version": PRIVATE_OBJECT_SCHEMA, "records": records}) + + +def sealed_label_object_bytes(partition: PopulationMaterialPartitionV1) -> bytes: + if partition.sealed_label_records != tuple(sorted(set(partition.sealed_label_records))): + raise PopulationMaterialError("sealed label records are not canonical") + records = tuple(_label_record_value(record) for record in partition.sealed_label_records) + return canonical_bytes({"schema_version": SEALED_LABEL_SCHEMA, "records": records}) + + +def _manifest_value(manifest: PublicPopulationMaterialManifestV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": PUBLIC_MANIFEST_SCHEMA, + "population_digest": _digest(manifest.population_digest, "population"), + "freeze_digest": _digest(manifest.freeze_digest, "freeze"), + "positive_change_digests": tuple(_digest(item, "positive change") for item in manifest.positive_change_digests), + "public_sources": tuple(_public_value(record) for record in manifest.public_sources), + "private_refs": tuple(_private_ref_value(record) for record in manifest.private_refs), + "private_object_digest": _digest(manifest.private_object_digest, "private object"), + "sealed_label_digest": _digest(manifest.sealed_label_digest, "sealed label object"), + "license_partitions": tuple((item.value, count) for item, count in manifest.license_partitions), + "exclusion_counts": manifest.exclusion_counts, + "public_count": manifest.public_count, + "private_count": manifest.private_count, + "partition_policy_digest": _digest(manifest.partition_policy_digest, "partition policy"), + } + if include_digest: + value["manifest_digest"] = _digest(manifest.manifest_digest, "public manifest") + return value + + +def _validate_manifest_counts(manifest: PublicPopulationMaterialManifestV1) -> None: + expected_licenses = tuple(sorted(set(manifest.license_partitions), key=lambda item: item[0].value)) + if manifest.license_partitions != expected_licenses: + raise PopulationMaterialError("license partitions are not canonical") + if any(type(count) is not int or count <= 0 for _, count in manifest.license_partitions): + raise PopulationMaterialError("license partition counts must be positive") + exclusion_identities = tuple(reason for reason, _ in manifest.exclusion_counts) + if len(exclusion_identities) != len(set(exclusion_identities)): + raise PopulationMaterialError("exclusion reason identities must be unique") + expected_exclusions = tuple(sorted(manifest.exclusion_counts)) + if manifest.exclusion_counts != expected_exclusions: + raise PopulationMaterialError("exclusion counts are not canonical") + for reason, count in manifest.exclusion_counts: + _digest(reason, "exclusion reason") + if type(count) is not int or count < 0: + raise PopulationMaterialError("exclusion counts must be nonnegative") + if any(type(count) is not int or count < 0 for count in (manifest.public_count, manifest.private_count)): + raise PopulationMaterialError("public/private counts must be nonnegative integers") + if manifest.public_count != len(manifest.public_sources) or manifest.private_count != len(manifest.private_refs): + raise PopulationMaterialError("public/private counts do not match records") + if sum(count for _, count in manifest.license_partitions) != len(manifest.positive_change_digests): + raise PopulationMaterialError("license partitions do not cover exact positive set") + + +def _public_manifest_bytes(partition: PopulationMaterialPartitionV1) -> bytes: + manifest = partition.manifest + if manifest.public_sources != tuple(sorted(set(manifest.public_sources))): + raise PopulationMaterialError("public sources are not canonical") + if manifest.private_refs != tuple(sorted(set(manifest.private_refs))): + raise PopulationMaterialError("private references are not canonical") + if manifest.positive_change_digests != tuple(sorted(set(manifest.positive_change_digests))): + raise PopulationMaterialError("positive identities are not canonical") + _validate_manifest_counts(manifest) + value = _manifest_value(manifest, include_digest=False) + if content_digest(value) != manifest.manifest_digest: + raise PopulationMaterialError("public manifest digest does not match") + return canonical_bytes(_manifest_value(manifest, include_digest=True)) + + +def _authority_value(authority: MaterialAccessAuthorityV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": MATERIAL_AUTHORITY_SCHEMA, + "population_digest": _digest(authority.population_digest, "authority population"), + "freeze_digest": _digest(authority.freeze_digest, "authority freeze"), + "manifest_digest": _digest(authority.manifest_digest, "authority manifest"), + "partition_policy_digest": _digest(authority.partition_policy_digest, "authority partition policy"), + "private_object_digest": _digest(authority.private_object_digest, "authority private object"), + "sealed_label_digest": _digest(authority.sealed_label_digest, "authority sealed label object"), + "actor_role": MaterialActorRole(authority.actor_role).value, + "permissions": tuple(MaterialPermission(item).value for item in authority.permissions), + "policy_digest": _digest(authority.policy_digest, "access policy"), + } + if include_digest: + value["authority_digest"] = _digest(authority.authority_digest, "material authority") + return value + + +def validate_material_authority( + authority: MaterialAccessAuthorityV1, + *, + expected_access_policy_digest: str, +) -> None: + permissions = tuple(sorted(set(authority.permissions), key=lambda item: item.value)) + if authority.permissions != permissions: + raise PopulationMaterialError("material permissions are not canonical") + if authority.actor_role is not MaterialActorRole.CUSTODIAN and permissions: + raise PopulationMaterialError("non-custodian material permissions are forbidden") + expected = _digest(expected_access_policy_digest, "expected access policy") + if authority.policy_digest != expected: + raise PopulationMaterialError("material access is not authorized: access policy mismatch") + if content_digest(_authority_value(authority, include_digest=False)) != authority.authority_digest: + raise PopulationMaterialError("material authority digest does not match") + + +__all__ = [ + "LicenseClass", + "MaterialAccessAuthorityV1", + "MaterialActorRole", + "MaterialPermission", + "OpaquePrivateMaterialRefV1", + "PERMISSIVE_PUBLIC_LICENSES", + "PopulationMaterialConflict", + "PopulationMaterialError", + "PopulationMaterialInputV1", + "PopulationMaterialPartitionV1", + "PrivateSourceRecordV1", + "PublicPopulationMaterialManifestV1", + "PublicSourceObjectV1", + "PublicSourceRecordV1", + "SealedLabelRecordV1", + "_authority_value", + "_manifest_value", + "private_object_bytes", + "public_source_record_bytes", + "sealed_label_object_bytes", + "validate_material_authority", +] diff --git a/benchmarks/valid/population_materials.py b/benchmarks/valid/population_materials.py new file mode 100644 index 00000000..aa9d5cf9 --- /dev/null +++ b/benchmarks/valid/population_materials.py @@ -0,0 +1,447 @@ +"""Partition frozen population material into public, private, and sealed bytes.""" + +from __future__ import annotations + +import re +from collections import Counter +from collections.abc import Iterable +from dataclasses import replace +from typing import Protocol + +from benchmarks.valid.population_freeze_contract import PopulationFreezeV3, population_freeze_bytes +from benchmarks.valid.population_material_contract import ( + PERMISSIVE_PUBLIC_LICENSES, + LicenseClass, + MaterialAccessAuthorityV1, + MaterialActorRole, + MaterialPermission, + OpaquePrivateMaterialRefV1, + PopulationMaterialConflict, + PopulationMaterialError, + PopulationMaterialInputV1, + PopulationMaterialPartitionV1, + PrivateSourceRecordV1, + PublicPopulationMaterialManifestV1, + PublicSourceObjectV1, + PublicSourceRecordV1, + SealedLabelRecordV1, + _authority_value, + _manifest_value, + _public_manifest_bytes, + private_object_bytes, + public_source_record_bytes, + sealed_label_object_bytes, + validate_material_authority, +) +from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes, content_digest + +MATERIAL_SUMMARY_SCHEMA = "openultrasast.valid-detection-benchmark.material-summary.v1" +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +class PopulationFreezeValidator(Protocol): + def validate(self, freeze: PopulationFreezeV3) -> bytes: ... + + +def _digest(value: object, field: str) -> str: + if not isinstance(value, str) or _DIGEST.fullmatch(value) is None: + raise PopulationMaterialError(f"{field} must be a full lowercase SHA-256 digest") + return value + + +def _validate_freeze(freeze: PopulationFreezeV3, validator: PopulationFreezeValidator) -> None: + try: + validated = validator.validate(freeze) + canonical = population_freeze_bytes(freeze) + except (TypeError, ValueError) as error: + raise PopulationMaterialError("freeze does not replay from exact authorities") from error + if not isinstance(validated, bytes) or not validated or validated != canonical: + raise PopulationMaterialError("freeze validator did not return exact canonical bytes") + + +def _material(item: PopulationMaterialInputV1) -> PopulationMaterialInputV1: + change = _digest(item.change_digest, "material change") + try: + license_class = LicenseClass(item.license_class) + except (TypeError, ValueError) as error: + raise PopulationMaterialError("license class is unsupported") from error + if not isinstance(item.license_expression, str) or not item.license_expression.strip(): + raise PopulationMaterialError("license expression must be nonempty") + for content, field in ( + (item.source_content, "source"), + (item.label_content, "label"), + (item.review_judgment_content, "review judgment"), + ): + if not isinstance(content, bytes) or not content: + raise PopulationMaterialError(f"{field} bytes must be nonempty") + if type(item.public_distribution_approved) is not bool: + raise PopulationMaterialError("public distribution approval must be boolean") + return PopulationMaterialInputV1( + change, + license_class, + item.license_expression.strip(), + item.source_content, + item.label_content, + item.review_judgment_content, + item.public_distribution_approved, + ) + + +def _safe_public(item: PopulationMaterialInputV1) -> bool: + return ( + item.license_class is LicenseClass.PERMISSIVE + and item.public_distribution_approved + and item.license_expression in PERMISSIVE_PUBLIC_LICENSES + ) + + +def _public_changes(items: tuple[PopulationMaterialInputV1, ...]) -> frozenset[str]: + return frozenset(item.change_digest for item in items if _safe_public(item)) + + +def _records( + items: tuple[PopulationMaterialInputV1, ...], +) -> tuple[ + tuple[PublicSourceRecordV1, ...], + tuple[PublicSourceObjectV1, ...], + tuple[OpaquePrivateMaterialRefV1, ...], + tuple[PrivateSourceRecordV1, ...], + tuple[SealedLabelRecordV1, ...], +]: + public: list[PublicSourceRecordV1] = [] + public_objects: list[PublicSourceObjectV1] = [] + refs: list[OpaquePrivateMaterialRefV1] = [] + private: list[PrivateSourceRecordV1] = [] + labels: list[SealedLabelRecordV1] = [] + public_changes = _public_changes(items) + for item in items: + source_digest = bytes_digest(item.source_content) + labels.append( + SealedLabelRecordV1( + item.change_digest, + bytes_digest(item.label_content), + bytes_digest(item.review_judgment_content), + item.label_content, + item.review_judgment_content, + ) + ) + if item.change_digest in public_changes: + public_object = PublicSourceObjectV1(item.change_digest, source_digest, item.source_content) + public_objects.append(public_object) + public.append( + PublicSourceRecordV1( + item.change_digest, + item.license_class, + item.license_expression, + source_digest, + len(item.source_content), + bytes_digest(public_source_record_bytes(public_object)), + ) + ) + else: + refs.append(OpaquePrivateMaterialRefV1(item.change_digest, item.license_class, source_digest, len(item.source_content))) + private.append(PrivateSourceRecordV1(item.change_digest, source_digest, item.source_content)) + return ( + tuple(sorted(public)), + tuple(sorted(public_objects)), + tuple(sorted(refs)), + tuple(sorted(private)), + tuple(sorted(labels)), + ) + + +def _draft_manifest( + freeze: PopulationFreezeV3, + items: tuple[PopulationMaterialInputV1, ...], + public: tuple[PublicSourceRecordV1, ...], + refs: tuple[OpaquePrivateMaterialRefV1, ...], + private_digest: str, + label_digest: str, + policy: str, +) -> PublicPopulationMaterialManifestV1: + counts = Counter(item.license_class for item in items) + exclusions = tuple(sorted((content_digest({"exclusion_reason": reason}), count) for reason, count in freeze.exclusion_counts)) + return PublicPopulationMaterialManifestV1( + freeze.population_digest, + freeze.freeze_digest, + freeze.positive_change_digests, + public, + refs, + private_digest, + label_digest, + tuple((item, counts[item]) for item in sorted(counts, key=lambda value: value.value)), + exclusions, + len(public), + len(refs), + _digest(policy, "partition policy"), + "", + ) + + +def _shell(private: tuple[PrivateSourceRecordV1, ...], labels: tuple[SealedLabelRecordV1, ...]) -> PopulationMaterialPartitionV1: + zero = "0" * 64 + manifest = PublicPopulationMaterialManifestV1(zero, zero, (), (), (), zero, zero, (), (), 0, 0, zero, "") + return PopulationMaterialPartitionV1(manifest, (), private, labels) + + +def build_population_material_partition( + freeze: PopulationFreezeV3, + inputs: Iterable[PopulationMaterialInputV1], + *, + freeze_validator: PopulationFreezeValidator, + partition_policy_digest: str, +) -> PopulationMaterialPartitionV1: + """Partition exact frozen positives without exposing private bytes publicly.""" + _validate_freeze(freeze, freeze_validator) + items = tuple(sorted((_material(item) for item in inputs), key=lambda item: item.change_digest)) + changes = tuple(item.change_digest for item in items) + if changes != freeze.positive_change_digests or len(changes) != len(set(changes)): + raise PopulationMaterialError("material inputs do not match exact positive set") + public, public_objects, refs, private, labels = _records(items) + shell = _shell(private, labels) + private_digest = bytes_digest(private_object_bytes(shell)) + label_digest = bytes_digest(sealed_label_object_bytes(shell)) + draft = _draft_manifest(freeze, items, public, refs, private_digest, label_digest, partition_policy_digest) + manifest = replace(draft, manifest_digest=content_digest(_manifest_value(draft, include_digest=False))) + partition = PopulationMaterialPartitionV1(manifest, public_objects, private, labels) + _validate_partition(partition) + return partition + + +def _validate_partition(partition: PopulationMaterialPartitionV1) -> None: + manifest = partition.manifest + if partition.public_source_objects != tuple(sorted(set(partition.public_source_objects))): + raise PopulationMaterialError("public source objects are not canonical") + private_content = private_object_bytes(partition) + label_content = sealed_label_object_bytes(partition) + if bytes_digest(private_content) != manifest.private_object_digest: + raise PopulationMaterialError("private object digest does not match manifest") + if bytes_digest(label_content) != manifest.sealed_label_digest: + raise PopulationMaterialError("sealed label digest does not match manifest") + sealed_changes = tuple(item.change_digest for item in partition.sealed_label_records) + if sealed_changes != manifest.positive_change_digests: + raise PopulationMaterialError("sealed labels do not cover exact positive set") + public_changes = {item.change_digest for item in manifest.public_sources} + private_changes = {item.change_digest for item in manifest.private_refs} + if public_changes & private_changes or public_changes | private_changes != set(manifest.positive_change_digests): + raise PopulationMaterialError("public/private partitions do not cover exact positive set") + object_bindings = { + (item.change_digest, item.source_digest, len(item.source_content), bytes_digest(public_source_record_bytes(item))) + for item in partition.public_source_objects + } + public_bindings = {(item.change_digest, item.source_digest, item.byte_length, item.object_digest) for item in manifest.public_sources} + if public_bindings != object_bindings or len(public_bindings) != len(partition.public_source_objects): + raise PopulationMaterialError("public source references do not match typed objects") + refs = {(item.change_digest, item.source_digest, item.byte_length) for item in manifest.private_refs} + records = {(item.change_digest, item.source_digest, len(item.source_content)) for item in partition.private_records} + if refs != records: + raise PopulationMaterialError("opaque private references do not match private object") + actual_licenses = Counter(item.license_class for item in manifest.private_refs) + if manifest.public_sources: + actual_licenses[LicenseClass.PERMISSIVE] += len(manifest.public_sources) + expected_licenses = tuple((item, actual_licenses[item]) for item in sorted(actual_licenses, key=lambda value: value.value)) + if manifest.license_partitions != expected_licenses: + raise PopulationMaterialError("license partitions do not match material records") + _public_manifest_bytes(partition) + + +def public_manifest_bytes(partition: PopulationMaterialPartitionV1) -> bytes: + """Serialize a public manifest only after validating every bound object.""" + _validate_partition(partition) + return _public_manifest_bytes(partition) + + +def public_source_object_bytes( + partition: PopulationMaterialPartitionV1, + reference: PublicSourceRecordV1, +) -> bytes: + """Resolve one exact public reference to its typed content-addressed object.""" + _validate_partition(partition) + if reference not in partition.manifest.public_sources: + raise PopulationMaterialError("public source reference is not authorized") + for record in partition.public_source_objects: + if (record.change_digest, record.source_digest) == (reference.change_digest, reference.source_digest): + serialized = public_source_record_bytes(record) + if bytes_digest(serialized) != reference.object_digest or len(record.source_content) != reference.byte_length: + raise PopulationMaterialError("public source reference does not match object") + return serialized + raise PopulationMaterialError("public source reference is unresolved") + + +def public_source_object_bytes_set(partition: PopulationMaterialPartitionV1) -> tuple[bytes, ...]: + """Return public objects in canonical manifest-reference order.""" + _validate_partition(partition) + return tuple(public_source_object_bytes(partition, reference) for reference in partition.manifest.public_sources) + + +def resolve_public_source(partition: PopulationMaterialPartitionV1, reference: PublicSourceRecordV1) -> bytes: + """Return exact public source bytes after validating their typed object.""" + public_source_object_bytes(partition, reference) + for record in partition.public_source_objects: + if (record.change_digest, record.source_digest) == (reference.change_digest, reference.source_digest): + return record.source_content + raise PopulationMaterialError("public source reference is unresolved") + + +def material_access_authority( + partition: PopulationMaterialPartitionV1, + actor_role: MaterialActorRole | str, + permissions: Iterable[MaterialPermission | str], + policy_digest: str, + *, + expected_access_policy_digest: str, +) -> MaterialAccessAuthorityV1: + _validate_partition(partition) + try: + role = MaterialActorRole(actor_role) + granted = tuple(sorted({MaterialPermission(item) for item in permissions}, key=lambda item: item.value)) + except (TypeError, ValueError) as error: + raise PopulationMaterialError("material authority values are unsupported") from error + access_policy = _digest(policy_digest, "access policy") + expected_policy = _digest(expected_access_policy_digest, "expected access policy") + if access_policy != expected_policy: + raise PopulationMaterialError("material access is not authorized: access policy mismatch") + manifest = partition.manifest + draft = MaterialAccessAuthorityV1( + manifest.population_digest, + manifest.freeze_digest, + manifest.manifest_digest, + manifest.partition_policy_digest, + manifest.private_object_digest, + manifest.sealed_label_digest, + role, + granted, + access_policy, + "", + ) + authority = replace(draft, authority_digest=content_digest(_authority_value(draft, include_digest=False))) + validate_material_authority(authority, expected_access_policy_digest=expected_policy) + return authority + + +def _require_permission( + partition: PopulationMaterialPartitionV1, + authority: MaterialAccessAuthorityV1, + permission: MaterialPermission, + expected_access_policy_digest: str, +) -> None: + expected_policy = _digest(expected_access_policy_digest, "expected access policy") + validate_material_authority(authority, expected_access_policy_digest=expected_policy) + manifest = partition.manifest + if ( + authority.population_digest != manifest.population_digest + or authority.freeze_digest != manifest.freeze_digest + or authority.manifest_digest != manifest.manifest_digest + or authority.partition_policy_digest != manifest.partition_policy_digest + or authority.private_object_digest != manifest.private_object_digest + or authority.sealed_label_digest != manifest.sealed_label_digest + or authority.actor_role is not MaterialActorRole.CUSTODIAN + or permission not in authority.permissions + ): + raise PopulationMaterialError("material access is not authorized") + + +def resolve_private_material( + partition: PopulationMaterialPartitionV1, + reference: OpaquePrivateMaterialRefV1, + authority: MaterialAccessAuthorityV1, + *, + expected_access_policy_digest: str, +) -> bytes: + _validate_partition(partition) + _require_permission( + partition, + authority, + MaterialPermission.PRIVATE_SOURCE, + expected_access_policy_digest, + ) + if reference not in partition.manifest.private_refs: + raise PopulationMaterialError("opaque private reference is not authorized") + for record in partition.private_records: + if (record.change_digest, record.source_digest) == (reference.change_digest, reference.source_digest): + return record.source_content + raise PopulationMaterialError("opaque private reference is unresolved") + + +def resolve_sealed_labels( + partition: PopulationMaterialPartitionV1, + authority: MaterialAccessAuthorityV1, + *, + expected_access_policy_digest: str, +) -> bytes: + _validate_partition(partition) + _require_permission( + partition, + authority, + MaterialPermission.SEALED_LABELS, + expected_access_policy_digest, + ) + return sealed_label_object_bytes(partition) + + +def operator_material_summary(partition: PopulationMaterialPartitionV1) -> bytes: + _validate_partition(partition) + manifest = partition.manifest + value: JsonValue = { + "schema_version": MATERIAL_SUMMARY_SCHEMA, + "status": "partitioned", + "population_digest": manifest.population_digest, + "freeze_digest": manifest.freeze_digest, + "manifest_digest": manifest.manifest_digest, + "private_object_digest": manifest.private_object_digest, + "sealed_label_digest": manifest.sealed_label_digest, + "public_count": manifest.public_count, + "private_count": manifest.private_count, + "reason_codes": ("private_material_opaque", "labels_custodian_sealed"), + } + return canonical_bytes(value) + + +def accept_population_material_partition( + partition: PopulationMaterialPartitionV1, + *, + existing: tuple[bytes, ...] | None = None, +) -> PopulationMaterialPartitionV1: + _validate_partition(partition) + current = material_artifact_bytes(partition) + if existing is not None and existing != current: + raise PopulationMaterialConflict("same material identity resolves to different bytes") + return partition + + +def material_artifact_bytes(partition: PopulationMaterialPartitionV1) -> tuple[bytes, ...]: + """Return manifest, public sources, private material, and labels in canonical order.""" + _validate_partition(partition) + return ( + public_manifest_bytes(partition), + *public_source_object_bytes_set(partition), + private_object_bytes(partition), + sealed_label_object_bytes(partition), + ) + + +__all__ = [ + "LicenseClass", + "MaterialAccessAuthorityV1", + "MaterialActorRole", + "MaterialPermission", + "OpaquePrivateMaterialRefV1", + "PopulationFreezeValidator", + "PopulationMaterialConflict", + "PopulationMaterialError", + "PopulationMaterialInputV1", + "PopulationMaterialPartitionV1", + "accept_population_material_partition", + "build_population_material_partition", + "material_artifact_bytes", + "material_access_authority", + "operator_material_summary", + "private_object_bytes", + "public_manifest_bytes", + "public_source_object_bytes", + "public_source_object_bytes_set", + "resolve_public_source", + "resolve_private_material", + "resolve_sealed_labels", + "sealed_label_object_bytes", +] diff --git a/tests/test_valid_benchmark_population_material_security.py b/tests/test_valid_benchmark_population_material_security.py new file mode 100644 index 00000000..db11bd5f --- /dev/null +++ b/tests/test_valid_benchmark_population_material_security.py @@ -0,0 +1,332 @@ +"""Boundary tests for typed public source objects and metadata-only manifests.""" + +from __future__ import annotations + +import base64 +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_population_materials import ( # noqa: E402 + _digest, + _freeze, + _inputs, + _Validator, +) + +from benchmarks.valid import population_materials as materials # noqa: E402 +from benchmarks.valid.population_freeze_contract import ( # noqa: E402 + PopulationFreezeV3, + _freeze_value, + _population_value, +) +from openultrasast.core.canonical import bytes_digest, canonical_bytes, content_digest # noqa: E402 + + +def _partition_with_source(source: bytes) -> materials.PopulationMaterialPartitionV1: + changes = tuple(_digest(f"typed-source-{index}") for index in range(3)) + freeze = _freeze(changes) + inputs = list(_inputs(changes)) + inputs[0] = replace(inputs[0], source_content=source) + return materials.build_population_material_partition( + freeze, + inputs, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + + +def _freeze_with_exclusions(changes: tuple[str, ...], exclusions: tuple[tuple[str, int], ...]) -> PopulationFreezeV3: + base = _freeze(changes) + draft = replace(base, exclusion_counts=exclusions, population_digest="", freeze_digest="") + with_population = replace(draft, population_digest=content_digest(_population_value(draft))) + return replace( + with_population, + freeze_digest=content_digest(_freeze_value(with_population, include_digest=False)), + ) + + +@pytest.mark.parametrize( + "source", + ( + b'x = 1\nopen("\\\\ProgramData\\\\service\\\\token.txt")\n', + b"x = 1\r\n\\secret.txt", + b"# \\secret.txt", + b"// \\secret.txt", + b"- \\secret.txt", + rb"\u0061", + rb"\uD83D\uDE00", + rb'print("\u0061")', + b"password=literal-used-by-a-security-test", + b"https://example.test/path/in/source", + b"private-label-0", + b"invalid-utf8-\xff", + ), +) +def test_arbitrary_approved_source_bytes_are_public_typed_objects(source: bytes) -> None: + partition = _partition_with_source(source) + manifest_bytes = materials.public_manifest_bytes(partition) + manifest = json.loads(manifest_bytes) + reference = next(item for item in partition.manifest.public_sources if item.change_digest == _digest("typed-source-0")) + + assert source not in manifest_bytes + assert base64.b64encode(source) not in manifest_bytes + assert "content_base64" not in manifest["public_sources"][0] + assert materials.resolve_public_source(partition, reference) == source + assert bytes_digest(materials.public_source_object_bytes(partition, reference)) == reference.object_digest + + +def test_manifest_is_metadata_only_and_has_no_path_or_payload_fields() -> None: + partition = _partition_with_source(b"/home/operator/private.py\nC:\\Users\\operator\\source.py") + manifest = json.loads(materials.public_manifest_bytes(partition)) + serialized = materials.public_manifest_bytes(partition) + + assert b"/home/" not in serialized + assert b"C:\\\\Users" not in serialized + assert b"content_base64" not in serialized + assert b"path" not in serialized.lower() + assert set(manifest["public_sources"][0]) == { + "byte_length", + "change_digest", + "license_class", + "license_expression", + "object_digest", + "source_digest", + } + + unsafe_metadata = replace(partition.manifest, exclusion_counts=(("/home/operator/result", 0),)) + with pytest.raises(materials.PopulationMaterialError, match="full lowercase SHA-256"): + materials.public_manifest_bytes(replace(partition, manifest=unsafe_metadata)) + + +@pytest.mark.parametrize("reason", ("api_key_supersecret123", "repository_owner_project")) +def test_public_manifest_projects_open_freeze_reasons_to_safe_digests(reason: str) -> None: + changes = tuple(_digest(f"reason-{index}") for index in range(3)) + freeze = _freeze_with_exclusions(changes, ((reason, 2),)) + partition = materials.build_population_material_partition( + freeze, + _inputs(changes), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + manifest_bytes = materials.public_manifest_bytes(partition) + manifest = json.loads(manifest_bytes) + + assert reason.encode() not in manifest_bytes + assert manifest["exclusion_counts"] == [[content_digest({"exclusion_reason": reason}), 2]] + + +def test_multi_reason_projection_sorts_by_projected_digest() -> None: + changes = tuple(_digest(f"multi-reason-{index}") for index in range(3)) + freeze = _freeze_with_exclusions(changes, (("r0", 1), ("r1", 2))) + partition = materials.build_population_material_partition( + freeze, + _inputs(changes), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + first = json.loads(materials.public_manifest_bytes(partition))["exclusion_counts"] + second = json.loads(materials.public_manifest_bytes(partition))["exclusion_counts"] + + assert first == second == sorted(first) + + +def test_rehashed_duplicate_exclusion_digest_with_conflicting_counts_is_rejected() -> None: + partition = _partition_with_source(b"duplicate-reason") + reason_digest = content_digest({"exclusion_reason": "review_excluded"}) + exclusions = ((reason_digest, 1), (reason_digest, 2)) + draft = replace(partition.manifest, exclusion_counts=exclusions, manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="unique"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) + + +def test_exported_manifest_serialization_rejects_rehashed_dangling_public_ref() -> None: + partition = _partition_with_source(b"bound-source") + reference = partition.manifest.public_sources[0] + tampered_ref = replace(reference, source_digest="0" * 64) + draft = replace(partition.manifest, public_sources=(tampered_ref,), manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="references do not match"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) + + +def test_public_object_reference_and_bytes_are_exactly_bound() -> None: + partition = _partition_with_source(b"source-object") + reference = partition.manifest.public_sources[0] + object_bytes = materials.public_source_object_bytes(partition, reference) + value = json.loads(object_bytes) + + assert value["byte_length"] == len(b"source-object") + assert value["source_digest"] == bytes_digest(b"source-object") + assert base64.b64decode(value["content_base64"]) == b"source-object" + + for tampered in ( + replace(reference, source_digest="0" * 64), + replace(reference, byte_length=reference.byte_length + 1), + replace(reference, object_digest="0" * 64), + ): + with pytest.raises(materials.PopulationMaterialError): + materials.public_source_object_bytes(partition, tampered) + + +def test_public_object_set_is_canonical_and_conflicts_on_any_changed_object() -> None: + partition = _partition_with_source(b"canonical-source") + artifacts = materials.material_artifact_bytes(partition) + assert artifacts == materials.material_artifact_bytes(partition) + + public_value = json.loads(artifacts[1]) + public_value["content_base64"] = base64.b64encode(b"changed-source").decode() + tampered = canonical_bytes(public_value) + with pytest.raises(materials.PopulationMaterialConflict, match="different bytes"): + materials.accept_population_material_partition( + partition, + existing=(artifacts[0], tampered, *artifacts[2:]), + ) + + +def test_nonpublic_license_and_distribution_decisions_remain_private() -> None: + changes = tuple(_digest(f"private-decision-{index}") for index in range(3)) + freeze = _freeze(changes) + inputs = list(_inputs(changes)) + inputs[0] = replace(inputs[0], public_distribution_approved=False) + partition = materials.build_population_material_partition( + freeze, + inputs, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + manifest = json.loads(materials.public_manifest_bytes(partition)) + + assert manifest["public_count"] == 0 + assert manifest["private_count"] == 3 + assert materials.public_source_object_bytes_set(partition) == () + + +@pytest.mark.parametrize( + ("license_class", "license_expression"), + ( + (materials.LicenseClass.NON_PERMISSIVE, "BUSL-1.1"), + (materials.LicenseClass.UNCERTAIN, "NOASSERTION"), + ), +) +def test_single_all_private_partition_has_no_zero_count_permissive_license( + license_class: materials.LicenseClass, + license_expression: str, +) -> None: + change = _digest(f"all-private-{license_class.value}") + freeze = _freeze((change,)) + item = materials.PopulationMaterialInputV1( + change, + license_class, + license_expression, + b"private source", + b"label", + b"judgment", + True, + ) + + partition = materials.build_population_material_partition( + freeze, + (item,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + manifest = json.loads(materials.public_manifest_bytes(partition)) + + assert manifest["public_count"] == 0 + assert manifest["private_count"] == 1 + assert manifest["license_partitions"] == [[license_class.value, 1]] + assert len(manifest["private_refs"]) == 1 + assert materials.public_source_object_bytes_set(partition) == () + + +def test_rehashed_boolean_public_count_is_rejected() -> None: + partition = _partition_with_source(b"boolean-public-count") + draft = replace(partition.manifest, public_count=True, manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="counts must be nonnegative integers"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) + + +def test_rehashed_false_public_count_is_rejected() -> None: + change = _digest("false-public-count") + freeze = _freeze((change,)) + item = materials.PopulationMaterialInputV1( + change, + materials.LicenseClass.NON_PERMISSIVE, + "BUSL-1.1", + b"private source", + b"label", + b"judgment", + True, + ) + partition = materials.build_population_material_partition( + freeze, + (item,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + draft = replace(partition.manifest, public_count=False, manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="counts must be nonnegative integers"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) + + +def test_rehashed_boolean_private_count_is_rejected() -> None: + change = _digest("boolean-private-count") + freeze = _freeze((change,)) + item = materials.PopulationMaterialInputV1( + change, + materials.LicenseClass.UNCERTAIN, + "NOASSERTION", + b"private source", + b"label", + b"judgment", + True, + ) + partition = materials.build_population_material_partition( + freeze, + (item,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + draft = replace(partition.manifest, private_count=True, manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="counts must be nonnegative integers"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) + + +def test_rehashed_false_private_count_is_rejected() -> None: + change = _digest("false-private-count") + freeze = _freeze((change,)) + item = materials.PopulationMaterialInputV1( + change, + materials.LicenseClass.PERMISSIVE, + "MIT", + b"public source", + b"label", + b"judgment", + True, + ) + partition = materials.build_population_material_partition( + freeze, + (item,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + draft = replace(partition.manifest, private_count=False, manifest_digest="") + manifest = replace(draft, manifest_digest=content_digest(materials._manifest_value(draft, include_digest=False))) + + with pytest.raises(materials.PopulationMaterialError, match="counts must be nonnegative integers"): + materials.public_manifest_bytes(replace(partition, manifest=manifest)) diff --git a/tests/test_valid_benchmark_population_materials.py b/tests/test_valid_benchmark_population_materials.py new file mode 100644 index 00000000..690a65da --- /dev/null +++ b/tests/test_valid_benchmark_population_materials.py @@ -0,0 +1,452 @@ +"""Public/private/sealed partition tests for the replacement population.""" + +from __future__ import annotations + +import base64 +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from benchmarks.valid import population_materials as materials # noqa: E402 +from benchmarks.valid.ecosystem_review import CanonicalEcosystem # noqa: E402 +from benchmarks.valid.population_freeze_contract import ( # noqa: E402 + PopulationClass, + PopulationClassificationReason, + PopulationFreezeV3, + PopulationScopeCountV1, + _freeze_value, + _population_value, + population_freeze_bytes, +) +from openultrasast.core.canonical import bytes_digest, canonical_bytes, content_digest # noqa: E402 + + +def _digest(label: str) -> str: + return content_digest({"fixture": label}) + + +def _percent_encoded(value: bytes) -> bytes: + return b"".join(f"%{byte:02X}".encode("ascii") for byte in value) + + +def _freeze(changes: tuple[str, ...]) -> PopulationFreezeV3: + changes = tuple(sorted(changes)) + scope_census = (PopulationScopeCountV1("injection", CanonicalEcosystem.PYTHON, len(changes)),) + ecosystem_reviews = tuple(sorted(_digest(f"ecosystem-{index}") for index in range(len(changes)))) + ground_truth_reviews = tuple(sorted(_digest(f"truth-{index}") for index in range(len(changes)))) + draft = PopulationFreezeV3( + PopulationClass.INSUFFICIENT, + ( + PopulationClassificationReason.BELOW_MINIMUM_POSITIVES, + PopulationClassificationReason.MISSING_ECOSYSTEM, + PopulationClassificationReason.MISSING_SECOND_FAMILY, + ), + len(changes), + (CanonicalEcosystem.PYTHON,), + ("injection",), + scope_census, + (), + changes, + content_digest( + { + "accepted_changes": changes, + "scope_census": tuple((item.vulnerability_family, item.ecosystem.value, item.count) for item in scope_census), + } + ), + ecosystem_reviews, + ground_truth_reviews, + content_digest( + { + "ecosystem_reviews": ecosystem_reviews, + "ground_truth_reviews": ground_truth_reviews, + } + ), + _digest("ordinary-selection"), + _digest("reservation-census"), + (("excluded", 0),), + _digest("provenance"), + _digest("ecosystem-policy"), + _digest("truth-policy"), + _digest("freeze-policy"), + "", + "", + ) + with_population = replace(draft, population_digest=content_digest(_population_value(draft))) + return replace(with_population, freeze_digest=content_digest(_freeze_value(with_population, include_digest=False))) + + +class _Validator: + def __init__(self, expected: PopulationFreezeV3) -> None: + self.expected = expected + self.calls = 0 + + def validate(self, freeze: PopulationFreezeV3) -> bytes: + self.calls += 1 + if freeze != self.expected: + raise materials.PopulationMaterialError("freeze does not replay from exact authorities") + return population_freeze_bytes(freeze) + + +def _inputs(changes: tuple[str, ...]) -> tuple[materials.PopulationMaterialInputV1, ...]: + classes = ( + materials.LicenseClass.PERMISSIVE, + materials.LicenseClass.NON_PERMISSIVE, + materials.LicenseClass.UNCERTAIN, + ) + return tuple( + materials.PopulationMaterialInputV1( + change, + classes[index], + ("Apache-2.0", "BUSL-1.1", "NOASSERTION")[index], + (f"safe source {index}\n").encode(), + (f"private-label-{index}").encode(), + (f"review-judgment-{index}").encode(), + index == 0, + ) + for index, change in enumerate(changes) + ) + + +def _partition() -> tuple[materials.PopulationMaterialPartitionV1, _Validator]: + changes = tuple(_digest(f"change-{index}") for index in range(3)) + freeze = _freeze(tuple(sorted(changes))) + validator = _Validator(freeze) + partition = materials.build_population_material_partition( + freeze, + _inputs(changes), + freeze_validator=validator, + partition_policy_digest=_digest("partition-policy"), + ) + return partition, validator + + +def test_partitions_permissive_public_and_opaque_private_material_deterministically() -> None: + first, validator = _partition() + second, _ = _partition() + + assert validator.calls == 1 + assert materials.public_manifest_bytes(first) == materials.public_manifest_bytes(second) + manifest = json.loads(materials.public_manifest_bytes(first)) + assert manifest["public_count"] == 1 + assert manifest["private_count"] == 2 + assert manifest["public_sources"][0]["license_class"] == "permissive" + assert tuple(row["license_class"] for row in manifest["private_refs"]) == ( + "non_permissive", + "uncertain", + ) + public_ref = first.manifest.public_sources[0] + assert "content_base64" not in manifest["public_sources"][0] + assert manifest["public_sources"][0]["object_digest"] == public_ref.object_digest + assert materials.resolve_public_source(first, public_ref) == b"safe source 0\n" + assert materials.public_source_object_bytes(first, public_ref) == materials.public_source_object_bytes(second, public_ref) + + +def test_public_manifest_excludes_private_labels_judgments_paths_and_credentials() -> None: + partition, _ = _partition() + content = materials.public_manifest_bytes(partition) + + for forbidden in ( + b"private-label", + b"review-judgment", + b"BUSL-1.1", + b"NOASSERTION", + b"/home/", + b"C:\\\\", + b"AKIA0000000000000000", + ): + assert forbidden not in content + assert base64.b64encode(forbidden) not in content + + for sealed in (b"private-label-0", b"review-judgment-0"): + assert sealed.hex().encode() not in content + assert _percent_encoded(sealed) not in content + + +def test_public_license_policy_is_closed_and_public_bytes_are_digest_bound() -> None: + change = _digest("closed-license") + freeze = _freeze((change,)) + unlisted = materials.PopulationMaterialInputV1( + change, materials.LicenseClass.PERMISSIVE, "private-label", b"source", b"label", b"judgment", True + ) + private = materials.build_population_material_partition( + freeze, + (unlisted,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + assert json.loads(materials.public_manifest_bytes(private))["public_count"] == 0 + + partition, _ = _partition() + source = partition.manifest.public_sources[0] + tampered_source = replace(source, source_digest="0" * 64) + tampered_manifest = replace(partition.manifest, public_sources=(tampered_source,)) + with pytest.raises(materials.PopulationMaterialError): + materials.public_manifest_bytes(replace(partition, manifest=tampered_manifest)) + + with pytest.raises(materials.PopulationMaterialError): + materials.resolve_public_source(partition, replace(source, byte_length=source.byte_length + 1)) + + with pytest.raises(materials.PopulationMaterialError): + materials.resolve_private_material( + partition, + source, # type: ignore[arg-type] + materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE,), + _digest("access-policy"), + expected_access_policy_digest=_digest("access-policy"), + ), + expected_access_policy_digest=_digest("access-policy"), + ) + + +def test_only_exact_custodian_authority_resolves_private_and_sealed_objects() -> None: + partition, _ = _partition() + manifest = json.loads(materials.public_manifest_bytes(partition)) + private_ref = partition.manifest.private_refs[0] + custodian = materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE, materials.MaterialPermission.SEALED_LABELS), + _digest("access-policy"), + expected_access_policy_digest=_digest("access-policy"), + ) + + assert materials.resolve_private_material( + partition, + private_ref, + custodian, + expected_access_policy_digest=_digest("access-policy"), + ).startswith(b"safe source") + assert materials.resolve_sealed_labels( + partition, + custodian, + expected_access_policy_digest=_digest("access-policy"), + ) == materials.sealed_label_object_bytes(partition) + assert manifest["private_object_digest"] == bytes_digest(materials.private_object_bytes(partition)) + + for role in ( + materials.MaterialActorRole.DETECTOR, + materials.MaterialActorRole.PRESENTER, + materials.MaterialActorRole.OPERATOR, + ): + authority = materials.material_access_authority( + partition, + role, + (), + _digest("access-policy"), + expected_access_policy_digest=_digest("access-policy"), + ) + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_private_material( + partition, + private_ref, + authority, + expected_access_policy_digest=_digest("access-policy"), + ) + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_sealed_labels( + partition, + authority, + expected_access_policy_digest=_digest("access-policy"), + ) + + +def test_opaque_reference_and_authority_tampering_are_refused() -> None: + partition, _ = _partition() + authority = materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE,), + _digest("access-policy"), + expected_access_policy_digest=_digest("access-policy"), + ) + reference = partition.manifest.private_refs[0] + + with pytest.raises(materials.PopulationMaterialError): + materials.resolve_private_material( + partition, + replace(reference, source_digest="0" * 64), + authority, + expected_access_policy_digest=_digest("access-policy"), + ) + with pytest.raises(materials.PopulationMaterialError): + materials.resolve_private_material( + partition, + reference, + replace(authority, population_digest="1" * 64), + expected_access_policy_digest=_digest("access-policy"), + ) + + +def _tampered_authorities( + authority: materials.MaterialAccessAuthorityV1, +) -> tuple[materials.MaterialAccessAuthorityV1, ...]: + return ( + replace(authority, freeze_digest="0" * 64), + replace(authority, manifest_digest="0" * 64), + replace(authority, partition_policy_digest="0" * 64), + replace(authority, private_object_digest="0" * 64), + replace(authority, sealed_label_digest="0" * 64), + ) + + +def test_custodian_authority_is_bound_to_the_exact_partition_and_every_object() -> None: + first, _ = _partition() + changes = first.manifest.positive_change_digests + freeze = _freeze(changes) + changed_inputs = list(_inputs(changes)) + changed_inputs[0] = replace(changed_inputs[0], label_content=b"different-sealed-label") + changed_inputs[1] = replace(changed_inputs[1], source_content=b"different-private-source") + second = materials.build_population_material_partition( + freeze, + changed_inputs, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("different-partition-policy"), + ) + authority = materials.material_access_authority( + first, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE, materials.MaterialPermission.SEALED_LABELS), + _digest("access-policy"), + expected_access_policy_digest=_digest("access-policy"), + ) + + assert authority.freeze_digest == first.manifest.freeze_digest + assert authority.manifest_digest == first.manifest.manifest_digest + assert authority.partition_policy_digest == first.manifest.partition_policy_digest + assert authority.private_object_digest == first.manifest.private_object_digest + assert authority.sealed_label_digest == first.manifest.sealed_label_digest + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_private_material( + second, + second.manifest.private_refs[0], + authority, + expected_access_policy_digest=_digest("access-policy"), + ) + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_sealed_labels( + second, + authority, + expected_access_policy_digest=_digest("access-policy"), + ) + + for tampered in _tampered_authorities(authority): + with pytest.raises(materials.PopulationMaterialError): + materials.resolve_sealed_labels( + first, + tampered, + expected_access_policy_digest=_digest("access-policy"), + ) + + +def test_access_policy_expectation_is_independent_and_required_at_every_boundary() -> None: + partition, _ = _partition() + reference = partition.manifest.private_refs[0] + expected = _digest("access-policy") + wrong = _digest("wrong-access-policy") + + with pytest.raises(materials.PopulationMaterialError, match="access policy"): + materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE,), + wrong, + expected_access_policy_digest=expected, + ) + wrong_authority = materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE, materials.MaterialPermission.SEALED_LABELS), + wrong, + expected_access_policy_digest=wrong, + ) + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_private_material( + partition, + reference, + wrong_authority, + expected_access_policy_digest=expected, + ) + with pytest.raises(TypeError): + materials.resolve_private_material(partition, reference, wrong_authority) # type: ignore[call-arg] + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_sealed_labels( + partition, + wrong_authority, + expected_access_policy_digest=expected, + ) + with pytest.raises(TypeError): + materials.resolve_sealed_labels(partition, wrong_authority) # type: ignore[call-arg] + with pytest.raises(TypeError): + materials.material_access_authority( # type: ignore[call-arg] + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.PRIVATE_SOURCE,), + expected, + ) + + +def test_material_set_must_match_exact_freeze_and_all_bytes_are_nonempty() -> None: + changes = (_digest("one"), _digest("two")) + freeze = _freeze(changes) + item = materials.PopulationMaterialInputV1(changes[0], materials.LicenseClass.PERMISSIVE, "MIT", b"source", b"label", b"judgment", True) + + with pytest.raises(materials.PopulationMaterialError, match="exact positive set"): + materials.build_population_material_partition( + freeze, + (item,), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + with pytest.raises(materials.PopulationMaterialError, match="nonempty"): + materials.build_population_material_partition( + _freeze((changes[0],)), + (replace(item, label_content=b""),), + freeze_validator=_Validator(_freeze((changes[0],))), + partition_policy_digest=_digest("partition-policy"), + ) + + +def test_exact_freeze_replay_is_required_and_tampered_freeze_is_refused() -> None: + partition, validator = _partition() + freeze = _freeze(partition.manifest.positive_change_digests) + + assert validator.calls == 1 + with pytest.raises(materials.PopulationMaterialError, match="freeze"): + materials.build_population_material_partition( + replace(freeze, reservation_census_digest=_digest("stale-census")), + _inputs(partition.manifest.positive_change_digests), + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + + +def test_same_identity_different_bytes_conflicts_and_summary_is_redacted() -> None: + partition, _ = _partition() + accepted = materials.accept_population_material_partition(partition) + existing = materials.material_artifact_bytes(partition) + + assert materials.accept_population_material_partition(partition, existing=existing) == accepted + assert len(existing) == 4 + with pytest.raises(materials.PopulationMaterialConflict, match="different bytes"): + materials.accept_population_material_partition(partition, existing=(*existing[:-1], existing[-1] + b"\n")) + + public_object = json.loads(existing[1]) + public_object["schema_version"] = "wrong" + changed_schema = canonical_bytes(public_object) + with pytest.raises(materials.PopulationMaterialConflict, match="different bytes"): + materials.accept_population_material_partition(partition, existing=(existing[0], changed_schema, *existing[2:])) + + summary = materials.operator_material_summary(partition) + assert json.loads(summary)["status"] == "partitioned" + assert b"private-label" not in summary + assert b"review-judgment" not in summary + assert b"safe source" not in summary + assert b"content_base64" not in summary