# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-pairwise-did-handshake-whose-verifiable-credential-chain-validates-cryptographically-but-whose-issuer-trust-an.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-pairwise-did-handshake-whose-verifiable-credential-chain-validates-cryptographically-but-whose-issuer-trust-an.warrant.json
# Markdown SHA-256:   beea4ddc9d856c17450f7abc40f69aff7e8ddbd5484918407bdf9060b3f43d45
# Code AST SHA-256:   c1b4901d5f2676bdf8e15bc16fb7018c13ac1787125182634b73036a76410b59
# Verified Classes:   StaleAnchorAuthorizationError, RegistryEntry, SessionToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAnchorAuthorizationError(RuntimeError):
    """Raised when a session token's registry binding is older than the
    verifier's cached registry entry, or when the cached entry cannot be
    proven current relative to the token's mint-time version."""


@dataclass(frozen=True)
class RegistryEntry:
    issuer_did: str
    version: int
    scope: frozenset[str]
    valid_until: float  # epoch seconds


@dataclass(frozen=True)
class SessionToken:
    pairwise_did: str
    issuer_did: str
    scope: frozenset[str]
    registry_version: int  # version the token was minted against
    expires_at: float


def authorize_action(
    token: SessionToken,
    action_scope: str,
    cached_entry: Optional[RegistryEntry],
    now: float,
) -> None:
    # 1. Session liveness.
    if now >= token.expires_at:
        raise StaleAnchorAuthorizationError(
            f"session token for {token.pairwise_did} expired at {token.expires_at}"
        )

    # 2. Anchor presence. A missing cache entry is not "trust the token";
    #    it is "cannot prove anchor-validity" and must fail closed.
    if cached_entry is None:
        raise StaleAnchorAuthorizationError(
            f"no cached registry entry for issuer {token.issuer_did}; "
            f"cannot validate token minted against v{token.registry_version}"
        )

    # 3. Anchor freshness: the cache must not be older than the token's
    #    mint-time version. A token cannot extend a stale cache's authority.
    if cached_entry.version < token.registry_version:
        raise StaleAnchorAuthorizationError(
            f"cached registry entry v{cached_entry.version} is older than "
            f"token mint-time v{token.registry_version} for "
            f"{token.issuer_did}; re-resolve before authorizing"
        )

    # 4. Anchor currency: if the cache is newer than the token, the token's
    #    scope may have been narrowed by rotation. Re-derive scope as the
    #    intersection of mint-time scope and live scope.
    if cached_entry.version > token.registry_version:
        effective_scope = token.scope & cached_entry.scope
    else:
        effective_scope = token.scope

    # 5. Anchor validity window.
    if now >= cached_entry.valid_until:
        raise StaleAnchorAuthorizationError(
            f"registry entry v{cached_entry.version} for "
            f"{token.issuer_did} lapsed at {cached_entry.valid_until}"
        )

    # 6. Scope check against the live-derived scope, not the mint-time scope.
    if action_scope not in effective_scope:
        raise StaleAnchorAuthorizationError(
            f"action {action_scope!r} not in effective scope "
            f"{sorted(effective_scope)} for {token.issuer_did} "
            f"(token v{token.registry_version}, live v{cached_entry.version})"
        )
