# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-that-its-own-trust-anchor-already-validated.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-that-its-own-trust-anchor-already-validated.warrant.json
# Markdown SHA-256:   942dc84fa691b659c656a4e5fa7105d543fb62c56fa73d20c3710456ad7ab3d4
# Code AST SHA-256:   e46386e9c743de28470714f546a2e540c83826ae7aa569aebb23151c392d1e5f
# Verified Classes:   FederationGrantError, ScopeWideningError, ChainIntegrityError, CustodianViolationError, DelegationLink
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class FederationGrantError(RuntimeError):
    """Base class for cross-org capability grant violations."""


class ScopeWideningError(FederationGrantError):
    """A delegation link claims a scope broader than its parent grant."""


class ChainIntegrityError(FederationGrantError):
    """The delegation chain is malformed and cannot be safely intersected."""


class CustodianViolationError(FederationGrantError):
    """The root issuer is not an allowed custodian for this receiver."""


# Classification lattice: higher rank == more restrictive.
_CLASSIFICATION_RANK = {"public": 0, "internal": 1, "confidential": 2, "restricted": 3}
_UNKNOWN_CLASSIFICATION_RANK = 99  # fail closed: unranked labels are treated as top


@dataclass(frozen=True)
class DelegationLink:
    issuer: str
    delegatee: str
    max_classification: str
    parent_scope_witness: Optional[str]  # hash commitment to parent link's scope
    anchor_valid_until: float  # epoch seconds; anchor freshness at use time


def _rank(label: str) -> int:
    return _CLASSIFICATION_RANK.get(label, _UNKNOWN_CLASSIFICATION_RANK)


def compute_effective_scope(
    chain: list[DelegationLink],
    receiver: str,
    custodian_allowlist: set[str],
    now: float,
) -> str:
    """
    Walk the delegation chain from root to terminal envelope and compute the
    effective authority as the meet (most restrictive) over all links.

    Invariants enforced:
      1. Chain is contiguous: link[i].delegatee == link[i+1].issuer.
      2. Monotonic narrowing: rank(link[i+1]) <= rank(link[i]).
      3. Root issuer is on the receiver's custodian allowlist.
      4. Every link's anchor is fresh at execution time (now), not negotiation time.
      5. Terminal delegatee is the receiver.
    """
    if not chain:
        raise ChainIntegrityError("empty delegation chain cannot be evaluated")

    # 1. Contiguity check.
    for i in range(len(chain) - 1):
        if chain[i].delegatee != chain[i + 1].issuer:
            raise ChainIntegrityError(
                f"chain discontinuity at link {i}: "
                f"{chain[i].delegatee!r} != {chain[i + 1].issuer!r}"
            )

    # 2. Monotonic narrowing (broker may narrow, never widen).
    for i in range(len(chain) - 1):
        parent = _rank(chain[i].max_classification)
        child = _rank(chain[i + 1].max_classification)
        if child < parent:
            raise ScopeWideningError(
                f"scope widening at link {i + 1}: "
                f"{chain[i + 1].max_classification!r} broader than "
                f"parent {chain[i].max_classification!r}"
            )

    # 3. Root custodian resolution — walk to terminus, not immediate signer.
    root_issuer = chain[0].issuer
    if root_issuer not in custodian_allowlist:
        raise CustodianViolationError(
            f"root issuer {root_issuer!r} not in custodian allowlist"
        )

    # 4. Anchor freshness at use time.
    for i, link in enumerate(chain):
        if link.anchor_valid_until <= now:
            raise ChainIntegrityError(
                f"anchor for link {i} (issuer {link.issuer!r}) expired at "
                f"{link.anchor_valid_until}, evaluated at {now}"
            )

    # 5. Terminal delegatee must be the receiver.
    if chain[-1].delegatee != receiver:
        raise ChainIntegrityError(
            f"terminal delegatee {chain[-1].delegatee!r} != receiver {receiver!r}"
        )

    # Effective scope is the meet over the chain.
    effective_rank = max(_rank(link.max_classification) for link in chain)
    for label, rank in _CLASSIFICATION_RANK.items():
        if rank == effective_rank:
            return label
    # Unknown label propagated through the meet: refuse rather than guess.
    raise ChainIntegrityError(
        "effective scope contains an unranked classification label; failing closed"
    )


def authorize_task(
    chain: list[DelegationLink],
    receiver: str,
    custodian_allowlist: set[str],
    now: float,
    requested_classification: str,
) -> bool:
    effective = compute_effective_scope(chain, receiver, custodian_allowlist, now)
    if _rank(requested_classification) > _rank(effective):
        raise CustodianViolationError(
            f"requested classification {requested_classification!r} exceeds "
            f"effective scope {effective!r}"
        )
    return True
