# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-delegated-authority-checks-when-its-aaif-credential-chain-is-re-signed-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-delegated-authority-checks-when-its-aaif-credential-chain-is-re-signed-mid-task.warrant.json
# Markdown SHA-256:   87c93072e0df662ebf638338654cf2986feac57f4ea323f786b0d4a1a7dac4ee
# Code AST SHA-256:   58b88f4be5f69a7eb709ab9183c178ec1a5644d6d79e645b2c8640bba4374415
# Verified Classes:   DelegationBindingError, Warrant, ReBindingGrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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

class DelegationBindingError(RuntimeError):
    """Raised when a credential refresh would produce a split-validity chain."""
    pass

@dataclass
class Warrant:
    iss: str
    sub: str
    kid: str
    iat: float
    exp: float
    scopes: frozenset
    parent_binding: Optional[str] = None  # hash of parent warrant canonical form

    def canonical(self) -> bytes:
        return f"{self.iss}|{self.sub}|{self.kid}|{self.iat}|{sorted(self.scopes)}".encode()

    def binding_hash(self) -> str:
        return hashlib.sha256(self.canonical()).hexdigest()

@dataclass
class ReBindingGrant:
    """Pre-issued by the parent, authorizes leaf kid rotation without parent re-derivation."""
    parent_kid: str
    allowed_sub: str
    trace_id: str
    exp: float
    signature: str  # parent-key signature over (parent_kid, allowed_sub, trace_id, exp)

def refresh_leaf(
    parent: Warrant,
    leaf: Warrant,
    parent_reachable: bool,
    grant: Optional[ReBindingGrant],
    trace_id: str,
    now: Optional[float] = None,
) -> Warrant:
    now = now if now is not None else time.time()

    if now >= leaf.exp:
        raise DelegationBindingError(
            f"leaf {leaf.kid} already expired at {leaf.exp}; cannot refresh in place"
        )

    if parent_reachable:
        # Safe path: re-derive parent link with fresh binding hash.
        new_leaf = Warrant(
            iss=parent.sub,
            sub=leaf.sub,
            kid=f"{leaf.kid}-r{int(now)}",
            iat=now,
            exp=min(leaf.exp + 300, parent.exp),  # never exceed parent ceiling
            scopes=leaf.scopes,  # attenuation already enforced upstream
            parent_binding=parent.binding_hash(),
        )
        # Local replay validation before handing to any verifier.
        if not new_leaf.scopes <= parent.scopes:
            raise DelegationBindingError("scope escalation detected during refresh")
        if new_leaf.parent_binding != parent.binding_hash():
            raise DelegationBindingError("parent binding mismatch after re-derivation")
        return new_leaf

    # Parent unreachable: only legal with a valid re-binding grant.
    if grant is None:
        raise DelegationBindingError(
            f"parent {parent.kid} unreachable and no re-binding grant for trace {trace_id}; "
            "refusing to produce split-validity chain"
        )
    if grant.parent_kid != parent.kid or grant.allowed_sub != leaf.sub:
        raise DelegationBindingError("re-binding grant does not match parent/leaf identity")
    if grant.trace_id != trace_id:
        raise DelegationBindingError("re-binding grant scoped to a different trace")
    if now >= grant.exp:
        raise DelegationBindingError("re-binding grant expired")

    rotated = Warrant(
        iss=parent.sub,
        sub=leaf.sub,
        kid=f"{leaf.kid}-g{int(now)}",
        iat=now,
        exp=min(leaf.exp, grant.exp),
        scopes=leaf.scopes,
        parent_binding=leaf.parent_binding,  # preserved hash; grant authorizes kid rotation
    )
    # Replay check: binding hash must still match the original parent link.
    if rotated.parent_binding != leaf.parent_binding:
        raise DelegationBindingError("grant-based rotation altered parent binding")
    return rotated
