# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-per-request-mcp-oauth-grant-as-invalid-even-when-the-token-signature-and-audience-both-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-per-request-mcp-oauth-grant-as-invalid-even-when-the-token-signature-and-audience-both-verify.warrant.json
# Markdown SHA-256:   570574ac26fbf7e046bbc0ca646432e39c4a5f60d644c7788b118b0796312368
# Code AST SHA-256:   be6c990ce8c15e82770e0d3ce965dcc2fa4b67c155d4dd6cc4407ebe0fd50161
# Verified Classes:   ResourceBindingError, Token, ToolInvocation
# Defensive Guards:   7 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 the resource being invoked."""
    pass


@dataclass(frozen=True)
class Token:
    aud: Optional[list[str]]
    scope: str
    nbf: float
    exp: float
    signature_valid: bool


@dataclass(frozen=True)
class ToolInvocation:
    tool_name: str
    resource_uri: str          # e.g. "mcp://host/db"
    request_resource_hint: Optional[str] = None


def authorize_per_request(
    token: Token,
    invocation: ToolInvocation,
    *,
    now: Optional[float] = None,
    clock_skew_s: float = 30.0,
    allow_multi_resource_grants: bool = False,
) -> None:
    """
    Enforce strict per-request resource binding for an MCP tool invocation.
    Raises ResourceBindingError on any violation of the binding invariant.
    """
    now = time.time() if now is None else now

    if not token.signature_valid:
        raise ResourceBindingError("token signature invalid")

    if not (token.nbf - clock_skew_s <= now <= token.exp + clock_skew_s):
        raise ResourceBindingError(
            f"token outside validity window: nbf={token.nbf} exp={token.exp} now={now}"
        )

    if not token.aud:
        raise ResourceBindingError("token has no aud claim; no resource binding present")

    if len(token.aud) > 1 and not allow_multi_resource_grants:
        raise ResourceBindingError(
            f"per-request grant has multi-audience {token.aud!r}; "
            "cannot satisfy single-resource binding invariant"
        )

    # The critical check: exact equality, NOT set intersection.
    if invocation.resource_uri not in token.aud:
        raise ResourceBindingError(
            f"token aud {token.aud!r} does not name invoked resource "
            f"{invocation.resource_uri!r} (cross-resource replay rejected)"
        )

    if len(token.aud) == 1 and token.aud[0] != invocation.resource_uri:
        # Unreachable given the membership check above, but kept explicit as the
        # binding invariant: the single audience must equal the invoked resource.
        raise ResourceBindingError(
            f"binding mismatch: aud[0]={token.aud[0]!r} != resource={invocation.resource_uri!r}"
        )

    if invocation.request_resource_hint is not None:
        if invocation.request_resource_hint != token.aud[0]:
            raise ResourceBindingError(
                f"request resource hint {invocation.request_resource_hint!r} "
                f"disagrees with token aud[0]={token.aud[0]!r}"
            )


# --- Example: the cross-resource replay that a naive check would admit ---

if __name__ == "__main__":
    fs_token = Token(
        aud=["mcp://host/fs"],
        scope="fs.read",
        nbf=time.time() - 5,
        exp=time.time() + 300,
        signature_valid=True,
    )

    # Legitimate call: bound resource matches.
    authorize_per_request(fs_token, ToolInvocation("fs.read", "mcp://host/fs"))

    # Replay: same token, different resource on the same host.
    try:
        authorize_per_request(fs_token, ToolInvocation("db.query", "mcp://host/db"))
    except ResourceBindingError as e:
        print(f"correctly rejected: {e}")
