# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-spiffe-svid-whose-trust-bundle-it-has-already-cached-and-validated.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-spiffe-svid-whose-trust-bundle-it-has-already-cached-and-validated.warrant.json
# Markdown SHA-256:   023b57f946a0646e23d9e10f87d09b8ab0c7cba32bc714a557e28afdbc66e7b9
# Code AST SHA-256:   770bcc56475873e76d1588bf695e3be718a3135db6fee9c0cc369251aec4d4f9
# Verified Classes:   FederatedTrustError, BundleStaleError, RevokedChainError, UnknownAuthorityError, BundleState, RemoteBundleHint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class FederatedTrustError(RuntimeError):
    """Base class for cross-org SPIFFE trust decision failures."""


class BundleStaleError(FederatedTrustError):
    """Local bundle epoch lags remote; reject as recoverable, do NOT quarantine peer."""


class RevokedChainError(FederatedTrustError):
    """Presented leaf chains to a revoked intermediate; reject and quarantine."""


class UnknownAuthorityError(FederatedTrustError):
    """Leaf chains to an intermediate absent from a *current* bundle; security event."""


@dataclass
class BundleState:
    epoch: int
    last_fetch_ts: float
    intermediates: set[str]
    revoked_intermediates: set[str]


@dataclass
class RemoteBundleHint:
    epoch: int
    refresh_hint_s: float
    revoked_intermediates: set[str]


def verify_federated_svid(
    leaf_signing_intermediate: str,
    local: BundleState,
    remote: RemoteBundleHint,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # (c) Revocation check runs first: a revoked intermediate is fatal regardless of cache state.
    if leaf_signing_intermediate in remote.revoked_intermediates:
        raise RevokedChainError(
            f"intermediate {leaf_signing_intermediate} revoked by remote trust domain"
        )

    # (b) Freshness: local epoch must not lag remote beyond tolerance.
    max_staleness = 2.0 * remote.refresh_hint_s
    if local.epoch < remote.epoch and (now - local.last_fetch_ts) > max_staleness:
        raise BundleStaleError(
            f"local epoch {local.epoch} < remote {remote.epoch}; "
            f"age {now - local.last_fetch_ts:.1f}s > max {max_staleness:.1f}s"
        )

    # (a) Chain verification against the (now-proven-current) local bundle.
    if leaf_signing_intermediate not in local.intermediates:
        raise UnknownAuthorityError(
            f"intermediate {leaf_signing_intermediate} not in current bundle epoch {local.epoch}"
        )

    # Trust decision: (identity, chain, freshness, revocation) all satisfied.
    return None


def handle_handoff_failure(exc: FederatedTrustError, peer_id: str, reputation: dict) -> str:
    """Map failure class to recovery action. The typing is the whole point."""
    if isinstance(exc, BundleStaleError):
        # Recoverable: force bundle refresh, retry handoff, no reputation penalty.
        return "refresh_and_retry"
    if isinstance(exc, RevokedChainError):
        reputation[peer_id] = ("quarantine", "revoked_chain")
        return "quarantine_and_alert"
    if isinstance(exc, UnknownAuthorityError):
        reputation[peer_id] = ("quarantine", "unknown_authority")
        return "quarantine_and_alert"
    raise FederatedTrustError(f"unclassified trust failure for {peer_id}: {exc}")
