# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-scope-widening-across-a-cross-issuer-trust-chain-when-an-intermediate-agent-attenuates-a-warrant-it-does.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-scope-widening-across-a-cross-issuer-trust-chain-when-an-intermediate-agent-attenuates-a-warrant-it-does.warrant.json
# Markdown SHA-256:   312953e546f93f8185fbbe900eac74195e8505a8f969a9f8cbb2d93480d6567e
# Code AST SHA-256:   6c9bcff3d0fa462f20ff2c9be6dd34dbf107d6494a0700e0a2fdb83d8ce4454f
# Verified Classes:   ScopeWideningError, Constraint, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a cross-issuer warrant chain's effective scope is not a
    monotone meet of the signed constraint sets from W_0..W_i."""


@dataclass(frozen=True)
class Constraint:
    key: str
    value: object

    def __hash__(self) -> int:
        return hash((self.key, repr(self.value)))


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    constraints: FrozenSet[Constraint]
    # Commitment to the *parent's signed constraint set*, not a free-text echo.
    # If None, the verifier MUST treat this as a root warrant.
    parent_commitment: str | None = None
    parent_scope_declared: FrozenSet[Constraint] = field(default_factory=frozenset)

    def constraint_digest(self) -> str:
        # Canonical digest over the signed constraint set only.
        items = sorted((c.key, repr(c.value)) for c in self.constraints)
        return hashlib.sha256(repr(items).encode()).hexdigest()


def _meet(chain: list[Warrant]) -> FrozenSet[Constraint]:
    """Intersection of all constraint objects across the signed chain.
    A constraint present in an ancestor but absent in a descendant is
    treated as *dropped* -> the descendant is wider -> meet will not
    contain it, and the monotonicity check below will catch it."""
    if not chain:
        return frozenset()
    acc = set(chain[0].constraints)
    for w in chain[1:]:
        acc &= set(w.constraints)
    return frozenset(acc)


def verify_chain(chain: list[Warrant]) -> FrozenSet[Constraint]:
    if not chain:
        raise ScopeWideningError("empty warrant chain")

    # Root must not claim a parent.
    if chain[0].parent_commitment is not None:
        raise ScopeWideningError(
            f"root warrant issued by {chain[0].issuer!r} claims a parent commitment"
        )

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

        # 1. Commitment must match the *actual* parent's signed bytes.
        if child.parent_commitment is None:
            raise ScopeWideningError(
                f"hop {i}: warrant from {child.issuer!r} lacks a parent commitment; "
                "cannot recompute the meet across the trust boundary"
            )
        if child.parent_commitment != parent.constraint_digest():
            raise ScopeWideningError(
                f"hop {i}: parent commitment mismatch "
                f"(declared {child.parent_commitment[:12]}..., "
                f"actual {parent.constraint_digest()[:12]}...)"
            )

        # 2. Declared parent_scope MUST equal the parent's signed constraints.
        #    This is the check Strategy L skips and the laundering exploits.
        if child.parent_scope_declared != parent.constraints:
            missing = parent.constraints - child.parent_scope_declared
            raise ScopeWideningError(
                f"hop {i}: intermediate {parent.subject!r} -> {child.subject!r} "
                f"laundered constraints {sorted(c.key for c in missing)}; "
                "declared parent_scope omits signed parent constraints"
            )

        # 3. Child scope must be a subset of the *accumulated* meet, not just
        #    of the immediately-declared parent scope.
        accumulated = _meet(chain[: i + 1])
        if not child.constraints <= accumulated:
            extra = child.constraints - accumulated
            raise ScopeWideningError(
                f"hop {i}: child scope widens beyond accumulated meet; "
                f"extra constraints {sorted(c.key for c in extra)}"
            )

    return _meet(chain)


# --- Reproduction of the observed laundering chain ---
if __name__ == "__main__":
    w0 = Warrant(
        issuer="A",
        subject="alpha",
        constraints=frozenset({
            Constraint("row_filter", "region='EU'"),
            Constraint("max_rows", 1000),
        }),
    )

    # alpha drops row_filter from its declared parent_scope echo (the bug).
    w1 = Warrant(
        issuer="A",
        subject="beta",
        constraints=frozenset({Constraint("max_rows", 500)}),
        parent_commitment=w0.constraint_digest(),
        parent_scope_declared=frozenset({Constraint("max_rows", 500)}),  # omits row_filter
    )

    w2 = Warrant(
        issuer="B",
        subject="gamma",
        constraints=frozenset({Constraint("max_rows", 200)}),
        parent_commitment=w1.constraint_digest(),
        parent_scope_declared=w1.constraints,
    )

    try:
        verify_chain([w0, w1, w2])
    except ScopeWideningError as e:
        print(f"REJECTED (correct): {e}")
