# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-tool-call-whose-token-exchange-succeeded-but-whose-audience-claim-drifted-across-a-token-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-tool-call-whose-token-exchange-succeeded-but-whose-audience-claim-drifted-across-a-token-refresh.warrant.json
# Markdown SHA-256:   2ffe9cf19c00dbd1f950c7acef5ee7970e52b42525209795fe877052db504fe1
# Code AST SHA-256:   346c53da0e8ec74cbaf91b5f67c54c8555b68c3457e644d8e0210a24de152f39
# Verified Classes:   AudienceMismatchError, TokenCacheCollisionError, ExchangedToken, ResourceBoundTokenCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Mapping, Sequence


class AudienceMismatchError(RuntimeError):
    """Raised when an exchanged token's aud does not name this resource server."""


class TokenCacheCollisionError(RuntimeError):
    """Raised when a cached token was minted for a different resource than the one about to be called."""


@dataclass(frozen=True)
class ExchangedToken:
    jwt_claims: Mapping[str, object]
    resource: str          # the `resource` parameter used at exchange time
    issued_at: float
    expires_at: float

    def audience(self) -> Sequence[str]:
        aud = self.jwt_claims.get("aud", [])
        return [aud] if isinstance(aud, str) else list(aud)

    def is_live(self, now: float, skew: float = 30.0) -> bool:
        return now < (self.expires_at - skew)


def validate_for_resource(
    token: ExchangedToken,
    my_resource_uri: str,
    now: float | None = None,
) -> None:
    """Resource-server side: audience must be MEMBERSHIP, not presence."""
    now = time.time() if now is None else now

    if not token.is_live(now):
        raise AudienceMismatchError(
            f"token expired or within skew: exp={token.expires_at} now={now}"
        )

    if my_resource_uri not in token.audience():
        # This is the boundary: signature valid, scope sufficient, audience wrong.
        raise AudienceMismatchError(
            f"audience mismatch: token bound to {token.audience()!r}, "
            f"presented to {my_resource_uri!r}"
        )


class ResourceBoundTokenCache:
    """Cache keyed on (issuer, subject, resource, scopes) — resource is load-bearing."""

    def __init__(self) -> None:
        self._store: dict[tuple, ExchangedToken] = {}

    @staticmethod
    def _key(issuer: str, subject: str, resource: str, scopes: Sequence[str]) -> tuple:
        return (issuer, subject, resource, tuple(sorted(scopes)))

    def get(self, issuer: str, subject: str, resource: str, scopes: Sequence[str]) -> ExchangedToken | None:
        return self._store.get(self._key(issuer, subject, resource, scopes))

    def put(self, issuer: str, subject: str, token: ExchangedToken, scopes: Sequence[str]) -> None:
        self._store[self._key(issuer, subject, token.resource, scopes)] = token

    def assert_no_drift(self, token: ExchangedToken, expected_resource: str) -> None:
        """Client-side guard: catch manifest re-derivation before the wire."""
        if token.resource != expected_resource:
            raise TokenCacheCollisionError(
                f"cached token minted for {token.resource!r}, "
                f"call path now targets {expected_resource!r}"
            )


def call_tool(
    cache: ResourceBoundTokenCache,
    issuer: str,
    subject: str,
    expected_resource: str,
    scopes: Sequence[str],
    now: float | None = None,
) -> ExchangedToken:
    token = cache.get(issuer, subject, expected_resource, scopes)
    if token is None:
        raise AudienceMismatchError(
            f"no token for resource {expected_resource!r}; refusing implicit reuse"
        )
    cache.assert_no_drift(token, expected_resource)
    validate_for_resource(token, expected_resource, now=now)
    return token
