# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-authorization-continuity-when-a-delegation-chain-crosses-a-token-minting-boundary-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-authorization-continuity-when-a-delegation-chain-crosses-a-token-minting-boundary-mid-task.warrant.json
# Markdown SHA-256:   e31d74b20ed70f1f0e360204d3416ab0948025f9c7d5d38ae71dd444dd044b6b
# Code AST SHA-256:   44a31de544fb306149b40bd740c57d8171e4fe9aa95c087827a54c8c2063c984
# Verified Classes:   DelegationChainViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class DelegationChainViolation(RuntimeError):
    """Raised when a re-minted leaf token cannot prove descent from the root grant."""
    pass


def verify_chain(leaf_token, root_token, now):
    """
    Walk a delegation chain from leaf to root. Reject if:
      - the leaf does not carry a parent claim (descent unprovable), or
      - leaf.exp exceeds root.exp (authority outlives source), or
      - leaf.scope is not a subset of root.scope.
    root_token must be resolved by signature, not by intermediate memory.
    """
    if "parent" not in leaf_token.claims:
        raise DelegationChainViolation(
            f"leaf issuer={leaf_token.issuer!r} carries no parent claim; "
            "descent from root is unprovable and over-scope is undetectable"
        )

    # Reconstruct chain by following parent pointers.
    chain = [leaf_token]
    cursor = leaf_token
    while "parent" in cursor.claims:
        cursor = cursor.claims["parent"]
        chain.append(cursor)
        if len(chain) > 16:
            raise DelegationChainViolation("delegation chain exceeds depth bound")

    resolved_root = chain[-1]
    if resolved_root.signature_key_id != root_token.signature_key_id:
        raise DelegationChainViolation(
            "chain terminates at an issuer that is not the trusted root"
        )

    if leaf_token.claims["exp"] > resolved_root.claims["exp"]:
        raise DelegationChainViolation(
            f"leaf exp={leaf_token.claims['exp']} exceeds root exp="
            f"{resolved_root.claims['exp']} by "
            f"{leaf_token.claims['exp'] - resolved_root.claims['exp']}s"
        )

    if not leaf_token.claims["scope"].issubset(resolved_root.claims["scope"]):
        raise DelegationChainViolation(
            f"leaf scope {leaf_token.claims['scope']} not subset of root "
            f"scope {resolved_root.claims['scope']}"
        )

    if now > resolved_root.claims["exp"]:
        raise DelegationChainViolation("root grant already expired at verification time")

    return True
