Search guides, workflows, and reference pages.

Docs/Tools

container-gateway

Capability: substrate:sandbox

Harness: agnostic

A per-project policy proxy in front of the container daemon socket. Sandboxed shell commands talk to it through CONTAINER_HOST / DOCKER_HOST; it forwards the Docker-compatible API to podman or docker after labelling every resource with the project, filtering every call to that label, and refusing any request that would turn a container into host access. Companion to tools/egress-gateway: that one bounds which hosts tools may reach, this one bounds what containers may touch. The contract (what / why) is in tool.md; this file is the how-to.

Prerequisites

  • Runtime: Python 3.11+ stdlib only; run with python3 -m container_gateway from src/, or uv run --directory tools/container-gateway container-gateway.
  • CLIs: podman and/or docker on the host (each optional); on macOS a running Podman machine or Docker Desktop.
  • Credentials / auth: None. The gateway never reads the machine ssh identity or ~/.config/containers/auth.json, and takes only the currentContext name from ~/.docker/config.json (never auths, credsStore or credHelpers); pulls are anonymous.
  • Network: None of its own. Connects only to the local daemon unix socket and, once at start, probes the egress gateway on loopback.
  • Optional: the dev dependency group (pytest, ruff, mypy); a running egress gateway for the proxy-injection mode.

Run it

One gateway process per project, keyed by the project root. It must run outside the sandbox. It connects to the real daemon socket, which the sandbox denies by design.

uv run --project tools/container-gateway container-gateway serve --project .

It listens on two unix sockets in its run directory: podman.sock (libpod + compat API, for the podman CLI) and docker.sock (compat API, for the docker CLI). The run directory is the run/ subdirectory of the personal config layer: <project>/.apache-magpie-local/run/ when the project has adopted Magpie (it has a committed .apache-magpie.lock), and <git-common-dir>/apache-magpie/run/<worktree-id>/ when it has not — inside the repository’s git directory, never the working tree. The git common directory is <project>/.git in a main checkout and the main checkout’s .git in a linked worktree. <worktree-id> is main for the main working tree and, for a linked worktree, the name of its private git directory (the <name> in .git/worktrees/<name>), which must match [A-Za-z0-9._-]+ — the gateway refuses to serve otherwise. Each worktree therefore runs its own gateway with its own sockets. serve refuses, before creating anything, a socket path longer than the 103 bytes a macOS unix socket allows; pass a shorter --run-dir then. Outside a git repository, a project that has not adopted Magpie has no default: pass --run-dir. Neither the run directory nor the personal layer is ever accepted as a bind-mount source. In a linked worktree of an adopted project both its own .apache-magpie-local/ and the main checkout’s (which it falls back to for configuration) are excluded; the run directory stays the worktree’s own. Configuration is CLI flags with environment-variable equivalents and no config file: --project, --run-dir, --backend podman|docker|auto (repeatable), --egress inject-if-available|require|off, --egress-port, --extra-bind-root (repeatable), --idle-timeout, --log-level, --pid-file. A second start for the same project is a no-op when the pid file names a live process. It exits on SessionEnd, on SIGTERM, or after an idle timeout (default 4h) as a backstop for sessions that end without the hook firing. The session hook’s ensure action, wired as a Claude Code PreToolUse hook on Bash, starts it again before a docker / podman command when it has exited mid-session, so none of these leave a session without a gateway.

Point the CLIs at it

