# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-handoff-when-spiffe-trust-domain-federation-silently-degrades-to-tofu-the-warrant-shadow-failure-at-the-mtls-atte.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-handoff-when-spiffe-trust-domain-federation-silently-degrades-to-tofu-the-warrant-shadow-failure-at-the-mtls-atte.warrant.json
# Markdown SHA-256:   6dd9ff7ea9b9b00df782dbd4f2833fb5f814ce7d56551180c3fb0cfeabd50b00
# Code AST SHA-256:   7305c56cdefb8070f454ae507bf436f22f4702715b1cfd7c5012827d4cd14422
# Verified Classes:   WarrantShadowError, FederatedBundle, Handshake
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class WarrantShadowError(RuntimeError):
    """Raised when a handshake's warrant attestation cannot be verified against
    a fresh federated bundle within the defer deadline, and the receiver is
    about to (incorrectly) fall back to channel-only trust."""
    pass


@dataclass
class FederatedBundle:
    trust_domain: str
    refresh_epoch: float          # wall-clock time the bundle was last refreshed
    active_kids: set[str]
    retired_kids: set[str]


@dataclass
class Handshake:
    peer_svid: str
    peer_trust_domain: str
    svid_verified: bool           # result of mTLS + SVID chain check
    attestation_jwt_kid: str
    attestation_signature_ok: bool  # signature check against *some* bundle


def verify_handshake(
    hs: Handshake,
    bundle_loader,               # callable: trust_domain -> FederatedBundle
    max_skew_s: float = 360.0,
    refresh_deadline_s: float = 5.0,
    now: Optional[float] = None,
) -> str:
    """Returns 'accept' or 'reject'. Never returns 'accept' on channel-only trust.

    Raises WarrantShadowError if the defer path would have to fall back to
    channel trust — i.e. if the invariant cannot be upheld.
    """
    now = time.time() if now is None else now

    # Gate 1: channel identity. Independent, binary.
    if not hs.svid_verified:
        return "reject"

    # Gate 2: warrant attestation. Must be verified against a *fresh* bundle.
    bundle = bundle_loader(hs.peer_trust_domain)
    bundle_fresh = (now - bundle.refresh_epoch) <= max_skew_s

    if hs.attestation_jwt_kid in bundle.active_kids:
        if not hs.attestation_signature_ok:
            return "reject"
        if not bundle_fresh:
            # kid is active in a stale bundle: rotation may have retired it.
            # Force synchronous refresh; do not trust stale.
            bundle = _force_refresh(bundle_loader, hs.peer_trust_domain)
            if hs.attestation_jwt_kid not in bundle.active_kids:
                return "reject"
        return "accept"

    if hs.attestation_jwt_kid in bundle.retired_kids:
        # Present but retired in a bundle we hold. If bundle is stale, refresh
        # to confirm; if fresh, the kid is genuinely retired -> reject.
        if bundle_fresh:
            return "reject"
        bundle = _force_refresh(bundle_loader, hs.peer_trust_domain)
        if hs.attestation_jwt_kid in bundle.retired_kids:
            return "reject"
        if hs.attestation_jwt_kid in bundle.active_kids and hs.attestation_signature_ok:
            return "accept"
        return "reject"

    # kid absent from cached bundle. This is the warrant-shadow window.
    # Defer with a hard deadline; NEVER fall back to channel trust.
    if bundle_fresh:
        # Fresh bundle lacks the kid -> peer is asserting a key we do not know.
        return "reject"

    deadline = now + refresh_deadline_s
    while time.time() < deadline:
        bundle = _force_refresh(bundle_loader, hs.peer_trust_domain)
        if hs.attestation_jwt_kid in bundle.active_kids:
            if not hs.attestation_signature_ok:
                return "reject"
            return "accept"
        if hs.attestation_jwt_kid in bundle.retired_kids:
            return "reject"
        time.sleep(0.1)

    # Deadline elapsed without resolution. The only safe outcome is reject.
    # If any caller would proceed on channel trust here, that is the bug.
    raise WarrantShadowError(
        f"warrant shadow unresolved for {hs.peer_svid}: kid "
        f"{hs.attestation_jwt_kid} absent from {hs.peer_trust_domain} bundle "
        f"after {refresh_deadline_s}s refresh deadline; refusing channel-trust fallback"
    )


def _force_refresh(bundle_loader, trust_domain: str) -> FederatedBundle:
    # In production: invalidate cache and re-fetch from federation endpoint.
    return bundle_loader(trust_domain)
