diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 468ffd44..efd68bb5 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -152,7 +152,7 @@ - _Requirements: 5.7, 7.4, 7.5, 7.8, 8.4, 8.5_ - _Boundary: Durable Custody Store_ - _Depends: 1.3_ -- [ ] 5.4 Implement monotonic durable custody compare-and-swap +- [x] 5.4 Implement monotonic durable custody compare-and-swap - Use canonical custody-log digests as domain identity and storage tokens only for conditional concurrency. - Conditional-create the first head, conditional-update the exact current head, and reread/validate the direct available-to-spent successor before returning success. - Reject stale heads, 409/412 conflicts, missing versions, invalid successors, ambiguous responses, and any attempt to restore available status. @@ -428,3 +428,4 @@ - Task 5.1 persists replacement-authorizing artifacts under deterministic digest keys with conditional create and strict readback; access is policy-bound before fetch, and provider failures cross the repository boundary only as closed reason codes without retained exception diagnostics. - Task 5.2 rebuilds exact caller-selected durable projection roots and ordered members from the object store alone; canonical root-envelope binding, mixed-access population recovery, and explicit optional expiry prevent forged authority, latest-value selection, and unintended terminal-artifact expiration. - Task 5.3 gates real-population admission on a canonical report bound to exact store namespaces and a typed retention profile; negative conditional-write proofs, distinct visible versions, bound pre-deadline current/noncurrent evidence, and closed handling of null IDs, delete markers, and provider ambiguity prevent plausible-but-unsupported capability passes. +- Task 5.4 persists one canonical AVAILABLE head and permits only its direct AVAILABLE-to-SPENT successor through capability-gated conditional writes; domain digests govern state while advancing version and ETag tokens prove storage concurrency and exact rereads before any caller may expose labels. diff --git a/benchmarks/valid/durable_custody_store.py b/benchmarks/valid/durable_custody_store.py new file mode 100644 index 00000000..9604f753 --- /dev/null +++ b/benchmarks/valid/durable_custody_store.py @@ -0,0 +1,426 @@ +"""Monotonic S3 compare-and-swap for population custody logs.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass +from enum import StrEnum +from typing import Protocol, cast + +from benchmarks.valid.custody_probe_contract import ( + CustodyCapabilityReport, + RealPopulationAdmissionDisabled, + require_real_population_admission, +) +from benchmarks.valid.custody_probe_io import valid_version_id +from benchmarks.valid.store_configuration import RetentionProfile, StorePurpose, StoreSettings, store_namespace_identity +from openultrasast.core import canonical +from openultrasast.core.custody import ( + CUSTODY_LOG_SCHEMA, + LineagePurpose, + PopulationCustodyError, + PopulationCustodyLog, + PopulationCustodyPolicy, + PopulationStatus, + PopulationUseReceipt, + PopulationUseRequest, + validate_population_custody_log, +) + +_CONFLICT_CODES = frozenset({"409", "412", "ConditionalRequestConflict", "PreconditionFailed"}) +_NOT_FOUND_CODES = frozenset({"404", "NoSuchKey", "NotFound", "NoSuchVersion"}) +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +class DurableCustodyReason(StrEnum): + CAPABILITY_DISABLED = "capability_disabled" + INVALID_INPUT = "invalid_input" + NOT_FOUND = "not_found" + INVALID_LOG = "invalid_log" + INVALID_SUCCESSOR = "invalid_successor" + UNREADABLE_RESPONSE = "unreadable_response" + READBACK_MISMATCH = "readback_mismatch" + STORE_FAILURE = "store_failure" + + +class DurableCustodyStoreError(RuntimeError): + def __init__(self, reason: DurableCustodyReason) -> None: + self.reason = reason + super().__init__(f"durable_custody_{reason.value}") + + +class S3DurableCustodyClient(Protocol): + def put_object(self, **kwargs: object) -> Mapping[str, object]: ... + + def get_object(self, **kwargs: object) -> Mapping[str, object]: ... + + +@dataclass(frozen=True) +class _StorageReceipt: + version_id: str + storage_token: str + + +@dataclass(frozen=True) +class _WriteAttempt: + receipt: _StorageReceipt | None + is_conflict: bool + reason: DurableCustodyReason | None + + +@dataclass(frozen=True) +class _StoredLog: + log: PopulationCustodyLog + body: bytes + receipt: _StorageReceipt + + +@dataclass(frozen=True) +class _ReadAttempt: + stored: _StoredLog | None + is_absent: bool + reason: DurableCustodyReason | None + + +def _provider_code(error: Exception) -> str: + try: + response = getattr(error, "response", None) + details = response.get("Error") if isinstance(response, Mapping) else None + code = details.get("Code", "") if isinstance(details, Mapping) else getattr(error, "code", "") + except Exception: + return "" + return code if isinstance(code, str) else str(code) if type(code) is int else "" + + +def _request_value(request: PopulationUseRequest) -> canonical.JsonValue: + return { + "population_digest": request.population_digest, + "arm_id": request.arm_id, + "purpose": request.purpose.value, + "labels_accessed": request.labels_accessed, + "influenced_artifact_digest": request.influenced_artifact_digest, + "expected_log_digest": request.expected_log_digest, + } + + +def _receipt_value(receipt: PopulationUseReceipt) -> canonical.JsonValue: + return { + "request": _request_value(receipt.request), + "request_digest": receipt.request_digest, + "population_digest": receipt.population_digest, + "custodian_identity": receipt.custodian_identity, + "sequence": receipt.sequence, + "predecessor_digest": receipt.predecessor_digest, + "prior_status": receipt.prior_status.value, + "status": receipt.status.value, + "reasons": receipt.reasons, + "receipt_digest": receipt.receipt_digest, + } + + +def canonical_population_custody_log_bytes(log: PopulationCustodyLog) -> bytes: + value: canonical.JsonValue = { + "schema_version": CUSTODY_LOG_SCHEMA, + "population_digest": log.population_digest, + "custodian_identity": log.custodian_identity, + "receipts": tuple(_receipt_value(receipt) for receipt in log.receipts), + "receipt_count": log.receipt_count, + "head_receipt_digest": log.head_receipt_digest, + "status": log.status.value, + "log_digest": log.log_digest, + } + return canonical.canonical_bytes(value) + + +def _request_from(value: object) -> PopulationUseRequest | None: + if not isinstance(value, Mapping): + return None + try: + return PopulationUseRequest( + cast(str, value["population_digest"]), + cast(str, value["arm_id"]), + LineagePurpose(value["purpose"]), + cast(bool, value["labels_accessed"]), + cast(str | None, value["influenced_artifact_digest"]), + cast(str, value["expected_log_digest"]), + ) + except (KeyError, TypeError, ValueError): + return None + + +def _receipt_from(value: object) -> PopulationUseReceipt | None: + if not isinstance(value, Mapping): + return None + request = _request_from(value.get("request")) + if request is None: + return None + try: + reasons = value["reasons"] + if not isinstance(reasons, list): + return None + return PopulationUseReceipt( + request, + cast(str, value["request_digest"]), + cast(str, value["population_digest"]), + cast(str, value["custodian_identity"]), + cast(int, value["sequence"]), + cast(str | None, value["predecessor_digest"]), + PopulationStatus(value["prior_status"]), + PopulationStatus(value["status"]), + tuple(cast(list[str], reasons)), + cast(str, value["receipt_digest"]), + ) + except (KeyError, TypeError, ValueError): + return None + + +def _decode_log(body: bytes) -> PopulationCustodyLog | None: + try: + value = json.loads(body) + if not isinstance(value, Mapping) or value.get("schema_version") != CUSTODY_LOG_SCHEMA: + return None + raw_receipts = value["receipts"] + if not isinstance(raw_receipts, list): + return None + receipts = tuple(_receipt_from(item) for item in raw_receipts) + if any(item is None for item in receipts): + return None + log = PopulationCustodyLog( + cast(str, value["population_digest"]), + cast(str, value["custodian_identity"]), + cast(tuple[PopulationUseReceipt, ...], receipts), + cast(int, value["receipt_count"]), + cast(str | None, value["head_receipt_digest"]), + PopulationStatus(value["status"]), + cast(str, value["log_digest"]), + ) + except (json.JSONDecodeError, KeyError, TypeError, UnicodeDecodeError, ValueError): + return None + return log if canonical_population_custody_log_bytes(log) == body else None + + +class S3DurableCustodyStore: + """Capability-gated durable head and content-addressed custody events.""" + + def __init__( + self, + settings: StoreSettings, + client: S3DurableCustodyClient, + policy: PopulationCustodyPolicy, + capability_report: CustodyCapabilityReport, + transient_store_identity: str, + transient_profile: RetentionProfile, + ) -> None: + valid = type(settings) is StoreSettings and settings.purpose is StorePurpose.DURABLE + if not valid or type(policy) is not PopulationCustodyPolicy: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_INPUT) + disabled = False + try: + require_real_population_admission( + capability_report, + store_namespace_identity(settings), + transient_store_identity, + transient_profile, + ) + except RealPopulationAdmissionDisabled: + disabled = True + if disabled: + raise DurableCustodyStoreError(DurableCustodyReason.CAPABILITY_DISABLED) + self._settings = settings + self._client = client + self._policy = policy + + def initialize(self, initial: PopulationCustodyLog) -> bool: + self._validate_initial(initial) + body = canonical_population_custody_log_bytes(initial) + self._persist_event(initial, body) + write = self._write(self._head_key(initial.population_digest), body, absent=True) + if write.is_conflict: + return False + receipt = self._require_write(write) + self._verify_committed(initial, body, receipt) + return True + + def current_log(self, population_digest: str) -> PopulationCustodyLog: + if not isinstance(population_digest, str) or _DIGEST.fullmatch(population_digest) is None: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_INPUT) + read = self._read(self._head_key(population_digest)) + if read.is_absent: + raise DurableCustodyStoreError(DurableCustodyReason.NOT_FOUND) + stored = self._require_read(read) + if stored.log.population_digest != population_digest: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_LOG) + self._validate_log(stored.log) + return stored.log + + def compare_and_swap(self, expected_log_digest: str, replacement: PopulationCustodyLog) -> bool: + if not isinstance(expected_log_digest, str) or _DIGEST.fullmatch(expected_log_digest) is None: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_INPUT) + self._validate_log(replacement) + current = self._read(self._head_key(replacement.population_digest)) + stored = self._require_read(current) + if stored.log.log_digest != expected_log_digest: + return False + self._validate_successor(stored.log, replacement) + body = canonical_population_custody_log_bytes(replacement) + self._persist_event(replacement, body) + write = self._write( + self._head_key(replacement.population_digest), + body, + token=stored.receipt.storage_token, + ) + if write.is_conflict: + return False + receipt = self._require_write(write) + if receipt.version_id == stored.receipt.version_id or receipt.storage_token == stored.receipt.storage_token: + raise DurableCustodyStoreError(DurableCustodyReason.UNREADABLE_RESPONSE) + self._verify_committed(replacement, body, receipt) + return True + + def _validate_log(self, log: PopulationCustodyLog) -> None: + invalid = False + try: + validate_population_custody_log(log, self._policy) + except (PopulationCustodyError, TypeError, ValueError): + invalid = True + if invalid: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_LOG) + + def _validate_initial(self, log: PopulationCustodyLog) -> None: + self._validate_log(log) + if log.status is not PopulationStatus.AVAILABLE or log.receipt_count != 0 or log.receipts: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_LOG) + + def _validate_successor(self, prior: PopulationCustodyLog, replacement: PopulationCustodyLog) -> None: + direct = ( + prior.status is PopulationStatus.AVAILABLE + and replacement.status is PopulationStatus.SPENT + and prior.population_digest == replacement.population_digest + and prior.custodian_identity == replacement.custodian_identity + and replacement.receipt_count == prior.receipt_count + 1 + and replacement.receipts[:-1] == prior.receipts + and replacement.receipts[-1].request.expected_log_digest == prior.log_digest + ) + if not direct: + raise DurableCustodyStoreError(DurableCustodyReason.INVALID_SUCCESSOR) + + def _persist_event(self, log: PopulationCustodyLog, body: bytes) -> None: + key = self._event_key(log.population_digest, log.log_digest) + write = self._write(key, body, absent=True) + if write.is_conflict: + existing = self._require_read(self._read(key)) + if existing.body != body or existing.log != log: + raise DurableCustodyStoreError(DurableCustodyReason.READBACK_MISMATCH) + return + receipt = self._require_write(write) + self._verify_exact(key, log, body, receipt) + + def _verify_committed(self, log: PopulationCustodyLog, body: bytes, receipt: _StorageReceipt) -> None: + self._verify_exact(self._head_key(log.population_digest), log, body, receipt) + + def _verify_exact(self, key: str, log: PopulationCustodyLog, body: bytes, receipt: _StorageReceipt) -> None: + read = self._require_read(self._read(key, receipt.version_id)) + if read.log != log or read.body != body or read.receipt != receipt: + raise DurableCustodyStoreError(DurableCustodyReason.READBACK_MISMATCH) + self._validate_log(read.log) + + def _write( + self, + key: str, + body: bytes, + *, + absent: bool = False, + token: str | None = None, + ) -> _WriteAttempt: + request: dict[str, object] = {"Bucket": self._settings.bucket, "Key": key, "Body": body} + if absent: + request["IfNoneMatch"] = "*" + if token is not None: + request["IfMatch"] = token + code = "" + try: + response = self._client.put_object(**request) + except Exception as error: + code = _provider_code(error) + response = None + if response is None: + return _WriteAttempt(None, code in _CONFLICT_CODES, DurableCustodyReason.STORE_FAILURE) + if not isinstance(response, Mapping): + return _WriteAttempt(None, False, DurableCustodyReason.UNREADABLE_RESPONSE) + version_id, token_value = response.get("VersionId"), response.get("ETag") + if not valid_version_id(version_id) or not isinstance(token_value, str) or not token_value: + return _WriteAttempt(None, False, DurableCustodyReason.UNREADABLE_RESPONSE) + return _WriteAttempt(_StorageReceipt(cast(str, version_id), token_value), False, None) + + def _read(self, key: str, version_id: str | None = None) -> _ReadAttempt: + request: dict[str, object] = {"Bucket": self._settings.bucket, "Key": key} + if version_id is not None: + request["VersionId"] = version_id + code = "" + try: + response = self._client.get_object(**request) + except Exception as error: + code = _provider_code(error) + response = None + if response is None: + absent = code in _NOT_FOUND_CODES + reason = None if absent else DurableCustodyReason.STORE_FAILURE + return _ReadAttempt(None, absent, reason) + return self._decode_read(response) + + @staticmethod + def _decode_read(response: Mapping[str, object]) -> _ReadAttempt: + source = response.get("Body") + try: + body = source.read() if hasattr(source, "read") else source + except Exception: + body = None + version_id, token, length = response.get("VersionId"), response.get("ETag"), response.get("ContentLength") + valid = ( + isinstance(body, bytes) + and bool(body) + and type(length) is int + and length == len(body) + and valid_version_id(version_id) + and isinstance(token, str) + and bool(token) + ) + if not valid: + return _ReadAttempt(None, False, DurableCustodyReason.UNREADABLE_RESPONSE) + log = _decode_log(cast(bytes, body)) + if log is None: + return _ReadAttempt(None, False, DurableCustodyReason.INVALID_LOG) + receipt = _StorageReceipt(cast(str, version_id), cast(str, token)) + return _ReadAttempt(_StoredLog(log, cast(bytes, body), receipt), False, None) + + @staticmethod + def _require_write(write: _WriteAttempt) -> _StorageReceipt: + if write.receipt is None: + raise DurableCustodyStoreError(write.reason or DurableCustodyReason.STORE_FAILURE) + return write.receipt + + @staticmethod + def _require_read(read: _ReadAttempt) -> _StoredLog: + if read.stored is None: + reason = DurableCustodyReason.NOT_FOUND if read.is_absent else read.reason + raise DurableCustodyStoreError(reason or DurableCustodyReason.STORE_FAILURE) + return read.stored + + @staticmethod + def _head_key(population_digest: str) -> str: + return f"custody/{population_digest}/head.json" + + @staticmethod + def _event_key(population_digest: str, log_digest: str) -> str: + return f"custody/{population_digest}/events/{log_digest}.json" + + +__all__ = [ + "DurableCustodyReason", + "DurableCustodyStoreError", + "S3DurableCustodyClient", + "S3DurableCustodyStore", + "canonical_population_custody_log_bytes", +] diff --git a/tests/test_valid_benchmark_durable_custody.py b/tests/test_valid_benchmark_durable_custody.py new file mode 100644 index 00000000..99c5172b --- /dev/null +++ b/tests/test_valid_benchmark_durable_custody.py @@ -0,0 +1,379 @@ +"""Production durable custody compare-and-swap tests.""" + +from __future__ import annotations + +import inspect +import io +import sys +import threading +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from hashlib import sha256 +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from benchmarks.valid.custody_probe_contract import ( + CUSTODY_CAPABILITY_REPORT_SCHEMA, + MANDATORY_PROBE_RESULTS, + RETENTION_PROBE_STATE_SCHEMA, + CustodyCapabilityReport, + CustodyCapabilityStatus, + ProbeResult, + ProbeResultReason, + ProbeResultStatus, + RetentionProbeState, + build_capability_report, + derive_retention_state_digest, + passed_result, +) +from benchmarks.valid.durable_custody_store import ( + DurableCustodyReason, + DurableCustodyStoreError, + S3DurableCustodyStore, +) +from benchmarks.valid.store_configuration import RetentionProfile, StorePurpose, StoreSettings, store_namespace_identity +from openultrasast.core.canonical import content_digest +from openultrasast.core.custody import ( + LineagePurpose, + PopulationCustodyLog, + PopulationCustodyPolicy, + PopulationUseRequest, + append_population_use, + derive_population_custody_policy_digest, + empty_population_custody_log, + record_population_use, +) + + +class _ProviderError(Exception): + def __init__(self, code: str, secret: str = "provider password=/private/path") -> None: + self.response = {"Error": {"Code": code, "Message": secret}} + super().__init__(secret) + + +class _Version: + def __init__(self, version_id: str, body: bytes, etag: str) -> None: + self.version_id = version_id + self.body = body + self.etag = etag + + +class _Client: + def __init__(self) -> None: + self.lock = threading.Lock() + self.values: dict[tuple[str, str], list[_Version]] = {} + self.requests: list[dict[str, object]] = [] + self.next_version = 1 + self.force_conflict = False + self.force_head_conflict = False + self.provider_failure = False + self.missing_version = False + self.fixed_version_id: str | None = None + self.constant_etag = False + self.head_update_barrier: threading.Barrier | None = None + self.corrupt_reads = False + + def put_object(self, **kwargs: object) -> dict[str, object]: + key = str(kwargs["Key"]) + if self.head_update_barrier is not None and key.endswith("/head.json") and "IfMatch" in kwargs: + self.head_update_barrier.wait(timeout=5) + with self.lock: + self.requests.append(dict(kwargs)) + if self.provider_failure: + raise _ProviderError("InternalError") + bucket = str(kwargs["Bucket"]) + versions = self.values.setdefault((bucket, key), []) + current = versions[-1] if versions else None + if self.force_conflict or (self.force_head_conflict and key.endswith("/head.json")): + raise _ProviderError("PreconditionFailed") + if kwargs.get("IfNoneMatch") == "*" and current is not None: + raise _ProviderError("PreconditionFailed") + expected = kwargs.get("IfMatch") + if expected is not None and (current is None or current.etag != expected): + raise _ProviderError("PreconditionFailed") + body = kwargs["Body"] + assert isinstance(body, bytes) and body + version_id = self.fixed_version_id if self.fixed_version_id is not None else f"version-{self.next_version}" + self.next_version += 1 + etag = "constant-etag" if self.constant_etag else sha256(body + version_id.encode()).hexdigest() + versions.append(_Version(version_id, body, etag)) + response: dict[str, object] = {"ETag": etag} + if not self.missing_version: + response["VersionId"] = version_id + return response + + def get_object(self, **kwargs: object) -> dict[str, object]: + with self.lock: + if self.provider_failure: + raise _ProviderError("InternalError") + bucket, key = str(kwargs["Bucket"]), str(kwargs["Key"]) + versions = self.values.get((bucket, key), []) + requested = kwargs.get("VersionId") + matching = [item for item in versions if requested is None or item.version_id == requested] + if not matching: + raise _ProviderError("NoSuchKey") + version = matching[-1] + body = b"corrupt" if self.corrupt_reads else version.body + return { + "Body": io.BytesIO(body), + "ContentLength": len(body), + "VersionId": version.version_id, + "ETag": version.etag, + } + + +def _settings(purpose: StorePurpose) -> StoreSettings: + return StoreSettings( + purpose, + f"https://{purpose.value}.invalid:9000", + f"valid-{purpose.value}", + "ACCESS-SECRET", + "SECRET-SECRET", + ) + + +def _profile() -> RetentionProfile: + return RetentionProfile(StorePurpose.TRANSIENT, True, True, True, 2, 1) + + +def _report() -> CustodyCapabilityReport: + durable_identity = store_namespace_identity(_settings(StorePurpose.DURABLE)) + transient_identity = store_namespace_identity(_settings(StorePurpose.TRANSIENT)) + input_digest = content_digest("capability-input") + draft = RetentionProbeState( + RETENTION_PROBE_STATE_SCHEMA, + input_digest, + 16, + 1_000, + durable_identity, + transient_identity, + _settings(StorePurpose.TRANSIENT).bucket, + "runs/probe/current.json", + "version-current", + 2_000, + "runs/probe/noncurrent.json", + "version-prior", + "version-successor", + 1_500, + "", + ) + state = replace(draft, state_digest=derive_retention_state_digest(draft)) + results = tuple(passed_result(name) for name in MANDATORY_PROBE_RESULTS) + return build_capability_report(input_digest, 16, _profile(), state, results) + + +def _policy_and_logs() -> tuple[PopulationCustodyPolicy, PopulationCustodyLog, PopulationCustodyLog]: + custodian = content_digest("reviewed-custodian") + policy = PopulationCustodyPolicy((custodian,), derive_population_custody_policy_digest((custodian,))) + available = empty_population_custody_log(content_digest("population"), custodian) + request = PopulationUseRequest( + available.population_digest, + "arm-v3", + LineagePurpose.ADMISSION_LABEL_OPEN, + True, + None, + available.log_digest, + ) + receipt = record_population_use(request, available, custodian, policy) + return policy, available, append_population_use(available, receipt, policy) + + +def _store(client: _Client, policy: PopulationCustodyPolicy, report: CustodyCapabilityReport | None = None) -> S3DurableCustodyStore: + return S3DurableCustodyStore( + _settings(StorePurpose.DURABLE), + client, + policy, + report or _report(), + store_namespace_identity(_settings(StorePurpose.TRANSIENT)), + _profile(), + ) + + +def test_initial_head_and_spent_successor_round_trip_after_restart() -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + store = _store(client, policy) + + assert store.initialize(available) is True + assert store.compare_and_swap(available.log_digest, spent) is True + restarted = _store(client, policy) + + assert restarted.current_log(available.population_digest) == spent + head_updates = [request for request in client.requests if str(request["Key"]).endswith("/head.json")] + assert head_updates[0]["IfNoneMatch"] == "*" + assert head_updates[1]["IfMatch"] != available.log_digest + assert any("IfMatch" in request for request in client.requests) + + +def test_concurrent_spend_has_exactly_one_winner() -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + store = _store(client, policy) + assert store.initialize(available) + + with ThreadPoolExecutor(max_workers=2) as pool: + outcomes = tuple(pool.map(lambda _: store.compare_and_swap(available.log_digest, spent), range(2))) + + assert sorted(outcomes) == [False, True] + assert store.current_log(available.population_digest) == spent + + +def test_constant_storage_token_cannot_authorize_two_callers_or_labels() -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + client.constant_etag = True + store = _store(client, policy) + assert store.initialize(available) + client.head_update_barrier = threading.Barrier(2) + label_reads = 0 + read_lock = threading.Lock() + + def attempt() -> bool | DurableCustodyStoreError: + nonlocal label_reads + try: + committed = store.compare_and_swap(available.log_digest, spent) + except DurableCustodyStoreError as error: + return error + if committed: + with read_lock: + label_reads += 1 + return committed + + with ThreadPoolExecutor(max_workers=2) as pool: + outcomes = tuple(pool.map(lambda _: attempt(), range(2))) + + assert not any(outcome is True for outcome in outcomes) + assert all( + isinstance(outcome, DurableCustodyStoreError) and outcome.reason is DurableCustodyReason.UNREADABLE_RESPONSE for outcome in outcomes + ) + assert label_reads == 0 + assert store.current_log(available.population_digest) == spent + + +def test_stale_or_provider_conflicted_cas_fails_without_changing_head() -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + store = _store(client, policy) + assert store.initialize(available) + assert store.compare_and_swap("0" * 64, spent) is False + client.force_head_conflict = True + assert store.compare_and_swap(available.log_digest, spent) is False + client.force_head_conflict = False + assert store.current_log(available.population_digest) == available + + +@pytest.mark.parametrize("operation", ("read", "cas")) +def test_malformed_domain_digest_is_refused_before_store_access(operation: str) -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + store = _store(client, policy) + with pytest.raises(DurableCustodyStoreError) as invalid: + if operation == "read": + store.current_log("../not-a-digest") + else: + store.compare_and_swap("not-a-digest", spent) + assert invalid.value.reason is DurableCustodyReason.INVALID_INPUT + assert client.requests == [] + + +def test_missing_head_and_missing_write_version_fail_closed() -> None: + policy, available, _ = _policy_and_logs() + client = _Client() + store = _store(client, policy) + with pytest.raises(DurableCustodyStoreError) as missing: + store.current_log(available.population_digest) + assert missing.value.reason is DurableCustodyReason.NOT_FOUND + + client.missing_version = True + with pytest.raises(DurableCustodyStoreError) as unreadable: + store.initialize(available) + assert unreadable.value.reason is DurableCustodyReason.UNREADABLE_RESPONSE + + +@pytest.mark.parametrize("version_id", ("", "null")) +def test_null_or_empty_write_version_fails_closed(version_id: str) -> None: + policy, available, _ = _policy_and_logs() + client = _Client() + client.fixed_version_id = version_id + + with pytest.raises(DurableCustodyStoreError) as unreadable: + _store(client, policy).initialize(available) + + assert unreadable.value.reason is DurableCustodyReason.UNREADABLE_RESPONSE + + +def test_aliased_same_key_successor_version_fails_closed() -> None: + policy, available, spent = _policy_and_logs() + client = _Client() + client.fixed_version_id = "constant-version" + store = _store(client, policy) + assert store.initialize(available) + + with pytest.raises(DurableCustodyStoreError) as unreadable: + store.compare_and_swap(available.log_digest, spent) + + assert unreadable.value.reason is DurableCustodyReason.UNREADABLE_RESPONSE + + +def test_invalid_non_direct_or_restoring_successors_are_rejected() -> None: + policy, available, spent = _policy_and_logs() + store = _store(_Client(), policy) + assert store.initialize(available) + with pytest.raises(DurableCustodyStoreError) as non_direct: + store.compare_and_swap(available.log_digest, available) + assert non_direct.value.reason is DurableCustodyReason.INVALID_SUCCESSOR + assert store.compare_and_swap(available.log_digest, spent) + with pytest.raises(DurableCustodyStoreError) as restore: + store.compare_and_swap(spent.log_digest, available) + assert restore.value.reason is DurableCustodyReason.INVALID_SUCCESSOR + + +def test_ambiguous_readback_and_provider_diagnostics_fail_closed() -> None: + policy, available, _ = _policy_and_logs() + client = _Client() + client.corrupt_reads = True + with pytest.raises(DurableCustodyStoreError) as mismatch: + _store(client, policy).initialize(available) + assert mismatch.value.reason is DurableCustodyReason.INVALID_LOG + + failed = _Client() + failed.provider_failure = True + with pytest.raises(DurableCustodyStoreError) as provider: + _store(failed, policy).initialize(available) + assert provider.value.reason is DurableCustodyReason.STORE_FAILURE + assert "password" not in str(provider.value) + assert "private" not in str(provider.value) + assert provider.value.__cause__ is None + assert provider.value.__context__ is None + + +def test_exact_ready_capability_report_is_required() -> None: + policy, available, _ = _policy_and_logs() + changed_result = ProbeResult( + MANDATORY_PROBE_RESULTS[0], + ProbeResultStatus.FAILED, + ProbeResultReason.CONDITIONAL_CREATE_UNSUPPORTED, + ) + invalid = replace( + _report(), + status=CustodyCapabilityStatus.UNSUPPORTED, + results=(changed_result, *_report().results[1:]), + ) + with pytest.raises(DurableCustodyStoreError) as disabled: + _store(_Client(), policy, invalid).initialize(available) + assert disabled.value.reason is DurableCustodyReason.CAPABILITY_DISABLED + + +def test_cas_api_cannot_receive_or_read_label_material() -> None: + parameters = tuple(inspect.signature(S3DurableCustodyStore.compare_and_swap).parameters) + assert parameters == ("self", "expected_log_digest", "replacement") + assert "label" not in inspect.getsource(S3DurableCustodyStore.compare_and_swap).lower() + + +def test_capability_report_fixture_is_canonical_ready() -> None: + report = _report() + assert report.schema_version == CUSTODY_CAPABILITY_REPORT_SCHEMA + assert report.status is CustodyCapabilityStatus.READY