# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-laundering-when-an-attenuated-a2a-delegation-token-is-re-minted-at-an-org-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-laundering-when-an-attenuated-a2a-delegation-token-is-re-minted-at-an-org-boundary.warrant.json
# Markdown SHA-256:   d581cd599a882b1c240f2bd22502383166e2e8b6f4c744fe58ad359a6c9c35cd
# Code AST SHA-256:   38b4cce1867eeb651828ed0a3c0a7d2e7dd7ad77e19bf05ee64cf6b14a2f0feb
# Verified Classes:   DelegationLaunderingError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationLaunderingError(RuntimeError):
    """Raised when an A2A child warrant cannot prove monotonic attenuation
    from an in-band, signature-covered parent scope set."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scopes: frozenset[str]
    parent_scopes: Optional[frozenset[str]]  # in-band, signature-covered
    iat: int
    exp: int
    sig_valid: bool


TRUSTED_ROOTS = frozenset({"org-a/planner"})
WILDCARD = "*"


def _normalize(scopes: frozenset[str]) -> frozenset[str]:
    # Reject wildcards outright at the boundary; they are undecidable
    # without org-specific policy and must be escalated, not guessed.
    for s in scopes:
        if WILDCARD in s:
            raise DelegationLaunderingError(
                f"wildcard scope {s!r} is undecidable at boundary; escalate"
            )
    return scopes


def verify_chain(chain: list[Warrant]) -> None:
    if not chain:
        raise DelegationLaunderingError("empty delegation chain")

    root = chain[0]
    if root.issuer not in TRUSTED_ROOTS:
        raise DelegationLaunderingError(
            f"root issuer {root.issuer!r} not in local trust anchors"
        )

    for i, w in enumerate(chain):
        if not w.sig_valid:
            raise DelegationLaunderingError(f"link {i} signature invalid")
        if i == 0:
            continue
        parent = chain[i - 1]
        if w.parent_scopes is None:
            raise DelegationLaunderingError(
                f"link {i} missing in-band parent scope; reference-only "
                f"delegation is unverifiable"
            )
        child_norm = _normalize(w.scopes)
        parent_norm = _normalize(w.parent_scopes)
        if not child_norm <= parent_norm:
            raise DelegationLaunderingError(
                f"link {i} scope laundering: child {sorted(child_norm)} "
                f"not subset of parent {sorted(parent_norm)}"
            )
        if w.iat < parent.iat or w.exp > parent.exp:
            raise DelegationLaunderingError(
                f"link {i} temporal drift: child window [{w.iat},{w.exp}] "
                f"exceeds parent [{parent.iat},{parent.exp}]"
            )
        if w.parent_scopes != parent.scopes:
            raise DelegationLaunderingError(
                f"link {i} parent scope mismatch: embedded copy differs "
                f"from actual parent (temporal scope drift)"
            )
