# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-agent-warrants-from-outliving-their-hardware-key-binding-during-cross-instance-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-agent-warrants-from-outliving-their-hardware-key-binding-during-cross-instance-attestation.warrant.json
# Markdown SHA-256:   c9e129e8ffa31bbeb3912d0766618804ff5ce8f9beff8567ebf7de9f2ef7f0dd
# Code AST SHA-256:   9794d5ce4b24cfc803815e98c07767f1e9170adc039b6f7204bf680deb718e60
# Verified Classes:   BindingAttestationError, WarrantLink
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class BindingAttestationError(RuntimeError):
    """Raised when a delegation chain's authority no longer maps to a live attested principal."""
    pass


@dataclass
class WarrantLink:
    issuer_key: str          # key that signed this link
    subject_key: str         # key authorized downstream
    capability: str
    expiry: float
    quote_timestamp: float   # when issuer's hardware binding was last attested
    signature_valid: bool


MAX_QUOTE_AGE = 300.0  # seconds; Delta


def verify_chain(links: list[WarrantLink], live_attested_key: dict[str, str],
                 revoked_links: set[int], now: float | None = None) -> bool:
    """
    Verify a delegation chain as a conjunction of per-node binding checks.
    Signature validity alone is insufficient: each non-leaf issuer must still
    hold the same key in a fresh attested enclave, or have revoked its edge.
    """
    now = time.time() if now is None else now

    for idx, link in enumerate(links):
        if idx in revoked_links:
            raise BindingAttestationError(
                f"link {idx} revoked by issuer {link.issuer_key}")

        if not link.signature_valid:
            raise BindingAttestationError(
                f"link {idx} signature invalid for issuer {link.issuer_key}")

        if link.expiry <= now:
            raise BindingAttestationError(
                f"link {idx} expired at {link.expiry}, now {now}")

        # The boundary condition: freshness + key identity of the *issuer*.
        age = now - link.quote_timestamp
        if age > MAX_QUOTE_AGE:
            raise BindingAttestationError(
                f"link {idx} issuer {link.issuer_key} binding stale: "
                f"quote age {age:.1f}s > {MAX_QUOTE_AGE}s")

        current = live_attested_key.get(link.issuer_key)
        if current is None:
            raise BindingAttestationError(
                f"link {idx} issuer {link.issuer_key} has no live attested key")
        if current != link.issuer_key:
            raise BindingAttestationError(
                f"link {idx} binding rotation: warrant signed by "
                f"{link.issuer_key}, live key is {current}, no revocation on record")

    return True


def grant_if_authorized(links, live_attested_key, revoked_links, capability):
    try:
        verify_chain(links, live_attested_key, revoked_links)
    except BindingAttestationError as e:
        # Fail closed: stale or rotated binding denies the grant.
        return {"granted": False, "reason": str(e)}
    if links[-1].capability != capability:
        return {"granted": False, "reason": "capability mismatch"}
    return {"granted": True, "reason": "chain and bindings valid"}
