# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-an-mcp-oauth-2-1-resource-binding-when-a-dynamically-registered-client-s-token-audience-silently-survives-a-tool-se.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-an-mcp-oauth-2-1-resource-binding-when-a-dynamically-registered-client-s-token-audience-silently-survives-a-tool-se.warrant.json
# Markdown SHA-256:   d02d46ff76539f5a3114b6f72c0b7511c55cb7d8b3bcbf7673a38b1d1dbd0a48
# Code AST SHA-256:   b0506c52fad069864201a5ebcd9d9ebc5cc6ab29b8512b568203061d5612522c
# Verified Classes:   ResourceBindingError, Token, ResourceMetadata
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ResourceBindingError(RuntimeError):
    """Raised when a live token's audience no longer matches the resource server's advertised resource.

    This is NOT a token-expiry or transient-network condition. It means the
    token is cryptographically valid but bound to a resource identifier that
    the server no longer claims. Retrying the same token will loop.
    """


@dataclass(frozen=True)
class Token:
    access_token: str
    aud: tuple[str, ...]          # from token introspection / JWT claim
    client_id: str
    expires_at: float


@dataclass(frozen=True)
class ResourceMetadata:
    resource: str                 # RFC 9728 "resource" identifier
    authorization_servers: tuple[str, ...]


def classify_401(
    status: int,
    error_code: Optional[str],
    token: Token,
    live_metadata: ResourceMetadata,
) -> str:
    """Return one of: 'resource_binding', 'lifecycle', 'scope', 'fatal'.

    The decision boundary: a 401 is never 'transient'. The only question is
    whether the credential is mis-bound (re-resolve + re-authorize) or
    genuinely dead (refresh) or under-scoped (re-request).
    """
    if status != 401:
        raise ValueError(f"classify_401 called with non-401 status {status}")

    if error_code == "insufficient_scope":
        return "scope"

    if error_code == "invalid_token":
        if live_metadata.resource not in token.aud:
            # Token is valid but bound to a different resource than the
            # server currently serves. This is the failover/cutover case.
            return "resource_binding"
        return "lifecycle"

    return "fatal"


def preflight_binding_check(token: Token, live_metadata: ResourceMetadata) -> None:
    """Fail closed BEFORE committing any tool output to task state.

    Must be called at every tool-call boundary where the result will be
    persisted. Cheap: one cached metadata fetch per resource per task.
    """
    if time.time() >= token.expires_at:
        # Expiry is a lifecycle event, handled by refresh, not here.
        return

    if live_metadata.resource not in token.aud:
        raise ResourceBindingError(
            f"token aud={token.aud!r} does not contain live resource "
            f"{live_metadata.resource!r}; client_id={token.client_id}. "
            f"Re-fetch RFC 9728 metadata and re-authorize with "
            f"resource={live_metadata.resource!r}. Do not retry this token."
        )
