# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-peer-s-policy-attestation-after-the-trust-anchor-has-already-been-rotated-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-peer-s-policy-attestation-after-the-trust-anchor-has-already-been-rotated-mid-session.warrant.json
# Markdown SHA-256:   8150f1485ca89296d8795e19e85445c73ca3daedcf4f41b84f56df4fbf2fb3e7
# Code AST SHA-256:   84886943bd6d5a32fc0f378824bcc24084e24884e1097352ecc3db5315ade26a
# Verified Classes:   StaleTrustAnchorError, AnchorCache, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustAnchorError(RuntimeError):
    """Raised when an attestation would be verified against an anchor that is
    no longer live (rotated/revoked) or whose freshness cannot be established."""


@dataclass
class AnchorCache:
    key_id: str
    version: int
    cached_at: float  # monotonic seconds


@dataclass
class Attestation:
    key_id: str
    not_after: float  # monotonic seconds
    granted_scopes: frozenset


# Invariant: anchor_age + propagation_latency < attestation_ttl.
# max_anchor_age is set strictly below attestation TTL minus propagation SLA.
MAX_ANCHOR_AGE = 180.0          # seconds
PROPAGATION_SLA = 30.0
ATTESTATION_TTL = 300.0


def verify_attestation(
    att: Attestation,
    cache: AnchorCache,
    live_anchor_key_ids: frozenset,
    now: float,
) -> frozenset:
    # 1. Freshness precondition — checked BEFORE signature, fail-closed.
    anchor_age = now - cache.cached_at
    if anchor_age > MAX_ANCHOR_AGE:
        raise StaleTrustAnchorError(
            f"anchor {cache.key_id} age {anchor_age:.1f}s exceeds "
            f"max {MAX_ANCHOR_AGE}s; refusing to verify against stale cache"
        )

    # 2. Liveness precondition — cached key must still be in the live set.
    if att.key_id not in live_anchor_key_ids:
        raise StaleTrustAnchorError(
            f"attestation signed by retired key {att.key_id}; "
            f"live set is {sorted(live_anchor_key_ids)}"
        )

    # 3. TTL precondition on the attestation itself.
    if now >= att.not_after:
        raise StaleTrustAnchorError(
            f"attestation expired at {att.not_after:.0f}, now {now:.0f}"
        )

    # 4. Only now is signature verification sound.
    return att.granted_scopes


def handle_tool_call(
    att: Attestation,
    cache: AnchorCache,
    live_anchor_key_ids: frozenset,
    now: float,
    requested_scope: str,
) -> bool:
    try:
        scopes = verify_attestation(att, cache, live_anchor_key_ids, now)
    except StaleTrustAnchorError:
        # No silent fallback to stale cache; degrade to read-only / block.
        raise
    if requested_scope not in scopes:
        raise StaleTrustAnchorError(
            f"scope {requested_scope!r} not granted under live anchor "
            f"{cache.key_id} v{cache.version}"
        )
    return True
