# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-session-token-across-a-capability-scope-downgrade-and-the-transport-still-authenticates-the-stale-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-session-token-across-a-capability-scope-downgrade-and-the-transport-still-authenticates-the-stale-grant.warrant.json
# Markdown SHA-256:   6150d3e73831055836fb29c1cca1178c82a23e9bf2e43f3fac27361147092380
# Code AST SHA-256:   e419369b05fba42fae4513742ab9934635a31e701509950ad1cbab479f0b742b
# Verified Classes:   CapabilityStalenessError, SessionRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class CapabilityStalenessError(RuntimeError):
    """Raised when a privileged MCP call would be authorized against a
    capability decision that is stale or wider than the current token scope."""


@dataclass
class SessionRecord:
    session_id: str
    negotiated: frozenset          # what client/server agreed to speak; safe to cache
    authorized_cache: frozenset    # MUST NOT be trusted past staleness ceiling
    decision_time: float           # monotonic timestamp of last introspection


MAX_SESSION_CAPABILITY_AGE = 30.0  # seconds; hard ceiling, never unbounded


def authorize_call(
    session: SessionRecord,
    requested_capability: str,
    introspect,                     # callable(token) -> frozenset current scope
    token: str,
    now: float | None = None,
) -> None:
    now = time.monotonic() if now is None else now

    # 1. Freshness gate: never trust a cached authorization decision past its ceiling.
    age = now - session.decision_time
    if age > MAX_SESSION_CAPABILITY_AGE:
        # Force synchronous re-derivation; do not fall through to the cache.
        current_scope = introspect(token)
        session.authorized_cache = frozenset(current_scope) & session.negotiated
        session.decision_time = now
    else:
        current_scope = introspect(token)  # cheap in-proc; in prod, cache with TTL

    # 2. Invariant gate: authorized set must be a subset of current token scope.
    if not session.authorized_cache.issubset(current_scope):
        raise CapabilityStalenessError(
            f"session {session.session_id!r}: cached capabilities "
            f"{sorted(session.authorized_cache)} exceed current token scope "
            f"{sorted(current_scope)}; revocation did not propagate to session"
        )

    # 3. Capability gate: the specific requested capability must be covered.
    if requested_capability not in session.authorized_cache:
        raise CapabilityStalenessError(
            f"session {session.session_id!r}: capability {requested_capability!r} "
            f"not authorized under current scope {sorted(current_scope)}"
        )


def handle_privileged_call(session: SessionRecord, capability: str, introspect, token: str) -> str:
    try:
        authorize_call(session, capability, introspect, token)
    except CapabilityStalenessError:
        # Fail closed at the call; force session re-initialization rather than
        # continuing on a grant that no longer reflects the principal's authority.
        raise
    return f"executed {capability} under session {session.session_id}"
