mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
feat(valid-detection-benchmark): separate public private and sealed materials
This commit is contained in:
@@ -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",
|
||||
]
|
||||
@@ -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",
|
||||
]
|
||||
Reference in New Issue
Block a user