# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-chains-from-authorizing-a-different-agent-than-the-one-the-human-intended.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-chains-from-authorizing-a-different-agent-than-the-one-the-human-intended.warrant.json
# Markdown SHA-256:   17cf25953e22b0287a3a9ce78b41dcef7865bbf8bece5a2ca8748804ed371d78
# Code AST SHA-256:   fc71f1ebc88e00ef8e0df7abcfb7b7e8e8a252a5d799fe4f07aa5c0a028db344
# Verified Classes:   DelegationBindingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationBindingError(RuntimeError):
    """Raised when a delegated AAIF chain authorizes a class, not an instance."""


def verify_delegated_chain(chain, presenting_key_thumbprint, request_nonce, transport):
    # Walk links, verify signatures and scope monotonicity (omitted for brevity).
    final = chain.links[-1]

    if final.bearer:
        raise DelegationBindingError(
            f"link {final.index} is bearer:true; non-transferability invariant violated"
        )

    if final.audience_is_did:
        if transport.supports_handshake:
            if not transport.verify_pop(presenting_key_thumbprint, request_nonce):
                raise DelegationBindingError(
                    "DID audience presented without valid proof-of-possession; "
                    "chain would authorize any instance sharing the DID"
                )
        else:
            raise DelegationBindingError(
                f"transport {transport.name!r} cannot bind DID audience to an instance; "
                "require instance thumbprint at issuance"
            )

    if chain.max_delegation_depth <= 0:
        raise DelegationBindingError("delegation depth exhausted; sub-delegation forbidden")

    return {"authorized": True, "instance": presenting_key_thumbprint, "chain_hash": chain.hash()}
