# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-trust-anchor-chain-in-cross-org-agent-federation-using-verifiable-credentials.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-trust-anchor-chain-in-cross-org-agent-federation-using-verifiable-credentials.warrant.json
# Markdown SHA-256:   4461d76100ee0183054cee230228a6dabbd154e456a5c70e462b4cf77cbef967
# Code AST SHA-256:   df0062da4bb904d185bd65ce1001161dc33c332a8912edc6ed9dc96b44f71e85
# Verified Classes:   TrustAnchorStructuralError, Hop, PresentedChain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class TrustAnchorStructuralError(RuntimeError):
    """Raised when a delegation chain is cryptographically valid but structurally
    non-isomorphic to the origin principal's signed delegation path."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str          # DID or org identifier of the delegating party
    actor: str           # subject acting at this hop
    scope: frozenset     # scopes granted at this hop (must narrow monotonically)


@dataclass(frozen=True)
class PresentedChain:
    hops: Sequence[Hop]
    origin_delegation_depth: int
    origin_path_hash: str   # hash over the origin principal's signed hop sequence


def _path_hash(hops: Sequence[Hop]) -> str:
    h = hashlib.sha256()
    for hop in hops:
        h.update(hop.issuer.encode())
        h.update(b"|")
        h.update(hop.actor.encode())
        h.update(b"|")
        h.update(b",".join(sorted(hop.scope)).encode())
        h.update(b";")
    return h.hexdigest()


def verify_chain_structure(chain: PresentedChain) -> None:
    """Enforce the structural invariant: reconstructed hop sequence must be
    isomorphic to the origin-signed sequence, and scope must narrow monotonically.
    """
    # 1. Depth check: a flattened chain has fewer hops than the origin signed.
    if len(chain.hops) != chain.origin_delegation_depth:
        raise TrustAnchorStructuralError(
            f"delegation depth mismatch: origin signed "
            f"{chain.origin_delegation_depth} hops, verifier reconstructed "
            f"{len(chain.hops)} — chain was likely flattened by a federation gateway"
        )

    # 2. Structural isomorphism: hash of reconstructed path must equal origin hash.
    reconstructed = _path_hash(chain.hops)
    if reconstructed != chain.origin_path_hash:
        raise TrustAnchorStructuralError(
            f"delegation path hash mismatch: origin={chain.origin_path_hash[:12]}… "
            f"reconstructed={reconstructed[:12]}… — hop order or issuer sequence altered"
        )

    # 3. Scope must narrow monotonically across the chain.
    for i in range(1, len(chain.hops)):
        prev, cur = chain.hops[i - 1].scope, chain.hops[i].scope
        if not cur.issubset(prev):
            raise TrustAnchorStructuralError(
                f"scope widened at hop {i}: {cur - prev} not granted by previous hop"
            )
