# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federation-trust-anchor-when-capability-attestation-is-cached-across-org-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federation-trust-anchor-when-capability-attestation-is-cached-across-org-boundaries.warrant.json
# Markdown SHA-256:   9c17e37f5d3429e3d378a89b367ca2c3d51a19499463e2d767be77d909cfa71e
# Code AST SHA-256:   16b108cd7ec2240cc09ea742bfb1a15d1ea4aa7e1afbf8af21a52f3fcdb64512
# Verified Classes:   StaleAttestationError, Attestation, CacheEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a cached capability attestation cannot be confirmed live."""


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    capability: str
    scope_limit: float
    expires_at: float          # issuer clock, seconds since epoch
    issued_at: float


@dataclass
class CacheEntry:
    attestation: Attestation
    last_liveness_check: float  # relying-party clock
    rolling_scope_used: float = 0.0


def admit_capability(
    entry: CacheEntry,
    now: float,
    skew: float,
    recheck_interval: float,
    requested_amount: float,
    liveness_probe,
) -> float:
    """
    Decide whether to honor a cached attestation for a requested amount.
    liveness_probe(issuer, subject, capability) -> bool, raises on failure.
    Returns the new rolling_scope_used.
    """
    att = entry.attestation

    # 1. Hard expiry with skew margin: never honor into the skew window.
    if now >= att.expires_at - skew:
        raise StaleAttestationError(
            f"attestation for {att.subject}/{att.capability} within skew of expiry"
        )

    # 2. Epoch bound: re-check liveness if the re-check interval has elapsed.
    if now - entry.last_liveness_check >= recheck_interval:
        try:
            live = liveness_probe(att.issuer, att.subject, att.capability)
        except Exception as exc:
            # Fail closed: a failed probe is NOT "no change".
            raise StaleAttestationError(
                f"liveness probe failed for {att.issuer}:{att.subject}: {exc}"
            ) from exc
        if not live:
            raise StaleAttestationError(
                f"issuer {att.issuer} reports {att.subject} no longer attested"
            )
        entry.last_liveness_check = now

    # 3. Aggregate scope: enforce against the attestation, not per-call limits.
    projected = entry.rolling_scope_used + requested_amount
    if projected > att.scope_limit:
        raise StaleAttestationError(
            f"aggregate scope exceeded: {projected} > {att.scope_limit}"
        )

    entry.rolling_scope_used = projected
    return entry.rolling_scope_used
