# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-verify-a-federated-peer-s-credential-after-revocation-and-why-verify-on-handoff-is-not-enough.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-verify-a-federated-peer-s-credential-after-revocation-and-why-verify-on-handoff-is-not-enough.warrant.json
# Markdown SHA-256:   fcbadb111be6105d662077df4a00239e315df9990f339d1f7baf14a06c1d3ef0
# Code AST SHA-256:   f89d595c14992e2efb1afec783d6be2ac52f7ee9d802aff0ce0c24cd81ad88cf
# Verified Classes:   StaleFederatedGrantError, VerificationEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleFederatedGrantError(RuntimeError):
    """Raised when a delegated authorization decision is used past its
    revocation-freshness bound, or when that bound cannot be established."""


@dataclass(frozen=True)
class VerificationEnvelope:
    verified_at: float          # unix seconds, when revocation was last checked
    revocation_root_version: str
    max_staleness: float | None # seconds the issuer permits; None == unbounded/unknown
    scope_version: str


def assert_grant_fresh(
    envelope: VerificationEnvelope,
    now: float | None = None,
    effect_irreversible: bool = True,
) -> None:
    """Gate a privileged side effect on revocation freshness.

    Fails closed: an unknown max_staleness is treated as zero, so an
    irreversible effect requires a check that is effectively per-effect.
    """
    now = time.time() if now is None else now

    if envelope.max_staleness is None:
        # Absence of a bound is not permission to invent one.
        if effect_irreversible:
            raise StaleFederatedGrantError(
                "issuer published no max_staleness; refusing irreversible "
                f"effect (root_version={envelope.revocation_root_version!r})"
            )
        return

    age = now - envelope.verified_at
    if age < 0:
        raise StaleFederatedGrantError(
            f"verification timestamp is in the future (age={age:.1f}s); "
            "clock skew or forged envelope"
        )
    if age > envelope.max_staleness:
        raise StaleFederatedGrantError(
            f"delegated grant stale: age={age:.1f}s exceeds "
            f"max_staleness={envelope.max_staleness:.1f}s "
            f"(root_version={envelope.revocation_root_version!r}, "
            f"scope_version={envelope.scope_version!r})"
        )


def emit_privileged_effect(
    envelope: VerificationEnvelope,
    effect,
    now: float | None = None,
) -> None:
    assert_grant_fresh(envelope, now=now, effect_irreversible=True)
    effect()
