# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-warrant-whose-attenuation-chain-was-silently-widened-by-a-re-delegating-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-delegated-warrant-whose-attenuation-chain-was-silently-widened-by-a-re-delegating-peer.warrant.json
# Markdown SHA-256:   6968e2e37c53a50d0da3f671cd14bef3c304b3a1840796358a2aa2022e9c3faf
# Code AST SHA-256:   1499a9c28bdab34a2deae9f8b9fd81160a27de959ae8097f6b9c97df38d2d10f
# Verified Classes:   AttenuationTaintError, Scope, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AttenuationTaintError(RuntimeError):
    """Raised when a delegated warrant's scope is not a subset of its named parent's scope."""


@dataclass(frozen=True)
class Scope:
    fs_read: frozenset = field(default_factory=frozenset)
    net_fetch: frozenset = field(default_factory=frozenset)

    def is_subset_of(self, other: "Scope") -> bool:
        return self.fs_read <= other.fs_read and self.net_fetch <= other.net_fetch


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    scope: Scope
    parent_id: str | None
    parent_scope_hash: str | None  # hash of parent's canonical scope, signed into this warrant
    issuer: str


def _scope_hash(scope: Scope) -> str:
    canon = f"fs={sorted(scope.fs_read)};net={sorted(scope.net_fetch)}"
    return hashlib.sha256(canon.encode()).hexdigest()


def mint_child(
    *,
    parent: Warrant,
    requested: Scope,
    issuer: str,
    held_warrants: list[Warrant],
) -> Warrant:
    """
    Mint a delegated warrant. The ONLY valid attenuation baseline is the named
    parent's scope. `held_warrants` is accepted for audit but MUST NOT be used
    to compute the granted scope -- using it is the taint-propagation bug.
    """
    # Guard: the parent must actually be one of the warrants this issuer holds.
    if parent.warrant_id not in {w.warrant_id for w in held_warrants}:
        raise AttenuationTaintError(
            f"issuer {issuer} does not hold parent warrant {parent.warrant_id}"
        )

    # Attenuate against the NAMED PARENT ONLY -- never against the union of
    # held warrants. This is the invariant that prevents ambient-tenant taint.
    granted = Scope(
        fs_read=requested.fs_read & parent.scope.fs_read,
        net_fetch=requested.net_fetch & parent.scope.net_fetch,
    )

    # Re-verify the post-condition: granted must be a subset of parent.scope.
    if not granted.is_subset_of(parent.scope):
        raise AttenuationTaintError(
            f"attenuation violated: granted {granted} not subset of parent {parent.scope}"
        )

    return Warrant(
        warrant_id=f"{issuer}-{parent.warrant_id}-{_scope_hash(granted)[:8]}",
        scope=granted,
        parent_id=parent.warrant_id,
        parent_scope_hash=_scope_hash(parent.scope),
        issuer=issuer,
    )


def verify_chain(child: Warrant, parent: Warrant) -> None:
    """End-to-end check: child scope must be subset of parent scope, and the
    parent's scope hash must match the value bound into the child at mint time."""
    if child.parent_scope_hash != _scope_hash(parent.scope):
        raise AttenuationTaintError(
            f"parent scope hash mismatch for {child.warrant_id}: "
            f"bound={child.parent_scope_hash} actual={_scope_hash(parent.scope)}"
        )
    if not child.scope.is_subset_of(parent.scope):
        raise AttenuationTaintError(
            f"transitive attenuation violated: {child.warrant_id} scope {child.scope} "
            f"not subset of parent {parent.warrant_id} scope {parent.scope}"
        )


# --- reproduction of the observed failure ---
W1 = Warrant(
    warrant_id="W1",
    scope=Scope(fs_read=frozenset({"/data/reports"}), net_fetch=frozenset()),
    parent_id=None,
    parent_scope_hash=None,
    issuer="orchestrator",
)
A = Warrant(
    warrant_id="A",
    scope=Scope(fs_read=frozenset({"/data/reports"}), net_fetch=frozenset({"*.internal"})),
    parent_id=None,
    parent_scope_hash=None,
    issuer="research-tenant",
)

# Correct mint: attenuates against W1 only -> net_fetch stays empty.
W2 = mint_child(
    parent=W1,
    requested=Scope(net_fetch=frozenset({"*.internal"})),
    issuer="planner",
    held_warrants=[W1, A],
)
assert W2.scope.net_fetch == frozenset(), "ambient grant leaked into delegation"

# The buggy path: intersect against union(W1, A) -> net_fetch={*.internal}.
tainted_scope = Scope(
    fs_read=(W1.scope.fs_read | A.scope.fs_read) & frozenset({"/data/reports"}),
    net_fetch=(W1.scope.net_fetch | A.scope.net_fetch) & frozenset({"*.internal"}),
)
tainted = Warrant(
    warrant_id="W2-tainted",
    scope=tainted_scope,
    parent_id="W1",
    parent_scope_hash=_scope_hash(W1.scope),
    issuer="planner",
)
try:
    verify_chain(tainted, W1)
except AttenuationTaintError as e:
    print(f"caught at verification: {e}")
    raise AttenuationTaintError(
        "taint propagation: delegated scope exceeds named parent; revoke and re-issue from root"
    ) from e
