# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-grant-whose-mtls-binding-no-longer-covers-the-presenting-workload.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-grant-whose-mtls-binding-no-longer-covers-the-presenting-workload.warrant.json
# Markdown SHA-256:   53c7ffa7204be7847ab4c3d8d3322db0eb7f727d7b1e9f6b342c387e5bae6319
# Code AST SHA-256:   21dc4a5ad5bd96edc09a2c4fb847177497116fdc32fd027d0dc0b06ad31b028f
# Verified Classes:   DelegatedGrantBindingError, IntrospectionResult, PresentedRequest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class DelegatedGrantBindingError(RuntimeError):
    """Raised when a delegated capability grant's mTLS binding cannot be
    verified against the presenting workload at the resource agent."""
    pass


@dataclass(frozen=True)
class IntrospectionResult:
    active: bool
    jti: str
    cnf_x5t_s256: Optional[str]   # thumbprint bound at issuance
    scope: frozenset[str]
    act_chain: tuple[str, ...]     # outermost actor first


@dataclass(frozen=True)
class PresentedRequest:
    jti: str
    client_cert_der: Optional[bytes]  # None if terminator stripped it
    requested_scope: frozenset[str]
    max_act_depth: int = 3


def _thumbprint(der: bytes) -> str:
    return hashlib.sha256(der).hexdigest()


def enforce_delegated_grant(
    req: PresentedRequest,
    intro: IntrospectionResult,
    actor_scope: frozenset[str],
) -> None:
    # 1. Token must be active.
    if not intro.active:
        raise DelegatedGrantBindingError(f"token {req.jti} inactive at introspection")

    # 2. Binding must be present and the presenting cert must be available.
    #    "No cert" is a hard failure, never a fallback.
    if intro.cnf_x5t_s256 is None:
        raise DelegatedGrantBindingError(
            f"token {req.jti} has no cnf binding; refusing bearer-style acceptance"
        )
    if req.client_cert_der is None:
        raise DelegatedGrantBindingError(
            f"no client cert propagated for {req.jti}; terminator must fail closed"
        )

    # 3. Binding must match the presenting workload, per-request.
    presented = _thumbprint(req.client_cert_der)
    if presented != intro.cnf_x5t_s256:
        raise DelegatedGrantBindingError(
            f"binding mismatch for {req.jti}: cnf={intro.cnf_x5t_s256} presented={presented}"
        )

    # 4. Delegated scope must be a subset of the immediate actor's scope,
    #    not merely the root subject's scope.
    if not req.requested_scope.issubset(actor_scope):
        raise DelegatedGrantBindingError(
            f"scope escalation on {req.jti}: {req.requested_scope - actor_scope} "
            f"not held by immediate actor"
        )

    # 5. act chain depth must be bounded.
    if len(intro.act_chain) > req.max_act_depth:
        raise DelegatedGrantBindingError(
            f"act chain depth {len(intro.act_chain)} exceeds max {req.max_act_depth} "
            f"for {req.jti}"
        )
