# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-narrowing-collusion-gap-when-two-delegated-capability-tokens-each-individually-satisfy-a-policy-but-their-intersec.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-narrowing-collusion-gap-when-two-delegated-capability-tokens-each-individually-satisfy-a-policy-but-their-intersec.warrant.json
# Markdown SHA-256:   ce6ddd09b35bed93ac1b10dfc75cb232225e7d279b8ddc0e719864ac7db49050
# Code AST SHA-256:   e8503b77f034cd2454cb8ef522fddfcbd097ddb8c778ed0212da19d3c52f5ed2
# Verified Classes:   ScopeCollusionGapError, CapabilityToken, IssuerPolicyManifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeCollusionGapError(RuntimeError):
    """Raised when a multi-issuer token set would authorize an action that
    voids a delegating principal's negative constraint via scope union."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    scope: FrozenSet[str]          # positive scope literals
    delegable: bool
    delegator: str
    policy_manifest_id: str        # identifies issuer's tenancy/policy model


@dataclass
class IssuerPolicyManifest:
    issuer: str
    manifest_id: str
    negatives: FrozenSet[str]      # subjects this issuer excludes by policy


def synthesize_effective_scope(
    tokens: list[CapabilityToken],
    manifests: dict[str, IssuerPolicyManifest],
    requested_action: str,
) -> FrozenSet[str]:
    """Collapse a presented token set into a single effective scope under ESCI.

    Raises ScopeCollusionGapError if the set spans multiple issuers and any
    token's positive grant shadows another issuer's negative constraint.
    """
    if not tokens:
        raise ScopeCollusionGapError("no tokens presented")

    issuers = {t.issuer for t in tokens}
    multi_issuer = len(issuers) > 1

    # Conjunction of positive scopes: action must be in EVERY token's scope.
    for t in tokens:
        if requested_action not in t.scope:
            raise ScopeCollusionGapError(
                f"action {requested_action!r} not in conjunction; "
                f"token from {t.issuer} excludes it"
            )

    # Per-issuer negative manifests must not be shadowed by any other token.
    if multi_issuer:
        for t in tokens:
            manifest = manifests.get(t.issuer)
            if manifest is None:
                raise ScopeCollusionGapError(
                    f"missing policy manifest for issuer {t.issuer}; "
                    "cannot evaluate cross-issuer negatives"
                )
            if requested_action in manifest.negatives:
                # This issuer forbids the action by policy, yet another
                # token's positive scope would have authorized it under union
                # semantics. That is the collusion gap.
                raise ScopeCollusionGapError(
                    f"scope collusion gap: action {requested_action!r} is "
                    f"negatively constrained by issuer {t.issuer} "
                    f"(manifest {manifest.manifest_id}) but positively "
                    f"granted by a co-presented token from another issuer"
                )

    # Effective scope is the intersection of all positive scopes.
    effective = frozenset.intersection(*(t.scope for t in tokens))
    if requested_action not in effective:
        raise ScopeCollusionGapError(
            f"action {requested_action!r} outside synthesized effective scope"
        )
    return effective


def authorize(
    tokens: list[CapabilityToken],
    manifests: dict[str, IssuerPolicyManifest],
    action: str,
) -> None:
    """Authorize only against the synthesized effective scope, never per-token."""
    try:
        synthesize_effective_scope(tokens, manifests, action)
    except ScopeCollusionGapError:
        raise
    # ... resource-server side effect only after synthesis passes ...
