From 936835477a4166d64fa09c0dad4efebf69cadb09 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:01:01 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 11.1 governance and confidentiality adversarial suites --- .../specs/valid-detection-benchmark/tasks.md | 3 +- ...t_valid_benchmark_governance_validation.py | 765 ++++++++++++++++++ ...k_governance_validation_confidentiality.py | 573 +++++++++++++ 3 files changed, 1340 insertions(+), 1 deletion(-) create mode 100644 tests/test_valid_benchmark_governance_validation.py create mode 100644 tests/test_valid_benchmark_governance_validation_confidentiality.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 4048745d..e6cbfebd 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -362,7 +362,7 @@ - _Boundary: Replacement Freeze Integration_ - _Depends: 2.4, 4.4, 5.1, 10.6_ - [ ] 11. Validate the complete replacement benchmark -- [ ] 11.1 (P) Run governance, review, population, and confidentiality adversarial suites +- [x] 11.1 (P) Run governance, review, population, and confidentiality adversarial suites - Exercise alias/fork reservation, enumerated-only events, historical path/digest changes, lifecycle forks, self-review, missing judgments, model-only labels, ecosystem ambiguity, license leakage, raw diagnostic access, and post-freeze contamination. - Prove every scoped fixture is readable and nonzero before interpreting a refusal or zero result. - Done when every mutation fails at its owning boundary, no private/label-bearing byte reaches an arm or shared report, and retirement/development opening never rewrites prior evidence. @@ -452,3 +452,4 @@ - Task 10.1 review: `sourcing_queue_build._request_order` sorts by (url, advisory_locator, reachability_digest, model_digest) with a stable sort, so two distinct candidates tying on all four keys get cap selection decided by input order (restart reproducibility still holds — decode is canonical-bytes-bound — but permutation-rebuild determinism does not). The next task owning that module (10.2+) should extend the sort key with the remaining content digests or refuse tied-but-distinct requests closed. Also noted: an `INSUFFICIENT_FAMILIES` refusal does not durably persist that attempt's exclusions (10.2 owns review-record exclusion durability). - Task 10.2 review (2026-11-22): both 10.1 fold-ins landed (7-key `_request_order` discriminating old four-key ties + `InsufficientFamiliesRefusal.attempt_exclusions` durable persistence). Residual, forwarded to the next owner of `sourcing_queue_build.py`: distinct candidates differing only in non-digest fix-site scalars (path/function under identical repo/advisory/reachability/manifest/license digests) still tie on all seven keys and get cap selection by input order (round-1 reviewer reproduced divergent state digests across permutations); fix is fix-site scalars in the key or a closed refusal of residual ties. Optional hardening forwarded for the cohort modules: `project_accepted_ground_truth` call sits outside a closed-refusal wrapper (defense-in-depth only; unreachable with a consistent queue), and `decode_cohort_batch` accepts self-consistent forgeries whose `pending_entries`/`outcome.queue_entry_digest` are non-digest strings (downstream matching fails closed; a digest check would match sibling-field rigor). Real Python cohort remains PENDING external review records — the 10.2 done criterion is fixture-verified only. - Task 10.4/10.5 reviews (2026-11-22), advisories forwarded to the next owners: (a) `cohort_selection.py` `_ledger_facts` accepts a non-tuple `pending_entries` iterable from forged in-process ledgers without STATE_MISMATCH (durable paths enforce tuple-of-digests upstream; failure direction is starvation, never acceptance) — one-line isinstance guard; (b) `positive_set_closure.py` `_validate_closure` lacks the `type() is int` strict check on `total_accepted_positives` (forged float 40.0/bool decodes; no gate can flip; integers are equally forgeable, store authority is the integrity boundary) — one-line strict-int guard; (c) `_pending_by_ecosystem` docstring equivalence claim is false in the CONFLICTING_ACCEPTED_REVIEW corner (committed third-round marks the entry answered, fourth-round conservatively keeps it pending; fail-safe direction, committed behavior untouched) — docstring fix only. Real cohorts for rounds 3 and 4 remain PENDING external review records; the 10.5 combined-set closure (48 positives, both ecosystems, 5 families) is fixture-verified only. +- Task 11.1 review (2026-11-22), advisory forwarded to the reservation-identity owner (pre-dates 11.1; load-bearing before the 11.6 real run): `reservation_identity.py:70` strips the `.git` suffix case-sensitively (`removesuffix(".git")`), and `reservation_guard.py:178` repeats the case-sensitive strip after an IGNORECASE regex, so a mixed-case `https://GITHUB.com/ACME/Core.GIT` URL normalizes to a distinct identity and escapes the reservation scan (admission still fails closed via the reviewed-registry check in population_freeze). Fix: case-insensitive suffix normalization at both sites + adversarial test. Also: the `license_class` conjunct of the public-material gate (`population_materials.py:92`) has no independent mismatch fixture (non-permissive class + allowlisted expression); one-line addition to the confidentiality suite when next owned. diff --git a/tests/test_valid_benchmark_governance_validation.py b/tests/test_valid_benchmark_governance_validation.py new file mode 100644 index 00000000..c6ec65a6 --- /dev/null +++ b/tests/test_valid_benchmark_governance_validation.py @@ -0,0 +1,765 @@ +"""Task 11.1 governance validation suite: reservation, review, history, lifecycle. + +Adversarial suites over the committed population-governance machinery. Every +refusal interpreted here is preceded by a nonzero readability proof of the +fixture it was built from (instrument rule). Digest-consistent hostile inputs +are constructed only through the real constructors and committed encoders. +""" + +from __future__ import annotations + +import json +import shutil +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_lifecycle import POLICY as LIFECYCLE_POLICY # noqa: E402 +from test_valid_benchmark_lifecycle import _withdrawal # noqa: E402 +from test_valid_benchmark_population_freeze import ( # noqa: E402 + ECOSYSTEM_POLICY, + FREEZE_POLICY, + GROUND_TRUTH_POLICY, + PROVENANCE, + _positives, + _selection, +) +from test_valid_benchmark_population_freeze import ( + _authority as _freeze_authority, +) +from test_valid_benchmark_population_freeze import ( + _census as _empty_census, +) + +from benchmarks.valid import ecosystem_review as ecosystem_module # noqa: E402 +from benchmarks.valid import ground_truth_review as truth_module # noqa: E402 +from benchmarks.valid import historical_authorization as historical # noqa: E402 +from benchmarks.valid import lifecycle, population_freeze, reservation # noqa: E402 +from benchmarks.valid.ecosystem_review import ( # noqa: E402 + CanonicalEcosystem, + EcosystemInsufficientReason, + EcosystemReviewAttestationV1, + EcosystemReviewDecision, + EcosystemReviewStatus, + project_accepted_ecosystems, + review_repository_ecosystem, +) +from benchmarks.valid.fix_site_catalog import ( # noqa: E402 + EvidenceRef, + FixSiteRequest, + LicenseEvidence, + PackageEcosystemEvidence, + SourceEvidence, + build_fix_site_candidate, +) +from benchmarks.valid.ground_truth_review import ( # noqa: E402 + GroundTruthAttestationV1, + GroundTruthExclusionReason, + GroundTruthStatus, + VerifiedScope, + review_ground_truth, +) +from openultrasast.core.canonical import content_digest # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +POPULATION = content_digest({"population": "governance-validation"}) +FREEZE = content_digest({"freeze": "governance-validation"}) +EVIDENCE = content_digest({"evidence": "governance-retirement"}) +RESERVATION_POLICY = content_digest({"policy": "governance-influence-review-v1"}) +SUBJECT = content_digest({"subject": "governance-selection-evidence"}) +PARENT = "a" * 40 +FIXED = "b" * 40 + + +def _loads(content: bytes) -> dict[str, object]: + """Hostile-decode-disciplined loads for asserting on encoded artifact bytes.""" + + def reject(value: str) -> object: + raise ValueError(f"non-finite constant in encoded artifact: {value}") + + def finite(value: str) -> float: + result = float(value) + if result != result or result in (float("inf"), float("-inf")): + raise ValueError("non-finite float in encoded artifact") + return result + + try: + decoded = json.loads(content, parse_constant=reject, parse_float=finite) + except RecursionError as error: + raise ValueError("encoded artifact nests too deeply") from error + if not isinstance(decoded, dict): + raise ValueError("encoded artifact is not an object") + return decoded + + +def _network() -> reservation.RepositoryNetworkIdentity: + return reservation.build_network_identity( + "https://github.com/acme/core", + aliases=("https://github.com/ACME/core.git",), + former_names=("https://github.com/acme/old-core",), + redirects=("https://github.com/acme/redirected-core",), + forks=("https://github.com/contributor/core-fork",), + ) + + +def _event( + resolver: reservation.RepositoryIdentityResolver, + *, + repository: str = "https://github.com/acme/core", + disposition: reservation.InfluenceDisposition = reservation.InfluenceDisposition.INFLUENCED, + kind: reservation.InfluenceKind = reservation.InfluenceKind.POPULATION_SELECTION, + actor: str = "producer@example.invalid", + reviewer: str = "reviewer@example.invalid", + disclosed: bool = True, +) -> bytes: + return reservation.reviewed_influence_event( + resolver, + repository=repository, + event_source="governance-validation-suite", + disposition=disposition, + influence_kind=kind, + subject_digest=SUBJECT, + actor_identity=actor, + reviewer_identity=reviewer, + conflict_disclosed=disclosed, + policy_digest=RESERVATION_POLICY, + ) + + +class _Reader: + def __init__(self, path: str, before: str, after: str) -> None: + self._path = path + self._sources = {PARENT: before, FIXED: after} + + def parents(self, revision: str) -> tuple[str, ...]: + return (PARENT,) if revision == FIXED else () + + def blob(self, revision: str, path: str) -> str | None: + return self._sources.get(revision) if path == self._path else None + + +def _candidate(language: str = "python", hint: str | None = None, repository: str | None = None): + suffix = "ts" if language == "typescript" else ("js" if language == "javascript" else "py") + path = f"src/app.{suffix}" + if language == "python": + before = 'def handle():\n return "before"\n' + after = 'def handle():\n return "after"\n' + else: + before = 'function handle() {\n return "before";\n}\n' + after = 'function handle() {\n return "after";\n}\n' + resolved_hint = hint or ("python" if language == "python" else "javascript") + manifest_path = "pyproject.toml" if resolved_hint == "python" else "package.json" + request = FixSiteRequest( + reservation.build_network_identity(repository or "https://github.com/example/application"), + PARENT, + FIXED, + path, + "handle", + language, + PackageEcosystemEvidence(resolved_hint, EvidenceRef(manifest_path, content_digest({"manifest": resolved_hint}), 17)), + LicenseEvidence("Apache-2.0", EvidenceRef("LICENSE", content_digest({"license": "Apache-2.0"}), 11)), + SourceEvidence("security_advisory", "fixture://advisory/governance", content_digest({"advisory": "governance"})), + content_digest({"parent": PARENT, "fixed": FIXED}), + ) + return build_fix_site_candidate(_Reader(path, before, after), request) + + +def _ecosystem_attestation(candidate, decision: EcosystemReviewDecision, **changes: object): + values: dict[str, object] = { + "candidate_digest": candidate.candidate_digest, + "source_evidence_digest": candidate.source_evidence.evidence_digest, + "producer_identity": "producer@example.invalid", + "reviewer_identity": "reviewer@example.invalid", + "conflict_disclosed": True, + "policy_digest": ECOSYSTEM_POLICY, + "policy_satisfied": True, + "decision": decision, + } + values.update(changes) + return EcosystemReviewAttestationV1(**values) # type: ignore[arg-type] + + +def _accepted_ecosystem_review(candidate): + decision = ( + EcosystemReviewDecision.PYTHON + if candidate.observed_language == "python" + else EcosystemReviewDecision.JAVASCRIPT + ) + return review_repository_ecosystem( + candidate, + _ecosystem_attestation(candidate, decision), + expected_policy_digest=ECOSYSTEM_POLICY, + ) + + +def _truth_attestation(candidate, ecosystem_review, **changes: object): + values: dict[str, object] = { + "candidate_digest": candidate.candidate_digest, + "ecosystem_review_digest": ecosystem_review.review_digest, + "producer_identity": "producer@example.invalid", + "reviewer_identity": "reviewer@example.invalid", + "conflict_disclosed": True, + "policy_digest": GROUND_TRUTH_POLICY, + "policy_satisfied": True, + "defect_present": True, + "fix_addresses": True, + "in_repository_reachable": True, + "verified_scopes": (VerifiedScope("injection", CanonicalEcosystem.PYTHON),), + "model_assistance_digest": None, + } + values.update(changes) + return GroundTruthAttestationV1(**values) # type: ignore[arg-type] + + +# ---------------------------------------------------------------- reservation + + +def test_alias_fork_network_reserves_every_member_and_enumeration_does_not() -> None: + enumerated_network = reservation.build_network_identity("https://github.com/acme/enumerated-only") + resolver = reservation.RepositoryIdentityResolver((_network(), enumerated_network)) + authority = reservation.ReservationAuthority(resolver) + + census = authority.append_influence(_event(resolver)) + + assert census.accepted_event_digests + assert census.reserved_network_digests + for member in ( + "https://github.com/acme/core", + "https://github.com/ACME/core.git", + "https://github.com/acme/old-core", + "https://github.com/acme/redirected-core", + "https://github.com/contributor/core-fork", + ): + assert authority.is_reserved(member, census) + enumerated = authority.append_influence( + _event( + resolver, + repository="https://github.com/acme/enumerated-only", + disposition=reservation.InfluenceDisposition.ENUMERATED_ONLY, + kind=reservation.InfluenceKind.ENUMERATION, + ) + ) + + assert len(enumerated.accepted_event_digests) == 2 + assert enumerated.reserved_network_digests == census.reserved_network_digests + assert enumerated_network.network_identity_digest not in enumerated.reserved_network_digests + assert not authority.is_reserved("https://github.com/acme/enumerated-only", enumerated) + + +def test_enumeration_disposition_with_influence_kind_is_refused_at_the_owning_boundary() -> None: + resolver = reservation.RepositoryIdentityResolver((_network(),)) + honest = reservation.decode_influence_event(_event(resolver)) + assert honest.event_digest + + with pytest.raises(reservation.ReservationError, match="enumerated disposition"): + _event( + resolver, + disposition=reservation.InfluenceDisposition.ENUMERATED_ONLY, + kind=reservation.InfluenceKind.POPULATION_SELECTION, + ) + + +def test_self_reviewed_influence_event_is_refused_before_any_census_change() -> None: + resolver = reservation.RepositoryIdentityResolver((_network(),)) + authority = reservation.ReservationAuthority(resolver) + + with pytest.raises(reservation.ReservationError, match="independent review"): + _event(resolver, actor="reviewer@example.invalid", reviewer="reviewer@example.invalid") + with pytest.raises(reservation.ReservationError, match="independent review"): + _event(resolver, disclosed=False) + assert authority.current_census().accepted_event_digests == () + + +def test_changed_event_bytes_cannot_reproduce_the_accepted_census_identity() -> None: + resolver = reservation.RepositoryIdentityResolver((_network(),)) + authority = reservation.ReservationAuthority(resolver) + census = authority.append_influence(_event(resolver)) + assert census.accepted_event_digests + + different_actor = authority.project_census( + (_event(resolver, actor="other-producer@example.invalid"),) + ) + + assert different_actor.census_digest != census.census_digest + raw = bytearray(_event(resolver)) + raw[0] = ord(" ") + with pytest.raises(reservation.ReservationError): + authority.append_influence(bytes(raw)) + + +def test_event_claiming_a_foreign_network_is_refused_as_a_conflict() -> None: + other = reservation.build_network_identity("https://github.com/other/project") + resolver = reservation.RepositoryIdentityResolver((_network(), other)) + authority = reservation.ReservationAuthority(resolver) + hostile = _foreign_network_event(resolver, other.network_identity_digest) + + with pytest.raises(reservation.ReservationConflict): + authority.append_influence(hostile) + assert authority.current_census().accepted_event_digests == () + + +def _foreign_network_event( + resolver: reservation.RepositoryIdentityResolver, + foreign_network_digest: str, +) -> bytes: + """Re-hash one digest-consistent event whose observed repository belongs to another network.""" + honest = reservation.decode_influence_event(_event(resolver)) + draft = reservation.InfluenceEventV1( + honest.canonical_repository, + honest.observed_repository, + foreign_network_digest, + honest.event_source, + honest.disposition, + honest.influence_kind, + honest.subject_digest, + honest.actor_identity, + honest.reviewer_identity, + honest.conflict_disclosed, + honest.policy_digest, + "", + "", + ) + reviewed = reservation.InfluenceEventV1( + **{**vars(draft), "review_digest": content_digest(reservation._review_value(draft))} + ) + complete = reservation.InfluenceEventV1( + **{ + **vars(reviewed), + "event_digest": content_digest(reservation._event_value(reviewed, include_digest=False)), + } + ) + return reservation.canonical_event_bytes(reservation._event_value(complete, include_digest=True)) + + +# --------------------------------------------------------- ecosystem review + + +@pytest.mark.parametrize( + "decision", + ( + EcosystemReviewDecision.UNRESOLVED, + EcosystemReviewDecision.CONFLICTING, + EcosystemReviewDecision.POLYGLOT_AMBIGUITY, + ), +) +def test_unresolved_ecosystem_decisions_record_bounded_insufficient_evidence(decision) -> None: + candidate = _candidate() + assert candidate.candidate_digest + + review = review_repository_ecosystem( + candidate, + _ecosystem_attestation(candidate, decision), + expected_policy_digest=ECOSYSTEM_POLICY, + ) + + assert review.status is EcosystemReviewStatus.INSUFFICIENT + assert review.ecosystem is None + assert review.insufficient_reason is EcosystemInsufficientReason(decision.value) + + +def test_conflicting_package_hint_against_observed_language_is_never_accepted() -> None: + candidate = _candidate("typescript", hint="python") + assert candidate.candidate_digest + + review = review_repository_ecosystem( + candidate, + _ecosystem_attestation(candidate, EcosystemReviewDecision.JAVASCRIPT), + expected_policy_digest=ECOSYSTEM_POLICY, + ) + + assert review.status is EcosystemReviewStatus.INSUFFICIENT + assert review.insufficient_reason is EcosystemInsufficientReason.CONFLICTING + + +def test_self_reviewed_ecosystem_attestation_stays_insufficient_never_accepted() -> None: + candidate = _candidate() + review = review_repository_ecosystem( + candidate, + _ecosystem_attestation( + candidate, + EcosystemReviewDecision.PYTHON, + producer_identity="reviewer@example.invalid", + ), + expected_policy_digest=ECOSYSTEM_POLICY, + ) + + assert review.status is EcosystemReviewStatus.INSUFFICIENT + assert review.insufficient_reason is EcosystemInsufficientReason.SELF_REVIEW + forged = replace( + replace(review, status=EcosystemReviewStatus.ACCEPTED, ecosystem=CanonicalEcosystem.PYTHON, insufficient_reason=None), + review_digest="", + ) + forged = replace( + forged, + review_digest=content_digest(ecosystem_module._review_value(forged, include_digest=False)), + ) + with pytest.raises(ecosystem_module.EcosystemReviewError, match="independent review policy|does not match"): + ecosystem_module.repository_ecosystem_review_bytes( + forged, + candidate=candidate, + expected_policy_digest=ECOSYSTEM_POLICY, + ) + + +def test_accepted_projection_allows_exactly_one_ecosystem_per_network() -> None: + first = _candidate("python", repository="https://github.com/example/python-application") + second = _candidate("javascript", repository="https://github.com/example/javascript-application") + for candidate in (first, second): + assert candidate.candidate_digest + candidates = {first.candidate_digest: first, second.candidate_digest: second} + reviews = ( + _accepted_ecosystem_review(first), + _accepted_ecosystem_review(second), + ) + + projected = project_accepted_ecosystems(reviews, candidates_by_digest=candidates, expected_policy_digest=ECOSYSTEM_POLICY) + + assert len(projected) == 2 + assert {item[1] for item in projected} == {CanonicalEcosystem.PYTHON, CanonicalEcosystem.JAVASCRIPT} + + +# -------------------------------------------------------- ground truth review + + +@pytest.mark.parametrize( + "changes,reason", + ( + ( + {"defect_present": None, "model_assistance_digest": content_digest({"model": "agrees"})}, + GroundTruthExclusionReason.MISSING_HUMAN_JUDGMENT, + ), + ({"fix_addresses": None}, GroundTruthExclusionReason.MISSING_HUMAN_JUDGMENT), + ({"in_repository_reachable": False}, GroundTruthExclusionReason.JUDGMENT_REJECTED), + ( + {"producer_identity": "reviewer@example.invalid"}, + GroundTruthExclusionReason.SELF_REVIEW, + ), + ({"verified_scopes": ()}, GroundTruthExclusionReason.MISSING_SCOPE), + ( + {"verified_scopes": (VerifiedScope("injection", CanonicalEcosystem.JAVASCRIPT),)}, + GroundTruthExclusionReason.SCOPE_SUBSTITUTION, + ), + ), +) +def test_defective_ground_truth_attestations_exclude_with_closed_reasons(changes, reason) -> None: + candidate = _candidate() + ecosystem = _accepted_ecosystem_review(candidate) + + review = review_ground_truth( + candidate, + ecosystem, + _truth_attestation(candidate, ecosystem, **changes), + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + assert review.status is GroundTruthStatus.EXCLUDED + assert review.exclusion_reason is reason + assert review.verified_scopes == () + + +def test_model_only_labels_cannot_satisfy_a_missing_human_judgment() -> None: + candidate = _candidate() + ecosystem = _accepted_ecosystem_review(candidate) + model_only = GroundTruthAttestationV1( + candidate.candidate_digest, + ecosystem.review_digest, + "model@example.invalid", + "model@example.invalid", + True, + GROUND_TRUTH_POLICY, + True, + None, + None, + None, + (VerifiedScope("injection", CanonicalEcosystem.PYTHON),), + content_digest({"model": "labels-everything-true"}), + ) + + review = review_ground_truth( + candidate, + ecosystem, + model_only, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + assert review.status is GroundTruthStatus.EXCLUDED + assert review.exclusion_reason in ( + GroundTruthExclusionReason.SELF_REVIEW, + GroundTruthExclusionReason.MISSING_HUMAN_JUDGMENT, + ) + assert review.verified_scopes == () + encoded = truth_module.ground_truth_review_bytes( + review, + candidate=candidate, + ecosystem_review=ecosystem, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + assert encoded + + +def test_legacy_model_record_alone_leaves_verification_pending_human() -> None: + from benchmarks.valid import verify + + record: dict[str, object] = { + "id": "governance-case", + "vulnerable_pre_fix": True, + "fix_addresses_it": True, + "reachable_in_repo": True, + "entry_point": "app.handle", + "model": "fixture-model", + "confidence": 0.99, + } + + assert verify.verdict(record) == "pending_human" + assistance = verify.model_assistance(record) + + assert assistance["authoritative"] is False + with pytest.raises(ValueError, match="human judgment"): + verify.review_attestation( + record, + candidate_digest="0" * 64, + ecosystem_review_digest="0" * 64, + human_judgment={"producer_identity": "producer"}, # type: ignore[arg-type] + ) + + +# ------------------------------------------------- historical exact authority + + +def test_historical_authorization_requires_exact_path_and_digest_pairs() -> None: + withdrawal = _withdrawal() + assert withdrawal.candidate.entries + entry = next( + item + for item in withdrawal.candidate.entries + if item.path == "benchmarks/valid/pilot/freeze-valid.json" + ) + assert entry.byte_length > 0 + + authorized = historical.authorize_historical_path(ROOT, entry.path, entry.content_digest, withdrawal) + + assert authorized == (ROOT / entry.path).read_bytes() + assert len(authorized) == entry.byte_length + + +def test_changed_bytes_relocated_paths_and_foreign_digests_are_refused(tmp_path: Path) -> None: + withdrawal = _withdrawal() + entry = next( + item + for item in withdrawal.candidate.entries + if item.path == "benchmarks/valid/pilot/freeze-valid.json" + ) + for relative in historical.PINNED_HISTORICAL_DIGESTS: + target = tmp_path / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + copied = (tmp_path / entry.path).read_bytes() + assert copied + (tmp_path / entry.path).write_bytes(copied + b" changed\n") + + with pytest.raises(historical.HistoricalAuthorizationError, match="changed"): + historical.authorize_historical_path(tmp_path, entry.path, entry.content_digest, withdrawal) + with pytest.raises(historical.HistoricalAuthorizationError): + historical.authorize_historical_path(tmp_path, "benchmarks/valid/pilot", entry.content_digest, withdrawal) + with pytest.raises(historical.HistoricalAuthorizationError): + historical.authorize_historical_path(tmp_path, "benchmarks/valid/pilot/pool-valid.toml", entry.content_digest, withdrawal) + + +def test_historical_authorization_is_never_blanket_across_entries() -> None: + withdrawal = _withdrawal() + entries = sorted(withdrawal.candidate.entries, key=lambda item: item.path) + assert len(entries) >= 2 + authorized, other = entries[0], entries[-1] + + with pytest.raises(historical.HistoricalAuthorizationError, match="not exactly authorized"): + historical.authorize_historical_path(ROOT, other.path, authorized.content_digest, withdrawal) + + +# ------------------------------------------------------------------ lifecycle + + +def _active_chain( + population: str = POPULATION, + freeze: str = FREEZE, +) -> tuple[lifecycle.BaselineLifecycleAuthority, str]: + root = lifecycle.withdrawn_event(_withdrawal()) + withdrawn = lifecycle.decode_lifecycle_event(root) + replacement = lifecycle.reviewed_replacement_event( + predecessor_digest=withdrawn.event_digest, + historical_withdrawal_digest=withdrawn.historical_withdrawal_digest, + population_digest=population, + freeze_digest=freeze, + producer_identity="lifecycle-producer", + reviewer_identity="lifecycle-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ) + authority = lifecycle.BaselineLifecycleAuthority() + authority.append(root) + head = authority.append(replacement) + return authority, head.head_event_digest + + +def _retirement(predecessor: str) -> bytes: + return lifecycle.reviewed_retirement_event( + predecessor_digest=predecessor, + population_digest=POPULATION, + freeze_digest=FREEZE, + evidence_digest=EVIDENCE, + reason_code="contaminated_negative", + producer_identity="retirement-producer", + reviewer_identity="retirement-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ) + + +def _development(predecessor: str) -> bytes: + resolver = reservation.RepositoryIdentityResolver((reservation.build_network_identity("https://github.com/acme/one"),)) + return lifecycle.reviewed_development_opening( + predecessor_digest=predecessor, + population_digest=POPULATION, + freeze_digest=FREEZE, + access_evidence_digest=EVIDENCE, + resolver=resolver, + repositories=("https://github.com/acme/one",), + producer_identity="opening-producer", + reviewer_identity="opening-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ).event_content + + +def test_lifecycle_fork_off_one_predecessor_is_refused() -> None: + authority, head = _active_chain() + first = lifecycle.decode_lifecycle_event(_retirement(head)) + second = lifecycle.decode_lifecycle_event(_development(head)) + assert first.event_digest != second.event_digest + + with pytest.raises(lifecycle.LifecycleConflict, match="fork"): + authority.project((lifecycle.withdrawn_event(_withdrawal()), *_retired_chain_contents(head), _development(head))) + + +def _retired_chain_contents(head: str) -> tuple[bytes, ...]: + root = lifecycle.withdrawn_event(_withdrawal()) + withdrawn = lifecycle.decode_lifecycle_event(root) + replacement = lifecycle.reviewed_replacement_event( + predecessor_digest=withdrawn.event_digest, + historical_withdrawal_digest=withdrawn.historical_withdrawal_digest, + population_digest=POPULATION, + freeze_digest=FREEZE, + producer_identity="lifecycle-producer", + reviewer_identity="lifecycle-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ) + return (root, replacement, _retirement(head)) + + +def test_retirement_is_terminal_and_never_rewrites_prior_evidence() -> None: + authority, head = _active_chain() + contents = _retired_chain_contents(head) + before = lifecycle.projection_bytes(authority.project(contents[:2])) + + retired = authority.append(_retirement(head)) + + assert retired.state is lifecycle.PopulationLifecycleState.RETIRED + assert not retired.admission_eligible + assert retired.event_digests == tuple( + lifecycle.decode_lifecycle_event(item).event_digest for item in contents + ) + assert lifecycle.projection_bytes(authority.project(contents[:2])) == before + with pytest.raises(lifecycle.LifecycleConflict, match="terminal"): + authority.append(_development(retired.head_event_digest)) + with pytest.raises(lifecycle.LifecycleError, match="eligible"): + authority.require_admission_eligible(POPULATION, FREEZE) + + +def test_development_opening_is_terminal_and_requires_durable_influence_events() -> None: + authority, head = _active_chain() + opening_content = _development(head) + + opened = authority.append(opening_content) + + assert opened.state is lifecycle.PopulationLifecycleState.DEVELOPMENT_OPENED + assert not opened.admission_eligible + assert opened.influence_event_digests + event = lifecycle.decode_lifecycle_event(opening_content) + assert event.influence_event_digests == opened.influence_event_digests + with pytest.raises(lifecycle.LifecycleConflict, match="terminal"): + authority.append(_retirement(opened.head_event_digest)) + + +def test_replacement_bound_must_name_the_exact_reviewed_withdrawal() -> None: + root = lifecycle.withdrawn_event(_withdrawal()) + withdrawn = lifecycle.decode_lifecycle_event(root) + assert withdrawn.historical_withdrawal_digest + + with pytest.raises(lifecycle.LifecycleConflict, match="exact historical withdrawal"): + lifecycle.BaselineLifecycleAuthority().project( + ( + root, + lifecycle.reviewed_replacement_event( + predecessor_digest=withdrawn.event_digest, + historical_withdrawal_digest=EVIDENCE, + population_digest=POPULATION, + freeze_digest=FREEZE, + producer_identity="lifecycle-producer", + reviewer_identity="lifecycle-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ), + ) + ) + + +def test_self_reviewed_terminal_events_are_refused_at_encoding() -> None: + authority, head = _active_chain() + assert authority.require_admission_eligible(POPULATION, FREEZE) + + with pytest.raises(lifecycle.LifecycleError, match="independent lifecycle review"): + lifecycle.reviewed_retirement_event( + predecessor_digest=head, + population_digest=POPULATION, + freeze_digest=FREEZE, + evidence_digest=EVIDENCE, + reason_code="contaminated_negative", + producer_identity="retirement-reviewer", + reviewer_identity="retirement-reviewer", + conflict_disclosed=True, + policy_digest=LIFECYCLE_POLICY, + ) + assert authority.require_admission_eligible(POPULATION, FREEZE) + + +# ------------------------------------------------- population classification + + +def test_scope_minimum_unmet_is_insufficient_despite_whole_population_size() -> None: + positives = _positives() + assert len(positives) >= 40 + authority = _freeze_authority(positives) + + freeze = population_freeze.freeze_population( + positives, + ordinary_selection=_selection(positives), + reservation_census=_empty_census(), + reservation_authority=authority, + scope_minimums=(population_freeze.ScopeMinimumV1("injection", CanonicalEcosystem.PYTHON, 10_000),), + source_provenance_digest=PROVENANCE, + freeze_policy_digest=FREEZE_POLICY, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + assert freeze.positive_count >= 40 + assert freeze.population_class is population_freeze.PopulationClass.INSUFFICIENT + assert population_freeze.PopulationClassificationReason.SCOPE_MINIMUM_UNMET in freeze.classification_reasons + assert population_freeze.population_freeze_bytes(freeze) diff --git a/tests/test_valid_benchmark_governance_validation_confidentiality.py b/tests/test_valid_benchmark_governance_validation_confidentiality.py new file mode 100644 index 00000000..f1581c56 --- /dev/null +++ b/tests/test_valid_benchmark_governance_validation_confidentiality.py @@ -0,0 +1,573 @@ +"""Task 11.1 confidentiality validation suite: partitions, labels, diagnostics, retirement. + +Adversarial suites over the committed confidentiality machinery: license +partitions (7.6), label-blind manifests (5.4), sealed pre-spend diagnostics and +reviewed development opening (5.2/5.6/10.3), and pre/post-freeze contamination +routing (3.5/3.6). Every refusal interpreted here is preceded by a nonzero +readability proof of the fixture (instrument rule). +""" + +from __future__ import annotations + +import base64 +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from cohort_ingestion_fixtures import case_for # noqa: E402 +from detection_core_fixtures import stored_artifact # noqa: E402 +from test_valid_benchmark_artifact_repository import _authority, _repo # noqa: E402 +from test_valid_benchmark_artifact_repository import _digest as _store_digest # noqa: E402 +from test_valid_benchmark_governance_validation import FREEZE, POPULATION, _active_chain # noqa: E402 +from test_valid_benchmark_isolated_executor import _authorities # noqa: E402 +from test_valid_benchmark_label_blind_manifest import _attestation, _policy, _sources # noqa: E402 +from test_valid_benchmark_observation_checkpoint import _frozen # noqa: E402 +from test_valid_benchmark_ordinary_draw import ( # noqa: E402 + LEAN_NAMES, + OrdinaryFixtureHistory, + _contamination, + _draw, + _lean_batches, + _lean_state, +) +from test_valid_benchmark_population_freeze import _positives, _selection # noqa: E402 +from test_valid_benchmark_population_materials import _digest, _freeze, _inputs, _Validator # noqa: E402 + +from benchmarks.valid import artifact_repository as repository # noqa: E402 +from benchmarks.valid import ( # noqa: E402 + lifecycle, + reservation, + sealed_diagnostics, # noqa: E402 +) +from benchmarks.valid import population_label_blind as label_blind +from benchmarks.valid import population_materials as materials # noqa: E402 +from benchmarks.valid.ordinary_change_contract import ( # noqa: E402 + ContaminationTiming, + OrdinaryExclusionReason, + OrdinarySelectionError, + ordinary_selection_bytes, + reviewed_contamination, +) +from benchmarks.valid.ordinary_changes import post_freeze_contamination_retirement # noqa: E402 +from benchmarks.valid.ordinary_draw import OrdinaryDrawError, OrdinaryDrawReason # noqa: E402 +from benchmarks.valid.population_material_contract import _manifest_value # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import ArtifactKind # noqa: E402 +from openultrasast.core import canonical # noqa: E402 +from openultrasast.core.canonical import bytes_digest # noqa: E402 +from openultrasast.core.factpack import ( # noqa: E402 + IndependenceAttestation, + ReviewIndependencePolicy, + derive_independence_attestation_digest, + derive_review_independence_policy_digest, +) + +CONTAMINATION_POLICY = _digest("governance-contamination-review") +ACCESS_POLICY = _store_digest("read-policy") + + +def _loads(content: bytes) -> dict[str, object]: + """Hostile-decode-disciplined loads for asserting on encoded artifact bytes.""" + + def reject(value: str) -> object: + raise ValueError(f"non-finite constant in encoded artifact: {value}") + + def finite(value: str) -> float: + result = float(value) + if result != result or result in (float("inf"), float("-inf")): + raise ValueError("non-finite float in encoded artifact") + return result + + try: + decoded = json.loads(content, parse_constant=reject, parse_float=finite) + except RecursionError as error: + raise ValueError("encoded artifact nests too deeply") from error + if not isinstance(decoded, dict): + raise ValueError("encoded artifact is not an object") + return decoded + + +# --------------------------------------------------- license partition (7.6) + + +def _changes() -> tuple[str, ...]: + return tuple(_digest(f"governance-change-{index}") for index in range(3)) + + +def _partitioned() -> tuple[materials.PopulationMaterialPartitionV1, tuple[bytes, ...], tuple[materials.PopulationMaterialInputV1, ...]]: + changes = _changes() + freeze = _freeze(changes) + inputs = _inputs(changes) + partition = materials.build_population_material_partition( + freeze, + inputs, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + artifacts = materials.material_artifact_bytes(partition) + assert all(artifacts) + return partition, artifacts, inputs + + +def test_nonpermissive_and_uncertain_material_stay_behind_opaque_references() -> None: + partition, artifacts, inputs = _partitioned() + manifest = partition.manifest + + assert {item.license_expression for item in manifest.public_sources} == {"Apache-2.0"} + assert len(manifest.private_refs) == 2 + public_bytes = materials.public_manifest_bytes(partition) + for item in inputs: + if item.license_class is not materials.LicenseClass.PERMISSIVE: + assert item.source_content not in public_bytes + assert item.label_content not in public_bytes + assert item.review_judgment_content not in public_bytes + for reference in manifest.public_sources: + source = materials.resolve_public_source(partition, reference) + assert source + assert bytes_digest(source) == reference.source_digest + covered = {item.change_digest for item in manifest.private_refs} | { + item.change_digest for item in manifest.public_sources + } + assert covered == set(manifest.positive_change_digests) + + +def test_permissive_material_without_distribution_approval_remains_private() -> None: + changes = tuple(_digest(f"unapproved-{index}") for index in range(3)) + freeze = _freeze(changes) + inputs = tuple( + materials.PopulationMaterialInputV1( + change, + materials.LicenseClass.PERMISSIVE if index < 2 else materials.LicenseClass.NON_PERMISSIVE, + "Apache-2.0" if index < 2 else "BUSL-1.1", + f"safe source {index}\n".encode(), + f"private-label-{index}".encode(), + f"review-judgment-{index}".encode(), + True, + ) + for index, change in enumerate(changes) + ) + unapproved = (replace(inputs[0], public_distribution_approved=False), *inputs[1:]) + + partition = materials.build_population_material_partition( + freeze, + unapproved, + freeze_validator=_Validator(freeze), + partition_policy_digest=_digest("partition-policy"), + ) + assert all(materials.material_artifact_bytes(partition)) + + assert partition.manifest.public_count == 1 + assert partition.manifest.private_count == 2 + + +def test_forged_public_reference_for_private_change_is_refused() -> None: + partition, artifacts, inputs = _partitioned() + private_reference = partition.manifest.private_refs[0] + private_record = next( + item for item in partition.private_records if item.change_digest == private_reference.change_digest + ) + assert private_record.source_content + permissive = partition.manifest.public_sources[0] + forged_record = replace( + permissive, + change_digest=private_reference.change_digest, + source_digest=private_reference.source_digest, + byte_length=private_reference.byte_length, + ) + forged_manifest = replace( + partition.manifest, + public_sources=tuple(sorted((forged_record, *partition.manifest.public_sources[1:]))), + private_refs=partition.manifest.private_refs[1:], + manifest_digest="", + ) + forged_manifest = replace( + forged_manifest, + manifest_digest=canonical.content_digest(_manifest_value(forged_manifest, include_digest=False)), + ) + forged = replace(partition, manifest=forged_manifest, public_source_objects=()) + + with pytest.raises(materials.PopulationMaterialError): + materials.public_manifest_bytes(forged) + + +def test_private_and_sealed_resolution_requires_the_custodian_boundary() -> None: + partition, artifacts, inputs = _partitioned() + reference = partition.manifest.private_refs[0] + matching_label = next( + item for item in partition.sealed_label_records if item.change_digest == reference.change_digest + ) + custodian = materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + ( + materials.MaterialPermission.PRIVATE_SOURCE, + materials.MaterialPermission.SEALED_LABELS, + ), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ) + + resolved = materials.resolve_private_material(partition, reference, custodian, expected_access_policy_digest=ACCESS_POLICY) + labels = materials.resolve_sealed_labels(partition, custodian, expected_access_policy_digest=ACCESS_POLICY) + + assert resolved + assert matching_label.label_content not in resolved + assert base64.b64encode(matching_label.label_content) in labels + assert base64.b64encode(matching_label.judgment_content) in labels + with pytest.raises(materials.PopulationMaterialError, match="non-custodian"): + materials.material_access_authority( + partition, + materials.MaterialActorRole.OPERATOR, + (materials.MaterialPermission.PRIVATE_SOURCE,), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ) + sealed_only = materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.SEALED_LABELS,), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ) + with pytest.raises(materials.PopulationMaterialError, match="not authorized"): + materials.resolve_private_material(partition, reference, sealed_only, expected_access_policy_digest=ACCESS_POLICY) + with pytest.raises(materials.PopulationMaterialError, match="policy mismatch"): + materials.material_access_authority( + partition, + materials.MaterialActorRole.CUSTODIAN, + (materials.MaterialPermission.SEALED_LABELS,), + _digest("other-policy"), + expected_access_policy_digest=ACCESS_POLICY, + ) + + +def test_operator_summary_carries_only_closed_codes_digests_and_counts() -> None: + partition, artifacts, inputs = _partitioned() + + summary = materials.operator_material_summary(partition) + decoded = _loads(summary) + + for item in inputs: + assert item.label_content not in summary + assert item.review_judgment_content not in summary + assert item.source_content not in summary + assert tuple(decoded["reason_codes"]) == ("private_material_opaque", "labels_custodian_sealed") + assert decoded["public_count"] == partition.manifest.public_count + assert set(decoded) == { + "schema_version", + "status", + "population_digest", + "freeze_digest", + "manifest_digest", + "private_object_digest", + "sealed_label_digest", + "public_count", + "private_count", + "reason_codes", + } + + +# --------------------------------------------- label-blind manifest (5.4/10.3) + + +def test_manifest_review_requires_independence_disclosure_and_exact_subject() -> None: + freeze, selection, partition = _sources() + draft = label_blind.build_label_blind_population_draft(freeze, partition, selection) + assert draft.input_digests + disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="governance-manifest-conflicts") + review = _attestation(draft.draft_digest, disclosure) + policy = _policy(review.reviewer_identity) + + accepted = label_blind.review_label_blind_population_manifest(draft, review, policy, resolver) + + assert label_blind.label_blind_population_manifest_bytes(accepted) + self_reviewed = replace(review, producer_identity=review.reviewer_identity, attestation_digest="0" * 64) + self_reviewed = replace(self_reviewed, attestation_digest=derive_independence_attestation_digest(self_reviewed)) + with pytest.raises(label_blind.LabelBlindManifestError, match="independent"): + label_blind.review_label_blind_population_manifest(draft, self_reviewed, policy, resolver) + stale = _attestation(_digest("another-draft"), disclosure) + with pytest.raises(label_blind.LabelBlindManifestError, match="stale"): + label_blind.review_label_blind_population_manifest(draft, stale, policy, resolver) + forbidden_policy = _policy(review.reviewer_identity, ((review.producer_identity, review.reviewer_identity),)) + with pytest.raises(label_blind.LabelBlindManifestError, match="forbidden"): + label_blind.review_label_blind_population_manifest(draft, review, forbidden_policy, resolver) + + +def test_manifest_bytes_hold_no_label_bearing_field_or_private_payload() -> None: + freeze, selection, partition = _sources() + draft = label_blind.build_label_blind_population_draft(freeze, partition, selection) + disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="governance-manifest-conflicts") + review = _attestation(draft.draft_digest, disclosure) + manifest = label_blind.review_label_blind_population_manifest(draft, review, _policy(review.reviewer_identity), resolver) + content = label_blind.label_blind_population_manifest_bytes(manifest) + assert content + decoded = _loads(content) + + for record in partition.sealed_label_records: + assert record.label_content not in content + assert record.judgment_content not in content + for record in partition.private_records: + assert record.source_content not in content + assert partition.manifest.private_object_digest not in content.decode() + assert set(decoded) == { + "schema_version", + "population_digest", + "freeze_digest", + "reservation_census_digest", + "review_set_digest", + "ordinary_selection_digest", + "public_material_manifest_digest", + "material_artifact_set_digest", + "scope_census", + "input_digests", + "positive_count", + "input_count", + "input_set_digest", + "draft_digest", + "review_digest", + "manifest_digest", + } + + +# ------------------------------------- sealed diagnostics and development (5.2/5.6) + + +def _custodian() -> repository.ArtifactReadAuthority: + return _authority( + repository.ArtifactActorRole.CUSTODIAN, + ( + repository.ArtifactReadPermission.CUSTODIAN_SEALED, + repository.ArtifactReadPermission.PRIVATE, + ), + ) + + +def _diagnostic_policy() -> ReviewIndependencePolicy: + reviewer = _digest("governance-diagnostic-reviewer") + policy_digest = derive_review_independence_policy_digest((reviewer,), (), ("trusted-store",), 4096) + return ReviewIndependencePolicy((reviewer,), (), ("trusted-store",), 4096, policy_digest) + + +def _development_review(subject_digest: str, policy: ReviewIndependencePolicy): + disclosure, review_resolver = stored_artifact(b'{"conflicts":[]}', artifact_id=f"governance-access-{subject_digest[:12]}") + producer = _digest("governance-requester") + reviewer = policy.reviewed_reviewer_digests[0] + draft = IndependenceAttestation(subject_digest, producer, reviewer, disclosure, "0" * 64) + return replace(draft, attestation_digest=derive_independence_attestation_digest(draft)), review_resolver + + +def _development_request(bundle, predecessor, checkpoint, selection, resolver, manifest): + policy = _diagnostic_policy() + subject = sealed_diagnostics.build_development_access_subject( + bundle.population_digest, + bundle.freeze_digest, + predecessor, + checkpoint, + bundle=bundle, + selection=selection, + resolver=resolver, + manifest=manifest, + artifact_access_policy_digest=ACCESS_POLICY, + lifecycle_review_policy_digest=policy.policy_digest, + ) + review, review_resolver = _development_review(subject.subject_digest, policy) + request = sealed_diagnostics.build_development_access_request(subject, review, policy, review_resolver) + return request, review_resolver + + +def _diagnostic_resolver(selection=None) -> reservation.RepositoryIdentityResolver: + selection = _authorities()[2] if selection is None else selection + networks = { + push.network_identity_digest: reservation.build_network_identity(push.canonical_repository) + for push in selection.pushes + } + return reservation.RepositoryIdentityResolver(tuple(networks.values())) + + +def test_pre_spend_projection_is_closed_and_instrumented_before_interpretation() -> None: + bundle, client, _, frozen = _frozen() + assert bundle.case_inputs + + projection = sealed_diagnostics.project_pre_spend_diagnostics( + frozen, + _repo(client), + _custodian(), + ACCESS_POLICY, + ) + + assert projection.status is sealed_diagnostics.DiagnosticStatus.COMPLETE + assert projection.input_count == len(bundle.case_inputs) > 0 + assert projection.observation_count > 0 + content = sealed_diagnostics.pre_spend_diagnostic_bytes(projection) + assert content + for forbidden in (b"finding", b"path", b"exception", b"password", b"label", b"repository"): + assert forbidden not in content.lower() + + +def test_self_reviewed_development_access_returns_no_raw_observation() -> None: + bundle, client, _, frozen = _frozen() + lifecycle_authority, predecessor = _active_chain(bundle.population_digest, bundle.freeze_digest) + manifest, _, selection = _authorities() + resolver = _diagnostic_resolver(selection) + policy = _diagnostic_policy() + subject = sealed_diagnostics.build_development_access_subject( + bundle.population_digest, + bundle.freeze_digest, + predecessor, + frozen, + bundle=bundle, + selection=selection, + resolver=resolver, + manifest=manifest, + artifact_access_policy_digest=ACCESS_POLICY, + lifecycle_review_policy_digest=policy.policy_digest, + ) + review, review_resolver = _development_review(subject.subject_digest, policy) + self_reviewed = replace(review, producer_identity=review.reviewer_identity, attestation_digest="0" * 64) + self_reviewed = replace(self_reviewed, attestation_digest=derive_independence_attestation_digest(self_reviewed)) + put_before = len(client.put_calls) + + with pytest.raises(sealed_diagnostics.SealedDiagnosticError) as captured: + sealed_diagnostics.build_development_access_request(subject, self_reviewed, policy, review_resolver) + + assert captured.value.reason is sealed_diagnostics.DiagnosticAccessReason.REVIEW_REQUIRED + assert len(client.put_calls) == put_before + lifecycle_authority.require_admission_eligible(bundle.population_digest, bundle.freeze_digest) + + +def test_development_opening_is_terminal_and_never_rewrites_prior_evidence() -> None: + bundle, client, _, frozen = _frozen() + lifecycle_authority, predecessor = _active_chain(bundle.population_digest, bundle.freeze_digest) + manifest, _, selection = _authorities() + resolver = _diagnostic_resolver(selection) + request, review_resolver = _development_request(bundle, predecessor, frozen, selection, resolver, manifest) + observation_before = _repo(client).get( + frozen.reference, + expected_kind=ArtifactKind.OBSERVATION, + authority=_custodian(), + expected_access_policy_digest=ACCESS_POLICY, + ).content + store_before = dict(client.objects) + prior_events = lifecycle_authority.require_admission_eligible( + bundle.population_digest, bundle.freeze_digest + ).event_digests + + opened = sealed_diagnostics.open_observation_for_development( + request, + repository=_repo(client), + artifact_authority=_custodian(), + lifecycle_authority=lifecycle_authority, + reservation_authority=reservation.ReservationAuthority(resolver), + resolver=resolver, + selection=selection, + manifest=manifest, + review_resolver=review_resolver, + ) + + assert opened.artifact.reference == frozen.reference + assert opened.artifact.content == observation_before + assert opened.artifact.content + assert opened.lifecycle_projection.state is lifecycle.PopulationLifecycleState.DEVELOPMENT_OPENED + assert not opened.lifecycle_projection.admission_eligible + assert opened.lifecycle_projection.event_digests[: len(prior_events)] == prior_events + for key, content in store_before.items(): + assert client.objects[key] == content + with pytest.raises(lifecycle.LifecycleError, match="eligible"): + lifecycle_authority.require_admission_eligible(bundle.population_digest, bundle.freeze_digest) + + +# ------------------------------------------- pre/post-freeze contamination (3.5/3.6) + + +def test_pre_freeze_contamination_excludes_the_change_with_reason() -> None: + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + assert batches + + draw = _draw(batches, resolved, history, reviews=(_contamination("py-00", str(case_for("py-00")["parent"])),)) + + assert draw.pushes + assert draw.exclusions + assert all(item.reason is OrdinaryExclusionReason.REVIEWED_SECURITY_DEFECT for item in draw.exclusions) + assert all(item.contamination_review_digest for item in draw.exclusions) + assert all(count >= 20 for count in dict(draw.per_positive_counts).values()) + + +def test_post_freeze_contamination_is_refused_by_the_draw_instead_of_excluding() -> None: + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + assert batches + clean = _draw(batches, resolved, history) + assert clean.pushes + + with pytest.raises(OrdinaryDrawError) as error: + _draw( + batches, + resolved, + history, + reviews=(_contamination("py-00", str(case_for("py-00")["parent"]), ContaminationTiming.POST_FREEZE),), + ) + + assert error.value.reason is OrdinaryDrawReason.POST_FREEZE_CONTAMINATION + + +def _post_freeze_review(push, timing: ContaminationTiming) -> object: + return reviewed_contamination( + network_identity_digest=push.network_identity_digest, + tip_revision=push.tip_revision, + timing=timing, + evidence_digest=_digest("governance-contamination-evidence"), + producer_identity="contamination-producer@example.invalid", + reviewer_identity="contamination-reviewer@example.invalid", + conflict_disclosed=True, + policy_digest=CONTAMINATION_POLICY, + ) + + +def test_retirement_event_binds_exact_selection_and_preserves_prior_evidence() -> None: + authority, head = _active_chain(POPULATION, FREEZE) + projection = authority.require_admission_eligible(POPULATION, FREEZE) + selection = _selection(_positives()) + push = selection.pushes[0] + before = ordinary_selection_bytes(selection) + assert before + + event_content = post_freeze_contamination_retirement(selection, _post_freeze_review(push, ContaminationTiming.POST_FREEZE), projection) + + assert ordinary_selection_bytes(selection) == before + with pytest.raises(OrdinarySelectionError, match="post-freeze contamination review"): + post_freeze_contamination_retirement(selection, _post_freeze_review(push, ContaminationTiming.PRE_FREEZE), projection) + hostile = _post_freeze_review(replace(push, tip_revision="e" * 40), ContaminationTiming.POST_FREEZE) + with pytest.raises(OrdinarySelectionError, match="one selected push"): + post_freeze_contamination_retirement(selection, hostile, projection) + + event = lifecycle.decode_lifecycle_event(event_content) + retired = authority.append(event_content) + + assert retired.state is lifecycle.PopulationLifecycleState.RETIRED + assert not retired.admission_eligible + assert retired.event_digests[: len(projection.event_digests)] == projection.event_digests + assert event.population_digest == POPULATION + assert event.freeze_digest == FREEZE + with pytest.raises(lifecycle.LifecycleError, match="eligible"): + authority.require_admission_eligible(POPULATION, FREEZE) + with pytest.raises(lifecycle.LifecycleConflict, match="terminal"): + authority.append( + lifecycle.reviewed_retirement_event( + predecessor_digest=retired.head_event_digest, + population_digest=POPULATION, + freeze_digest=FREEZE, + evidence_digest=_digest("governance-second-retirement"), + reason_code="contaminated_negative", + producer_identity="retirement-producer", + reviewer_identity="retirement-reviewer", + conflict_disclosed=True, + policy_digest=_digest("lifecycle-policy"), + ) + )