# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-oauth-2-1-resource-indicator-binding-failure-when-an-mcp-server-s-audience-restricted-token-survives-a-transport-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-oauth-2-1-resource-indicator-binding-failure-when-an-mcp-server-s-audience-restricted-token-survives-a-transport-r.warrant.json
# Markdown SHA-256:   c781faf122c286bc3f5341a6734e11ffa12054bb33c4e706a81c8fc510466ad7
# Code AST SHA-256:   82c4b76d5918c821b2c5466eb99e5c298d9f6c76cfaf7de2b01407fbd28dd564
# Verified Classes:   AudienceBindingError, ProtectedResourceMetadata, AccessToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AudienceBindingError(RuntimeError):
    """Raised when a token's aud claim does not exactly match the target resource indicator."""
    pass


@dataclass(frozen=True)
class ProtectedResourceMetadata:
    resource: str          # the resource indicator this server advertises
    issuer: str
    fetched_at: float      # unix seconds; used to reject stale metadata


@dataclass(frozen=True)
class AccessToken:
    raw: str
    aud: str | None        # exact resource indicator, or None if absent
    iss: str
    exp: float


METADATA_MAX_AGE_S = 300.0


def _metadata_is_fresh(meta: ProtectedResourceMetadata, now: float) -> bool:
    return (now - meta.fetched_at) <= METADATA_MAX_AGE_S


def validate_for_hop(
    token: AccessToken,
    target: ProtectedResourceMetadata,
    *,
    now: float | None = None,
) -> None:
    """
    Enforce the audience-binding invariant at a single transport hop.

    Fails closed on: missing aud, stale target metadata, issuer mismatch,
    expired token, or any non-exact aud/resource match.
    """
    now = time.time() if now is None else now

    if not _metadata_is_fresh(target, now):
        # Fail closed: we cannot confirm the target's expected resource indicator.
        raise AudienceBindingError(
            f"target metadata for {target.resource!r} is stale "
            f"({now - target.fetched_at:.0f}s old); refusing to forward token"
        )

    if token.exp <= now:
        raise AudienceBindingError(
            f"token expired at {token.exp:.0f} (now {now:.0f})"
        )

    if token.iss != target.issuer:
        raise AudienceBindingError(
            f"issuer mismatch: token.iss={token.iss!r} target.issuer={target.issuer!r}"
        )

    if token.aud is None:
        # Absence of aud is not "wildcard"; it is unbound and must be rejected.
        raise AudienceBindingError(
            "token has no aud claim; unbound tokens are rejected at resource-indicator hops"
        )

    if token.aud != target.resource:
        # Exact equality only. Same host, different path => different audience.
        raise AudienceBindingError(
            f"audience binding failed: token.aud={token.aud!r} "
            f"!= target.resource={target.resource!r}; "
            "perform RFC 8693 token exchange or abort the hop"
        )


def forward_or_exchange(
    token: AccessToken,
    target: ProtectedResourceMetadata,
    *,
    exchange_fn,
    now: float | None = None,
) -> AccessToken:
    """
    Client-side decision boundary: forward iff aud matches exactly; otherwise
    attempt token exchange; if exchange cannot produce a bound token, raise.
    """
    now = time.time() if now is None else now
    try:
        validate_for_hop(token, target, now=now)
        return token  # safe to forward
    except AudienceBindingError:
        rebound = exchange_fn(token, target.resource)
        if rebound is None or rebound.aud != target.resource:
            raise AudienceBindingError(
                f"token exchange failed to bind aud to {target.resource!r}"
            ) from None
        validate_for_hop(rebound, target, now=now)
        return rebound
