# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-delegated-authority-when-a-scoped-capability-token-outlives-the-grant-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-delegated-authority-when-a-scoped-capability-token-outlives-the-grant-that-minted-it.warrant.json
# Markdown SHA-256:   77a457d3f42c4f3a755f590266d70a6f6f708cd636ba3cb911555f6cf94adcbb
# Code AST SHA-256:   13f7c25abbf1b429cc52744c349ce68a55f5dafed192e2d83a1e8f141fff6106
# Verified Classes:   GrantStateUnconfirmed, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class GrantStateUnconfirmed(RuntimeError):
    """Raised when a delegated token's remaining TTL exceeds the
    revocation-propagation bound and live grant state cannot be confirmed."""
    pass


@dataclass
class CapabilityToken:
    grant_id: str
    scope: str
    audience: str
    expires_at: float          # epoch seconds, frozen at mint
    max_propagation_lag: float  # measured bound, seconds


def authorize_use(
    token: CapabilityToken,
    requested_scope: str,
    requesting_audience: str,
    grant_store,               # callable: grant_id -> "active"|"revoked"|"unknown"
    now: float | None = None,
) -> bool:
    now = time.time() if now is None else now

    # Local, mint-time-style checks: necessary, never sufficient.
    if now >= token.expires_at:
        return False
    if requested_scope != token.scope:
        return False
    if requesting_audience != token.audience:
        return False

    remaining_ttl = token.expires_at - now

    # The boundary inequality. If the token can outlive the propagation
    # bound, its embedded caveats are NOT a complete proof.
    if remaining_ttl > token.max_propagation_lag:
        try:
            state = grant_store(token.grant_id)
        except Exception as exc:
            raise GrantStateUnconfirmed(
                f"grant store unreachable for {token.grant_id}; "
                f"remaining_ttl={remaining_ttl:.0f}s exceeds "
                f"propagation bound={token.max_propagation_lag:.0f}s"
            ) from exc
        if state != "active":
            return False
        return True

    # remaining_ttl <= propagation bound: stateless verification is sound,
    # because any revocation is guaranteed to have propagated by expiry.
    return True


def attenuate(
    parent: CapabilityToken,
    child_expires_at: float,
    child_audience: str,
) -> CapabilityToken:
    # Attenuation must not launder the grant-state obligation: the child
    # may not outlive the parent, and inherits the parent's propagation bound.
    if child_expires_at > parent.expires_at:
        raise GrantStateUnconfirmed(
            "attenuated token would outlive parent; grant-state obligation "
            "cannot be re-established at the child hop"
        )
    return CapabilityToken(
        grant_id=parent.grant_id,
        scope=parent.scope,
        audience=child_audience,
        expires_at=child_expires_at,
        max_propagation_lag=parent.max_propagation_lag,
    )
