# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-issuer-delegated-scope-escalation-when-a-dpop-bound-agent-credential-is-re-minted-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-issuer-delegated-scope-escalation-when-a-dpop-bound-agent-credential-is-re-minted-mid-handoff.warrant.json
# Markdown SHA-256:   31fab57a0b371de47bee39bbbf78c02612708415bb05c6d954fd29d4b48d9cbf
# Code AST SHA-256:   50cae4e3efeb7d6caebb5263cf77035101f6ab54f048315f977e916f1ca8b1e2
# Verified Classes:   ScopeEscalationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScopeEscalationError(RuntimeError):
    """Raised when a re-minted agent token's effective scope is not a subset
    of the origin principal's granted scope set."""
    pass


def verify_delegation_chain(
    hop_tokens: list[dict],
    origin_grant: dict,
    origin_public_key: str,
) -> set[str]:
    """
    Verify that the composed scope set across a delegation chain is a subset
    of the origin principal's grant.

    Each hop token must carry a 'delegation_chain' claim whose root is signed
    by the origin principal. DPoP jkt binding is checked separately and is
    NOT accepted as evidence of scope authority.
    """
    origin_scopes = set(origin_grant["scope"].split())

    effective: set[str] = set()
    for i, token in enumerate(hop_tokens):
        chain = token.get("delegation_chain")
        if chain is None:
            raise ScopeEscalationError(
                f"hop {i}: token lacks delegation_chain claim; "
                f"immediate-predecessor trust is insufficient"
            )

        # The chain root must be signed by the origin principal, not the
        # immediate predecessor issuer.
        if chain.get("root_signer") != origin_grant["issuer"]:
            raise ScopeEscalationError(
                f"hop {i}: delegation chain rooted at {chain.get('root_signer')!r}, "
                f"expected origin principal {origin_grant['issuer']!r}"
            )
        if not _verify_signature(chain, origin_public_key):
            raise ScopeEscalationError(
                f"hop {i}: delegation chain signature does not verify "
                f"against origin public key"
            )

        hop_scopes = set(token["scope"].split())

        # Non-expanding mapping check: this hop's scopes must be a subset of
        # the scopes carried in the chain's previous edge, and ultimately of
        # the origin grant.
        if not hop_scopes <= origin_scopes:
            raise ScopeEscalationError(
                f"hop {i}: effective scope {sorted(hop_scopes)} is not a "
                f"subset of origin grant {sorted(origin_scopes)}; "
                f"cross-issuer scope mapping expanded authority"
            )

        # DPoP binding is orthogonal: verify it, but never use it to justify
        # scope authority.
        if not _verify_dpop_binding(token):
            raise ScopeEscalationError(
                f"hop {i}: DPoP jkt binding invalid (key possession failure, "
                f"not a scope failure)"
            )

        effective |= hop_scopes

    return effective


def _verify_signature(chain: dict, public_key: str) -> bool:
    # Placeholder: real implementation verifies JWS over chain['edges'].
    return chain.get("sig") is not None


def _verify_dpop_binding(token: dict) -> bool:
    # Placeholder: real implementation checks cnf.jkt against DPoP proof.
    return token.get("cnf", {}).get("jkt") is not None
