# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-re-signed-capability-token-whose-warrant-chain-is-cryptographically-valid-but-semantically-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-re-signed-capability-token-whose-warrant-chain-is-cryptographically-valid-but-semantically-stale.warrant.json
# Markdown SHA-256:   d2ce0ec07dbbd5669e4d61987d7da0a32d2408942fb1fefa9bd39479587b643e
# Code AST SHA-256:   70c7b1f65f764489867ee283d9e308ae3fab567f52ac6a88ac092c5a2fedf63f
# Verified Classes:   StaleWarrantError, Hop, Warrant, RevocationCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a cryptographically valid token encodes an authority that no longer exists."""
    pass


@dataclass
class Hop:
    issuer: str
    scope: dict
    exp: float          # absolute epoch seconds
    root_id: str


@dataclass
class Warrant:
    leaf_scope: dict
    leaf_exp: float
    chain: list[Hop]    # root-first
    signature_valid: bool = True


@dataclass
class RevocationCache:
    deny: set[str] = field(default_factory=set)
    fetched_at: float = 0.0

    def age(self) -> float:
        return time.time() - self.fetched_at


def validate(w: Warrant, self_aud: str, cache: RevocationCache,
             min_leaf_lifetime: float = 5.0) -> None:
    now = time.time()

    # 1. Cryptographic layer — necessary, not sufficient.
    if not w.signature_valid:
        raise StaleWarrantError("signature chain invalid")

    # 2. Monotone narrowing must have held across every hop.
    for h in w.chain:
        for k, v in w.leaf_scope.items():
            if k not in h.scope or v > h.scope[k]:
                raise StaleWarrantError(f"scope amplification at hop {h.issuer}")

    # 3. THE BOUNDARY: leaf lifetime must not exceed any ancestor's.
    #    If this fails, expiry laundering occurred at delegation time and
    #    no downstream check can recover the true warrant lifetime.
    min_ancestor_exp = min(h.exp for h in w.chain)
    if w.leaf_exp > min_ancestor_exp + 1e-6:
        raise StaleWarrantError(
            f"expiry laundering: leaf_exp={w.leaf_exp:.1f} > "
            f"min_ancestor_exp={min_ancestor_exp:.1f}"
        )

    # 4. Root liveness. Fail closed if the cache is too stale to trust.
    root_id = w.chain[0].root_id
    if cache.age() > min_leaf_lifetime:
        raise StaleWarrantError(
            f"revocation cache age {cache.age():.1f}s exceeds bound "
            f"{min_leaf_lifetime:.1f}s; cannot confirm root {root_id} is live"
        )
    if root_id in cache.deny:
        raise StaleWarrantError(f"root warrant {root_id} revoked")


def delegate(parent: Warrant, child_scope: dict, hop_budget: float) -> Warrant:
    """Mint a child warrant. The clamp here is the invariant that makes
    stateless validation sound downstream."""
    parent_remaining = min(h.exp for h in parent.chain) - time.time()
    if parent_remaining <= 0:
        raise StaleWarrantError("cannot delegate from an expired warrant")
    # Clamp: never exceed the parent's remaining life, never exceed hop_budget.
    child_exp = time.time() + min(hop_budget, parent_remaining)
    new_hop = Hop(
        issuer="self",
        scope=child_scope,
        exp=child_exp,
        root_id=parent.chain[0].root_id,
    )
    return Warrant(
        leaf_scope=child_scope,
        leaf_exp=child_exp,
        chain=parent.chain + [new_hop],
    )
