# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-transitive-trust-attenuation-failure-when-a-delegated-capability-s-attestation-chain-exceeds-its-policy-s-re-delegation-de.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-transitive-trust-attenuation-failure-when-a-delegated-capability-s-attestation-chain-exceeds-its-policy-s-re-delegation-de.warrant.json
# Markdown SHA-256:   9456a11abaf3f57082626ac5e46f157393248bc1d951a3dafda687bbaf87eded
# Code AST SHA-256:   7197e0d2c51d069e4421695782e06ad34d6a3a089802b14e97fd3a80aff31ef8
# Verified Classes:   TrustAttenuationError, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TrustAttenuationError(RuntimeError):
    """Raised when a delegation chain's effective authority exceeds the root policy bound."""
    pass


@dataclass
class Attestation:
    issuer: str
    subject: str
    claimed_delegation_depth: int
    parent_attestation_hash: str | None
    root_policy_hash: str
    signature: str  # opaque; assumed verified upstream


def recompute_chain_depth(chain: list[Attestation]) -> int:
    """Depth is structural: number of links minus one. Never trust the claim."""
    if not chain:
        raise TrustAttenuationError("empty attestation chain")
    # Contiguity: each attestation must reference its parent's hash.
    for i in range(1, len(chain)):
        expected_parent = _hash(chain[i - 1])
        if chain[i].parent_attestation_hash != expected_parent:
            raise TrustAttenuationError(
                f"non-contiguous chain at link {i}: parent hash mismatch "
                f"(possible ancestor stripping)"
            )
    return len(chain) - 1


def enforce_attenuation_bound(
    chain: list[Attestation],
    policy_max_delegation_depth: int,
    expected_root_policy_hash: str,
) -> int:
    if chain[0].root_policy_hash != expected_root_policy_hash:
        raise TrustAttenuationError(
            "root policy hash does not match the verifier's trusted policy"
        )

    structural_depth = recompute_chain_depth(chain)
    claimed_depth = chain[-1].claimed_delegation_depth

    # The fingerprint: claimed must equal structural. Divergence = laundering or strip.
    if claimed_depth != structural_depth:
        raise TrustAttenuationError(
            f"depth claim {claimed_depth} != structural depth {structural_depth}: "
            f"reference-frame divergence or chain stripping detected"
        )

    if structural_depth > policy_max_delegation_depth:
        raise TrustAttenuationError(
            f"effective depth {structural_depth} exceeds policy bound "
            f"{policy_max_delegation_depth}: authority laundering"
        )

    return structural_depth


def _hash(att: Attestation) -> str:
    payload = f"{att.issuer}|{att.subject}|{att.parent_attestation_hash}|{att.root_policy_hash}"
    return hashlib.sha256(payload.encode()).hexdigest()
