# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-identity-rotation-silently-invalidate-in-flight-delegated-tokens-in-zero-trust-multi-agent-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-identity-rotation-silently-invalidate-in-flight-delegated-tokens-in-zero-trust-multi-agent-meshes.warrant.json
# Markdown SHA-256:   0ef860e6562ff3768a804827d63da3e96775d7917d6ade61d47d5ee6e37fa1e9
# Code AST SHA-256:   723a56b70223c7d5de5665f4e0f5060dc7be31eb7eeaedffe4f4ca098040b3b6
# Verified Classes:   IdentityRotationBindingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class IdentityRotationBindingError(RuntimeError):
    """Raised when a delegated token's minting identity no longer matches
    the identity resolved by the verifier, indicating rotation drift."""
    pass


def authorize_delegated_token(token, identity_ledger, now):
    # token fields: sub, iat, exp, kid
    if now >= token.exp:
        raise IdentityRotationBindingError(
            f"token expired: exp={token.exp} now={now}"
        )

    minting_identity = identity_ledger.resolve_at(token.sub, token.iat)
    if minting_identity is None:
        raise IdentityRotationBindingError(
            f"no identity record for sub={token.sub} at iat={token.iat}; "
            "ledger is current-state only or rotation overlap too short"
        )

    current_identity = identity_ledger.resolve_current(token.sub)
    if current_identity is None:
        # Identity rotated out entirely; token is orphaned.
        raise IdentityRotationBindingError(
            f"sub={token.sub} has no current identity; token orphaned by rotation"
        )

    if current_identity.lineage_id != minting_identity.lineage_id:
        # Supersession alias present: would silently re-principal the call.
        raise IdentityRotationBindingError(
            f"sub={token.sub} minted under lineage "
            f"{minting_identity.lineage_id} but resolves to "
            f"{current_identity.lineage_id}; refusing to re-principal"
        )

    if token.kid not in minting_identity.active_keys_at(token.iat):
        raise IdentityRotationBindingError(
            f"token kid={token.kid} not valid for sub={token.sub} at iat={token.iat}"
        )

    return minting_identity.policy_attachment
