# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-trust-brokered-capability-grant-survived-federation-but-its-provenance-did-not.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-trust-brokered-capability-grant-survived-federation-but-its-provenance-did-not.warrant.json
# Markdown SHA-256:   0c6c37ac1b6d6938678d6dae8d5be17016b7d288f442dcb864711a3f5fd6a2b2
# Code AST SHA-256:   3070ed5e3bb113270975777fd136b7b9606978c059441f696f7e8e97da960e34
# Verified Classes:   ProvenanceOrphanedError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ProvenanceOrphanedError(RuntimeError):
    """Raised when a brokered capability grant lacks the provenance envelope
    required to evaluate delegation-depth and originating-principal policy."""
    pass


def verify_brokered_grant(grant: dict, *, verifier_trust_root: str) -> dict:
    """Verify a capability grant received across a federation trust boundary.

    Enforces the provenance-completeness invariant: a grant re-signed by an
    intermediary (brokered_by is not None) MUST carry a delegation_chain field.
    Absent provenance is a hard failure, distinct from an empty (depth-0) chain.
    """
    # 1. Signature validity against the issuer we actually trust.
    issuer = grant.get("issuer")
    if issuer != verifier_trust_root:
        raise ProvenanceOrphanedError(
            f"grant issuer {issuer!r} is not the configured trust root "
            f"{verifier_trust_root!r}; cannot verify signature chain"
        )

    # 2. Distinguish brokered from direct grants. The broker MUST stamp this.
    if "brokered_by" not in grant:
        raise ProvenanceOrphanedError(
            "grant schema is missing 'brokered_by'; cannot determine whether "
            "provenance fields are required. Fail closed."
        )
    brokered_by = grant["brokered_by"]

    # 3. Provenance-completeness check, branched on brokered/direct.
    if brokered_by is not None:
        if "delegation_chain" not in grant:
            raise ProvenanceOrphanedError(
                f"grant brokered by {brokered_by!r} has no 'delegation_chain' "
                "field; provenance was dropped at the trust boundary. "
                "Refusing to default absent provenance to depth 0."
            )
        chain = grant["delegation_chain"]
        if not isinstance(chain, list):
            raise ProvenanceOrphanedError(
                f"'delegation_chain' must be a list, got {type(chain).__name__}"
            )
        # 4. Linkage check: each entry must name its parent's signature hash,
        #    so a truncated (not absent) chain fails here rather than silently
        #    under-reporting depth.
        prev_sig = None
        for i, link in enumerate(chain):
            if not isinstance(link, dict) or "signature" not in link:
                raise ProvenanceOrphanedError(
                    f"delegation_chain[{i}] missing 'signature'; cannot link"
                )
            if i > 0 and link.get("parent_signature") != prev_sig:
                raise ProvenanceOrphanedError(
                    f"delegation_chain[{i}] parent_signature does not match "
                    f"prior link signature {prev_sig!r}; chain is truncated "
                    "or reordered"
                )
            prev_sig = link["signature"]
        depth = len(chain)
    else:
        # Direct grant: empty chain is legitimate, depth is zero.
        depth = 0

    return {
        "originating_principal": (chain[0]["principal"] if depth else grant.get("subject")),
        "delegation_depth": depth,
        "brokered_by": brokered_by,
        "scope": grant.get("scope"),
    }
