# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-credential-chain-that-has-been-silently-re-rooted-by-an-intermediate-issuer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-credential-chain-that-has-been-silently-re-rooted-by-an-intermediate-issuer.warrant.json
# Markdown SHA-256:   e693e11da4eff620df9532bb8b35a38a4f97b1fe36afe5e6170ad2ecd644a69c
# Code AST SHA-256:   de8b3ecfde7beb38c3bbfd89cd65adf364c30ac747767bf2102810775e1eaa85
# Verified Classes:   UnverifiableProvenanceError, Credential
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnverifiableProvenanceError(RuntimeError):
    """Raised when a delegated credential chain cannot prove its provenance.

    The chain is structurally valid (signatures, expiry, capability) but the
    leaf issuer is neither the root subject, nor a registered trust anchor,
    nor backed by an authority_grant. This is the re-rooting signature.
    """


@dataclass
class Credential:
    iss: str
    sub: str
    capability: str
    act: list[str]
    authority_grant: Optional[str] = None


def verify_chain_provenance(
    leaf: Credential,
    root_subject: str,
    trust_anchors: set[str],
) -> None:
    """Fail closed if the leaf's provenance cannot be established.

    Accept if any of:
      1. leaf.iss == root_subject            (direct issuance)
      2. leaf.iss in trust_anchors           (anchor-rooted)
      3. leaf.authority_grant == leaf.capability  (authorized mint)
    Otherwise the chain has been re-rooted and must be rejected.
    """
    if leaf.iss == root_subject:
        return
    if leaf.iss in trust_anchors:
        return
    if leaf.authority_grant is not None and leaf.authority_grant == leaf.capability:
        return

    raise UnverifiableProvenanceError(
        f"leaf iss={leaf.iss!r} is not root_subject={root_subject!r}, "
        f"not a trust anchor, and carries no authority_grant for "
        f"capability={leaf.capability!r}; chain appears re-rooted "
        f"(act={leaf.act!r})"
    )


def resolve_revocation_scope(leaf: Credential, root_subject: str) -> str:
    """Return the principal whose status list governs this credential.

    Re-rooted chains would otherwise resolve to the intermediate and miss
    root-level revocations; the provenance check above prevents that path.
    """
    verify_chain_provenance(leaf, root_subject, trust_anchors=set())
    return root_subject
