# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-an-aaif-credential-whose-aud-matches-the-verifier-but-whose-delegated-scope-was-issued-against-a-stale-parent-c.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-an-aaif-credential-whose-aud-matches-the-verifier-but-whose-delegated-scope-was-issued-against-a-stale-parent-c.warrant.json
# Markdown SHA-256:   8038da84068aad1c62c013850c36c7c8c0c82f7140d149db0957f049d943d780
# Code AST SHA-256:   33b786190822974563fb0a205b9af8634737ebf8c12dcb0333b206804e947bfc
# Verified Classes:   StaleDelegationChainError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleDelegationChainError(RuntimeError):
    """Raised when a leaf AAIF credential was issued against a parent
    state that has since been superseded (parent.iat > leaf.iat)."""
    pass


def verify_aaif_leaf(leaf: dict, expected_aud: str, now: int) -> None:
    if leaf.get("aud") != expected_aud:
        raise StaleDelegationChainError(
            f"audience mismatch: {leaf.get('aud')!r} != {expected_aud!r}"
        )
    if leaf.get("exp", 0) <= now:
        raise StaleDelegationChainError("leaf credential expired")

    leaf_iat = leaf.get("iat", 0)
    for hop in leaf.get("act", []):
        parent_iat = hop.get("iat", 0)
        if parent_iat > leaf_iat:
            raise StaleDelegationChainError(
                f"leaf iat={leaf_iat} predates parent iat={parent_iat} "
                f"for actor {hop.get('sub')!r}; chain may be superseded"
            )
