# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-oauth-token-exchange-it-cannot-verify-end-to-end.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-oauth-token-exchange-it-cannot-verify-end-to-end.warrant.json
# Markdown SHA-256:   5ceb8a9faf93eca341b826f970eb76439c3b99c499a2efd08862e1cb7abc2561
# Code AST SHA-256:   4eeabbf83d5d24aacddcdd3a2944125ac7c8508b7bad25997def1c2736ef79fb
# Verified Classes:   UnverifiableExchangeError, TokenView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class UnverifiableExchangeError(RuntimeError):
    """Raised when a scoped token exchange cannot be corroborated end-to-end."""


@dataclass(frozen=True)
class TokenView:
    jti: str
    subject: str
    scope: frozenset
    act: Optional[str]
    exp: float


def _scope_set(raw: str) -> frozenset:
    return frozenset(s for s in raw.split() if s)


def corroborate_and_propagate(
    subject_token: TokenView,
    granted_token: TokenView,
    requested_scope: str,
    introspect,
    now: Optional[float] = None,
) -> TokenView:
    """
    Verify granted_scope subset of (subject_scope intersect requested_scope)
    before allowing the granted token to be presented to a resource agent.
    Fails closed on any inability to corroborate.
    """
    now = time.time() if now is None else now

    if granted_token.exp <= now:
        raise UnverifiableExchangeError(
            f"granted token {granted_token.jti} already expired at {granted_token.exp}"
        )

    if granted_token.act is None:
        raise UnverifiableExchangeError(
            f"granted token {granted_token.jti} missing act claim; "
            "delegation chain unattributable"
        )

    # Independent reading of the subject token's scope. No trust in the AS here.
    try:
        live_subject = introspect(subject_token.jti)
    except Exception as exc:
        raise UnverifiableExchangeError(
            f"introspection of subject token {subject_token.jti} failed: {exc!r}; "
            "granted scope is unverified and must not be propagated"
        ) from exc

    if live_subject is None or live_subject.scope != subject_token.scope:
        raise UnverifiableExchangeError(
            f"subject token {subject_token.jti} scope drifted or unreadable; "
            "cannot establish subset relation"
        )

    requested = _scope_set(requested_scope)
    permitted = live_subject.scope & requested

    if not granted_token.scope <= permitted:
        widened = granted_token.scope - permitted
        raise UnverifiableExchangeError(
            f"granted scope exceeds subject-authorized scope for jti "
            f"{granted_token.jti}; widened by {sorted(widened)}"
        )

    return granted_token
