# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-in-aaif-delegated-credential-chains-the-transitive-scope-narrowing-invariant-and-its-cross-issuer-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-boundary-be-enforced-in-aaif-delegated-credential-chains-the-transitive-scope-narrowing-invariant-and-its-cross-issuer-failure.warrant.json
# Markdown SHA-256:   7ad5645090c3bfcb87e5bbc5dd7abd1249e65a83a87a7362a17b67e6001329ac
# Code AST SHA-256:   0b2e4c70a7deb144aaf5684b69571f0472c70dc5f9e243ad467b18d7e6b14b7b
# Verified Classes:   ScopeNarrowingViolation, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeNarrowingViolation(RuntimeError):
    """Raised when a delegated credential's scope is not a subset of its
    delegator's resolved scope across an issuer trust boundary."""


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject_instance: str
    scope: FrozenSet[str]
    provenance: tuple  # tuple of (issuer, resolved_scope) from root to leaf


def verify_transitive_narrowing(cred: Credential, resource_scope: FrozenSet[str]) -> FrozenSet[str]:
    """
    Enforce the transitive scope-narrowing invariant.

    Returns the effective scope to grant at the resource server, which is the
    intersection of every hop's resolved scope. Raises if the presented scope
    exceeds any ancestor's scope (i.e. the chain re-widened somewhere).
    """
    if not cred.provenance:
        raise ScopeNarrowingViolation(
            f"credential from {cred.issuer} for {cred.subject_instance} has empty provenance; "
            "cannot verify narrowing"
        )

    effective = cred.scope
    for hop_issuer, hop_scope in cred.provenance:
        if not effective.issubset(hop_scope):
            widened = effective - hop_scope
            raise ScopeNarrowingViolation(
                f"scope re-widened at issuer boundary {hop_issuer!r}: "
                f"presented scope {sorted(effective)} exceeds ancestor scope {sorted(hop_scope)}; "
                f"amplified permissions: {sorted(widened)}"
            )
        effective = effective & hop_scope

    if not effective.issubset(resource_scope):
        raise ScopeNarrowingViolation(
            f"effective scope {sorted(effective)} not satisfiable by resource scope "
            f"{sorted(resource_scope)}"
        )
    return effective


# Example: the observed failure — I2 translated read:dataset to dataset:* (full access)
observed = Credential(
    issuer="I2",
    subject_instance="B",
    scope=frozenset({"read:dataset", "write:dataset", "admin:dataset"}),
    provenance=(
        ("I1", frozenset({"read:dataset", "write:dataset", "admin:dataset"})),  # root
        ("I1", frozenset({"read:dataset"})),  # A's narrowing to B
    ),
)

try:
    verify_transitive_narrowing(observed, frozenset({"read:dataset", "write:dataset", "admin:dataset"}))
except ScopeNarrowingViolation as e:
    print(f"REJECTED: {e}")
