# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-delegation-workload-identity-rebinding-silently-invalidates-downstream-capability-warrants-in-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-delegation-workload-identity-rebinding-silently-invalidates-downstream-capability-warrants-in-agent-chain.warrant.json
# Markdown SHA-256:   4766a1af5ccab9aacfed80b46ea04b7e380c76003368078e90238da2ebc689ee
# Code AST SHA-256:   36a6ec35c02fad87e70d00a86ed87e5c7b3174fb82561890c7df112d071c48dc
# Verified Classes:   WarrantBindingError, RebindingIncompleteError, Identity, Warrant, DelegationChain
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class WarrantBindingError(RuntimeError):
    """Raised when a warrant's subject binding does not match the live presenter."""
    pass


class RebindingIncompleteError(WarrantBindingError):
    """Raised when an issuer attempts delegated action before re-binding propagates."""
    pass


@dataclass
class Identity:
    spiffe_id: str
    pubkey_thumbprint: str  # sha256 of public key
    issued_at: float


@dataclass
class Warrant:
    issuer: str
    subject: str
    capability: str
    subject_binding: str  # thumbprint the warrant was minted against
    ttl_seconds: float
    minted_at: float = field(default_factory=time.time)

    def is_expired(self, now: float | None = None) -> bool:
        now = now if now is not None else time.time()
        return (now - self.minted_at) > self.ttl_seconds


class DelegationChain:
    def __init__(self, rotation_interval_seconds: float):
        self.rotation_interval = rotation_interval_seconds
        self.warrants: list[Warrant] = []
        self.stale_issuers: set[str] = set()

    def mint(self, issuer: Identity, subject: Identity, capability: str, ttl: float) -> Warrant:
        # Guard: warrant TTL must fit inside rotation interval, else fail-closed is unsafe.
        if ttl >= self.rotation_interval:
            raise WarrantBindingError(
                f"warrant TTL {ttl}s >= rotation interval {self.rotation_interval}s; "
                "fail-closed regime will freeze agents on rotation; "
                "require re-bind-and-continue control plane"
            )
        w = Warrant(
            issuer=issuer.spiffe_id,
            subject=subject.spiffe_id,
            capability=capability,
            subject_binding=issuer.pubkey_thumbprint,
            ttl_seconds=ttl,
        )
        self.warrants.append(w)
        return w

    def on_reattestation(self, issuer: Identity, new_identity: Identity) -> None:
        """Issuer rotated. Mark its outstanding warrants stale; block until re-bound."""
        self.stale_issuers.add(issuer.spiffe_id)
        # Re-bind: re-mint every outstanding warrant this issuer signed under new binding.
        for w in self.warrants:
            if w.issuer == issuer.spiffe_id:
                w.subject_binding = new_identity.pubkey_thumbprint
                w.minted_at = time.time()
        self.stale_issuers.discard(issuer.spiffe_id)

    def verify(self, warrant: Warrant, presenter: Identity) -> bool:
        if warrant.is_expired():
            raise WarrantBindingError(
                f"warrant for {warrant.subject} expired before verification"
            )
        if warrant.issuer in self.stale_issuers:
            raise RebindingIncompleteError(
                f"issuer {warrant.issuer} rotated but re-binding not acknowledged; "
                "delegated action barred"
            )
        if warrant.subject_binding != presenter.pubkey_thumbprint:
            raise WarrantBindingError(
                f"warrant subject_binding {warrant.subject_binding[:12]}... does not match "
                f"presenter {presenter.pubkey_thumbprint[:12]}...; rebind_required"
            )
        return True


def exercise_delegated_tool(chain: DelegationChain, w: Warrant, presenter: Identity) -> str:
    """Entry point for a delegated action. Must be called with the live presenter identity."""
    try:
        chain.verify(w, presenter)
    except RebindingIncompleteError as e:
        # Distinguish rotation from impersonation: rebind_required, not auth failure.
        raise RebindingIncompleteError(
            f"rebind_required: {e}; control plane must re-mint before action"
        ) from e
    except WarrantBindingError as e:
        raise WarrantBindingError(
            f"warrant_binding_mismatch: {e}; chain authority continuity broken"
        ) from e
    return f"executed {w.capability} for {w.subject}"
