# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-transitive-trust-laundering-failure-in-cross-org-agent-identity-attestation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-transitive-trust-laundering-failure-in-cross-org-agent-identity-attestation-chains.warrant.json
# Markdown SHA-256:   57baf7bcbf20d7045fdb4464bbae566158abc43c2b48e5f7ee56b3964e64d875
# Code AST SHA-256:   0bfe75023de1ee0751cdae4af6c3f3d5cd4a1f74775b646b3b8d4a0bf1d059fa
# Verified Classes:   TrustLaunderingError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class TrustLaunderingError(RuntimeError):
    """Raised when a delegated warrant's interpretation authority does not
    terminate at the resource owner's trust root, or when an intermediate
    hop reinterprets scope without a verifiable narrowing proof."""

@dataclass
class Warrant:
    subject: str
    scope: str
    issuer_org: str
    policy_ref: str          # e.g. "A:policy-v7" — must be signed
    parent: Optional["Warrant"] = None
    narrowing_proof: Optional[str] = None  # signed proof child-interp ⊆ parent-interp

def _org_of(policy_ref: str) -> str:
    return policy_ref.split(":", 1)[0]

def verify_chain(w: Warrant, resource_owner_org: str, resolve) -> None:
    """resolve(policy_ref, scope) -> frozenset of concrete resources.
    Enforces: terminal policy authority == resource owner; each hop narrows."""
    chain = []
    node = w
    while node is not None:
        chain.append(node)
        node = node.parent
    chain.reverse()  # root (resource-owner warrant) first

    root = chain[0]
    if _org_of(root.policy_ref) != resource_owner_org:
        raise TrustLaunderingError(
            f"root warrant policy_ref {root.policy_ref!r} not owned by "
            f"resource owner {resource_owner_org!r}"
        )

    prev_resources = resolve(root.policy_ref, root.scope)
    for hop in chain[1:]:
        if hop.policy_ref is None:
            raise TrustLaunderingError(
                f"hop {hop.issuer_org}/{hop.subject} has no resolvable policy_ref; "
                f"refusing default-interpretation fallback"
            )
        if _org_of(hop.policy_ref) != resource_owner_org:
            if hop.narrowing_proof is None:
                raise TrustLaunderingError(
                    f"hop {hop.issuer_org}/{hop.subject} reinterprets scope under "
                    f"{hop.policy_ref!r} (owner={resource_owner_org!r}) without "
                    f"a narrowing proof — transitive trust laundering"
                )
        hop_resources = resolve(hop.policy_ref, hop.scope)
        if not hop_resources <= prev_resources:
            raise TrustLaunderingError(
                f"hop {hop.issuer_org}/{hop.subject} widens authority: "
                f"{hop_resources - prev_resources} not authorized upstream"
            )
        prev_resources = hop_resources

def mint_delegation(parent: Warrant, subject: str, scope: str,
                    host_org: str, narrowing_proof: Optional[str] = None) -> Warrant:
    """Minting hop must never default policy_ref to the host org."""
    if _org_of(parent.policy_ref) != host_org and narrowing_proof is None:
        # carry the upstream policy_ref forward unchanged; do NOT rewrite to host
        return Warrant(subject=subject, scope=scope, issuer_org=host_org,
                       policy_ref=parent.policy_ref, parent=parent)
    return Warrant(subject=subject, scope=scope, issuer_org=host_org,
                   policy_ref=parent.policy_ref, parent=parent,
                   narrowing_proof=narrowing_proof)