# adopted project
export CONTAINER_HOST=unix://$PWD/.apache-magpie-local/run/podman.sock
export DOCKER_HOST=unix://$PWD/.apache-magpie-local/run/docker.sock
# project that has not adopted Magpie
common=$(cd "$(git rev-parse --git-common-dir)" && pwd -P)
gitdir=$(cd "$(git rev-parse --git-dir)" && pwd -P)
if [ "$gitdir" = "$common" ]; then id=main; else id=${gitdir##*/}; fi
export CONTAINER_HOST=unix://$common/apache-magpie/run/$id/podman.sock
export DOCKER_HOST=unix://$common/apache-magpie/run/$id/docker.sock

The path must be absolute. A unix:// URL’s authority is parsed as a host component, so a project-relative spelling never reaches the socket: unix://./x dials /.//x, unix://x dials /x/, and unix:x dials //.

The podman CLI needs the libpod API and therefore only ever talks to a podman backend. The docker CLI talks to a docker backend when one exists, otherwise to podman’s compat API. Persist these per-machine in .claude/settings.local.json’s env block, and allow the two sockets in sandbox.network.allowUnixSockets, never the real daemon socket.

container-gateway settings prints that block for a project, computed from the same run directory serve binds, so the paths always match. It takes no --run-dir: the block ends up in allowUnixSockets, so the run directory is always the gateway’s default, resolved as serve resolves it and checked as serve and status check it (a symlinked, foreign-owned or group/world-writable component, or a project with no default, exits 2).

uv run --project tools/container-gateway container-gateway settings --project .
uv run --project tools/container-gateway container-gateway settings --project . --apply .claude/settings.local.json

Without --apply it only prints {"proposal": {...}}. --apply merges the block into the named file: it adds the two env keys and two socket entries and keeps everything else; it takes an exclusive flock, re-parses the file under it, and refuses to replace it when what is at the path moved before the write (a different inode, as an editor saving by rename leaves, or a changed mtime or size); it writes and fsyncs a sibling temp file and os.replaces it, keeping the file’s mode; and it refuses a symlinked target, a symlinked directory above it (it creates only that last directory, and works relative to a descriptor of it), or a file that is not a JSON object. A file that already carries the block is not rewritten (status: unchanged). An env key that already holds a different value is never overwritten: it is reported under conflicts and the command exits 3; an unmergeable file exits 2 with nothing written. It never writes the Linux allowAllUnixSockets widening, which is the operator’s decision. /magpie-setup:setup config Step 3h runs it from the operator’s own install under ~/.claude/scripts/container-gateway/src, with the interpreter the hook vets and -I -S (never from a framework checkout, which the agent can edit), applying only on the operator’s yes.

What the policy refuses

The policy is a pure function over the parsed request (method, normalised path, query, JSON body), applied identically to the compat and libpod path families. Every container and pod is labelled with the project slug, and every list / act call is filtered to that label.

The create body, the exec body, the update body and the build query are allow-lists. A create body may carry only the fields the gateway has learned — the ones it reasons about, plus the inert ones a real docker run / podman run sends — and any other key, at the top level or under HostConfig, comes back as unknown-field. The fields that turn a container into host access on their own (rootfs, overlay_volumes, env_host, log_configuration, secret_env / secrets, cni_networks, compat Links / Cgroup / ContainerIDFile / VolumeDriver) are refused with a reason of their own, and only when they carry a value: both CLIs send the zero value of every field on every create.

The create-time rules below apply to containers and pods (the same fields under HostConfig in compat and at top level in libpod):

Field Rule
Privileged deny
CapAdd deny any; CapDrop allowed
Devices, DeviceRequests, DeviceCgroupRules deny
PidMode, IpcMode, UTSMode, UsernsMode, CgroupnsMode deny host and container:<id> unless <id> carries the label
NetworkMode deny host; container:<id> only with the label; named networks must carry the label
SecurityOpt deny seccomp=unconfined, apparmor=unconfined, label=disable, no-new-privileges=false, systempaths=unconfined
Sysctls, CgroupParent, Runtime, Isolation deny
MaskedPaths, ReadonlyPaths deny when set to an empty list
Binds, Mounts[type=bind], libpod mounts source must resolve (symlinks followed, on the host) under the project root or a --extra-bind-root; anything else denied. A writable bind is also denied when its source is, contains or sits under a write-protected path (below); the same bind read-only is allowed. tmpfs allowed
Mounts[type=volume], named volumes in Binds, VolumesFrom the volume / container must carry the label; a volume driver configuration (compat VolumeOptions.DriverConfig, libpod volume-opt=) is refused whatever the driver, since local with type=none,device=/,o=bind is a host-root bind
PortBindings / publish allowed; an empty HostIp is rewritten to 127.0.0.1
LogConfig deny any driver but json-file, local, none or unset; options (--log-opt, compose logging.options) only on json-file / local, and only rotation-shaped keys — path is refused
Env proxy variables injected per the egress rule below; a client-supplied value for the same names is replaced

Write-protected paths. The agent harness refuses sandboxed writes to the files that configure or run code outside the sandbox, but a container is started by the daemon, which the sandbox does not confine. So a bind that is writable is refused when its source is, contains, or sits under any of the paths below — except a writable bind of a checkout root (the project root, an extra bind root, or any directory holding a .git, which covers every worktree), which is split instead: the root is mounted read-only, every child that covers none of these paths gets a writable bind of its own, a child that still covers one is split the same way one level down, and a child that is one of them (or a symlink) stays read-only under its read-only parent. Because the root stays read-only, a container cannot create a protected path that is missing today either. Only binds whose options the split reproduces on every sub-mount are split (rw, z, Z, cached, delegated, consistent; libpod rbind / bind); a split deeper than 6 levels or larger than 512 mounts is refused, and a split that can no longer be computed when the request is rewritten becomes a read-only bind. The protected paths are:

  • .claude/settings.json, .claude/settings.local.json, .claude/hooks, .claude/skills, .claude/commands, .claude/agents and .mcp.json under the project root, under every --extra-bind-root, and under the main checkout of a linked worktree, and inside each worktree under any of those roots’ .claude/worktrees/;
  • the other harnesses’ workspace config in the same places, where each keeps its hooks, MCP servers, plugins, rules or skills (docs/adapters/): .agents/, .agent/, .codex/, .github/hooks/, .github/copilot/, .github/skills/, .gemini/, .grok/, .junie/, .kiro/, .opencode/, opencode.json, opencode.jsonc, .pi/, .cursor/, .aider.conf.yml, and .env (Aider loads it from the git root, and its AIDER_LINT_CMD / AIDER_TEST_CMD run commands);
  • any .claude/worktrees/ directory and what holds it, at any depth, even before any worktree is in it, since one created while the container runs would get its .claude/ and .git from the container; a path in a worktree directory that does not exist yet, which -v would create; and, for an existing worktree at any depth, its own in-tree entries above (a bind inside a worktree that covers none of them is allowed);
  • .git under each of those roots — the directory in a main checkout, the gitdir: file in a linked worktree or submodule;
  • the common git directory’s hooks and config, and a linked worktree’s own git directory (.git/worktrees/<name>), located by following the .git file, which matters when an extra bind root reaches them;
  • the run directory and the personal config layer.

A path counts whether or not it exists yet, since a writable parent could create it. Sources are compared after resolving symlinks, case-insensitively, and by file identity, so neither a symlink nor a .Claude spelling on a case-insensitive file system gets around the check. The set is taken when the gateway starts and recomputed on every request, so rewriting a worktree’s .git file mid-session does not move the real git directory out of view. A bind is read-only when it says so exactly: ro in a Binds entry’s options, ReadOnly: true on a compat mount, ro in a libpod mount’s options, in each case with no rw / ro=false / readonly=false beside it; anything else is writable. A libpod mount’s options go to the runtime as written, and runc reads ro=true or readonly as filesystem data rather than as the read-only flag, so those spellings count as writable. So does U beside ro: podman changes the source’s ownership on the host before mounting, read-only or not. Overlay mounts (O, upperdir=, workdir=) are refused on every bind and volume: their writes land in a host directory the bind rules never see. In practice: -v "$PWD":/src is split (the container can write src/, build/ and everything else that exists, but not /src/.claude/settings.json, not /src/.git, and it cannot create /src/.mcp.json), while -v "$PWD":/src:ro and -v "$PWD/build":/out pass through unchanged and -v "$PWD/.claude":/c is refused. The split does not mask protected paths with overlay mounts, which would have to cover paths that do not exist yet and could be undone by renaming an unmasked parent such as .claude/ or .git/. It keeps the checkout root itself read-only instead, so nothing can be created, renamed or removed directly under it, and only children that cover no protected path become writable. A mount the request itself names below the split’s target wins over the generated ones, and a child whose name holds a : is mounted through a structured Mounts entry (or, with relabelling options a structured mount cannot carry, left read-only).

POST /build gets the same treatment: volume, remote, securityopt, cgroupparent, ulimits, devices, secrets, ssh, session, podman’s addcaps / labelopts / extrahosts, a networkmode outside the keyword set above, an nsoptions entry joining a host namespace other than user, and an output / outputs that names a filesystem destination — a path-shaped bare value, a local / tar / oci exporter, any dest= attribute, anything but type=image / type=registry in the JSON or comma form — are all refused, as is any parameter the gateway has not learned. A build also gets the egress proxy merged into its buildargs, so RUN obeys the same allow-list a container does. A volume create gets the project label and is refused when it names a driver other than local or carries any driver options (compat DriverOpts, libpod options), for the same reason as the mount rule above: a labelled volume can then be mounted by name. An exec body is allow-listed to the exec fields, with Privileged: true refused; an update body to resource limits and the restart policy.

A denial comes back as 403 with a one-line reason both CLIs print verbatim. An inspect of a container, pod, volume or network whose name is not one of the project’s resources is the exception: it answers 404, whether the name is missing or another project’s, because clients probe for a name with an inspect and carry on only after a 404. When the daemon gives no usable answer to the label check, the inspect is refused with 403 like every other call. auth (registry login), image push, swarm, services, tasks, nodes, plugins, secrets, configs, distribution, session and system/dial-stdio are denied outright, along with any path not in the allowed families. So are checkpoint, restore, generate and play (the first two write a host path daemon-side, the last two hand the daemon a Kubernetes manifest), and export / import as query parameters on any route.

Egress modes

At start the gateway resolves the egress gateway address for each backend and probes it once. inject-if-available (the default) injects HTTP_PROXY / HTTPS_PROXY / NO_PROXY into every container it creates when the probe succeeded, and logs one warning per session otherwise. require refuses container creation with 403 while the egress gateway is unreachable. off never injects, for adopters who run their own filtering. This is the extent of the network control. --network host is denied above, but a raw socket or custom DNS from inside a container is not intercepted.

Socket paths

Verification of project-relative socket paths is pending; see the implementation plan’s Task 1. Task 12 records the result here.

Test

uv run --project tools/container-gateway --group dev pytest

Unit tests are table-driven over the policy families and need no backend. Integration tests (-m integration) exercise whichever real backend is installed and auto-skip when none is.

Caveat — containers only, not a container security boundary

The gateway keeps the agent off the daemon socket and off resources outside its own project’s label; it does not harden the container runtime itself. The runtime remains the real boundary between a container and the VM or host kernel. A malicious image that escapes its container is not this gateway’s problem to solve. Network filtering is limited to the proxy-variable injection above; raw sockets and DNS from inside a container are not intercepted.

Limits and residual risks

Known and accepted, in the order you are likely to meet them:

  • An unknown field is refused, so a new daemon feature is unavailable until the gateway learns it. That is the allow-list working as designed; the 403 names the field, which is the signal to add it to policy_shape.py (create / exec / update) or to decisions.py (build query) with a test.
  • The run directory’s trust anchor is --project (resolved), or a custom --run-dir’s own parent (resolved). A symlink in the ancestor chain above that anchor is the host’s own layout — /tmp and /var are symlinks on macOS, a home directory can sit on a linked volume — and is followed, not refused. Below the anchor, every component the gateway itself creates is checked with lstat: a symlink, a foreign owner or a group- or world-writable mode there is refused, and the pid file and the daemon log are opened O_NOFOLLOW regardless.
  • In a linked worktree of a project that has not adopted Magpie, the run directory’s anchor is located from the worktree’s .git file. The gateway verifies that the git common directory it names is owned by the user and not group- or world-writable, holds HEAD and objects/, and that its worktrees/<name>/gitdir links back to this worktree. An agent able to write files can still forge a complete layout of that shape inside directories it can already write, and the check cannot tell it from a real worktree. The consequences are bounded: sockets only land where the agent could already create files, they are reachable only if that exact path is allowlisted in settings the agent cannot edit, and container binds stay limited to the worktree’s own bind roots. To remove the residual risk, pass --run-dir explicitly, or adopt Magpie, which puts the run directory in the worktree itself (.apache-magpie-local/run/).
  • A writable bind of a checkout root is split, not passed through. The container can write everything that exists below the root except the protected paths, but cannot create or delete entries directly under the root, nor anything under a protected directory such as .claude/ or .git. A writable bind of .claude, .git or any other subdirectory that covers a protected path is still refused. Only the listed paths are protected, compared by path and file identity: the target of a symlink inside a protected directory, a hard link to a protected file, a .claude/worktrees/<name> created after the request, other files under .claude/, and other in-tree files that a tool runs later — a Makefile, a git hook directory named by core.hooksPath inside the tree — are as writable through a subdirectory bind as they are to the sandboxed shell.
  • A bind source is checked on the host at decision time and re-resolved by the daemon at mount time. A symlink swapped between those two moments is not caught — the check and the mount are two separate resolutions of the same path, and the gateway holds no lock on the filesystem in between.
  • Images are shared across projects by design. Pull, list, inspect, history, save and build are allowed on any image on the host; only remove and tag are label-checked. A project can therefore see, and run, an image another project pulled.
  • /info, /version and /_ping return host-level daemon facts — the daemon’s version, its storage driver, the number of containers on the whole host — not a per-project view.
  • Container egress is a friction layer, not a wall. The gateway injects proxy variables; a tool that ignores them, or a raw socket, or DNS, goes straight out. RFC-AI-0004 says the same of the permission layer.
  • Backend discovery happens at start. A Podman machine or Docker Desktop started after the gateway is not picked up until the gateway restarts, which normally means the next session.
  • A bare relative build-output value with no leading ., ~ or / (-o outdir) is indistinguishable from an image reference and passes, since it is resolved against the daemon’s own working directory, not a path the agent chose.
Suggest a change