# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-confuses-its-own-attestation-scope-with-the-caller-s-requested-scope-in-a-delegated-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-confuses-its-own-attestation-scope-with-the-caller-s-requested-scope-in-a-delegated-tool-call.warrant.json
# Markdown SHA-256:   90a2f19606734a08f1a7e4cb71419d4d6033f54aa26f946e0ce022f9967ad059
# Code AST SHA-256:   76859eeefb76b7c4201c24509cdfb56c0db7f267971a59314fae864c654a5089
# Verified Classes:   SelectorProvenance, ConfusedDeputyError, TaskEnvelope, ToolCall, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import FrozenSet, Tuple


class SelectorProvenance(Enum):
    PRINCIPAL = "principal"   # named in the principal-authored task envelope
    MODEL = "model"           # invented by the model, no untrusted source
    UNTRUSTED = "untrusted"   # drawn from tool output / retrieval / peer msg


class ConfusedDeputyError(RuntimeError):
    """Raised when a tool call's selector provenance or composition
    violates the pre-commitment invariant. Must route to task-abort,
    never to a model-visible retry, or the model will re-attempt with
    a freshly invented selector."""


@dataclass(frozen=True)
class TaskEnvelope:
    principal: str
    committed_selectors: FrozenSet[str]        # exact, principal-authored
    allowed_flows: FrozenSet[Tuple[str, str]]  # (source_tool, sink_tool)


@dataclass(frozen=True)
class ToolCall:
    tool: str
    selector: str
    provenance: SelectorProvenance


@dataclass(frozen=True)
class Warrant:
    sub: str
    aud: str
    scope_prefix: str
    jti: str


def admit(
    envelope: TaskEnvelope,
    warrant: Warrant,
    call: ToolCall,
    prior_calls: Tuple[ToolCall, ...],
) -> None:
    # Gate 1: provenance. An untrusted selector is never eligible,
    # even if the warrant would validate it. This is the invariant
    # that exfiltration defenses do not cover.
    if call.provenance is SelectorProvenance.UNTRUSTED:
        raise ConfusedDeputyError(
            f"selector for {call.tool!r} derived from untrusted channel; "
            f"refusing to construct call under warrant {warrant.jti}"
        )

    # Gate 2: pre-commitment. The selector must be a member of the
    # principal-authored set. Scope-prefix matching is deliberately
    # NOT consulted here; prefix matching is exactly the predicate
    # that path traversal defeats.
    if call.selector not in envelope.committed_selectors:
        raise ConfusedDeputyError(
            f"selector {call.selector!r} not in principal envelope for "
            f"{envelope.principal!r}; model-invented selectors are rejected"
        )

    # Gate 3: audience pinning. The warrant's audience is fixed at
    # issuance; a model-selected audience is warrant laundering.
    if call.tool != warrant.aud:
        raise ConfusedDeputyError(
            f"audience mismatch: warrant aud={warrant.aud!r}, "
            f"call tool={call.tool!r}; audience may not be re-targeted"
        )

    # Gate 4: composition envelope. Each hop may be individually
    # in-scope while the (source, sink) pair is outside the task.
    for prior in prior_calls:
        if (prior.tool, call.tool) not in envelope.allowed_flows:
            raise ConfusedDeputyError(
                f"composition escape: flow {prior.tool!r}->{call.tool!r} "
                f"not in task envelope for {envelope.principal!r}"
            )


# --- Trace that triggers the failure ---
env = TaskEnvelope(
    principal="ops-team",
    committed_selectors=frozenset({"/data/reports/index.json"}),
    allowed_flows=frozenset({("filesystem", "summarize")}),
)
w = Warrant(sub="W", aud="filesystem", scope_prefix="/data/reports", jti="j-8812")

# Model reads a poisoned doc and emits a traversal selector tagged
# untrusted (the runtime must tag it; a runtime that tags it MODEL
# still fails Gate 2, which is the defense-in-depth property).
poisoned = ToolCall(
    tool="filesystem",
    selector="/data/reports/../../etc/agent-secrets/warrant-signing.pem",
    provenance=SelectorProvenance.UNTRUSTED,
)

try:
    admit(env, w, poisoned, prior_calls=())
except ConfusedDeputyError as e:
    # Correct behavior: abort the task, do not return the error to
    # the model as a retryable tool result.
    print(f"ABORT: {e}")
