# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-authorization-token-exchange-as-non-transitive-across-a-multi-hop-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-delegated-authorization-token-exchange-as-non-transitive-across-a-multi-hop-agent-chain.warrant.json
# Markdown SHA-256:   c61f6cce50017da74001467a95cb7b53ee43623aa1690f0d09bf589be81b6c8b
# Code AST SHA-256:   414e97a829dc2042903a9233ba6b1c3730fc58df6767dd882f17af56fc1788fd
# Verified Classes:   DelegationChainViolation
# Defensive Guards:   11 fail-closed invariants (zero external deps)

class DelegationChainViolation(RuntimeError):
    """Raised when a delegated AAIF token's provenance does not terminate at the presenter."""
    pass


def verify_delegated_token(token: dict, presenter_attestation: dict, request_nonce: str) -> dict:
    # 1. Signature and audience are necessary but NOT sufficient.
    if not token.get("sig_valid"):
        raise DelegationChainViolation("signature invalid")
    if token["aud"] != presenter_attestation["instance_id"]:
        raise DelegationChainViolation(
            f"audience {token['aud']} != presenter {presenter_attestation['instance_id']}"
        )

    # 2. Proof-of-possession bound to this request.
    if presenter_attestation.get("nonce") != request_nonce:
        raise DelegationChainViolation("stale or replayed attestation nonce")

    # 3. Terminal anchoring: the LAST chain entry must be the presenter.
    chain = token.get("exchange_chain", [])
    if not chain:
        raise DelegationChainViolation("missing exchange provenance")
    if chain[-1] != presenter_attestation["instance_id"]:
        # This is the exact condition the attacker's laundered T3 hits:
        # chain = [O, W1], presenter = attacker -> membership passes, terminal fails.
        raise DelegationChainViolation(
            f"provenance terminal {chain[-1]} != presenter {presenter_attestation['instance_id']}"
        )

    # 4. Scope monotonicity across the chain (each hop subset of prior).
    scopes = token.get("scope_per_hop", [])
    for parent, child in zip(scopes, scopes[1:]):
        if not child.issubset(parent):
            raise DelegationChainViolation("scope widened across hop")

    # 5. Hop budget must be signed, not recomputed.
    if token.get("max_hops", 0) < 0:
        raise DelegationChainViolation("hop budget exhausted")

    return token


def exchange_token(presented: dict, presenter_attestation: dict, request_nonce: str,
                   delegate_to: str, requested_scope: set) -> dict:
    # Exchange must require fresh proof-of-possession, not just a bearer value.
    if presenter_attestation.get("nonce") != request_nonce:
        raise DelegationChainViolation("exchange requires fresh attestation")
    if presented["aud"] != presenter_attestation["instance_id"]:
        # Blocks the T1->T3 laundering path: attacker's attestation != aud=W1.
        raise DelegationChainViolation("presenter is not the token audience")
    if not requested_scope.issubset(presented["scope"]):
        raise DelegationChainViolation("sub-delegation widens scope")
    if presented.get("max_hops", 0) <= 0:
        raise DelegationChainViolation("no hops remaining")
    return {
        "aud": delegate_to,
        "scope": requested_scope,
        "exchange_chain": presented["exchange_chain"] + [presenter_attestation["instance_id"]],
        "max_hops": presented["max_hops"] - 1,
        "sig_valid": True,
    }
