# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-scope-attenuation-when-a-delegated-capability-token-is-re-signed-across-three-or-more-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-scope-attenuation-when-a-delegated-capability-token-is-re-signed-across-three-or-more-hops.warrant.json
# Markdown SHA-256:   8e749ebc4315fe32384abb6d5a4e3ed9c73cc2c170e16985b373982c0c0faa52
# Code AST SHA-256:   2d66840d688bd81e2be3f7c8b0102f297e7f4a7bf306867d53b79e14008d60f1
# Verified Classes:   ScopeAttenuationViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeAttenuationViolation(RuntimeError):
    """Raised when a delegated token's scope is not a subset of its parent's scope."""
    pass


def verify_delegation_chain(chain):
    """
    chain: list of dicts ordered root -> leaf, each with:
      {'issuer': str, 'scope': {'read': set[str], 'write': set[str]}}
    Enforces monotonic attenuation by intersecting the full chain.
    Returns effective scope; raises on any widening hop.
    """
    if not chain:
        raise ScopeAttenuationViolation("empty delegation chain")

    effective = {
        "read": set(chain[0]["scope"]["read"]),
        "write": set(chain[0]["scope"]["write"]),
    }

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

        for verb in ("read", "write"):
            parent_set = set(parent.get(verb, ()))
            child_set = set(child.get(verb, ()))
            widened = child_set - parent_set
            if widened:
                raise ScopeAttenuationViolation(
                    f"hop {i} ({chain[i]['issuer']}) widened '{verb}' scope "
                    f"beyond parent ({chain[i-1]['issuer']}): {sorted(widened)}"
                )
            effective[verb] &= child_set

    return effective


def authorize(action_verb, resource, effective_scope):
    allowed = effective_scope.get(action_verb, set())
    if resource not in allowed:
        raise ScopeAttenuationViolation(
            f"action {action_verb}:{resource} not in effective scope {sorted(allowed)}"
        )
    return True
