# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-attestation-whose-trust-chain-was-re-signed-after-the-leaf-was-issued.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-brokered-capability-attestation-whose-trust-chain-was-re-signed-after-the-leaf-was-issued.warrant.json
# Markdown SHA-256:   ea36afc189e1203b2c2505fe58517f84f14bc4b48538a96e98a1d91b06c45922
# Code AST SHA-256:   a598650395bbb8bf142580a920b5772445bfed691a2be9b371b7c935ff079aff
# Verified Classes:   AttestationContinuityError, LeafWarrant, BrokerCert
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class AttestationContinuityError(RuntimeError):
    """Raised when a warrant's chain verifies but its issuance-time anchor was re-parented."""
    pass


@dataclass(frozen=True)
class LeafWarrant:
    subject: str
    capability: str
    expires_at: float
    issuer_cert_hash: str  # pinned at mint time; the continuity anchor


@dataclass(frozen=True)
class BrokerCert:
    key_id: str
    scope: frozenset
    not_before: float
    not_after: float

    def fingerprint(self) -> str:
        material = f"{self.key_id}|{sorted(self.scope)}|{self.not_before}|{self.not_after}"
        return hashlib.sha256(material.encode()).hexdigest()


def admit_warrant(
    leaf: LeafWarrant,
    resolved_broker_cert: BrokerCert,
    now: float,
    chain_verified: bool,
) -> None:
    if not chain_verified:
        raise AttestationContinuityError(
            f"chain did not verify for subject={leaf.subject!r} capability={leaf.capability!r}"
        )
    if now >= leaf.expires_at:
        raise AttestationContinuityError(
            f"leaf expired: now={now} exp={leaf.expires_at} subject={leaf.subject!r}"
        )
    # Freshness passed. Now the continuity predicate: the broker cert resolved
    # during validation must be the same identity that anchored the leaf at mint.
    resolved = resolved_broker_cert.fingerprint()
    if resolved != leaf.issuer_cert_hash:
        raise AttestationContinuityError(
            "attestation lineage discontinuity: leaf was re-signed under a successor "
            f"broker identity. leaf pinned={leaf.issuer_cert_hash[:12]} "
            f"resolved={resolved[:12]} key_id={resolved_broker_cert.key_id!r}. "
            "Reject and require re-issuance; do not admit under the widened scope."
        )
    # Scope is now trustworthy because it is the scope of the pinned cert.
    if leaf.capability not in resolved_broker_cert.scope:
        raise AttestationContinuityError(
            f"capability {leaf.capability!r} not in pinned broker scope "
            f"{sorted(resolved_broker_cert.scope)}"
        )
