# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-broker-scope-amplification-during-cross-org-agent-card-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-broker-scope-amplification-during-cross-org-agent-card-exchange.warrant.json
# Markdown SHA-256:   20d41e4fdf83ca4a814ae91464b8f3e390378007fc942eebabb56afc963e0bce
# Code AST SHA-256:   5dd20a19c9c47b9ebc2b2a7be533180c428a0e1c7bbe2ac49197de4cbc92112c
# Verified Classes:   ScopeAmplificationError, AgentCard, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class ScopeAmplificationError(RuntimeError):
    """Raised when a warrant's effective scope exceeds the callee's advertised card."""


@dataclass(frozen=True)
class AgentCard:
    capabilities: frozenset[str]
    constraints: Mapping[str, str]
    version: str  # content hash, not timestamp

    @staticmethod
    def build(capabilities, constraints) -> "AgentCard":
        h = hashlib.sha256(
            repr((sorted(capabilities), sorted(constraints.items()))).encode()
        ).hexdigest()[:16]
        return AgentCard(frozenset(capabilities), dict(constraints), h)


@dataclass(frozen=True)
class Warrant:
    subject: str
    audience: str
    capabilities: frozenset[str]
    ext_constraints: Mapping[str, str]
    card_version_at_mint: str
    iat: int


KNOWN_CONSTRAINT_KEYS = frozenset({"tenant", "scope"})


def authorize_effect(
    op: str,
    params: Mapping[str, str],
    warrant: Warrant,
    card: AgentCard,
    self_identity: str,
) -> None:
    # (1) audience must bind to this callee, not the broker
    if warrant.audience != self_identity:
        raise ScopeAmplificationError(
            f"warrant aud={warrant.audience!r} != callee {self_identity!r}"
        )

    # (2) card-warrant consistency: card must not have changed since mint
    if warrant.card_version_at_mint != card.version:
        raise ScopeAmplificationError(
            f"card version skew: mint={warrant.card_version_at_mint} "
            f"current={card.version}; force re-mint"
        )

    # (3) fail-closed on unknown constraint keys (do not treat as absent)
    unknown = set(warrant.ext_constraints) - KNOWN_CONSTRAINT_KEYS
    if unknown:
        raise ScopeAmplificationError(f"unparseable constraints: {sorted(unknown)}")

    # (4) capability must be in BOTH warrant and current card
    if op not in warrant.capabilities or op not in card.capabilities:
        raise ScopeAmplificationError(
            f"op {op!r} not in effective scope "
            f"(warrant={sorted(warrant.capabilities)}, card={sorted(card.capabilities)})"
        )

    # (5) constraints must be enforced against call params at point of effect
    if "scope" in warrant.ext_constraints:
        if params.get("scope") != warrant.ext_constraints["scope"]:
            raise ScopeAmplificationError(
                f"scope param {params.get('scope')!r} violates warrant constraint "
                f"{warrant.ext_constraints['scope']!r}"
            )
    if "tenant" in warrant.ext_constraints:
        if params.get("tenant") != warrant.ext_constraints["tenant"]:
            raise ScopeAmplificationError(
                f"tenant {params.get('tenant')!r} outside warrant tenant "
                f"{warrant.ext_constraints['tenant']!r}"
            )
