# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-principal-attestation-rebind-when-an-mcp-server-silently-re-mints-its-aaif-subject-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-principal-attestation-rebind-when-an-mcp-server-silently-re-mints-its-aaif-subject-mid-session.warrant.json
# Markdown SHA-256:   befd1ac329206e7114a5a6d22dbcd2ad0fc9b3cae53b5ed6dff55c1f47137ad7
# Code AST SHA-256:   9f5ca03f420fe58ac804805cd5bef3bb9a73af91098470809e8925c893ab81c2
# Verified Classes:   AttestationRebindError, AttestationUnverifiableError, PinnedPrincipal, PlanBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttestationRebindError(RuntimeError):
    """Raised when an MCP response's attested subject diverges from the pinned principal."""


class AttestationUnverifiableError(RuntimeError):
    """Raised when a mutating call returns no attestation echo to diff against."""


@dataclass(frozen=True)
class PinnedPrincipal:
    issuer: str
    sub: str
    act_chain: tuple[str, ...]
    scopes: frozenset[str]


@dataclass
class PlanBinding:
    plan_id: str
    pinned: PinnedPrincipal
    rebinds: list[dict] = field(default_factory=list)


def verify_call(
    binding: PlanBinding,
    echo: Optional[dict],
    *,
    is_mutating: bool,
) -> str:
    """
    Returns 'ok' | 'rebind_reauthorized'.
    Raises AttestationRebindError on upward/ambiguous rebind for mutating or
    out-of-scope calls; AttestationUnverifiableError when no echo is present.
    """
    if echo is None:
        if is_mutating:
            raise AttestationUnverifiableError(
                f"plan {binding.plan_id}: mutating call returned no attestation echo; "
                "subject continuity cannot be verified"
            )
        return "ok"

    echo_sub = echo.get("sub")
    echo_chain = tuple(echo.get("act_chain", ()))
    echo_scopes = frozenset(echo.get("scopes", ()))

    sub_ok = echo_sub == binding.pinned.sub
    chain_ok = echo_chain == binding.pinned.act_chain
    if sub_ok and chain_ok:
        return "ok"

    # A rebind was detected. Decide halt vs re-attest by scope containment.
    contained = echo_scopes.issubset(binding.pinned.scopes)
    if is_mutating or not contained:
        raise AttestationRebindError(
            f"plan {binding.plan_id}: subject rebind {binding.pinned.sub!r} -> {echo_sub!r} "
            f"(chain {binding.pinned.act_chain!r} -> {echo_chain!r}); "
            f"mutating={is_mutating}, scope_contained={contained}; halt required"
        )

    binding.rebinds.append(
        {"from": binding.pinned.sub, "to": echo_sub, "scopes": sorted(echo_scopes)}
    )
    return "rebind_reauthorized"
