# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-depth-collapse-when-a-cross-org-trust-broker-truncates-a-delegated-credential-s-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-depth-collapse-when-a-cross-org-trust-broker-truncates-a-delegated-credential-s-provenance.warrant.json
# Markdown SHA-256:   d0486a39fb7bbc45cdfddd7bb6825a402b33d13a86e3d8bc19ac6517117b9d06
# Code AST SHA-256:   74a7ee4405ac1fffb11e42a64b0b6015916c78d09dc1c51dde8f9946af68dafc
# Verified Classes:   ProvenanceTruncationError, Link, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceTruncationError(RuntimeError):
    """Raised when a brokered credential asserts transitive authority
    but its attestation chain cannot be reconstructed to a trusted root."""


@dataclass
class Link:
    issuer: str
    subject: str
    scope: frozenset
    revocation_epoch: int
    parent_hash: Optional[str] = None

    def self_hash(self) -> str:
        payload = f"{self.issuer}|{self.subject}|{sorted(self.scope)}|{self.revocation_epoch}|{self.parent_hash}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class Credential:
    leaf: Link
    chain: list = field(default_factory=list)  # ordered root -> ... -> leaf.parent
    provenance_complete: bool = False
    broker_as_authority: bool = False


def verify_chain(cred: Credential, trusted_roots: set, require_provenance: bool) -> str:
    """Returns the effective grantor identity. Raises on truncation when
    transitive authority is claimed but the chain is not reconstructible."""
    if not cred.provenance_complete:
        if cred.broker_as_authority:
            # Broker is a first-class root; enforce broker TTL/revocation only.
            if cred.leaf.issuer not in trusted_roots:
                raise ProvenanceTruncationError(
                    f"broker {cred.leaf.issuer} not in trust set for broker-as-authority mode"
                )
            return cred.leaf.issuer
        # Claims transitive authority without a reconstructible chain: reject.
        raise ProvenanceTruncationError(
            f"credential from {cred.leaf.issuer} claims transitive authority "
            f"but provenance_complete=False; refusing to infer chain from scope"
        )

    # Reconstruct: walk from leaf.parent back through chain to a trusted root.
    expected_parent = cred.leaf.parent_hash
    for link in reversed(cred.chain):
        if link.self_hash() != expected_parent:
            raise ProvenanceTruncationError(
                f"hash mismatch at link {link.issuer}: chain tampered or reordered"
            )
        expected_parent = link.parent_hash
    root = cred.chain[0].issuer
    if root not in trusted_roots:
        raise ProvenanceTruncationError(
            f"reconstructed root {root} is not in the verifier's trust set"
        )
    if require_provenance and not cred.provenance_complete:
        raise ProvenanceTruncationError("policy requires provenance_complete; got False")
    return root


def authorize(cred: Credential, requested_scope: str, trusted_roots: set,
              current_epoch: dict, require_provenance: bool = True) -> None:
    grantor = verify_chain(cred, trusted_roots, require_provenance)
    # Enforce the *original grantor's* revocation epoch, not the broker's.
    if current_epoch.get(grantor, 0) > cred.leaf.revocation_epoch:
        raise ProvenanceTruncationError(
            f"grant from {grantor} revoked at epoch {current_epoch[grantor]}; "
            f"credential carries epoch {cred.leaf.revocation_epoch}"
        )
    if requested_scope not in cred.leaf.scope:
        raise ProvenanceTruncationError(
            f"scope {requested_scope} not in brokered grant {sorted(cred.leaf.scope)}"
        )
