# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-verifiable-credential-identity-attestation-has-silently-degraded-to-bearer-token-semantics-in-a-federated-agent-mesh.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-verifiable-credential-identity-attestation-has-silently-degraded-to-bearer-token-semantics-in-a-federated-agent-mesh.warrant.json
# Markdown SHA-256:   4223676bb85e39e6e2892762d697d4844af717e50766ce5113419eccd296a5df
# Code AST SHA-256:   668cb6dbcfc1ee7495e387be81e4e007985599afa5b8e0732194ece27af311e8
# Verified Classes:   HolderBindingError, Presentation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class HolderBindingError(RuntimeError):
    """Raised when a presentation's cryptographic binding to its subject is absent,
    stale, or has been substituted across a forwarding hop."""
    pass

@dataclass
class Presentation:
    subject_id: str
    envelope_signer_id: Optional[str]   # None => no proof-of-possession present
    challenge: Optional[str]
    challenge_consumed: bool
    forwarded_by: Optional[str]         # broker identity, if re-signed across a hop

def verify_presentation(
    pres: Presentation,
    expected_challenge: str,
    authorized_forwarders: set[str],
) -> None:
    # Boundary 2: missing envelope proof is a hard reject, never a fallback.
    if pres.envelope_signer_id is None:
        raise HolderBindingError(
            f"presentation for subject {pres.subject_id!r} carries no "
            "proof-of-possession; credential has degraded to bearer semantics"
        )

    # Boundary 1: binding must hold against the subject, not just the body signature.
    if pres.envelope_signer_id != pres.subject_id:
        # A forwarder may re-sign, but only if separately authorized (Boundary 3).
        if pres.forwarded_by is None or pres.forwarded_by not in authorized_forwarders:
            raise HolderBindingError(
                f"envelope signed by {pres.envelope_signer_id!r} but subject is "
                f"{pres.subject_id!r}; no authorized forwarder attested"
            )

    # Freshness: challenge must match the request and be unconsumed.
    if pres.challenge != expected_challenge:
        raise HolderBindingError(
            f"challenge mismatch for subject {pres.subject_id!r}: "
            f"expected {expected_challenge!r}, got {pres.challenge!r}"
        )
    if pres.challenge_consumed:
        raise HolderBindingError(
            f"challenge for subject {pres.subject_id!r} already consumed; "
            "replay suspected"
        )
