# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credentials-from-surviving-an-agent-to-agent-handoff-after-a-mid-task-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credentials-from-surviving-an-agent-to-agent-handoff-after-a-mid-task-re-delegation.warrant.json
# Markdown SHA-256:   ced3d88d576ebe0d08a418046625f5f9c708833777e8758fabfcc944c41719dd
# Code AST SHA-256:   4f86274ccbe880fc459f52361c06f1e0ba04c64f4e41154607544f27bfe1a64a
# Verified Classes:   AAIFDelegationError, Credential
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AAIFDelegationError(RuntimeError):
    """Raised when a delegated AAIF credential is presented by an unauthorized party
    or carries a fabricated delegation chain."""


@dataclass
class Credential:
    cred_id: str
    issuer: str
    audience: str            # 'aud' claim: the agent this credential was minted FOR
    scope: frozenset[str]
    expires_at: float
    signature_valid: bool
    delegation_chain: list[tuple[str, str, bool]]  # (parent, child, child_signed_edge)


def verify_presentation(
    cred: Credential,
    presenter_identity: str,      # from channel attestation, NOT from the cred
    requested_op: str,
    now: float,
    trusted_issuers: set[str],
) -> None:
    # Loud, retryable failures first.
    if not cred.signature_valid:
        raise AAIFDelegationError(f"bad signature on {cred.cred_id}")
    if now >= cred.expires_at:
        raise AAIFDelegationError(f"expired credential {cred.cred_id}")
    if cred.issuer not in trusted_issuers:
        raise AAIFDelegationError(f"untrusted issuer {cred.issuer}")

    # INVARIANT 1: audience-presenter equality. This is the confused-deputy gate.
    if cred.audience != presenter_identity:
        raise AAIFDelegationError(
            f"audience/presenter mismatch: aud={cred.audience!r} "
            f"presenter={presenter_identity!r} on {cred.cred_id}"
        )

    # INVARIANT 2: every chain edge must be signed by the parent for the child,
    # and each edge's parent must be the audience of the preceding link.
    prev_audience: Optional[str] = None
    for parent, child, child_signed_edge in cred.delegation_chain:
        if not child_signed_edge:
            raise AAIFDelegationError(
                f"fabricated edge {parent}->{child}: no consent signature"
            )
        if prev_audience is not None and parent != prev_audience:
            raise AAIFDelegationError(
                f"chain discontinuity: edge parent {parent!r} "
                f"!= prior audience {prev_audience!r}"
            )
        prev_audience = child
    if prev_audience is not None and prev_audience != cred.audience:
        raise AAIFDelegationError(
            f"chain terminus {prev_audience!r} != aud {cred.audience!r}"
        )

    # INVARIANT 3: scope is the chain intersection; here we trust the leaf's
    # declared scope only after confirming it was narrowed (caller supplies
    # parent scopes out-of-band in real deployments).
    if requested_op not in cred.scope:
        raise AAIFDelegationError(
            f"scope escalation: {requested_op!r} not in effective scope "
            f"{sorted(cred.scope)}"
        )
