# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-audience-binding-failure-when-an-mcp-resource-server-accepts-a-token-minted-for-a-sibling-resource.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-audience-binding-failure-when-an-mcp-resource-server-accepts-a-token-minted-for-a-sibling-resource.warrant.json
# Markdown SHA-256:   7ad573367b9571ce789ba73b5bfe0e3750eeb987189c3e437b6812cc1c0ee88c
# Code AST SHA-256:   a2d542b5b02c885c402689cec101b0bf0320ac2684c269ebbed5ec134226c282
# Verified Classes:   AudienceBindingError, DCRReRegistrationStorm, Token
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class AudienceBindingError(RuntimeError):
    """Raised when a token's aud claim does not name this resource server."""
    pass


class DCRReRegistrationStorm(RuntimeError):
    """Raised when a client re-registers on an audience mismatch instead of re-authorizing."""
    pass


@dataclass
class Token:
    jti: str
    aud: list[str]
    exp: int
    scope: list[str]
    client_id: str


def validate_token_for_resource(
    token: Token,
    resource_uri: str,
    audience_check_enabled: bool,
    registration_count_window: int,
    window_seconds: int = 90,
) -> None:
    now = int(time.time())
    if token.exp <= now:
        raise AudienceBindingError(f"token {token.jti} expired at {token.exp}")

    if not audience_check_enabled:
        # The dangerous default: signature+exp+scope pass, aud is ignored.
        # We refuse to silently accept; surface the misconfiguration instead.
        raise AudienceBindingError(
            f"audience_check disabled for {resource_uri}; cannot validate aud of {token.jti}. "
            "Refusing to authorize under shared-AS deployment."
        )

    if resource_uri not in token.aud:
        raise AudienceBindingError(
            f"token {token.jti} aud={token.aud} does not contain {resource_uri}"
        )

    # Guard against DCR amplification: a client re-registering on 401 is a storm.
    if registration_count_window > 2:
        raise DCRReRegistrationStorm(
            f"client {token.client_id} registered {registration_count_window} times "
            f"in {window_seconds}s; likely re-registering on audience mismatch. "
            "Client must re-authorize with correct `resource`, not re-register."
        )


def handle_request(token: Token, resource_uri: str, audience_check_enabled: bool,
                   registration_count_window: int = 0) -> None:
    try:
        validate_token_for_resource(
            token, resource_uri, audience_check_enabled, registration_count_window
        )
    except AudienceBindingError as e:
        # Emit 401 invalid_token with WWW-Authenticate naming the correct resource.
        raise AudienceBindingError(
            f"401 invalid_token; WWW-Authenticate: Bearer resource={resource_uri}; detail={e}"
        ) from e


if __name__ == "__main__":
    # Negative test that must exist in CI for any shared-AS deployment:
    fs_token = Token(jti="abc", aud=["https://fs.mcp.local"], exp=int(time.time()) + 600,
                     scope=["write:git"], client_id="client-1")
    try:
        handle_request(fs_token, "https://git.mcp.local", audience_check_enabled=True)
    except AudienceBindingError as e:
        print("PASS: cross-resource token rejected ->", e)
