# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-scope-has-silently-widened-past-the-issuing-agent-s-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-aaif-credential-scope-has-silently-widened-past-the-issuing-agent-s-authority.warrant.json
# Markdown SHA-256:   341b4f748a30a49bdc9b496520483f105af544905471bec427b71f32dfdff0d8
# Code AST SHA-256:   885dc7011c9d9aebdf097576df20127d6cf9a64ac4317629d9db1a65475befa7
# Verified Classes:   ScopeWideningError, Binding, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple


class ScopeWideningError(RuntimeError):
    """Raised when a delegated warrant's per-binding scope exceeds its parent's."""
    pass


@dataclass(frozen=True)
class Binding:
    resource: str
    action: str


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: str | None
    scope: FrozenSet[Binding]


def flattened_subset(child: Warrant, parent: Warrant) -> bool:
    # The WEAK check: passes on widened credentials. Kept only to show the trap.
    child_res = {b.resource for b in child.scope}
    child_act = {b.action for b in child.scope}
    parent_res = {b.resource for b in parent.scope}
    parent_act = {b.action for b in parent.scope}
    return child_res <= parent_res and child_act <= parent_act


def binding_subset(child: Warrant, parent: Warrant) -> bool:
    # The STRONG check: per-(resource, action) binding containment.
    return child.scope <= parent.scope


def verify_attenuation(
    child: Warrant,
    parent: Warrant,
    revoked: FrozenSet[Tuple[str, str]],
) -> None:
    # Guardrail 1: binding-level subset, not flattened projection.
    if not binding_subset(child, parent):
        raise ScopeWideningError(
            f"warrant {child.warrant_id} asserts bindings not present in "
            f"parent {parent.warrant_id}: "
            f"{sorted(child.scope - parent.scope)}"
        )
    # Guardrail 2: revocation keyed on the scope tuple, not the warrant id.
    for b in child.scope:
        if (b.resource, b.action) in revoked:
            raise ScopeWideningError(
                f"warrant {child.warrant_id} re-expresses revoked binding "
                f"({b.resource}, {b.action}) under a new warrant id"
            )


def admit(child: Warrant, parent: Warrant, revoked: FrozenSet[Tuple[str, str]]) -> None:
    # Demonstrate the trap: flattened check passes, binding check must fire.
    if flattened_subset(child, parent) and not binding_subset(child, parent):
        # Structural signal of silent widening: weak-true, strong-false.
        verify_attenuation(child, parent, revoked)  # will raise; do not swallow
    verify_attenuation(child, parent, revoked)
