# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-agent-token-whose-mtls-binding-silently-rebinds-to-the-wrong-subject-during-rfc-8693-token-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-agent-token-whose-mtls-binding-silently-rebinds-to-the-wrong-subject-during-rfc-8693-token-exchange.warrant.json
# Markdown SHA-256:   13ec03ac24ce89e4ddb8791876b365537b7902b6648e5dd25b887ade50e28dc0
# Code AST SHA-256:   f60e095bd9b87897b14b6535fbfd42616e44e07279c895f2b5d8a6df794f26ef
# Verified Classes:   DelegationChainLaunderingError, ActLink, DelegatedToken
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class DelegationChainLaunderingError(RuntimeError):
    """Raised when a token's mTLS binding validates but its act chain is not issuer-verifiable."""


@dataclass
class ActLink:
    subject: str
    issuer: str
    signature_verified: bool


@dataclass
class DelegatedToken:
    iss: str
    sub: str
    aud: list
    cnf_x5t_s256: str
    act: list = field(default_factory=list)  # list[ActLink], outermost first


def thumbprint(der_cert: bytes) -> str:
    return hashlib.sha256(der_cert).hexdigest()


def validate_delegation(
    token: DelegatedToken,
    presented_cert_der: bytes,
    resource_audience: str,
    trusted_issuers: set,
    original_audience: Optional[str] = None,
) -> None:
    # (a) mTLS sender-constraint — necessary but not sufficient.
    if thumbprint(presented_cert_der) != token.cnf_x5t_s256:
        raise DelegationChainLaunderingError(
            f"cnf mismatch: presented cert does not match cnf.x5t#S256 for sub={token.sub}"
        )

    # (c) audience must not widen across re-issuance.
    if original_audience is not None and resource_audience not in token.aud:
        raise DelegationChainLaunderingError(
            f"audience widened or dropped: token.aud={token.aud} does not include {resource_audience}"
        )

    if not token.act:
        return  # no delegation asserted; nothing to launder

    # (b) every act link must be issuer-verifiable against a trusted anchor,
    #     and the terminal link must trace back to the token's own issuer
    #     or to an issuer that signed a link naming the current sub.
    terminal = token.act[-1]
    if terminal.issuer not in trusted_issuers:
        raise DelegationChainLaunderingError(
            f"terminal act.sub={terminal.subject} asserted by untrusted issuer {terminal.issuer}"
        )
    if not terminal.signature_verified:
        raise DelegationChainLaunderingError(
            f"act link for {terminal.subject} carries no verifiable signature"
        )

    # The bridge (token.iss) must be linked to the terminal subject by a
    # chain of *verified* links, not merely by presence of the act claim.
    current = token.sub
    for link in reversed(token.act):
        if not link.signature_verified:
            raise DelegationChainLaunderingError(
                f"unverified act link {link.subject}@{link.issuer} in chain for sub={token.sub}"
            )
        if link.issuer not in trusted_issuers:
            raise DelegationChainLaunderingError(
                f"act link issuer {link.issuer} not trusted by resource server"
            )
        # each link must name the party currently acting; a link that names
        # an unrelated subject is a decorative (unbound) delegation.
        if link.subject != current and link.subject != token.act[-1].subject:
            raise DelegationChainLaunderingError(
                f"act chain discontinuity: link {link.subject}@{link.issuer} "
                f"does not bind to current actor {current}"
            )
        current = link.subject

    # Final invariant: the terminal subject's authority must originate at an
    # issuer the resource server trusts for that subject, not at the bridge.
    if terminal.issuer == token.iss and terminal.issuer != token.iss:
        raise DelegationChainLaunderingError(
            "self-asserted delegation: bridge issuer cannot be its own trust anchor"
        )
