# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-peer-s-capability-warrant-that-validates-but-was-signed-under-a-superseded-trust-anchor-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-peer-s-capability-warrant-that-validates-but-was-signed-under-a-superseded-trust-anchor-epoch.warrant.json
# Markdown SHA-256:   7274a697ee6f64dd34f722a220d97a203f1b9af6ad8680be74251ef882974767
# Code AST SHA-256:   913ce3f1f06e0690b231701e524615594522bd0014a7bae93fa0cf2002136dc6
# Verified Classes:   EpochSupersededForCapability, Warrant, EpochPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping, Optional


class EpochSupersededForCapability(RuntimeError):
    """Raised when a warrant's signature verifies but its signing epoch is no
    longer authorized to grant the asserted capability at the moment of use."""
    pass


@dataclass(frozen=True)
class Warrant:
    cap: str
    epoch: str
    iat: float
    exp: float
    signature_ok: bool


@dataclass(frozen=True)
class EpochPolicy:
    published: bool
    # capability -> absolute unix time after which this epoch may no longer
    # authorize the capability, regardless of signature validity.
    capability_not_after: Mapping[str, float]


def authorize_warrant(
    warrant: Warrant,
    epoch_policies: Mapping[str, EpochPolicy],
    now: float,
) -> None:
    if not warrant.signature_ok:
        raise EpochSupersededForCapability(
            f"warrant signature invalid for cap={warrant.cap}"
        )
    if now >= warrant.exp:
        raise EpochSupersededForCapability(
            f"warrant expired for cap={warrant.cap}"
        )

    policy: Optional[EpochPolicy] = epoch_policies.get(warrant.epoch)
    if policy is None or not policy.published:
        raise EpochSupersededForCapability(
            f"epoch {warrant.epoch} not published; cannot authorize {warrant.cap}"
        )

    # Fail closed: a missing per-capability entry means the epoch never
    # authorized this capability beyond its publish instant.
    not_after = policy.capability_not_after.get(warrant.cap)
    if not_after is None:
        raise EpochSupersededForCapability(
            f"epoch {warrant.epoch} has no authorization entry for "
            f"cap={warrant.cap}; refusing (fail-closed)"
        )
    if now > not_after:
        raise EpochSupersededForCapability(
            f"epoch {warrant.epoch} superseded for cap={warrant.cap} "
            f"at {not_after}; use={now}"
        )
    # Authorized: signature valid, epoch published, capability still in window.
