# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-widening-authority-across-cross-issuer-trust-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-widening-authority-across-cross-issuer-trust-chains.warrant.json
# Markdown SHA-256:   7e428b9286b77d375edc5ceb22580445dc8b0a78c7cce88eefe83189053c96f8
# Code AST SHA-256:   1388fbbc4e19e1a694f587c52ffd62b64ba505ff5087f763bd8fbd29ef32ce75
# Verified Classes:   DelegationGraphError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationGraphError(RuntimeError):
    """Raised when a delegated token's parent set is not fully validated."""


@dataclass(frozen=True)
class CapabilityToken:
    token_hash: str
    issuer: str
    parents: FrozenSet[str]          # hashes of parent tokens; empty for root
    authority: FrozenSet[str]        # canonicalized scope strings


def validate_chain(
    leaf: CapabilityToken,
    issued: dict[str, CapabilityToken],
    trusted_issuers: FrozenSet[str],
) -> FrozenSet[str]:
    """
    Return the effective authority of `leaf`, or raise DelegationGraphError.

    Sound only if every parent reachable from `leaf` is present in `issued`
    and every issuer is in `trusted_issuers`. A missing parent is a hard
    failure, not a warning: accepting it would let the leaf exercise
    authority from an unaudited branch of the delegation DAG.
    """
    if leaf.issuer not in trusted_issuers:
        raise DelegationGraphError(
            f"issuer {leaf.issuer!r} not in trusted set for token {leaf.token_hash}"
        )

    if not leaf.parents:
        # Root token: authority is whatever the trusted issuer granted.
        return leaf.authority

    parent_authority: set[str] = set()
    for ph in leaf.parents:
        parent = issued.get(ph)
        if parent is None:
            raise DelegationGraphError(
                f"token {leaf.token_hash} names parent {ph!r} "
                f"that is not present in the issued set; refusing to "
                f"validate a partial delegation graph"
            )
        parent_authority |= validate_chain(parent, issued, trusted_issuers)

    if not leaf.authority.issubset(parent_authority):
        widened = leaf.authority - parent_authority
        raise DelegationGraphError(
            f"token {leaf.token_hash} widens authority beyond its parents: "
            f"{sorted(widened)}"
        )

    return leaf.authority


def merge_tokens(
    a: CapabilityToken, b: CapabilityToken, merged_hash: str, issuer: str
) -> CapabilityToken:
    """
    Explicit merge of two capability tokens. The merged authority is the
    INTERSECTION, not the union: a merge may only narrow, never widen.
    """
    if a.issuer != b.issuer:
        raise DelegationGraphError(
            f"cannot merge tokens from different issuers "
            f"({a.issuer!r} vs {b.issuer!r}) without a cross-issuer merge token"
        )
    return CapabilityToken(
        token_hash=merged_hash,
        issuer=issuer,
        parents=frozenset({a.token_hash, b.token_hash}),
        authority=a.authority & b.authority,
    )
