# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-foreign-domain-capability-shims-from-laundering-trust-across-federated-agent-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-foreign-domain-capability-shims-from-laundering-trust-across-federated-agent-boundaries.warrant.json
# Markdown SHA-256:   4ad6c6e10c8357c0c979d419b8df25c491f827662c82cbdc8ce60659871328f4
# Code AST SHA-256:   b92cdc368a6b8b516c94bdc67630891720decaec157f2b247a741b714054acf7
# Verified Classes:   TrustLaunderingError, Constraint, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustLaunderingError(RuntimeError):
    """Raised when a federated hop breaks the warrant-binding invariant."""
    pass


@dataclass
class Constraint:
    key: str
    op: str          # "<=", "==", "in"
    value: object


@dataclass
class Warrant:
    subject: str
    scope: dict
    budget: int
    budget_quantifier: str          # "per_warrant" | "per_invocation"
    hop_chain: list = field(default_factory=list)   # signed hop attestations


TRANSLATION_TABLE = {
    # orgB's vocabulary -> orgA's vocabulary (equal-or-stricter only)
    "sensitivity": {"public": "public", "corp": "internal"},   # "restricted" absent on purpose
}


def translate_constraints(inbound: list, target_vocab: dict) -> list:
    out = []
    for c in inbound:
        if c.key not in target_vocab:
            raise TrustLaunderingError(
                f"constraint {c.key!r} has no mapping in target vocabulary; "
                f"refusing delegation (fail-closed)"
            )
        mapped = target_vocab[c.key].get(c.value)
        if mapped is None:
            raise TrustLaunderingError(
                f"constraint value {c.value!r} for {c.key!r} untranslatable; "
                f"refusing delegation"
            )
        out.append(Constraint(c.key, c.op, mapped))
    return out


def re_mint_warrant(inbound: Warrant, executor_id: str,
                    target_vocab: dict, attested_subjects: set) -> Warrant:
    if executor_id not in attested_subjects:
        raise TrustLaunderingError(
            f"executor {executor_id!r} not in attested subject set "
            f"{attested_subjects}; would launder trust"
        )
    translated = translate_constraints(
        [Constraint(k, "<=", v) for k, v in inbound.scope.items()],
        target_vocab,
    )
    if inbound.budget_quantifier not in ("per_warrant", "per_invocation"):
        raise TrustLaunderingError(
            f"unknown budget quantifier {inbound.budget_quantifier!r}"
        )
    return Warrant(
        subject=executor_id,
        scope={c.key: c.value for c in translated},
        budget=inbound.budget,
        budget_quantifier=inbound.budget_quantifier,   # preserved, never coerced
        hop_chain=inbound.hop_chain + [executor_id],
    )


def verify_response_hop_chain(warrant: Warrant, expected_hops: int) -> None:
    if len(warrant.hop_chain) != expected_hops:
        raise TrustLaunderingError(
            f"hop-count mismatch: expected {expected_hops}, "
            f"got {len(warrant.hop_chain)}; description-bound shim suspected"
        )
    if not warrant.hop_chain:
        raise TrustLaunderingError("empty hop chain; no attested executor")


# --- incident reproduction ---
inbound = Warrant(
    subject="orgA/orchestrator-1",
    scope={"data_classification": "internal"},
    budget=8192,
    budget_quantifier="per_warrant",
)

try:
    # orgB's shim tries to re-dispatch to orgC's executor, but orgB's
    # vocabulary lacks "data_classification" -> must refuse, not drop.
    re_mint_warrant(
        inbound,
        executor_id="orgC/C-exec-2",
        target_vocab=TRANSLATION_TABLE,
        attested_subjects={"orgB/B-shim-7"},
    )
except TrustLaunderingError as e:
    print(f"REFUSED (correct): {e}")

# If a shim silently drops the constraint instead, the response-path
# verifier catches the hop-chain break:
laundered = Warrant(
    subject="orgC/C-exec-2",
    scope={},
    budget=8192,
    budget_quantifier="per_invocation",     # coerced quantifier
    hop_chain=["orgB/B-shim-7"],
)
try:
    verify_response_hop_chain(laundered, expected_hops=2)
except TrustLaunderingError as e:
    raise TrustLaunderingError(f"trust laundering detected: {e}") from e
