# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-policy-digest-matches-but-whose-warrant-chain-has-been-re-signed-by-an-intermediate-bro.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-policy-digest-matches-but-whose-warrant-chain-has-been-re-signed-by-an-intermediate-bro.warrant.json
# Markdown SHA-256:   1803d038337687d96f154891fc79752b7604fe818176f0d0b95bf9f1adef77e3
# Code AST SHA-256:   c6e51d9ca0a2cf76203d6b3a3f1d8af6faf7adea99eb25e67e8faa68ab9a0b83
# Verified Classes:   WarrantChainError, Warrant, TrustConfig
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WarrantChainError(RuntimeError):
    """Raised when a brokered capability grant fails chain verification."""


@dataclass
class Warrant:
    issuer: str
    capability: str
    policy_digest: str
    parent: "Warrant | None" = None
    signature_valid: bool = True


@dataclass
class TrustConfig:
    trust_anchors: set[str]
    policy_authorized_by: dict[str, str]  # policy_digest -> principal
    max_depth: int = 4


def canonical_policy_digest(policy_text: str) -> str:
    return hashlib.sha256(policy_text.encode("utf-8")).hexdigest()


def verify_chain(grant: Warrant, cfg: TrustConfig) -> str:
    """Walk parent links to a trust anchor; return terminal (principal) issuer.

    Digest equality is a precondition, not an authorization. If the grant's
    issuer is not the policy's authorized_by, the parent chain MUST be walked
    and MUST terminate at authorized_by via trusted hops.
    """
    principal = cfg.policy_authorized_by.get(grant.policy_digest)
    if principal is None:
        raise WarrantChainError(
            f"policy digest {grant.policy_digest!r} has no configured principal"
        )

    if grant.issuer == principal:
        if not grant.signature_valid:
            raise WarrantChainError(f"principal {principal!r} signature invalid")
        return principal

    # Brokered grant: walk the chain, fail closed on any break.
    seen: set[int] = set()
    depth = 0
    node: Warrant | None = grant
    while node is not None:
        if id(node) in seen:
            raise WarrantChainError("cycle detected in warrant parent chain")
        seen.add(id(node))
        depth += 1
        if depth > cfg.max_depth:
            raise WarrantChainError(
                f"warrant chain exceeds max_depth={cfg.max_depth}"
            )
        if not node.signature_valid:
            raise WarrantChainError(
                f"invalid signature at hop issuer={node.issuer!r}"
            )
        if node.issuer == principal:
            return principal
        if node.parent is None:
            raise WarrantChainError(
                f"chain terminates at {node.issuer!r}, not at principal "
                f"{principal!r}; absent parent is not a short chain"
            )
        if node.parent.issuer not in cfg.trust_anchors and \
                node.parent.issuer != principal:
            raise WarrantChainError(
                f"hop issuer {node.parent.issuer!r} not in trust set"
            )
        node = node.parent

    raise WarrantChainError("chain walk exhausted without reaching principal")


def admit(grant: Warrant, policy_text: str, cfg: TrustConfig) -> str:
    expected = canonical_policy_digest(policy_text)
    if grant.policy_digest != expected:
        raise WarrantChainError(
            f"policy digest mismatch: grant={grant.policy_digest!r} "
            f"expected={expected!r}"
        )
    # Digest matched; now the actual authorization check.
    return verify_chain(grant, cfg)


# Reproduces the observed failure: a broker-forged grant with a byte-identical
# policy in its parent blob is admitted by digest equality alone, and rejected
# once the chain walk is enforced.
if __name__ == "__main__":
    policy = "allow read:dataset-7 for role=analyst"
    digest = canonical_policy_digest(policy)
    cfg = TrustConfig(
        trust_anchors={"alpha", "gamma"},
        policy_authorized_by={digest: "alpha"},
    )
    forged = Warrant(
        issuer="broker",
        capability="read:dataset-7",
        policy_digest=digest,
        parent=Warrant(issuer="attacker", capability="read:dataset-7",
                       policy_digest=digest),
    )
    try:
        admit(forged, policy, cfg)
    except WarrantChainError as e:
        print(f"rejected: {e}")
