# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-capability-scoped-routing-grant-as-revoked-at-the-moment-of-transit-not-at-the-moment-of-issuance-in-cross.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-capability-scoped-routing-grant-as-revoked-at-the-moment-of-transit-not-at-the-moment-of-issuance-in-cross.warrant.json
# Markdown SHA-256:   ad760acd0afa28b1da21fc5188207f3e29f8cc436ae5610b3287a8da594e2550
# Code AST SHA-256:   ba8fa38b5ccf6449e4b8706461076af611254ada36c6144159d54feef5c83369
# Verified Classes:   CapabilityStaleError, RevocationResponse, Capability
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class CapabilityStaleError(RuntimeError):
    """Raised when a delegated capability cannot be confirmed live at forward time."""


@dataclass(frozen=True)
class RevocationResponse:
    revoked: bool
    produced_at: float  # issuer's timestamp, seconds since epoch


@dataclass(frozen=True)
class Capability:
    subject: str
    scope: str
    expires_at: float
    issuer: str


MAX_ACCEPTABLE_STALENESS_S = 30.0


def forward_capability(
    cap: Capability,
    now: float,
    fetch_revocation,
    max_staleness_s: float = MAX_ACCEPTABLE_STALENESS_S,
) -> Capability:
    """
    Validate a received capability at FORWARD time, not receive time.
    Fails closed if the issuer's revocation response is stale, revoked,
    or if the capability has expired during the delegation chain.
    """
    if now >= cap.expires_at:
        raise CapabilityStaleError(
            f"capability for {cap.subject} expired at {cap.expires_at}, now {now}"
        )

    resp: RevocationResponse = fetch_revocation(cap.issuer, cap.subject)

    if resp.produced_at > now:
        raise CapabilityStaleError(
            f"revocation response from {cap.issuer} is future-dated "
            f"({resp.produced_at} > {now}); clock skew or forged response"
        )

    staleness = now - resp.produced_at
    if staleness > max_staleness_s:
        raise CapabilityStaleError(
            f"revocation response from {cap.issuer} is {staleness:.1f}s stale "
            f"(max {max_staleness_s}s); cannot confirm liveness at forward time"
        )

    if resp.revoked:
        raise CapabilityStaleError(
            f"capability for {cap.subject} was revoked by {cap.issuer} "
            f"at {resp.produced_at}; refusing to re-delegate"
        )

    return cap  # forward only after fresh, non-revoked confirmation
