# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-ebpf-tool-hook-policy-is-keyed-on-process-identity-but-the-agent-runtime-multiplexes-concurrent-tool-calls-through-one.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-ebpf-tool-hook-policy-is-keyed-on-process-identity-but-the-agent-runtime-multiplexes-concurrent-tool-calls-through-one.warrant.json
# Markdown SHA-256:   caac67c0282279e46e2f22c68d9361187efa4087b9e3e31f58c5d294da2e245e
# Code AST SHA-256:   5543398370fe75e3e642473253f2e22f9f601a147764e492f73b68b7cfba9c20
# Verified Classes:   EgressWarrantAliasingError, InvocationWarrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EgressWarrantAliasingError(RuntimeError):
    """Raised when an eBPF tool/egress hook cannot resolve a syscall to a
    unique invocation-scoped warrant, i.e. the enforcement key (PID/TGID)
    is coarser than the policy domain (invocation)."""
    pass


class InvocationWarrant:
    def __init__(self, invocation_id: str, allowlist: frozenset[str]):
        self.invocation_id = invocation_id
        self.allowlist = allowlist


def bind_worker_to_invocation(worker_pid: int,
                              warrant: InvocationWarrant,
                              live_bindings: dict[int, str]) -> None:
    """Register an invocation's warrant against a worker PID.

    Refuses to bind if the PID already carries a live binding for a
    *different* invocation with a *different* allowlist. This is the
    guardrail: it converts a silent key-aliasing bug into a loud
    refusal at registration time, before any tool call executes.
    """
    existing = live_bindings.get(worker_pid)
    if existing is not None and existing != warrant.invocation_id:
        raise EgressWarrantAliasingError(
            f"worker pid {worker_pid} already bound to invocation "
            f"{existing!r}; refusing to alias invocation "
            f"{warrant.invocation_id!r} onto the same enforcement key. "
            f"Lease the worker exclusively or key the hook on an "
            f"invocation nonce."
        )
    live_bindings[worker_pid] = warrant.invocation_id


def authorize_egress(worker_pid: int,
                     dest: str,
                     warrants: dict[str, InvocationWarrant],
                     live_bindings: dict[int, str]) -> bool:
    """Hook-side decision. Fails closed if the binding is missing or
    if the resolved warrant does not cover the destination."""
    invocation_id = live_bindings.get(worker_pid)
    if invocation_id is None:
        # Orphaned or unbound worker: default-deny, never default-allow.
        return False
    warrant = warrants.get(invocation_id)
    if warrant is None:
        raise EgressWarrantAliasingError(
            f"binding for pid {worker_pid} references unknown invocation "
            f"{invocation_id!r}; warrant table and binding table diverged."
        )
    return dest in warrant.allowlist


def unbind_worker(worker_pid: int, live_bindings: dict[int, str]) -> None:
    """Must run on every exit path including SIGKILL-adjacent cleanup;
    orphaned entries are the privilege-escalation vector on PID reuse."""
    live_bindings.pop(worker_pid, None)
