# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-expiry-is-silently-degrading-cross-org-agent-federation-before-policy-gateways-reject.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-expiry-is-silently-degrading-cross-org-agent-federation-before-policy-gateways-reject.warrant.json
# Markdown SHA-256:   bb32fbe1ab32581c054bb11bed2255b325ef1f424e9cfb8e46c4c20390331558
# Code AST SHA-256:   6afd885faf19152a72705aa2e7c96594a7552813da194f69282dc67c7348d904
# Verified Classes:   TrustAnchorExpiryDrift, CachedAnchor, InteropGateway
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TrustAnchorExpiryDrift(RuntimeError):
    """Raised when a cached trust anchor is past its notAfter but still granting."""
    pass


@dataclass
class CachedAnchor:
    issuer: str
    not_after: float          # absolute epoch seconds, NOT a boolean
    fetched_at: float
    cache_ttl: float


class InteropGateway:
    def __init__(self, anchor: CachedAnchor):
        self.anchor = anchor
        self.last_refresh_success = anchor.fetched_at
        self.grant_count = 0
        self.refresh_count = 0

    def _refresh_diverged(self, now: float) -> bool:
        # Structural signal: no successful refresh for longer than the
        # anchor's remaining validity at last fetch => grants are unbacked.
        horizon = self.anchor.not_after - self.anchor.fetched_at
        return (now - self.last_refresh_success) > horizon

    def grant_interop(self, now: float) -> bool:
        # Re-evaluate absolute expiry at grant time, not fetch time.
        if now >= self.anchor.not_after:
            raise TrustAnchorExpiryDrift(
                f"anchor for {self.anchor.issuer} expired at "
                f"{self.anchor.not_after}, grant attempted at {now}"
            )
        if self._refresh_diverged(now):
            raise TrustAnchorExpiryDrift(
                f"refresh diverged: no success since "
                f"{self.last_refresh_success}, horizon exceeded at {now}"
            )
        self.grant_count += 1
        return True


def validate_and_grant(gateway: InteropGateway, now: float) -> bool:
    try:
        return gateway.grant_interop(now)
    except TrustAnchorExpiryDrift:
        # Fail closed: deny cross-org interop, do not fall back to stale cache.
        return False


# Reproduction of the drift: anchor valid to T+24h, fetched at T+0,
# cache TTL 4h. At T+26h the cached anchor is past notAfter but a
# boolean-collapsing gateway would still grant. Timestamp check denies.
anchor = CachedAnchor(issuer="org-a", not_after=24 * 3600, fetched_at=0, cache_ttl=4 * 3600)
gw = InteropGateway(anchor)
assert validate_and_grant(gw, now=10 * 3600) is True   # in-window, backed
assert validate_and_grant(gw, now=26 * 3600) is False  # expired, denied
