# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-capability-token-whose-caveat-chain-outlives-the-delegating-agent-s-attestation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-capability-token-whose-caveat-chain-outlives-the-delegating-agent-s-attestation-window.warrant.json
# Markdown SHA-256:   cdc8153ba7c15a57e8f9814e090ac05b0fb11332a9947626ed3046e3bf5870c0
# Code AST SHA-256:   202c3b514216f256b36bf31f4453cbfcd53a09ce2531e5fef05b7c1a80166595
# Verified Classes:   AttestationLapsedError, KeyRotatedError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AttestationLapsedError(RuntimeError):
    """Raised when a delegated capability token's chain contains an attestation
    whose TTL has elapsed, or whose subject key no longer matches the current
    attestation, even though the token itself is unexpired."""
    pass


class KeyRotatedError(AttestationLapsedError):
    """Raised when a delegating agent's key has rotated since the token was
    minted; the embedded attestation names a key that is no longer current."""
    pass


def verify_delegated_token(token, now, attestation_store):
    """
    token: dict with keys 'exp', 'chain' (list of attestation records, root-first)
    attestation_store: callable(subject) -> current attestation record or None
    """
    if now >= token["exp"]:
        raise AttestationLapsedError(
            f"token expired at {token['exp']}, now={now}"
        )

    for att in token["chain"]:
        subject = att["subject"]
        deadline = att["attested_at"] + att["ttl"]

        # The invariant most verifiers skip: the attestation clock, not just the token clock.
        if now >= deadline:
            raise AttestationLapsedError(
                f"attestation for {subject} lapsed at {deadline}, now={now}; "
                f"token exp={token['exp']} is irrelevant — the root authority is dead"
            )

        current = attestation_store(subject)
        if current is None:
            raise AttestationLapsedError(
                f"no current attestation for {subject}; cannot confirm liveness"
            )
        if current["key"] != att["key"]:
            raise KeyRotatedError(
                f"{subject} key rotated: token embeds {att['key']!r}, "
                f"current is {current['key']!r}; delegated authority is stale, re-mint required"
            )

    return True
