# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-traceparent-across-an-organizational-trust-boundary-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-propagate-a-traceparent-across-an-organizational-trust-boundary-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   4c9bcec0bc4743f3cacfeaf5c7570065bad90de204c0b257ace0b216ecb972fc
# Code AST SHA-256:   2a62241f0f65102fbc35bf3e61600e437ba3938f0a7d64043ea703d37566a370
# Verified Classes:   TraceContextLaunderingError, TraceContext, LocalDomain
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceContextLaunderingError(RuntimeError):
    """Raised when a foreign traceparent would create an unverified causal edge
    across an organizational trust boundary."""


@dataclass(frozen=True)
class TraceContext:
    trace_id: str
    parent_id: str
    trust_domain: str
    warrant_id: Optional[str] = None
    xfed_signature: Optional[str] = None  # signature over (trace_id, parent_id, warrant_id)


@dataclass(frozen=True)
class LocalDomain:
    name: str
    trust_root: str
    verifier: object  # callable(sig, payload) -> bool


def admit_inbound_trace(
    inbound: TraceContext,
    local: LocalDomain,
    inbound_trust_root: str,
    uses_trace_id_as_authz: bool,
) -> TraceContext:
    same_root = inbound_trust_root == local.trust_root

    if same_root:
        return inbound  # parentage sound; continue verbatim

    if inbound.xfed_signature is not None:
        payload = f"{inbound.trace_id}:{inbound.parent_id}:{inbound.warrant_id}"
        if local.verifier(inbound.xfed_signature, payload):
            return inbound  # attested cross-domain edge is legal

    # Unsigned or failed-signature foreign context.
    if uses_trace_id_as_authz:
        # Continuing would launder an unverified edge into an authz key.
        raise TraceContextLaunderingError(
            f"refusing to continue foreign trace {inbound.trace_id} from "
            f"domain {inbound.trust_domain}: unsigned traceparent and local "
            f"domain uses trace-id as authorization key"
        )

    # Sever: new trace, preserve foreign context as a non-causal link.
    severed = TraceContext(
        trace_id=_new_trace_id(),
        parent_id=_new_span_id(),
        trust_domain=local.name,
        warrant_id=inbound.warrant_id,
        xfed_signature=None,
    )
    # Caller MUST emit a span link to (inbound.trace_id, inbound.parent_id)
    # with attribute xfed.verified=false, never a parent-child edge.
    return severed


def _new_trace_id() -> str:
    import secrets
    return secrets.token_hex(16)


def _new_span_id() -> str:
    import secrets
    return secrets.token_hex(8)
