# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-the-mcp-http-transport-accept-a-token-minted-for-a-sibling-resource-oauth-resource-binding-token-audience-restriction-and-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-the-mcp-http-transport-accept-a-token-minted-for-a-sibling-resource-oauth-resource-binding-token-audience-restriction-and-repl.warrant.json
# Markdown SHA-256:   e2b8df3ab15440cc237568fa341a78df9a17dcc6626a49a538e86b397489d21b
# Code AST SHA-256:   9cd5d8a8568b43d68c89d4bfd8e5b61d7e92506360212a7251daddf90416df72
# Verified Classes:   ResourceBindingError, ReplayWindowExceededError, TokenClaims, ResourceServerConfig
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ResourceBindingError(RuntimeError):
    """Raised when a bearer token is not bound to this MCP resource server."""


class ReplayWindowExceededError(RuntimeError):
    """Raised when a token's remaining lifetime exceeds the accepted replay window."""


@dataclass(frozen=True)
class TokenClaims:
    issuer: str
    audience: list[str]
    subject: str
    issued_at: int
    expires_at: int
    sender_constrained: bool


@dataclass(frozen=True)
class ResourceServerConfig:
    own_resource_indicator: str  # e.g. "https://mcp-db.internal/"
    trusted_issuer: str
    max_replay_window_seconds: int  # 0 means sender-constrained required
    allow_sibling_instances: bool  # same logical server, different process


def validate_token_for_resource(
    claims: TokenClaims,
    config: ResourceServerConfig,
    now: Optional[int] = None,
) -> None:
    now = int(time.time()) if now is None else now

    if claims.issuer != config.trusted_issuer:
        raise ResourceBindingError(
            f"issuer {claims.issuer!r} is not the trusted issuer "
            f"{config.trusted_issuer!r}"
        )

    if claims.expires_at <= now:
        raise ResourceBindingError(
            f"token expired at {claims.expires_at}, now={now}"
        )

    # The binding check. Fail closed: empty audience is a rejection, not a pass.
    if not claims.audience:
        raise ResourceBindingError(
            "token carries no audience claim; refusing to accept an unbound token"
        )

    if config.own_resource_indicator not in claims.audience:
        raise ResourceBindingError(
            f"token audience {claims.audience!r} does not include this resource "
            f"{config.own_resource_indicator!r}; token was minted for a sibling "
            f"or unrelated resource and must not be accepted here"
        )

    # Replay defense. An unconstrained bearer token is replayable for its
    # remaining lifetime; if that lifetime exceeds the configured window,
    # the deployment has not actually bounded the replay surface.
    remaining = claims.expires_at - now
    if not claims.sender_constrained:
        if config.max_replay_window_seconds <= 0:
            raise ReplayWindowExceededError(
                "sender-constrained tokens are required by policy, but this "
                "token is a plain bearer token"
            )
        if remaining > config.max_replay_window_seconds:
            raise ReplayWindowExceededError(
                f"bearer token has {remaining}s remaining, exceeding the "
                f"accepted replay window of {config.max_replay_window_seconds}s"
            )


def handle_mcp_request(
    claims: TokenClaims,
    config: ResourceServerConfig,
    tool_name: str,
) -> dict:
    validate_token_for_resource(claims, config)
    return {"tool": tool_name, "accepted": True}
