# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-session-hijack-replay-across-an-mcp-streamable-http-transport-when-the-origin-header-is-absent-and-the-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-session-hijack-replay-across-an-mcp-streamable-http-transport-when-the-origin-header-is-absent-and-the-session.warrant.json
# Markdown SHA-256:   88d8c4aab032f54c44033ab2e83999243cf19583df119c85825de451ba2766a8
# Code AST SHA-256:   fdefd8497ff9c986b87923beca5d2fd7398757ee449d5861e12949affe3bb93d
# Verified Classes:   SessionReplayError, SessionBinding
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass, field


class SessionReplayError(RuntimeError):
    """Raised when a request cannot be proven fresh within its MCP session."""


@dataclass
class SessionBinding:
    session_id: str
    principal: str                      # bound at initialize, not carried in header
    issued_at: float
    seen_nonces: set = field(default_factory=set)
    last_counter: int = -1
    ttl_seconds: float = 300.0


def authorize_request(
    session: SessionBinding,
    presented_session_id: str,
    presented_principal: str,
    origin: str | None,
    nonce: str | None,
    counter: int | None,
    body: bytes,
    signing_key: bytes,
    signature: bytes | None,
    is_browser_client: bool,
    now: float | None = None,
) -> None:
    now = now if now is not None else time.time()

    # 1. Session ID is a routing key only; it must match a live session.
    if not hmac.compare_digest(presented_session_id, session.session_id):
        raise SessionReplayError("session id does not match a live session")

    # 2. TTL bounds the replay window even if a nonce leaks.
    if now - session.issued_at > session.ttl_seconds:
        raise SessionReplayError("session binding expired; re-initialize required")

    # 3. Principal binding: the header alone is never sufficient.
    if not hmac.compare_digest(presented_principal, session.principal):
        raise SessionReplayError(
            f"principal mismatch: session bound to {session.principal!r}"
        )

    # 4. Origin is REQUIRED for browser-shaped clients (absence is a failure,
    #    not a pass). Non-browser clients must instead carry a signature.
    if is_browser_client:
        if origin is None:
            raise SessionReplayError(
                "missing Origin header from browser client; cannot bind request"
            )
        expected = f"https://{session.principal}"
        if origin != expected:
            raise SessionReplayError(f"origin {origin!r} does not match binding")

    # 5. Freshness: either a monotonic counter or a one-shot nonce, plus a
    #    signature over (session_id || nonce/counter || body) to prevent forgery.
    if signature is None:
        raise SessionReplayError("unsigned request; freshness unprovable")

    if counter is not None:
        if counter <= session.last_counter:
            raise SessionReplayError(
                f"replayed counter {counter} <= {session.last_counter}"
            )
        material = f"{session.session_id}:{counter}".encode() + body
    elif nonce is not None:
        if nonce in session.seen_nonces:
            raise SessionReplayError(f"replayed nonce {nonce!r}")
        material = f"{session.session_id}:{nonce}".encode() + body
    else:
        raise SessionReplayError("no nonce or counter supplied; replay undetectable")

    expected_sig = hmac.new(signing_key, material, hashlib.sha256).digest()
    if not hmac.compare_digest(signature, expected_sig):
        raise SessionReplayError("request signature invalid; body or binding tampered")

    # Commit the freshness marker only after all checks pass, so a failed
    # request cannot poison the replay window for a legitimate retry.
    if counter is not None:
        session.last_counter = counter
    else:
        session.seen_nonces.add(nonce)
