# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-warrant-after-the-issuing-agent-s-attestation-key-rotates-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-warrant-after-the-issuing-agent-s-attestation-key-rotates-mid-chain.warrant.json
# Markdown SHA-256:   9f29c5badad82fed2d046691543acf2c1ccdfa8c25bab6c55e516b9d3444d4f9
# Code AST SHA-256:   478d4c480cf662c3e6fbbf4c37d3ea5883aa3bc7bfc15efd09a5c5b70bf41d9e
# Verified Classes:   WarrantChainResolutionError, WarrantLink
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class WarrantChainResolutionError(RuntimeError):
    """Raised when a delegated warrant chain cannot be resolved to a
    temporally-anchored, content-bound signing authority at every link."""
    pass


@dataclass(frozen=True)
class WarrantLink:
    issuer_did: str
    key_id: str            # must be content-bound (RFC 7638 thumbprint), not positional
    signed_at: float       # epoch seconds; pins resolution to issuance time
    embedded_jwk: Optional[bytes]  # detached JWS key material, if present


def _thumbprint(jwk_bytes: bytes) -> str:
    return "urn:ietf:params:oauth:jwk-thumbprint:sha-256:" + hashlib.sha256(jwk_bytes).hexdigest()


def verify_warrant_chain(links: list[WarrantLink], revoked_thumbprints: set[str]) -> bool:
    if not links:
        raise WarrantChainResolutionError("empty warrant chain")

    for idx, link in enumerate(links):
        # Condition 2: identifier must be content-bound to the embedded key.
        if link.embedded_jwk is None:
            raise WarrantChainResolutionError(
                f"link {idx} ({link.issuer_did}) has no embedded JWK; "
                f"resolution depends on mutable DID document state and cannot be "
                f"temporally pinned — refusing chain rather than trusting leaf"
            )
        expected = _thumbprint(link.embedded_jwk)
        if link.key_id != expected:
            raise WarrantChainResolutionError(
                f"link {idx} keyId {link.key_id!r} is not content-bound to its key "
                f"(expected thumbprint {expected!r}); identifier reuse across "
                f"rotation events is possible"
            )

        # Condition 1: signing time must be within a sane window of presentation.
        if link.signed_at > time.time() + 300:
            raise WarrantChainResolutionError(
                f"link {idx} signed_at is in the future beyond clock skew tolerance"
            )

        # Condition 3: revocation must be checked at every link, not just the leaf.
        if expected in revoked_thumbprints:
            raise WarrantChainResolutionError(
                f"link {idx} ({link.issuer_did}) signed by revoked key {expected!r}; "
                f"chain authority is broken even though leaf signature may validate"
            )

    return True
