# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-laundering-across-cross-issuer-aaif-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-laundering-across-cross-issuer-aaif-delegation-chains.warrant.json
# Markdown SHA-256:   f17256a8c90dfb73456def59bebcccfe71a276a41774ea130880d30b55a481ac
# Code AST SHA-256:   fce8b22d2b63eaeb0fb16593fa1bf0bd86ca9522cadc17bebd272566aab84d3a
# Verified Classes:   ScopeLaunderingError, CapabilityToken
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ScopeLaunderingError(RuntimeError):
    """Raised when a delegation chain attempts to attenuate scope across
    incompatible grammars, or when chain integrity/depth invariants fail."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    subject: str
    audience: str
    scope: str
    scope_grammar_id: str
    scope_grammar_version: int
    parent_scope: Optional[str]
    parent_hash: Optional[str]
    delegable: bool
    depth: int  # asserted by delegator; verifier MUST recompute


MAX_DELEGATION_DEPTH = 2  # verifier-side constant, not token-asserted


def _hash(tok: CapabilityToken) -> str:
    # stable content hash for parent linkage; real impl uses SHA-256 over canonical form
    return f"{tok.issuer}|{tok.subject}|{tok.scope}|{tok.scope_grammar_id}@{tok.scope_grammar_version}"


def verify_chain(chain: list[CapabilityToken]) -> CapabilityToken:
    """Verify a delegation chain from root to leaf.

    Enforces: (1) parent_hash linkage, (2) recomputed depth bound,
    (3) grammar compatibility at every hop, (4) verbatim parent_scope
    presence when grammars differ. Returns the leaf token whose
    authoritative scope is the root scope minus deletions.
    """
    if not chain:
        raise ScopeLaunderingError("empty delegation chain")

    root = chain[0]
    if root.depth != 0 or root.parent_hash is not None:
        raise ScopeLaunderingError("root token must have depth=0 and no parent")

    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        # Invariant 1: linkage integrity
        if child.parent_hash != _hash(parent):
            raise ScopeLaunderingError(
                f"hop {i}: parent_hash mismatch (re-parenting attack?)"
            )

        # Invariant 2: depth bound recomputed, not trusted
        recomputed_depth = i
        if recomputed_depth > MAX_DELEGATION_DEPTH:
            raise ScopeLaunderingError(
                f"hop {i}: depth {recomputed_depth} exceeds "
                f"max {MAX_DELEGATION_DEPTH}"
            )
        if child.depth != recomputed_depth:
            raise ScopeLaunderingError(
                f"hop {i}: asserted depth {child.depth} != recomputed "
                f"{recomputed_depth}"
            )

        # Invariant 3: grammar compatibility
        if child.scope_grammar_id != parent.scope_grammar_id or \
           child.scope_grammar_version != parent.scope_grammar_version:
            # Grammar change across issuer boundary: require verbatim parent scope
            if child.parent_scope != parent.scope:
                raise ScopeLaunderingError(
                    f"hop {i}: grammar changed "
                    f"({parent.scope_grammar_id} -> {child.scope_grammar_id}) "
                    f"without verbatim parent_scope; scope translation "
                    f"across grammars is non-monotonic and prohibited"
                )
            # Even with verbatim parent scope, cross-grammar attenuation
            # is only sound if the verifier can load the parent grammar.
            # Default: reject.
            raise ScopeLaunderingError(
                f"hop {i}: cross-grammar attenuation requires a registered "
                f"grammar bridge; none available for "
                f"{parent.scope_grammar_id} -> {child.scope_grammar_id}"
            )

        # Invariant 4: same-grammar subset check (string lattice is sound here)
        if not _subset_same_grammar(child.scope, parent.scope):
            raise ScopeLaunderingError(
                f"hop {i}: child scope {child.scope!r} not a subset of "
                f"parent scope {parent.scope!r} under grammar "
                f"{parent.scope_grammar_id}"
            )

    return chain[-1]


def _subset_same_grammar(child: str, parent: str) -> bool:
    # Simplified: real impl parses atoms and checks set inclusion.
    # Glob suffix match is sound ONLY within a single pinned grammar.
    if parent.endswith("/*"):
        return child.startswith(parent[:-1]) or child == parent
    return child == parent


def effective_authority(chain: list[CapabilityToken], resource: str) -> bool:
    """Authoritative check: evaluate resource against ROOT scope minus
    deletions, never against the leaf's re-expressed scope."""
    leaf = verify_chain(chain)
    root = chain[0]
    # The leaf scope is a deletion set against root, in root's grammar.
    # Here we conservatively require the leaf scope to be a same-grammar
    # subset; the resource is checked against root, and the leaf only
    # further restricts.
    if not _subset_same_grammar(leaf.scope, root.scope):
        raise ScopeLaunderingError(
            "leaf scope is not a deletion of root scope; cannot compute "
            "effective authority"
        )
    return _matches(root.scope, resource) and _matches(leaf.scope, resource)


def _matches(scope: str, resource: str) -> bool:
    if scope.endswith("/*"):
        return resource.startswith(scope[:-1])
    return resource == scope
