# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-context-forgery-when-a-federated-hop-re-signs-spans-under-its-own-privacy-key-and-drops-the-parent-linkage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-context-forgery-when-a-federated-hop-re-signs-spans-under-its-own-privacy-key-and-drops-the-parent-linkage.warrant.json
# Markdown SHA-256:   bd092ead96bd11e967888290bca51afd603258f969a692cb8c344d64fee3c30b
# Code AST SHA-256:   fb3037b5c9dc7a956cf487cd90181e9ca93af87a45121b07aadaa6b1c4ab89cd
# Verified Classes:   TraceLinkageSeveranceError, ExportedSpan, LinkAssertion
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hmac
import hashlib
from dataclasses import dataclass
from typing import Optional


class TraceLinkageSeveranceError(RuntimeError):
    """Raised when a re-signed span carries a parent token with no verifiable link assertion."""
    pass


@dataclass
class ExportedSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    hop_key_id: str
    signature_valid: bool


@dataclass
class LinkAssertion:
    trace_id: str
    local_parent_token: str
    upstream_token_hash: str  # HMAC(K_hop, upstream_span_id), never the raw ID
    hop_key_id: str
    signature_valid: bool


def verify_causal_edge(
    span: ExportedSpan,
    parent_span: Optional[ExportedSpan],
    links: list[LinkAssertion],
    authorized_keys: dict[str, str],
) -> bool:
    """
    Returns True only if the causal edge span -> parent is established.
    Raises TraceLinkageSeveranceError if the span is orphan-by-policy
    (rewritten parent, no signed link) and the caller demanded a join.
    """
    if not span.signature_valid:
        raise TraceLinkageSeveranceError(
            f"span {span.span_id} signature invalid at hop {span.hop_key_id}"
        )

    if span.parent_span_id is None:
        return True  # genuine root

    # Case A: parent token is in the same namespace as a visible parent span.
    if parent_span is not None and span.parent_span_id == parent_span.span_id:
        return True

    # Case B: a signed link assertion bridges the rewritten parent token.
    for link in links:
        if link.trace_id != span.trace_id:
            continue
        if link.local_parent_token != span.parent_span_id:
            continue
        if not link.signature_valid:
            continue
        if link.hop_key_id not in authorized_keys:
            raise TraceLinkageSeveranceError(
                f"link signed by unauthorized hop key {link.hop_key_id}"
            )
        # Verify the link's upstream hash is consistent with the parent span
        # using the forwarding hop's published key.
        expected = hmac.new(
            authorized_keys[link.hop_key_id].encode(),
            (parent_span.span_id if parent_span else "").encode(),
            hashlib.sha256,
        ).hexdigest()
        if parent_span is not None and not hmac.compare_digest(expected, link.upstream_token_hash):
            raise TraceLinkageSeveranceError(
                f"link hash mismatch for {span.span_id}: forged upstream binding"
            )
        if parent_span is None:
            # Link exists but parent span absent from export: edge is asserted,
            # not reconstructible. Treat as attached-but-unverifiable and refuse
            # to fabricate causality.
            raise TraceLinkageSeveranceError(
                f"link present but parent span {link.upstream_token_hash} not exported"
            )
        return True

    # No same-namespace parent, no link: orphan-by-policy.
    raise TraceLinkageSeveranceError(
        f"span {span.span_id} parent {span.parent_span_id} severed by re-signing "
        f"at hop {span.hop_key_id} with no signed link assertion"
    )
