# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-substitution-attacks-when-a2a-agent-cards-are-discovered-over-mtls-bound-oauth2-delegated-grants.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-substitution-attacks-when-a2a-agent-cards-are-discovered-over-mtls-bound-oauth2-delegated-grants.warrant.json
# Markdown SHA-256:   84e4727087784aadab67a1e237325eb055396c00a8845ae99419a68e3ed2b9f1
# Code AST SHA-256:   9668ad039c7f1bbdba926240c9b8676293972ec13283a32559b7fec9a89c45e7
# Verified Classes:   ScopeSubstitutionError, Grant, DelegatedToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeSubstitutionError(RuntimeError):
    """Raised when a delegated token's scope set is not closed under the
    delegating principal's actual AS-issued grant. The Agent Card's advertised
    scope union is NOT a valid authority for this check."""


@dataclass(frozen=True)
class Grant:
    actor: str
    scopes: FrozenSet[str]
    as_issuer: str
    cert_thumbprint: str


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    scopes: FrozenSet[str]
    aud: str
    cnf_thumbprint: str
    act_chain: tuple  # ordered root -> leaf
    scope_history: tuple  # tuple[Grant, ...] root -> leaf


def validate_delegation(
    presented: DelegatedToken,
    delegated: DelegatedToken,
    card_advertised_scopes: FrozenSet[str],
    discovery_thumbprint: str,
) -> None:
    # Card is advertisement only; it must never widen the grant.
    if not delegated.scopes <= presented.scopes:
        raise ScopeSubstitutionError(
            f"scope inflation at hop {delegated.subject}: "
            f"delegated={sorted(delegated.scopes)} not subset of "
            f"presented={sorted(presented.scopes)}; "
            f"card advertised {sorted(card_advertised_scopes)} but card is not authority"
        )

    # Card-union disjointness: a scope the caller's AS never granted cannot be
    # laundered into the request merely because the card lists it.
    unknown = delegated.scopes - presented.scopes - card_advertised_scopes
    if unknown:
        raise ScopeSubstitutionError(
            f"delegated scopes {sorted(unknown)} are in neither the presented "
            f"grant nor the card union; provenance unverifiable"
        )

    # Thumbprint continuity: the cert that authenticated discovery must be the
    # cert the token is bound to, or mid-chain rotation has broken the binding.
    if delegated.cnf_thumbprint != discovery_thumbprint:
        raise ScopeSubstitutionError(
            f"cnf thumbprint {delegated.cnf_thumbprint} does not match "
            f"discovery thumbprint {discovery_thumbprint}; "
            f"card was fetched under a different identity than the token asserts"
        )

    # scope_history must be monotone non-increasing in scope set and must end
    # at the delegated token's scope set.
    prev = None
    for grant in delegated.scope_history:
        if prev is not None and not grant.scopes <= prev.scopes:
            raise ScopeSubstitutionError(
                f"scope_history non-monotone at actor {grant.actor}: "
                f"{sorted(grant.scopes)} not subset of {sorted(prev.scopes)}"
            )
        prev = grant
    if prev is None or prev.scopes != delegated.scopes:
        raise ScopeSubstitutionError(
            "scope_history terminal grant does not equal delegated token scope; "
            "chain is incomplete or forged"
        )

    # Actor chain length must equal scope_history length minus one (root has no
    # delegator).
    if len(delegated.act_chain) != len(delegated.scope_history) - 1:
        raise ScopeSubstitutionError(
            f"act_chain length {len(delegated.act_chain)} inconsistent with "
            f"scope_history length {len(delegated.scope_history)}"
        )
