# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-narrows-a-delegated-credential-and-the-child-scope-silently-inherits-the-parent-s-revocation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-narrows-a-delegated-credential-and-the-child-scope-silently-inherits-the-parent-s-revocation-window.warrant.json
# Markdown SHA-256:   f9d519634a1c8abe8a60af644286c65641e437df6af07dd689bd7586130d791b
# Code AST SHA-256:   b7259412b55f56cd1d01bfc12e3f5425519e63f1564bfc7b34dd2a32b2615ee5
# Verified Classes:   DelegationEnvelopeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationEnvelopeError(RuntimeError):
    """Raised when a derived credential's validity envelope is not causally
    bound to its parent's revocation state."""
    pass


def mint_child_warrant(parent_warrant, child_scope, principal_state):
    # Scope narrowing is correct and enforced.
    if not child_scope <= parent_warrant.scope:
        raise DelegationEnvelopeError(
            f"child scope {child_scope} is not a subset of parent {parent_warrant.scope}"
        )

    # BUG: copying the envelope by reference. The child inherits the parent's
    # epoch verbatim, so a later revocation of the parent does not bump the child.
    # This is the silent-inheritance failure.
    child_epoch = parent_warrant.epoch  # <-- copy, not re-derivation

    # Correct path: re-derive from the principal's live state AND register a
    # revocation handle so parent revocation fans out to this child.
    live_epoch = principal_state.current_epoch(parent_warrant.principal_id)
    if parent_warrant.epoch < live_epoch:
        raise DelegationEnvelopeError(
            f"parent warrant epoch {parent_warrant.epoch} is stale "
            f"(principal at {live_epoch}); refusing to mint derivative credential"
        )

    child = ChildWarrant(
        scope=child_scope,
        expiry=parent_warrant.expiry,
        epoch=live_epoch,  # re-derived, not copied
        parent_handle=parent_warrant.handle,
    )
    # Fan-out registration: revoking the parent kills this child.
    principal_state.register_descendant(parent_warrant.handle, child.handle)
    return child


def authorize_presented(warrant, principal_state):
    # Leaf-local predicate is only sound if descendants are epoch-bound at mint.
    current = principal_state.current_epoch(warrant.principal_id)
    if warrant.epoch < current:
        raise DelegationEnvelopeError(
            f"warrant {warrant.handle} epoch {warrant.epoch} < current {current}"
        )
    if principal_state.handle_revoked(warrant.handle):
        raise DelegationEnvelopeError(
            f"warrant {warrant.handle} revoked via ancestor fan-out"
        )
    return True
