# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-delegated-credential-chain-at-the-moment-of-use-not-at-the-moment-of-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-aaif-delegated-credential-chain-at-the-moment-of-use-not-at-the-moment-of-issuance.warrant.json
# Markdown SHA-256:   f6dfe36f74bd87da62ed8c5a2a6fa003ed5505832424a59c6832e2a4ca8c124a
# Code AST SHA-256:   435a708a4eef02aac945f4ae04698b7eec76384629d362fbc3f2b59ec95a03c3
# Verified Classes:   ScopeWideningError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated credential's scope exceeds its parent's scope."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    expiry: int
    scope: FrozenSet[str]


def verify_attenuation_chain(chain: list[Warrant]) -> FrozenSet[str]:
    """
    Walk root -> leaf, enforcing scope(child) subset-of scope(parent)
    at every edge, and return the effective (intersected) authority.
    Fails loudly on any widening edge instead of trusting the leaf claim.
    """
    if not chain:
        raise ScopeWideningError("empty credential chain")

    root = chain[0]
    effective = root.scope

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

        if child.issuer != parent.subject:
            raise ScopeWideningError(
                f"edge {i}: issuer {child.issuer!r} != parent subject {parent.subject!r}"
            )

        if child.expiry > parent.expiry:
            raise ScopeWideningError(
                f"edge {i}: child expiry {child.expiry} exceeds parent {parent.expiry}"
            )

        widened = child.scope - parent.scope
        if widened:
            # This is the boundary failure: signatures all verified,
            # but the child claims authority its parent never held.
            raise ScopeWideningError(
                f"edge {i} ({parent.subject}->{child.subject}) widens scope by {sorted(widened)}"
            )

        effective = effective & child.scope

    return effective


def authorize(warrant_chain: list[Warrant], requested: str) -> bool:
    """Authorize a single capability against the intersected chain authority."""
    try:
        effective = verify_attenuation_chain(warrant_chain)
    except ScopeWideningError as exc:
        # Detection point: log, quarantine the delegating subject, deny.
        raise ScopeWideningError(f"chain rejected at use time: {exc}") from exc

    if requested not in effective:
        return False
    return True
