# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-federated-handoff-after-the-brokered-credential-has-already-been-minted.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-federated-handoff-after-the-brokered-credential-has-already-been-minted.warrant.json
# Markdown SHA-256:   ebad93237cc666e6faedf271569a24cd0527d2a632b03600d3a5b3bd677f57a3
# Code AST SHA-256:   9c20760457f33a20adf7affd2379cf92fc37b9c393feb4d239e1b16e3c93a3c1
# Verified Classes:   FederationHandoffRejected, EnforcementProfile, Warrant
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class FederationHandoffRejected(RuntimeError):
    """Raised when a brokered cross-org handoff cannot be safely completed."""


@dataclass(frozen=True)
class EnforcementProfile:
    pol_rev_enforced: bool
    revocation_skew_bound_s: float
    jti_single_use: bool
    state_binding: bool
    valid_until: float  # wall-clock; descriptor itself must be fresh


@dataclass(frozen=True)
class Warrant:
    jti: str
    iss: str
    sub: str
    aud: str
    scope: str
    pol_rev: int
    exp: float


def state_digest(state: bytes, w: Warrant) -> str:
    h = hashlib.sha256()
    h.update(state)
    h.update(f"{w.jti}|{w.iss}|{w.sub}|{w.aud}|{w.scope}".encode())
    return h.hexdigest()


def pre_mint_gate(profile: EnforcementProfile | None, requested_ttl_s: float,
                  scope_requires_revocable: bool, now: float | None = None) -> None:
    """Decide BEFORE minting whether the delegate can honor the warrant we are about to create."""
    now = time.time() if now is None else now
    if profile is None:
        raise FederationHandoffRejected("no enforcement profile from delegate; cannot verify C1-C4")
    if profile.valid_until <= now:
        raise FederationHandoffRejected(
            f"delegate enforcement profile stale (valid_until={profile.valid_until}, now={now})"
        )
    if scope_requires_revocable:
        if not profile.pol_rev_enforced:
            raise FederationHandoffRejected(
                "delegate treats pol_rev as advisory; any minted token is a bearer credential "
                "for its full ttl and cannot be revoked before expiry"
            )
        if requested_ttl_s > profile.revocation_skew_bound_s:
            raise FederationHandoffRejected(
                f"requested ttl {requested_ttl_s}s exceeds delegate revocation skew bound "
                f"{profile.revocation_skew_bound_s}s; revocation would be invisible for the gap"
            )
    if not profile.jti_single_use:
        raise FederationHandoffRejected("delegate does not consume jti atomically; replay C4 unenforced")
    if not profile.state_binding:
        raise FederationHandoffRejected(
            "delegate cannot bind task state to warrant; confused-deputy replay possible"
        )


def complete_handoff(w: Warrant, state: bytes, profile: EnforcementProfile,
                     delegate_min_acceptable_rev: int, bound_digest: str,
                     now: float | None = None) -> str:
    """Delegate-side acceptance. Re-checks against CURRENT policy, not negotiation-time cache."""
    now = time.time() if now is None else now
    if w.exp <= now:
        raise FederationHandoffRejected(f"warrant {w.jti} expired at {w.exp}")
    if w.pol_rev < delegate_min_acceptable_rev:
        raise FederationHandoffRejected(
            f"warrant pol_rev {w.pol_rev} older than delegate min_acceptable_rev "
            f"{delegate_min_acceptable_rev}; issuer policy may have been revoked since mint"
        )
    if state_digest(state, w) != bound_digest:
        raise FederationHandoffRejected(
            f"state digest mismatch for jti {w.jti}; state not bound to this warrant"
        )
    return w.jti  # caller must atomically consume jti in replay cache
