mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(detection-core): validate exact retry histories
This commit is contained in:
@@ -529,7 +529,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- _Requirements: 17.5, 17.6, 20.8_
|
||||
- _Boundary: Evaluation Observation_
|
||||
- _Depends: 13.3_
|
||||
- [ ] 14.2 Validate reviewed attempt history, sealed access, and exact retries
|
||||
- [x] 14.2 Validate reviewed attempt history, sealed access, and exact retries
|
||||
- Bind each attempt event to the complete retry identity, closed access policy, raw-observation and diagnostic access counts, public status projection, disposition, review, and predecessor.
|
||||
- Resolve the reviewed predecessor chain from its declared head and require every unspent attempt to have the identical population, plan, arms, inputs, configurations, budgets, and execution identities.
|
||||
- Permit public pre-spend projection only for closed status codes, counts, and digests; any raw/diagnostic access or identity change produces a terminal development-opened or spent disposition.
|
||||
@@ -717,6 +717,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- Task 13.3 added exact label-sealed scope/ecosystem census contracts and an independently reviewed plan manifest that binds the declaration, baselines, census, readiness, custody, and bounded trust-resolved review evidence before feasibility.
|
||||
- Task 13.4 revalidates the reviewed manifest before deriving one exact arm/scope feasibility row, preserves the V2 reachability witnesses and same-ecosystem ordinary capacity, and keeps insufficiency and zero denominators outside GO/NO-GO while blocking shared spend.
|
||||
- Task 14.1 added strict canonical, nonzero, label-blind observation records and sealed references whose trusted resolved bytes, read/stage evidence, configuration identities, and complete slot set must match the reviewed plan before authority.
|
||||
- Task 14.2 added strict canonical reviewed attempt events and exact predecessor-chain validation so only unchanged, closed-access, all-sealed retry histories remain eligible before authority.
|
||||
- The frozen migration inventory is a reviewed worklist with stable identities, not a semantic-use census. It may only close entries as `v2_migrated` or `retired`; it never grows, deletes entries, or proves absence by interpreting Python flow.
|
||||
- Cutover is proved by explicit syntax checks plus deletion of the compatibility and v1 write capability. No task extends the discarded alias/data-flow interpreter.
|
||||
- Task 10.5 debug established that executable owner probes cannot compensate for blanket source-closure acceptance; resumed hunt attempts also require collision-resistant attempt identity and create-only persistence before handoff validation is authoritative.
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Trust resolution and eligibility checks for reviewed V3 attempt histories."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_attempt import (
|
||||
_PUBLIC_STATUS_SCHEMA,
|
||||
AttemptEventV3,
|
||||
AttemptHistoryV3,
|
||||
AttemptIdentityV3,
|
||||
EvaluationAttemptError,
|
||||
PreSpendDispositionV3,
|
||||
_digest,
|
||||
_pairs,
|
||||
decode_attempt_event,
|
||||
derive_attempt_identity,
|
||||
)
|
||||
from openultrasast.core.evaluation_plan import EvaluationPlanManifestV3, validate_reviewed_evaluation_plan
|
||||
from openultrasast.core.factpack import (
|
||||
FactPackValidationError,
|
||||
ReviewIndependencePolicy,
|
||||
derive_independence_attestation_digest,
|
||||
derive_review_independence_policy_digest,
|
||||
)
|
||||
|
||||
|
||||
def _validate_policy(policy: ReviewIndependencePolicy) -> None:
|
||||
if type(policy) is not ReviewIndependencePolicy:
|
||||
raise EvaluationAttemptError("review policy must use exact ReviewIndependencePolicy")
|
||||
try:
|
||||
policy.__post_init__()
|
||||
except FactPackValidationError as exc:
|
||||
raise EvaluationAttemptError(f"review policy is invalid: {exc}") from exc
|
||||
expected = derive_review_independence_policy_digest(
|
||||
policy.reviewed_reviewer_digests,
|
||||
policy.forbidden_identity_pairs,
|
||||
policy.trusted_store_identities,
|
||||
policy.maximum_evidence_bytes,
|
||||
)
|
||||
if policy.policy_digest != expected:
|
||||
raise EvaluationAttemptError("review policy digest cannot be re-derived")
|
||||
|
||||
|
||||
def _resolve(
|
||||
reference: canonical.ContentRef,
|
||||
policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
field: str,
|
||||
) -> bytes:
|
||||
try:
|
||||
content = canonical.resolve_content(
|
||||
reference,
|
||||
resolver,
|
||||
trusted_store_identities=policy.trusted_store_identities,
|
||||
maximum_bytes=policy.maximum_evidence_bytes,
|
||||
)
|
||||
except (canonical.ArtifactResolutionError, canonical.ArtifactValidationError):
|
||||
raise
|
||||
except (AttributeError, TypeError) as exc:
|
||||
raise EvaluationAttemptError(f"{field} resolver returned a malformed result") from exc
|
||||
if not content:
|
||||
raise EvaluationAttemptError(f"resolved {field} bytes must be nonzero")
|
||||
return content
|
||||
|
||||
|
||||
def _validate_review(
|
||||
event: AttemptEventV3,
|
||||
policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> None:
|
||||
review = event.review
|
||||
if review.subject_digest != event.payload_digest:
|
||||
raise EvaluationAttemptError("attempt review subject does not match its payload digest")
|
||||
if review.producer_identity == review.reviewer_identity:
|
||||
raise EvaluationAttemptError("attempt producer and reviewer must be independent")
|
||||
if review.reviewer_identity not in policy.reviewed_reviewer_digests:
|
||||
raise EvaluationAttemptError("attempt reviewer is not admitted by policy")
|
||||
if (review.producer_identity, review.reviewer_identity) in policy.forbidden_identity_pairs:
|
||||
raise EvaluationAttemptError("attempt producer/reviewer pair is forbidden")
|
||||
if review.attestation_digest != derive_independence_attestation_digest(review):
|
||||
raise EvaluationAttemptError("attempt review attestation digest cannot be re-derived")
|
||||
_resolve(review.conflict_disclosure, policy, resolver, "review conflict disclosure")
|
||||
|
||||
|
||||
def _validate_projection(
|
||||
event: AttemptEventV3,
|
||||
policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> None:
|
||||
content = _resolve(event.public_status_projection, policy, resolver, "public status projection")
|
||||
try:
|
||||
value = json.loads(content.decode("utf-8"), object_pairs_hook=_pairs)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise EvaluationAttemptError("public status projection must be valid UTF-8 JSON") from exc
|
||||
allowed = {item.value for item in event.access_policy.allowed_public_fields}
|
||||
if type(value) is not dict or value.get("schema_version") != _PUBLIC_STATUS_SCHEMA:
|
||||
raise EvaluationAttemptError("public status projection has an unknown schema")
|
||||
projected = set(value) - {"schema_version"}
|
||||
if not projected or not projected <= allowed:
|
||||
raise EvaluationAttemptError("public status projection exposes a field outside the closed access policy")
|
||||
if "status_code" in value and (type(value["status_code"]) is not str or not value["status_code"]):
|
||||
raise EvaluationAttemptError("public status projection status code must be nonempty exact text")
|
||||
if "count" in value and (type(value["count"]) is not int or value["count"] < 0):
|
||||
raise EvaluationAttemptError("public status projection count must be a non-negative integer")
|
||||
if "digest" in value:
|
||||
_digest(value["digest"], "public status projection digest")
|
||||
if canonical.canonical_bytes(value) != content:
|
||||
raise EvaluationAttemptError("public status projection must use canonical JSON")
|
||||
|
||||
|
||||
def _resolve_events(
|
||||
history: AttemptHistoryV3,
|
||||
policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> tuple[AttemptEventV3, ...]:
|
||||
events = []
|
||||
for reference in history.events:
|
||||
event = decode_attempt_event(_resolve(reference.event, policy, resolver, "attempt event"))
|
||||
if event.event_digest != reference.event_digest:
|
||||
raise EvaluationAttemptError("resolved attempt event does not match its reference")
|
||||
_validate_review(event, policy, resolver)
|
||||
_validate_projection(event, policy, resolver)
|
||||
events.append(event)
|
||||
return tuple(events)
|
||||
|
||||
|
||||
def _ordered_chain(history: AttemptHistoryV3, events: tuple[AttemptEventV3, ...]) -> tuple[AttemptEventV3, ...]:
|
||||
by_digest = {event.event_digest: event for event in events}
|
||||
if len(by_digest) != len(events):
|
||||
raise EvaluationAttemptError("attempt history contains duplicate event identities")
|
||||
reverse_chain = []
|
||||
current: str | None = history.head_event_digest
|
||||
seen: set[str] = set()
|
||||
while current is not None:
|
||||
if current in seen:
|
||||
raise EvaluationAttemptError("attempt predecessor chain contains a cycle")
|
||||
seen.add(current)
|
||||
try:
|
||||
event = by_digest[current]
|
||||
except KeyError as exc:
|
||||
raise EvaluationAttemptError("attempt predecessor chain is broken") from exc
|
||||
reverse_chain.append(event)
|
||||
current = event.predecessor_event_digest
|
||||
chain = tuple(reversed(reverse_chain))
|
||||
if tuple(item.event_digest for item in chain) != tuple(item.event_digest for item in events):
|
||||
raise EvaluationAttemptError("attempt history is forked, skipped, or reordered")
|
||||
return chain
|
||||
|
||||
|
||||
def _validate_eligibility(events: tuple[AttemptEventV3, ...], expected: AttemptIdentityV3) -> None:
|
||||
terminal_seen = False
|
||||
for event in events:
|
||||
is_terminal = event.disposition is not PreSpendDispositionV3.SEALED
|
||||
access_opened = (
|
||||
event.access_policy.raw_observation_access_allowed
|
||||
or event.access_policy.population_diagnostic_access_allowed
|
||||
or event.raw_observation_access_count > 0
|
||||
or event.population_diagnostic_access_count > 0
|
||||
)
|
||||
if terminal_seen and not is_terminal:
|
||||
raise EvaluationAttemptError("a sealed event cannot follow a terminal disposition")
|
||||
if not is_terminal and event.attempt_identity != expected:
|
||||
raise EvaluationAttemptError("a changed retry identity requires a terminal disposition")
|
||||
if not is_terminal and access_opened:
|
||||
raise EvaluationAttemptError("raw or diagnostic access requires a terminal disposition")
|
||||
terminal_seen = terminal_seen or is_terminal
|
||||
if terminal_seen:
|
||||
raise EvaluationAttemptError("terminal attempt history cannot authorize admission")
|
||||
|
||||
|
||||
def validate_attempt_history(
|
||||
manifest: EvaluationPlanManifestV3,
|
||||
history: AttemptHistoryV3,
|
||||
review_policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> tuple[AttemptEventV3, ...]:
|
||||
"""Validate the reviewed plan, exact predecessor chain, and sealed eligibility."""
|
||||
if type(manifest) is not EvaluationPlanManifestV3 or type(history) is not AttemptHistoryV3:
|
||||
raise EvaluationAttemptError("manifest and attempt history must use exact V3 contract types")
|
||||
history.__post_init__()
|
||||
_validate_policy(review_policy)
|
||||
validate_reviewed_evaluation_plan(manifest.census, manifest, review_policy, resolver)
|
||||
expected = derive_attempt_identity(manifest)
|
||||
if history.population_digest != expected.population_digest:
|
||||
raise EvaluationAttemptError("attempt history population does not match the reviewed plan")
|
||||
events = _resolve_events(history, review_policy, resolver)
|
||||
chain = _ordered_chain(history, events)
|
||||
_validate_eligibility(chain, expected)
|
||||
return chain
|
||||
|
||||
|
||||
__all__ = ["validate_attempt_history"]
|
||||
@@ -0,0 +1,471 @@
|
||||
"""Immutable reviewed attempt-history contracts for evaluation admission V3."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import ClassVar, cast
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_plan import EvaluationPlanManifestV3
|
||||
from openultrasast.core.evaluation_version import (
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
EvaluationV3Contract,
|
||||
NonAuthorizingV3,
|
||||
require_exact_v3_contract,
|
||||
)
|
||||
from openultrasast.core.factpack import IndependenceAttestation, ReviewIndependencePolicy
|
||||
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_IDENTITY_SCHEMA = "openultrasast.detection-core.evaluation-attempt-identity.v3"
|
||||
_ACCESS_SCHEMA = "openultrasast.detection-core.evaluation-observation-access-policy.v3"
|
||||
_PAYLOAD_SCHEMA = "openultrasast.detection-core.evaluation-attempt-payload.v3"
|
||||
_EVENT_SCHEMA = "openultrasast.detection-core.evaluation-attempt-event.v3"
|
||||
_REFERENCE_SCHEMA = "openultrasast.detection-core.evaluation-attempt-reference.v3"
|
||||
_HISTORY_SCHEMA = "openultrasast.detection-core.evaluation-attempt-history.v3"
|
||||
_PUBLIC_STATUS_SCHEMA = "openultrasast.detection-core.evaluation-public-status.v3"
|
||||
_CONTENT_REF_FIELDS = frozenset(
|
||||
{"artifact_id", "content_digest", "media_type", "byte_length", "retention_policy_digest", "storage_receipt_digest"}
|
||||
)
|
||||
_REVIEW_FIELDS = frozenset({"subject_digest", "producer_identity", "reviewer_identity", "conflict_disclosure", "attestation_digest"})
|
||||
_IDENTITY_FIELDS = frozenset(
|
||||
{
|
||||
"population_digest",
|
||||
"plan_declaration_digest",
|
||||
"baseline_digests",
|
||||
"input_set_digest",
|
||||
"configuration_digests",
|
||||
"registered_budget_digests",
|
||||
"execution_identities",
|
||||
"retry_identity_digest",
|
||||
}
|
||||
)
|
||||
_ACCESS_FIELDS = frozenset(
|
||||
{"allowed_public_fields", "raw_observation_access_allowed", "population_diagnostic_access_allowed", "policy_digest"}
|
||||
)
|
||||
_EVENT_FIELDS = frozenset(
|
||||
{
|
||||
"schema_version",
|
||||
"attempt_identity",
|
||||
"disposition",
|
||||
"access_policy",
|
||||
"raw_observation_access_count",
|
||||
"population_diagnostic_access_count",
|
||||
"public_status_projection",
|
||||
"predecessor_event_digest",
|
||||
"payload_digest",
|
||||
"review",
|
||||
"event_digest",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class EvaluationAttemptError(ValueError):
|
||||
"""A V3 attempt history is malformed, exposed, or ineligible for admission."""
|
||||
|
||||
|
||||
class PreSpendDispositionV3(Enum):
|
||||
SEALED = "sealed"
|
||||
DEVELOPMENT_OPENED = "development_opened"
|
||||
SPENT = "spent"
|
||||
|
||||
|
||||
class PublicStatusFieldV3(Enum):
|
||||
STATUS_CODE = "status_code"
|
||||
COUNT = "count"
|
||||
DIGEST = "digest"
|
||||
|
||||
|
||||
def _digest(value: object, field: str) -> str:
|
||||
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||
raise EvaluationAttemptError(f"{field} must be a full lowercase SHA-256 digest")
|
||||
return value
|
||||
|
||||
|
||||
def _digest_tuple(value: object, field: str) -> tuple[str, ...]:
|
||||
if type(value) is not tuple or not value:
|
||||
raise EvaluationAttemptError(f"{field} must be a nonempty tuple")
|
||||
for item in value:
|
||||
_digest(item, field)
|
||||
return value
|
||||
|
||||
|
||||
def _text_tuple(value: object, field: str) -> tuple[str, ...]:
|
||||
if type(value) is not tuple or not value or any(type(item) is not str or not item for item in value):
|
||||
raise EvaluationAttemptError(f"{field} must be a nonempty exact-text tuple")
|
||||
return value
|
||||
|
||||
|
||||
def _bind(value: object, field: str, expected: str) -> None:
|
||||
actual = getattr(value, field)
|
||||
if actual == "":
|
||||
object.__setattr__(value, field, expected)
|
||||
elif _digest(actual, field) != expected:
|
||||
raise EvaluationAttemptError(f"{field} does not match canonical content")
|
||||
|
||||
|
||||
def _content_ref_value(value: canonical.ContentRef) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"artifact_id": value.artifact_id,
|
||||
"content_digest": value.content_digest,
|
||||
"media_type": value.media_type,
|
||||
"byte_length": value.byte_length,
|
||||
"retention_policy_digest": value.retention_policy_digest,
|
||||
"storage_receipt_digest": value.storage_receipt_digest,
|
||||
}
|
||||
|
||||
|
||||
def _review_value(value: IndependenceAttestation) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"subject_digest": value.subject_digest,
|
||||
"producer_identity": value.producer_identity,
|
||||
"reviewer_identity": value.reviewer_identity,
|
||||
"conflict_disclosure": _content_ref_value(value.conflict_disclosure),
|
||||
"attestation_digest": value.attestation_digest,
|
||||
}
|
||||
|
||||
|
||||
def _identity_value(value: AttemptIdentityV3) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"population_digest": value.population_digest,
|
||||
"plan_declaration_digest": value.plan_declaration_digest,
|
||||
"baseline_digests": value.baseline_digests,
|
||||
"input_set_digest": value.input_set_digest,
|
||||
"configuration_digests": value.configuration_digests,
|
||||
"registered_budget_digests": value.registered_budget_digests,
|
||||
"execution_identities": value.execution_identities,
|
||||
"retry_identity_digest": value.retry_identity_digest,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttemptIdentityV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
population_digest: str
|
||||
plan_declaration_digest: str
|
||||
baseline_digests: tuple[str, ...]
|
||||
input_set_digest: str
|
||||
configuration_digests: tuple[str, ...]
|
||||
registered_budget_digests: tuple[str, ...]
|
||||
execution_identities: tuple[str, ...]
|
||||
retry_identity_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, AttemptIdentityV3, field="attempt identity")
|
||||
_digest(self.population_digest, "attempt population digest")
|
||||
_digest(self.plan_declaration_digest, "attempt plan declaration digest")
|
||||
baselines = _digest_tuple(self.baseline_digests, "attempt baseline digest")
|
||||
_digest(self.input_set_digest, "attempt input set digest")
|
||||
configurations = _digest_tuple(self.configuration_digests, "attempt configuration digest")
|
||||
budgets = _digest_tuple(self.registered_budget_digests, "attempt registered budget digest")
|
||||
executions = _text_tuple(self.execution_identities, "attempt execution identities")
|
||||
if len({len(baselines), len(configurations), len(budgets), len(executions)}) != 1:
|
||||
raise EvaluationAttemptError("attempt arm identity columns must have equal length")
|
||||
payload = dict(_identity_value(self))
|
||||
payload.pop("retry_identity_digest")
|
||||
_bind(self, "retry_identity_digest", canonical.content_digest({"schema_version": _IDENTITY_SCHEMA, **payload}))
|
||||
|
||||
|
||||
def _access_value(value: ObservationAccessPolicyV3) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"allowed_public_fields": tuple(item.value for item in value.allowed_public_fields),
|
||||
"raw_observation_access_allowed": value.raw_observation_access_allowed,
|
||||
"population_diagnostic_access_allowed": value.population_diagnostic_access_allowed,
|
||||
"policy_digest": value.policy_digest,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ObservationAccessPolicyV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
allowed_public_fields: tuple[PublicStatusFieldV3, ...]
|
||||
raw_observation_access_allowed: bool
|
||||
population_diagnostic_access_allowed: bool
|
||||
policy_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, ObservationAccessPolicyV3, field="observation access policy")
|
||||
if type(self.allowed_public_fields) is not tuple or not self.allowed_public_fields:
|
||||
raise EvaluationAttemptError("allowed public fields must be a nonempty canonical tuple")
|
||||
if any(type(item) is not PublicStatusFieldV3 for item in self.allowed_public_fields):
|
||||
raise EvaluationAttemptError("allowed public fields must use the closed PublicStatusFieldV3 enum")
|
||||
canonical_fields = tuple(item for item in PublicStatusFieldV3 if item in self.allowed_public_fields)
|
||||
if self.allowed_public_fields != canonical_fields:
|
||||
raise EvaluationAttemptError("allowed public fields must be unique and canonical")
|
||||
if type(self.raw_observation_access_allowed) is not bool or type(self.population_diagnostic_access_allowed) is not bool:
|
||||
raise EvaluationAttemptError("observation access flags must be exact booleans")
|
||||
payload = dict(_access_value(self))
|
||||
payload.pop("policy_digest")
|
||||
_bind(self, "policy_digest", canonical.content_digest({"schema_version": _ACCESS_SCHEMA, **payload}))
|
||||
|
||||
|
||||
def _event_payload_value(value: AttemptEventV3) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"schema_version": _PAYLOAD_SCHEMA,
|
||||
"attempt_identity": _identity_value(value.attempt_identity),
|
||||
"disposition": value.disposition.value,
|
||||
"access_policy": _access_value(value.access_policy),
|
||||
"raw_observation_access_count": value.raw_observation_access_count,
|
||||
"population_diagnostic_access_count": value.population_diagnostic_access_count,
|
||||
"public_status_projection": _content_ref_value(value.public_status_projection),
|
||||
"predecessor_event_digest": value.predecessor_event_digest,
|
||||
}
|
||||
|
||||
|
||||
def _event_value(value: AttemptEventV3) -> dict[str, canonical.JsonValue]:
|
||||
payload = dict(_event_payload_value(value))
|
||||
payload["schema_version"] = _EVENT_SCHEMA
|
||||
return {**payload, "payload_digest": value.payload_digest, "review": _review_value(value.review), "event_digest": value.event_digest}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttemptEventV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
attempt_identity: AttemptIdentityV3
|
||||
disposition: PreSpendDispositionV3
|
||||
access_policy: ObservationAccessPolicyV3
|
||||
raw_observation_access_count: int
|
||||
population_diagnostic_access_count: int
|
||||
public_status_projection: canonical.ContentRef
|
||||
predecessor_event_digest: str | None
|
||||
payload_digest: str
|
||||
review: IndependenceAttestation
|
||||
event_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, AttemptEventV3, field="attempt event")
|
||||
if type(self.attempt_identity) is not AttemptIdentityV3 or type(self.access_policy) is not ObservationAccessPolicyV3:
|
||||
raise EvaluationAttemptError("attempt event identity and access policy must use exact V3 values")
|
||||
self.attempt_identity.__post_init__()
|
||||
self.access_policy.__post_init__()
|
||||
if type(self.disposition) is not PreSpendDispositionV3:
|
||||
raise EvaluationAttemptError("attempt disposition must use the closed PreSpendDispositionV3 enum")
|
||||
for count, field in (
|
||||
(self.raw_observation_access_count, "raw observation access count"),
|
||||
(self.population_diagnostic_access_count, "population diagnostic access count"),
|
||||
):
|
||||
if type(count) is not int or count < 0:
|
||||
raise EvaluationAttemptError(f"{field} must be a non-negative integer")
|
||||
if type(self.public_status_projection) is not canonical.ContentRef:
|
||||
raise EvaluationAttemptError("public status projection must use exact ContentRef")
|
||||
self.public_status_projection.__post_init__()
|
||||
if self.predecessor_event_digest is not None:
|
||||
_digest(self.predecessor_event_digest, "predecessor event digest")
|
||||
if type(self.review) is not IndependenceAttestation:
|
||||
raise EvaluationAttemptError("attempt review must use exact IndependenceAttestation")
|
||||
self.review.__post_init__()
|
||||
_bind(self, "payload_digest", canonical.content_digest(_event_payload_value(self)))
|
||||
_bind(
|
||||
self,
|
||||
"event_digest",
|
||||
canonical.content_digest(
|
||||
{"schema_version": _EVENT_SCHEMA, "payload_digest": self.payload_digest, "review": _review_value(self.review)}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _reference_value(value: AttemptEventRefV3) -> dict[str, canonical.JsonValue]:
|
||||
return {"schema_version": _REFERENCE_SCHEMA, "event": _content_ref_value(value.event), "event_digest": value.event_digest}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttemptEventRefV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
event: canonical.ContentRef
|
||||
event_digest: str
|
||||
ref_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, AttemptEventRefV3, field="attempt event reference")
|
||||
if type(self.event) is not canonical.ContentRef:
|
||||
raise EvaluationAttemptError("attempt event reference must use exact ContentRef")
|
||||
self.event.__post_init__()
|
||||
_digest(self.event_digest, "referenced attempt event digest")
|
||||
_bind(self, "ref_digest", canonical.content_digest(_reference_value(self)))
|
||||
|
||||
|
||||
def _history_value(value: AttemptHistoryV3) -> dict[str, canonical.JsonValue]:
|
||||
return {
|
||||
"schema_version": _HISTORY_SCHEMA,
|
||||
"population_digest": value.population_digest,
|
||||
"event_ref_digests": tuple(item.ref_digest for item in value.events),
|
||||
"head_event_digest": value.head_event_digest,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttemptHistoryV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
population_digest: str
|
||||
events: tuple[AttemptEventRefV3, ...]
|
||||
head_event_digest: str
|
||||
history_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, AttemptHistoryV3, field="attempt history")
|
||||
_digest(self.population_digest, "attempt history population digest")
|
||||
if type(self.events) is not tuple or not self.events or any(type(item) is not AttemptEventRefV3 for item in self.events):
|
||||
raise EvaluationAttemptError("attempt history events must be a nonempty tuple of exact references")
|
||||
for item in self.events:
|
||||
item.__post_init__()
|
||||
_digest(self.head_event_digest, "attempt history head digest")
|
||||
_bind(self, "history_digest", canonical.content_digest(_history_value(self)))
|
||||
|
||||
|
||||
def derive_attempt_identity(manifest: EvaluationPlanManifestV3) -> AttemptIdentityV3:
|
||||
"""Derive the complete collision-resistant retry identity from one reviewed plan shape."""
|
||||
if type(manifest) is not EvaluationPlanManifestV3:
|
||||
raise EvaluationAttemptError("attempt identity requires exact EvaluationPlanManifestV3")
|
||||
manifest.__post_init__()
|
||||
declaration = manifest.declaration
|
||||
configurations = declaration.arm_configurations
|
||||
return AttemptIdentityV3(
|
||||
declaration.population_digest,
|
||||
declaration.declaration_digest,
|
||||
tuple(item.baseline_digest for item in manifest.baselines),
|
||||
declaration.input_set_digest,
|
||||
tuple(item.configuration_identity_digest for item in configurations),
|
||||
tuple(item.registered_budget_digest for item in configurations),
|
||||
tuple(item.execution_identity for item in configurations),
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def encode_attempt_event(value: AttemptEventV3) -> bytes:
|
||||
if type(value) is not AttemptEventV3:
|
||||
raise EvaluationAttemptError("attempt event must use exact AttemptEventV3")
|
||||
value.__post_init__()
|
||||
return canonical.canonical_bytes(_event_value(value))
|
||||
|
||||
|
||||
def _pairs(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
||||
result: dict[str, object] = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise EvaluationAttemptError(f"duplicate attempt event field: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _document(content: bytes) -> dict[str, object]:
|
||||
if type(content) is not bytes or not content:
|
||||
raise EvaluationAttemptError("attempt event bytes must be nonzero exact bytes")
|
||||
try:
|
||||
value = json.loads(content.decode("utf-8"), object_pairs_hook=_pairs)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise EvaluationAttemptError("attempt event bytes must contain valid UTF-8 JSON") from exc
|
||||
if type(value) is not dict or frozenset(value) != _EVENT_FIELDS or value["schema_version"] != _EVENT_SCHEMA:
|
||||
raise EvaluationAttemptError("attempt event document must use the exact V3 field set and schema")
|
||||
return value
|
||||
|
||||
|
||||
def _decode_ref(value: object) -> canonical.ContentRef:
|
||||
if type(value) is not dict or frozenset(value) != _CONTENT_REF_FIELDS:
|
||||
raise EvaluationAttemptError("content reference must use the exact canonical field set")
|
||||
try:
|
||||
return canonical.ContentRef(**value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise EvaluationAttemptError("content reference is malformed") from exc
|
||||
|
||||
|
||||
def _decode_identity(value: object) -> AttemptIdentityV3:
|
||||
if type(value) is not dict or frozenset(value) != _IDENTITY_FIELDS:
|
||||
raise EvaluationAttemptError("attempt identity must use the exact canonical field set")
|
||||
try:
|
||||
return AttemptIdentityV3(
|
||||
value["population_digest"],
|
||||
value["plan_declaration_digest"],
|
||||
tuple(value["baseline_digests"]),
|
||||
value["input_set_digest"],
|
||||
tuple(value["configuration_digests"]),
|
||||
tuple(value["registered_budget_digests"]),
|
||||
tuple(value["execution_identities"]),
|
||||
value["retry_identity_digest"],
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise EvaluationAttemptError("attempt identity is malformed") from exc
|
||||
|
||||
|
||||
def _decode_access(value: object) -> ObservationAccessPolicyV3:
|
||||
if type(value) is not dict or frozenset(value) != _ACCESS_FIELDS:
|
||||
raise EvaluationAttemptError("access policy must use the exact canonical field set")
|
||||
try:
|
||||
fields = tuple(PublicStatusFieldV3(item) for item in value["allowed_public_fields"])
|
||||
return ObservationAccessPolicyV3(
|
||||
fields, value["raw_observation_access_allowed"], value["population_diagnostic_access_allowed"], value["policy_digest"]
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise EvaluationAttemptError("access policy is malformed") from exc
|
||||
|
||||
|
||||
def _decode_review(value: object) -> IndependenceAttestation:
|
||||
if type(value) is not dict or frozenset(value) != _REVIEW_FIELDS:
|
||||
raise EvaluationAttemptError("attempt review must use the exact canonical field set")
|
||||
try:
|
||||
return IndependenceAttestation(
|
||||
value["subject_digest"],
|
||||
value["producer_identity"],
|
||||
value["reviewer_identity"],
|
||||
_decode_ref(value["conflict_disclosure"]),
|
||||
value["attestation_digest"],
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise EvaluationAttemptError("attempt review is malformed") from exc
|
||||
|
||||
|
||||
def decode_attempt_event(content: bytes) -> AttemptEventV3:
|
||||
"""Decode only the exact canonical reviewed attempt-event representation."""
|
||||
value = _document(content)
|
||||
try:
|
||||
predecessor = value["predecessor_event_digest"]
|
||||
if predecessor is not None:
|
||||
predecessor = _digest(predecessor, "predecessor event digest")
|
||||
event = AttemptEventV3(
|
||||
_decode_identity(value["attempt_identity"]),
|
||||
PreSpendDispositionV3(value["disposition"]),
|
||||
_decode_access(value["access_policy"]),
|
||||
cast(int, value["raw_observation_access_count"]),
|
||||
cast(int, value["population_diagnostic_access_count"]),
|
||||
_decode_ref(value["public_status_projection"]),
|
||||
predecessor,
|
||||
_digest(value["payload_digest"], "attempt payload digest"),
|
||||
_decode_review(value["review"]),
|
||||
_digest(value["event_digest"], "attempt event digest"),
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
if isinstance(exc, EvaluationAttemptError):
|
||||
raise
|
||||
raise EvaluationAttemptError("attempt event document contains malformed values") from exc
|
||||
if encode_attempt_event(event) != content:
|
||||
raise EvaluationAttemptError("attempt event document is not canonical JSON")
|
||||
return event
|
||||
|
||||
|
||||
def validate_evaluation_attempt_history(
|
||||
manifest: EvaluationPlanManifestV3,
|
||||
history: AttemptHistoryV3,
|
||||
review_policy: ReviewIndependencePolicy,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> tuple[AttemptEventV3, ...]:
|
||||
"""Resolve a reviewed chain and return it only when every exact retry remains sealed."""
|
||||
from openultrasast.core._evaluation_attempt_validation import validate_attempt_history
|
||||
|
||||
return validate_attempt_history(manifest, history, review_policy, resolver)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AttemptEventRefV3",
|
||||
"AttemptEventV3",
|
||||
"AttemptHistoryV3",
|
||||
"AttemptIdentityV3",
|
||||
"EvaluationAttemptError",
|
||||
"ObservationAccessPolicyV3",
|
||||
"PreSpendDispositionV3",
|
||||
"PublicStatusFieldV3",
|
||||
"decode_attempt_event",
|
||||
"derive_attempt_identity",
|
||||
"encode_attempt_event",
|
||||
"validate_evaluation_attempt_history",
|
||||
]
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Reviewed immutable attempt-history validation for evaluation admission V3."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import fields, replace
|
||||
|
||||
import pytest
|
||||
from detection_core_fixtures import InMemoryContentResolver, stored_artifact
|
||||
from test_core_evaluation_plan import _digest
|
||||
from test_core_evaluation_plan_review import _attestation, _case
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_attempt import (
|
||||
AttemptEventRefV3,
|
||||
AttemptEventV3,
|
||||
AttemptHistoryV3,
|
||||
AttemptIdentityV3,
|
||||
EvaluationAttemptError,
|
||||
ObservationAccessPolicyV3,
|
||||
PreSpendDispositionV3,
|
||||
PublicStatusFieldV3,
|
||||
decode_attempt_event,
|
||||
derive_attempt_identity,
|
||||
encode_attempt_event,
|
||||
validate_evaluation_attempt_history,
|
||||
)
|
||||
from openultrasast.core.evaluation_version import NonAuthorizingV3
|
||||
|
||||
|
||||
def _projection(*, artifact_id: str = "attempt-status"):
|
||||
content = canonical.canonical_bytes(
|
||||
{
|
||||
"schema_version": "openultrasast.detection-core.evaluation-public-status.v3",
|
||||
"status_code": "observation_complete",
|
||||
"count": 6,
|
||||
"digest": _digest("closed-status"),
|
||||
}
|
||||
)
|
||||
return stored_artifact(content, artifact_id=artifact_id)
|
||||
|
||||
|
||||
def _event(
|
||||
identity: AttemptIdentityV3,
|
||||
disposition: PreSpendDispositionV3,
|
||||
access: ObservationAccessPolicyV3,
|
||||
projection: canonical.ContentRef,
|
||||
predecessor: str | None,
|
||||
disclosure: canonical.ContentRef,
|
||||
reviewer: str,
|
||||
*,
|
||||
raw_count: int = 0,
|
||||
diagnostic_count: int = 0,
|
||||
producer: str | None = None,
|
||||
) -> AttemptEventV3:
|
||||
producer = producer or _digest(f"producer-{predecessor}")
|
||||
provisional = _attestation("0" * 64, producer, reviewer, disclosure)
|
||||
draft = AttemptEventV3(
|
||||
identity,
|
||||
disposition,
|
||||
access,
|
||||
raw_count,
|
||||
diagnostic_count,
|
||||
projection,
|
||||
predecessor,
|
||||
"",
|
||||
provisional,
|
||||
"",
|
||||
)
|
||||
review = _attestation(draft.payload_digest, producer, reviewer, disclosure)
|
||||
return replace(draft, review=review, event_digest="")
|
||||
|
||||
|
||||
def _reference(event: AttemptEventV3, artifact_id: str):
|
||||
reference, resolver = stored_artifact(encode_attempt_event(event), artifact_id=artifact_id)
|
||||
return AttemptEventRefV3(reference, event.event_digest, ""), resolver.artifacts[artifact_id]
|
||||
|
||||
|
||||
def _history_case(dispositions=(PreSpendDispositionV3.SEALED, PreSpendDispositionV3.SEALED)):
|
||||
_, manifest, policy, plan_resolver = _case()
|
||||
projection, projection_resolver = _projection()
|
||||
identity = derive_attempt_identity(manifest)
|
||||
access = ObservationAccessPolicyV3(tuple(PublicStatusFieldV3), False, False, "")
|
||||
events = []
|
||||
references = []
|
||||
artifacts = {**plan_resolver.artifacts, **projection_resolver.artifacts}
|
||||
predecessor = None
|
||||
for index, disposition in enumerate(dispositions):
|
||||
event = _event(
|
||||
identity,
|
||||
disposition,
|
||||
access,
|
||||
projection,
|
||||
predecessor,
|
||||
manifest.review.conflict_disclosure,
|
||||
manifest.review.reviewer_identity,
|
||||
)
|
||||
reference, resolved = _reference(event, f"attempt-{index}")
|
||||
events.append(event)
|
||||
references.append(reference)
|
||||
artifacts[reference.event.artifact_id] = resolved
|
||||
predecessor = event.event_digest
|
||||
history = AttemptHistoryV3(manifest.declaration.population_digest, tuple(references), predecessor, "")
|
||||
return manifest, policy, history, tuple(events), InMemoryContentResolver(artifacts)
|
||||
|
||||
|
||||
def _validate(case):
|
||||
manifest, policy, history, _, resolver = case
|
||||
return validate_evaluation_attempt_history(manifest, history, policy, resolver)
|
||||
|
||||
|
||||
def _replace_event(case, index: int, **changes):
|
||||
manifest, policy, history, events, resolver = case
|
||||
changed = replace(events[index], **changes, payload_digest="", event_digest="")
|
||||
changed = replace(
|
||||
changed,
|
||||
review=_attestation(
|
||||
changed.payload_digest,
|
||||
changed.review.producer_identity,
|
||||
changed.review.reviewer_identity,
|
||||
changed.review.conflict_disclosure,
|
||||
),
|
||||
event_digest="",
|
||||
)
|
||||
reference, resolved = _reference(changed, f"changed-attempt-{index}")
|
||||
references = history.events[:index] + (reference,) + history.events[index + 1 :]
|
||||
changed_history = AttemptHistoryV3(history.population_digest, references, references[-1].event_digest, "")
|
||||
artifacts = {**resolver.artifacts, reference.event.artifact_id: resolved}
|
||||
return manifest, policy, changed_history, events[:index] + (changed,) + events[index + 1 :], InMemoryContentResolver(artifacts)
|
||||
|
||||
|
||||
def test_unchanged_all_sealed_reviewed_retry_chain_validates() -> None:
|
||||
case = _history_case()
|
||||
assert _validate(case) == case[3]
|
||||
identity = case[3][0].attempt_identity
|
||||
declaration = case[0].declaration
|
||||
assert identity.population_digest == declaration.population_digest
|
||||
assert identity.plan_declaration_digest == declaration.declaration_digest
|
||||
assert identity.input_set_digest == declaration.input_set_digest
|
||||
assert identity.baseline_digests == tuple(row.baseline_digest for row in case[0].baselines)
|
||||
assert identity.configuration_digests == tuple(row.configuration_identity_digest for row in declaration.arm_configurations)
|
||||
assert identity.registered_budget_digests == tuple(row.registered_budget_digest for row in declaration.arm_configurations)
|
||||
assert identity.execution_identities == tuple(row.execution_identity for row in declaration.arm_configurations)
|
||||
|
||||
|
||||
def test_contracts_are_exact_registered_non_authorizing_v3_values() -> None:
|
||||
expected = {
|
||||
AttemptIdentityV3: {
|
||||
"population_digest",
|
||||
"plan_declaration_digest",
|
||||
"baseline_digests",
|
||||
"input_set_digest",
|
||||
"configuration_digests",
|
||||
"registered_budget_digests",
|
||||
"execution_identities",
|
||||
"retry_identity_digest",
|
||||
},
|
||||
ObservationAccessPolicyV3: {
|
||||
"allowed_public_fields",
|
||||
"raw_observation_access_allowed",
|
||||
"population_diagnostic_access_allowed",
|
||||
"policy_digest",
|
||||
},
|
||||
AttemptEventV3: {
|
||||
"attempt_identity",
|
||||
"disposition",
|
||||
"access_policy",
|
||||
"raw_observation_access_count",
|
||||
"population_diagnostic_access_count",
|
||||
"public_status_projection",
|
||||
"predecessor_event_digest",
|
||||
"payload_digest",
|
||||
"review",
|
||||
"event_digest",
|
||||
},
|
||||
AttemptEventRefV3: {"event", "event_digest", "ref_digest"},
|
||||
AttemptHistoryV3: {"population_digest", "events", "head_event_digest", "history_digest"},
|
||||
}
|
||||
for value_type, names in expected.items():
|
||||
assert {field.name for field in fields(value_type)} == names
|
||||
assert issubclass(value_type, NonAuthorizingV3)
|
||||
assert "authorize" not in names
|
||||
|
||||
|
||||
def test_event_encoding_is_strict_canonical_and_round_trips() -> None:
|
||||
event = _history_case()[3][0]
|
||||
encoded = encode_attempt_event(event)
|
||||
assert encoded
|
||||
assert decode_attempt_event(encoded) == event
|
||||
assert json.dumps(json.loads(encoded), sort_keys=True, separators=(",", ":")).encode() == encoded
|
||||
with pytest.raises(EvaluationAttemptError):
|
||||
decode_attempt_event(json.dumps(json.loads(encoded), indent=2).encode())
|
||||
with pytest.raises(EvaluationAttemptError, match="nonzero"):
|
||||
decode_attempt_event(b"")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ("broken", "skipped", "reordered", "forked", "head"))
|
||||
def test_history_must_be_one_complete_declared_predecessor_chain(failure: str) -> None:
|
||||
case = _history_case()
|
||||
manifest, policy, history, events, resolver = case
|
||||
if failure == "broken":
|
||||
case = _replace_event(case, 1, predecessor_event_digest=_digest("missing-predecessor"))
|
||||
elif failure == "skipped":
|
||||
changed = AttemptHistoryV3(history.population_digest, history.events[1:], history.head_event_digest, "")
|
||||
case = manifest, policy, changed, events[1:], resolver
|
||||
elif failure == "reordered":
|
||||
changed = AttemptHistoryV3(history.population_digest, tuple(reversed(history.events)), history.head_event_digest, "")
|
||||
case = manifest, policy, changed, tuple(reversed(events)), resolver
|
||||
elif failure == "forked":
|
||||
root = events[0]
|
||||
sibling = _event(
|
||||
root.attempt_identity,
|
||||
PreSpendDispositionV3.SEALED,
|
||||
root.access_policy,
|
||||
root.public_status_projection,
|
||||
root.event_digest,
|
||||
root.review.conflict_disclosure,
|
||||
root.review.reviewer_identity,
|
||||
producer=_digest("sibling-producer"),
|
||||
)
|
||||
sibling_ref, sibling_content = _reference(sibling, "forked-attempt")
|
||||
refs = (history.events[0], history.events[1], sibling_ref)
|
||||
changed = AttemptHistoryV3(history.population_digest, refs, sibling.event_digest, "")
|
||||
case = (
|
||||
manifest,
|
||||
policy,
|
||||
changed,
|
||||
events + (sibling,),
|
||||
InMemoryContentResolver({**resolver.artifacts, "forked-attempt": sibling_content}),
|
||||
)
|
||||
else:
|
||||
changed = AttemptHistoryV3(history.population_digest, history.events, events[0].event_digest, "")
|
||||
case = manifest, policy, changed, events, resolver
|
||||
with pytest.raises(EvaluationAttemptError):
|
||||
_validate(case)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field",
|
||||
[
|
||||
"population_digest",
|
||||
"plan_declaration_digest",
|
||||
"baseline_digests",
|
||||
"input_set_digest",
|
||||
"configuration_digests",
|
||||
"registered_budget_digests",
|
||||
"execution_identities",
|
||||
],
|
||||
)
|
||||
def test_each_complete_retry_identity_column_must_remain_exact(field: str) -> None:
|
||||
case = _history_case((PreSpendDispositionV3.SEALED,))
|
||||
event = case[3][0]
|
||||
identity = event.attempt_identity
|
||||
value: object = _digest(f"changed-{field}")
|
||||
if field in {"baseline_digests", "configuration_digests", "registered_budget_digests"}:
|
||||
original = getattr(identity, field)
|
||||
value = (*original[:-1], _digest(f"changed-{field}"))
|
||||
elif field == "execution_identities":
|
||||
value = (*identity.execution_identities[:-1], "changed-execution")
|
||||
changed_identity = replace(identity, **{field: value}, retry_identity_digest="")
|
||||
with pytest.raises(EvaluationAttemptError, match="identity"):
|
||||
_validate(_replace_event(case, 0, attempt_identity=changed_identity))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count_field", ["raw_observation_access_count", "population_diagnostic_access_count"])
|
||||
def test_each_access_count_requires_terminal_disposition(count_field: str) -> None:
|
||||
case = _history_case((PreSpendDispositionV3.SEALED,))
|
||||
with pytest.raises(EvaluationAttemptError, match="access"):
|
||||
_validate(_replace_event(case, 0, **{count_field: 1}))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("policy_field", ["raw_observation_access_allowed", "population_diagnostic_access_allowed"])
|
||||
def test_each_open_access_policy_requires_terminal_disposition(policy_field: str) -> None:
|
||||
case = _history_case((PreSpendDispositionV3.SEALED,))
|
||||
event = case[3][0]
|
||||
opened = replace(event.access_policy, **{policy_field: True}, policy_digest="")
|
||||
with pytest.raises(EvaluationAttemptError, match="access"):
|
||||
_validate(_replace_event(case, 0, access_policy=opened))
|
||||
|
||||
|
||||
def test_terminal_history_and_terminal_then_sealed_cannot_restore_eligibility() -> None:
|
||||
terminal = _history_case((PreSpendDispositionV3.DEVELOPMENT_OPENED,))
|
||||
with pytest.raises(EvaluationAttemptError, match="terminal"):
|
||||
_validate(terminal)
|
||||
restored = _history_case((PreSpendDispositionV3.SPENT, PreSpendDispositionV3.SEALED))
|
||||
with pytest.raises(EvaluationAttemptError, match="terminal"):
|
||||
_validate(restored)
|
||||
|
||||
|
||||
def test_self_review_untrusted_bytes_and_open_projection_are_refused() -> None:
|
||||
case = _history_case((PreSpendDispositionV3.SEALED,))
|
||||
event = case[3][0]
|
||||
self_review = _attestation(
|
||||
event.payload_digest,
|
||||
event.review.reviewer_identity,
|
||||
event.review.reviewer_identity,
|
||||
event.review.conflict_disclosure,
|
||||
)
|
||||
with pytest.raises(EvaluationAttemptError, match="independent"):
|
||||
_validate(_replace_event(case, 0, review=self_review))
|
||||
|
||||
manifest, policy, history, events, resolver = case
|
||||
open_bytes = canonical.canonical_bytes(
|
||||
{
|
||||
"schema_version": "openultrasast.detection-core.evaluation-public-status.v3",
|
||||
"raw_observations": ("secret",),
|
||||
}
|
||||
)
|
||||
open_ref, open_resolver = stored_artifact(open_bytes, artifact_id="open-status")
|
||||
changed_case = _replace_event(case, 0, public_status_projection=open_ref)
|
||||
changed_case = changed_case[:-1] + (InMemoryContentResolver({**changed_case[-1].artifacts, **open_resolver.artifacts}),)
|
||||
with pytest.raises(EvaluationAttemptError, match="projection"):
|
||||
_validate(changed_case)
|
||||
|
||||
resolved = resolver.artifacts[history.events[0].event.artifact_id]
|
||||
truncated = replace(resolved, content=resolved.content[:-1])
|
||||
bad_resolver = InMemoryContentResolver({**resolver.artifacts, history.events[0].event.artifact_id: truncated})
|
||||
with pytest.raises(canonical.ArtifactValidationError):
|
||||
validate_evaluation_attempt_history(manifest, history, policy, bad_resolver)
|
||||
|
||||
|
||||
def test_wrong_population_subclasses_and_noncanonical_policy_are_refused() -> None:
|
||||
manifest, policy, history, _, resolver = _history_case()
|
||||
with pytest.raises(EvaluationAttemptError, match="population"):
|
||||
validate_evaluation_attempt_history(
|
||||
manifest,
|
||||
replace(history, population_digest=_digest("other-population"), history_digest=""),
|
||||
policy,
|
||||
resolver,
|
||||
)
|
||||
with pytest.raises(EvaluationAttemptError, match="canonical"):
|
||||
ObservationAccessPolicyV3(tuple(reversed(tuple(PublicStatusFieldV3))), False, False, "")
|
||||
|
||||
class DerivedHistory(AttemptHistoryV3):
|
||||
pass
|
||||
|
||||
derived = object.__new__(DerivedHistory)
|
||||
with pytest.raises((EvaluationAttemptError, TypeError, ValueError)):
|
||||
validate_evaluation_attempt_history(manifest, derived, policy, resolver)
|
||||
Reference in New Issue
Block a user