# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-capability-warrant-outlives-its-issuing-trust-broker-in-a-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-capability-warrant-outlives-its-issuing-trust-broker-in-a-cross-org-federation.warrant.json
# Markdown SHA-256:   2ebdab9559e700196de5d63fcf449160382068d1bbe03953cb7db0c8a3893087
# Code AST SHA-256:   00b0bab0d96ab564aaf7bcd7ad2976dfa605036e9cf1f878bb52c5ba4664f5a7
# Verified Classes:   WarrantContinuityError, Warrant, GrantStatus
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantContinuityError(RuntimeError):
    """Raised when a capability warrant's authority chain cannot be shown
    live within the federation's revocation-propagation bound."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    scope: str
    not_after: float          # absolute epoch seconds
    issuer: str               # broker id that signed this warrant
    parent_grant_id: str | None  # link in delegation chain, None if root-issued
    signature_valid: bool


@dataclass(frozen=True)
class GrantStatus:
    grant_id: str
    live: bool
    propagation_bound_s: float  # max time for revocation to reach resource owners


def honor_warrant(
    warrant: Warrant,
    now: float,
    fetch_grant_status,       # callable(grant_id) -> GrantStatus
    max_chain_depth: int = 4,
) -> bool:
    """Resource-owner-side validation. Enforces BOTH signature validity AND
    authority continuity: every link in the delegation chain must be live,
    and the warrant's remaining lifetime must not exceed the propagation
    bound of its issuing broker."""

    if not warrant.signature_valid:
        raise WarrantContinuityError(
            f"warrant for {warrant.subject} has invalid signature"
        )

    if now >= warrant.not_after:
        raise WarrantContinuityError(
            f"warrant for {warrant.subject} expired at {warrant.not_after}"
        )

    # Walk the delegation chain. Depth-bounded to prevent unbounded recursion
    # from a maliciously deep or cyclic chain.
    chain = []
    gid = warrant.parent_grant_id
    depth = 0
    while gid is not None:
        if depth >= max_chain_depth:
            raise WarrantContinuityError(
                f"delegation chain exceeds max depth {max_chain_depth} "
                f"for warrant subject {warrant.subject}"
            )
        status = fetch_grant_status(gid)
        chain.append(status)
        if not status.live:
            raise WarrantContinuityError(
                f"warrant for {warrant.subject} rests on revoked grant {gid}"
            )
        gid = None  # in a real impl: follow to parent of this grant
        depth += 1

    # Continuity bound: the warrant must expire before the issuer's revocation
    # could fail to reach us. If it outlives that bound, it is continuity-unsafe.
    if chain:
        bound = min(s.propagation_bound_s for s in chain)
        remaining = warrant.not_after - now
        if remaining > bound:
            raise WarrantContinuityError(
                f"warrant for {warrant.subject} outlives revocation bound "
                f"({remaining:.0f}s remaining > {bound:.0f}s bound); "
                f"authority continuity cannot be guaranteed"
            )

    return True


def mint_from_cached_parent(
    parent_grant_id: str,
    fetch_grant_status,
    requested_ttl_s: float,
) -> Warrant:
    """Guard against warrant laundering: refuse to mint a child warrant from a
    cached parent grant whose liveness we have not confirmed *now*."""
    status = fetch_grant_status(parent_grant_id)
    if not status.live:
        raise WarrantContinuityError(
            f"refusing to mint from grant {parent_grant_id}: not live"
        )
    if requested_ttl_s > status.propagation_bound_s:
        raise WarrantContinuityError(
            f"refusing to mint warrant with ttl {requested_ttl_s}s > "
            f"propagation bound {status.propagation_bound_s}s for "
            f"parent {parent_grant_id}"
        )
    return Warrant(
        subject="<derived>",
        scope="<derived>",
        not_after=time.time() + requested_ttl_s,
        issuer="<self>",
        parent_grant_id=parent_grant_id,
        signature_valid=True,
    )
