# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-laundering-when-a2a-agent-cards-re-broker-oauth-token-exchanges-across-org-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-laundering-when-a2a-agent-cards-re-broker-oauth-token-exchanges-across-org-boundaries.warrant.json
# Markdown SHA-256:   fd519aa0694f1e7dd97cfca239713124a4aa991d97371cc6d3b37827ce56b72d
# Code AST SHA-256:   876214d691761ae168737a589b7ffab169018769d2fc568d49f93c6770a59391
# Verified Classes:   ScopeLaunderingError, Token, Broker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeLaunderingError(RuntimeError):
    """Raised when an exchanged token's effective scope escapes the subject grant."""
    pass


@dataclass(frozen=True)
class Token:
    subject: str
    audience: str
    scope: FrozenSet[str]


@dataclass
class Broker:
    # cache keyed by (subject, audience, effective_scope) — content-addressed
    _cache: dict = field(default_factory=dict)

    def exchange(
        self,
        subject_token: Token,
        card_required_scopes: FrozenSet[str],
        requested_need: FrozenSet[str],
        as_response_scope: FrozenSet[str],
    ) -> Token:
        # 1. Card may only narrow need; it is never a grant.
        requested = requested_need & card_required_scopes

        # 2. Request scope must be bounded by the subject grant.
        if not requested <= subject_token.scope:
            raise ScopeLaunderingError(
                f"request scope {sorted(requested)} exceeds subject grant "
                f"{sorted(subject_token.scope)}"
            )

        # 3. Effective scope is read from the AS response, never the request.
        effective = as_response_scope

        # 4. Invariant: response scope ⊆ subject grant AND ⊆ requested.
        if not effective <= subject_token.scope:
            raise ScopeLaunderingError(
                f"AS widened scope: response {sorted(effective)} ⊄ subject "
                f"{sorted(subject_token.scope)}"
            )
        if not effective <= requested:
            raise ScopeLaunderingError(
                f"AS issued unrequested scope: {sorted(effective - requested)}"
            )

        # 5. Cache key includes effective scope so widened tokens cannot be reused.
        key = (subject_token.subject, subject_token.audience, effective)
        self._cache[key] = Token(subject_token.subject, subject_token.audience, effective)
        return self._cache[key]
