# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-sse-last-event-id-resumption-as-invalid-across-an-oauth-2-1-token-rotation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-sse-last-event-id-resumption-as-invalid-across-an-oauth-2-1-token-rotation-boundary.warrant.json
# Markdown SHA-256:   d0df81024c8e38b0f22c77cf44f0fb05b9cc40de93fd78ea151583153b73fb97
# Code AST SHA-256:   689aedb44db90f5dcadd3d3ebce0e1767165f2a9f00edca7b36a9c1491446cac
# Verified Classes:   ResumptionDenied, BufferOwnership, TokenClaims, EventCursor
# Defensive Guards:   7 fail-closed invariants (zero external deps)

"""Resumption authorization gate for MCP streamable transport with OAuth 2.1 RS binding.

Encodes the invariant: a Last-Event-ID resumption is valid only when the
presented token's (sub, aud) match the values recorded at buffer creation,
the cursor lies within retention, and the cursor does not point past the
token's exp.
"""

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Optional


class ResumptionDenied(RuntimeError):
    """Raised when an SSE resumption request fails the authorization-continuity gate."""

    def __init__(self, code: str, detail: str) -> None:
        super().__init__(f"{code}: {detail}")
        self.code = code
        self.detail = detail


@dataclass(frozen=True)
class BufferOwnership:
    owner_sub: str
    owner_aud: str
    opened_at: float
    retention_s: float


@dataclass(frozen=True)
class TokenClaims:
    sub: str
    aud: str          # canonical resource URI per RFC 8707
    exp: float        # absolute epoch seconds, no skew applied
    jti: str


@dataclass(frozen=True)
class EventCursor:
    last_event_id: str
    emitted_at: float  # epoch seconds of the referenced event


def authorize_resumption(
    *,
    ownership: Optional[BufferOwnership],
    claims: TokenClaims,
    cursor: EventCursor,
    resource_uri: str,
    now: Optional[float] = None,
) -> None:
    """Raise ResumptionDenied unless resumption is authorized under the current token.

    Returns None on success. Callers must treat any raise as a terminal
    resumption failure and instruct the client to re-initialize the stream.
    """
    now = time.time() if now is None else now

    if ownership is None:
        raise ResumptionDenied(
            "unknown_buffer",
            f"no replay buffer for Last-Event-ID={cursor.last_event_id!r}",
        )

    # 1. Audience continuity: token must be scoped to this resource.
    if claims.aud != resource_uri:
        raise ResumptionDenied(
            "audience_mismatch",
            f"token aud={claims.aud!r} does not match resource {resource_uri!r}",
        )
    if claims.aud != ownership.owner_aud:
        raise ResumptionDenied(
            "audience_drift",
            f"token aud={claims.aud!r} != buffer owner_aud={ownership.owner_aud!r}",
        )

    # 2. Subject continuity: same principal that opened the stream.
    if claims.sub != ownership.owner_sub:
        raise ResumptionDenied(
            "subject_mismatch",
            f"token sub={claims.sub!r} != buffer owner_sub={ownership.owner_sub!r}",
        )

    # 3. Temporal validity of the presented credential.
    if claims.exp <= now:
        raise ResumptionDenied(
            "token_expired",
            f"token exp={claims.exp} <= now={now}",
        )

    # 4. Cursor must lie within retention.
    if now - cursor.emitted_at > ownership.retention_s:
        raise ResumptionDenied(
            "cursor_outside_retention",
            f"event age {now - cursor.emitted_at:.1f}s exceeds retention "
            f"{ownership.retention_s:.1f}s",
        )

    # 5. Cursor must not point past the token's exp.
    #    Events emitted after exp are not replayable under this token.
    if cursor.emitted_at > claims.exp:
        raise ResumptionDenied(
            "cursor_past_token_exp",
            f"event emitted_at={cursor.emitted_at} > token exp={claims.exp}",
        )
