# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-capability-attestation-has-silently-expired-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-capability-attestation-has-silently-expired-mid-handoff.warrant.json
# Markdown SHA-256:   c4e777477164633bd28c7c61095e883161b63c5a283424150fbe840a68a528a9
# Code AST SHA-256:   b2ec168a97e3ab6a88034c7a38846bbe1f5e07c23e4fc42ce3df522b82c8319c
# Verified Classes:   AttestationExpiredMidHandoff, Warrant, ValidationReceipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationExpiredMidHandoff(RuntimeError):
    """Raised when a delegated warrant's validity window does not cover the
    moment of a privileged action, despite having validated at handoff ingress."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: frozenset
    nbf: float          # epoch seconds
    exp: float          # epoch seconds


@dataclass(frozen=True)
class ValidationReceipt:
    warrant_id: str
    validated_at: float
    validator_id: str
    skew_allowance: float


def execute_privileged_action(
    warrant: Warrant,
    receipt: ValidationReceipt,
    op: str,
    *,
    now: float,
    freshness_epsilon: float = 30.0,
    trusted_issuers: frozenset = frozenset({"org-alpha"}),
) -> None:
    # 1. The receipt must describe *this* warrant, not a sibling.
    if receipt.warrant_id != warrant.warrant_id:
        raise AttestationExpiredMidHandoff(
            f"receipt for {receipt.warrant_id} cannot authorize {warrant.warrant_id}"
        )

    # 2. Issuer must still be trusted at action time (revocation can land mid-task).
    if warrant.issuer not in trusted_issuers:
        raise AttestationExpiredMidHandoff(
            f"issuer {warrant.issuer} no longer trusted at action time"
        )

    # 3. Freshness: a cached verdict older than epsilon is not admissible.
    if now - receipt.validated_at > freshness_epsilon:
        # Re-verify the full window against *this* domain's clock plus negotiated skew.
        lo = warrant.nbf + receipt.skew_allowance
        hi = warrant.exp - receipt.skew_allowance
        if not (lo <= now <= hi):
            raise AttestationExpiredMidHandoff(
                f"warrant {warrant.warrant_id} expired mid-handoff: "
                f"now={now:.0f} not in [{lo:.0f},{hi:.0f}] "
                f"(validated_at={receipt.validated_at:.0f}, eps={freshness_epsilon})"
            )

    # 4. Scope must cover the concrete operation.
    if op not in warrant.scope:
        raise AttestationExpiredMidHandoff(
            f"op {op!r} outside scope {sorted(warrant.scope)} of {warrant.warrant_id}"
        )

    # Action proceeds; caller MUST record (warrant_id, receipt.validated_at, now, op)
    # in the audit event so replay auditors can converge with this domain's ledger.


def demo() -> None:
    w = Warrant("W-7731", "org-alpha", frozenset({"fs.read:/shared/reports"}),
                nbf=0.0, exp=300.0)
    # Ingress validated at T=0; subtask fires at T=340.
    r = ValidationReceipt("W-7731", validated_at=0.0, validator_id="org-beta", skew_allowance=5.0)
    execute_privileged_action(w, r, "fs.read:/shared/reports", now=340.0)


if __name__ == "__main__":
    demo()
