# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-dpop-bound-a2a-handoff-because-the-delegation-warrant-and-the-proof-of-possession-key-disagree-on-the-channel-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-dpop-bound-a2a-handoff-because-the-delegation-warrant-and-the-proof-of-possession-key-disagree-on-the-channel-binding.warrant.json
# Markdown SHA-256:   1c67332b0d90fcb79de71411a83be93c0174816c5b8a43e5907c35c5fec07368
# Code AST SHA-256:   98dc030293c5ad064b48f7b646e2942c28b53d4cdb08cfb51742d4e68ce0872d
# Verified Classes:   ChannelBindingMismatch, PayloadKeyDerivationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac

class ChannelBindingMismatch(RuntimeError):
    """Raised when mTLS, DPoP, and warrant key bindings disagree."""
    pass

class PayloadKeyDerivationError(RuntimeError):
    """Raised when E2E payload key cannot be bound to a consistent identity triple."""
    pass


def jkt_from_jwk(jwk: dict) -> str:
    # RFC 7638 thumbprint; canonical member order per key type.
    if jwk["kty"] == "EC":
        members = f'{{"crv":"{jwk["crv"]}","kty":"EC","x":"{jwk["x"]}","y":"{jwk["y"]}"}}'
    elif jwk["kty"] == "RSA":
        members = f'{{"e":"{jwk["e"]}","kty":"RSA","n":"{jwk["n"]}"}}'
    else:
        raise ChannelBindingMismatch(f"unsupported kty {jwk['kty']}")
    return _b64url(hashlib.sha256(members.encode()).digest())


def _b64url(b: bytes) -> str:
    import base64
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()


def admit_a2a_handshake(
    peer_cert_der: bytes,
    dpop_proof_jwk: dict,
    warrant_claims: dict,
    tls_exporter: bytes,
    session_nonce: bytes,
) -> bytes:
    """
    Enforce jkt_mtls == jkt_dpop == jkt_warrant before deriving the E2E key.
    Returns the derived payload key only on full agreement.
    """
    jkt_mtls = _b64url(hashlib.sha256(peer_cert_der).digest())
    jkt_dpop = jkt_from_jwk(dpop_proof_jwk)
    jkt_warrant = warrant_claims.get("cnf", {}).get("jkt")

    if jkt_warrant is None:
        raise ChannelBindingMismatch("warrant missing cnf.jkt; cannot bind delegation")
    if not (jkt_mtls == jkt_dpop == jkt_warrant):
        raise ChannelBindingMismatch(
            f"binding disagreement: mtls={jkt_mtls} dpop={jkt_dpop} warrant={jkt_warrant}"
        )

    # Bind the proof to this exact TLS channel so a captured proof cannot be
    # replayed on a different certificate even if jkt_dpop matches.
    expected_binding = hmac.new(
        tls_exporter,
        session_nonce + jkt_dpop.encode(),
        hashlib.sha256,
    ).digest()
    if not hmac.compare_digest(expected_binding, warrant_claims.get("chan_bind", b"")):
        raise ChannelBindingMismatch("DPoP proof not bound to negotiated TLS channel")

    # Derive payload key from the agreed triple, not from K_eph alone.
    info = b"a2a-e2e|" + jkt_mtls.encode() + b"|" + jkt_dpop.encode() + b"|" + jkt_warrant.encode()
    if len(info) == 0:
        raise PayloadKeyDerivationError("empty derivation info")
    return hmac.new(tls_exporter, info + session_nonce, hashlib.sha256).digest()
