# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-did-bound-agent-passport-has-silently-outlived-its-mtls-channel-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-did-bound-agent-passport-has-silently-outlived-its-mtls-channel-binding.warrant.json
# Markdown SHA-256:   bb5f3bcb6c72dceda9316ff1ccd2dd31b2f01acfe614da0543855ddba5087e41
# Code AST SHA-256:   a17f76bbffc15009bbc3bee34de260b372b1872d579784faa7466d9659170314
# Verified Classes:   StaleChannelBindingError, TrustTuple
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StaleChannelBindingError(RuntimeError):
    """Raised when a cached trust decision is exercised outside the
    transport session it was derived from, or when the live peer
    certificate cannot be recomputed to validate the binding."""
    pass


@dataclass(frozen=True)
class TrustTuple:
    did: str
    scope: frozenset
    bound_thumbprint: str  # x5t#S256 the passport's cnf claim named
    expires_at: float


def authorize_tool_call(
    *,
    live_peer_cert_der: Optional[bytes],
    cache: dict,
    envelope_sub: str,
    requested_scope: str,
    now: float,
) -> TrustTuple:
    # Invariant 1: the application MUST be able to see the live peer cert.
    # If TLS was terminated upstream and only a boolean was forwarded,
    # we cannot recompute the binding and must fail closed.
    if live_peer_cert_der is None:
        raise StaleChannelBindingError(
            "peer certificate unavailable at application layer; "
            "channel binding cannot be verified, refusing to authorize"
        )

    live_thumbprint = hashlib.sha256(live_peer_cert_der).hexdigest()

    # Invariant 2: cache key is the live thumbprint, never a socket
    # handle, pool slot, or caller-asserted sub.
    tuple_ = cache.get(live_thumbprint)
    if tuple_ is None:
        raise StaleChannelBindingError(
            f"no trust tuple bound to live channel {live_thumbprint[:12]}...; "
            "reassignment or unbound session — re-bootstrap required"
        )

    # Invariant 3: the tuple's bound thumbprint must equal the live one.
    # A mismatch means the entry was cached against a channel that has
    # since been replaced (the silent-decoupling failure).
    if tuple_.bound_thumbprint != live_thumbprint:
        raise StaleChannelBindingError(
            f"trust tuple bound to {tuple_.bound_thumbprint[:12]}... "
            f"but live channel is {live_thumbprint[:12]}..."
        )

    if now >= tuple_.expires_at:
        raise StaleChannelBindingError(
            f"trust tuple for {tuple_.did} expired at {tuple_.expires_at}"
        )

    # Invariant 4: caller-asserted identity is a hint, not authority.
    # Disagreement is the observable signature of a stale binding.
    if envelope_sub != tuple_.did:
        raise StaleChannelBindingError(
            f"envelope sub {envelope_sub!r} disagrees with authorized "
            f"DID {tuple_.did!r} on live channel {live_thumbprint[:12]}..."
        )

    if requested_scope not in tuple_.scope:
        raise StaleChannelBindingError(
            f"scope {requested_scope!r} not granted to {tuple_.did}"
        )

    return tuple_
