Skip to content

feat: run OCI containers as lab devices - #45

Open
Frando wants to merge 1 commit into
feat/process-lifetimefrom
feat/containers
Open

Frando wants to merge 1 commit into
feat/process-lifetimefrom
feat/containers

Conversation

@Frando

@Frando Frando commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Description

Based on #101, which makes spawned commands end with the patchbay process. Merge that first.

Integration tests written against patchbay often need an auxiliary service next to the code under test, for example an ACME test server like Pebble, a database or a real DNS server. These are usually easier to run as a container than to embed. This PR runs OCI images with podman as lab nodes, from Rust and from TOML.

Containers as devices

Lab::add_container(name, image) returns a builder that mirrors the device builder for wiring (uplink, iface, default_via, mtu, ipv6_provisioning_mode) and adds container settings on top. It creates the device's namespace and uplink like any device, then runs the image in that network namespace. Other lab devices reach the service at the container's lab IP.

let pebble = lab
    .add_container("pebble", "ghcr.io/letsencrypt/pebble:latest")
    .uplink(net.id())
    .env("PEBBLE_VA_NOSLEEP", "1")
    .volume_ro(config_dir.join("pebble.json"), "/test/config/pebble.json")
    .args(["-config", "/test/config/pebble.json"])
    .ready_tcp(14000)
    .build()
    .await?;

let directory = format!("https://{}:14000/dir", pebble.ip().unwrap());

Device::add_container(name, image) starts a container in an existing device instead. Several containers and the device's own Rust tasks then share one network namespace.

The builder also takes entrypoint, volume/volume_ro (relative host paths resolve on the host), tmpfs, run_arg, pull (PullPolicy::{Missing, Always, Never}) and ready_timeout. Lab::pull_image(image) pulls an image ahead of time, for example before a build from a device task, where the lab namespace has no internet access.

Commands in a container

container.command("sh").args([..]).env(..).workdir(..).user(..) runs a command inside the container with podman exec, in the image's file system. Use output(), spawn() (async) or spawn_sync(). kill() and dropping a running child stop the process inside the container, including background children and processes that ignore SIGTERM or clear their environment. kill() fails if podman itself had to be killed. exec is a shortcut for command(..).output(). Container also has logs, stop, copy_to/copy_from and write_file/read_file.

TOML

A device with a container table runs an image:

[device.web.container]
image = "docker.io/library/nginx:alpine"
ready_tcp = 80

The table also takes args, entrypoint, env, volumes, tmpfs, run_args, pull and ready_timeout_secs. run and spawn steps take container = true to run inside the device's container. Other step kinds reject container and root. Step env, ${...} substitution, captures, asserts and ready_after work as for other steps, and root = true means uid 0 in the container.

Lifetime

The lab owns its containers, as it owns devices and routers. A container runs until Container::stop, Lab::remove_device of its device, or the drop of the last Lab handle. stop also removes the device that Lab::add_container created. Dropping a Container handle does nothing, and Lab::container_by_name returns a handle to any of them.

ready_tcp(port) makes build() wait until the port accepts a connection on the container's lab IP. It fails early if the container exits, and at once if the port is already open before the start, for example from another container in the device.

Runtime and requirements

Containers run with podman, which must be on PATH. Docker cannot do this rootlessly, because its daemon runs in a separate namespace. The host needs the standard rootless-podman setup: newuidmap/newgidmap and /etc/subuid and /etc/subgid entries for the user. Without it, build() fails with an error that names these requirements. containers_supported() reports whether the host can run containers, so tests can skip.

User namespaces

This builds on #94, now in main: init_userns() keeps the caller's uid and maps the ids around it onto the subordinate range.

podman runs in a user namespace nested in patchbay's, laid out like podman's own rootless one: root is the host user, and 1.. are the subordinate ids in host order. Every podman call joins it with the environment of podman's own rootless re-exec. So podman uses the user's normal rootless storage and images, while the patchbay process keeps its uid for the session D-Bus or PipeWire portals. A supported podman flag for this setup is the open request podman-container-tools/podman#7774.

All podman calls share one mount namespace, as rootless podman does with its pause process. Without it, podman exec could not see a container's root file system, and images whose USER is a name failed. The shared namespace has no device DNS overlay, so the container gets the device's /etc/hosts and /etc/resolv.conf as read-only bind mounts. Device::set_host now reaches a running container.

Container root has no capabilities in the lab's network namespaces, so a container cannot change routes or firewall rules. build() sets ip_unprivileged_port_start and ping_group_range in the device, so services can still bind low ports and ping.

Cleanup

  • Normal exit: stop, device removal and lab drop remove the container. The removal runs on a plain thread, so a runtime shutdown cannot cancel it. remove_device first deletes the device's links, so the container is unreachable at once.
  • Failed or cancelled build: podman run is waited for on a thread of its own, and the container is removed after podman exits, also when the device or the lab went away meanwhile. A new device from Lab::add_container is removed too, so the name can be used again.
  • Crash or Ctrl-C: the first build starts a watcher, a sh in podman's namespaces with a process group of its own that ignores SIGINT, SIGTERM and SIGHUP. It blocks reading a pipe that only the patchbay process holds. When that process dies, also on SIGKILL, the watcher runs podman rm -f on the containers with the process's patchbay.owner=<pid>:<start time> label.
  • Watcher killed too, for example when systemd stops the unit: the containers keep running. The guide says how to remove them.

Earlier versions of this PR kept a helper process in the initial user namespace for every patchbay process, with a request protocol and orphan removal across processes. The watcher replaces it with stock podman calls, only in processes that start containers.

Notes

  • The API borrows its shape from testcontainers-rs but stays smaller.
  • Some ideas come from feat: add support for containers #97: containers in existing devices, cleanup when the owner dies, --remote=false on every podman call, entrypoint, and an explicit pull API. feat: add support for containers #97 nests patchbay's namespace inside podman's, which makes the test process uid 0 and breaks portals, so this PR keeps the opposite order.

Testing

  • Unit tests: run arguments, mounts, id-map parsing, the nested map layout, ping_group_range, number-or-string config errors, and parallel namespace creation.
  • Lab tests (skipped without podman or a subordinate id range):
    • nginx answers from another device
    • bind mounts, including relative paths and paths with : or ,
    • file transfer
    • commands in the container: output, env, workdir, a named image USER, kill and drop, also of processes that cleared their environment
    • the DNS files, including entries added after start
    • the lifetime rule and config containers
    • a failed, cancelled or wrongly wired build frees the device name, a build whose device goes away during podman run leaves no container, and removal during runtime shutdown
    • ready_tcp on a port that is already open, a timeout too large for an Instant, and a container that exits before it is ready
    • remove_device cuts the container off at once
    • a build from a device task
  • tests/container_crash.rs: the watcher removes the containers when the owner is SIGKILLed, on Ctrl-C, and when the owner's whole process group is SIGKILLed. Without the watcher, all three fail.
  • A CLI sim test runs a container device, run and spawn steps inside it, and a client device that fetches from it.
  • No containers are left after the suite, and podman's storage stays owned by the user.

🤖 Generated with Claude Code

@Frando
Frando changed the base branch from main to feat/userns-root November 23, 2026 15:38
@Frando
Frando force-pushed the feat/containers branch 3 times, most recently from a11265e to afe7da7 Compare November 24, 2026 18:50
Frando added a commit that referenced this pull request Nov 26, 2026
The hosts and resolv.conf files of the DNS overlay got their mode from
the umask. Under umask 077 they were 0600, and a root command that
switched to another user, such as nobody, could not read them. They are
now 0644, whatever the umask.

The root test runs under umask 077 and reads both files as nobody.

Taken from the container work in #45.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Frando added a commit that referenced this pull request Nov 26, 2026
…s_root() (#94)

## Problem

patchbay had two bootstraps. `init_userns()` mapped the user to uid 0,
which breaks services that check the caller's uid, such as the session
D-Bus and PipeWire portals. `init_userns_keep_uid()` kept the uid, but
then no command could run as root. A process had to pick one, and each
had a libc-only `_for_ctor` twin.

## Approach

One bootstrap, `init_userns()`. The process always keeps its uid and
gid.

If the host has a subordinate id range for the user
(`newuidmap`/`newgidmap` on `PATH`, `/etc/subuid` and `/etc/subgid`
entries), the ids around the user's map onto that range. For uid 1000
and `100000:65536`:

```
1000  1000    1       the user, to itself
0     100000  1000    inner 0..=999
1001  101000  64536   inner 1001..=65536
```

Root, system users and `nobody` exist inside, so a daemon that drops
from root to another user works.

Commands run as root through `Device::as_root()`, `Router::as_root()`
and `Ix::as_root()` (the IX root namespace):

```rust
let child = device.as_root().spawn_command_sync(cmd)?;
```

`as_root()` returns an `AsRoot` handle with `spawn_command` and
`spawn_command_sync`. They set uid and gid 0 on the command. The
patchbay process has `CAP_SETUID` in the namespace, so this needs no
setuid binary. In a sim, `run` and `spawn` steps take `root = true`.

Root is only for spawned commands. The patchbay process already has all
capabilities in the namespace, and glibc applies `setuid` to every
thread, so an in-process "become root" would not be clean.

Without root, the spawn error says why: no subordinate ids, a nested
user namespace (where patchbay does not try the helpers), or the
helpers' own error output. If `newuidmap` or `newgidmap` fails after the
unshare, the bootstrap falls back to the single-id map instead of
leaving the process without a mapping.

`patchbay-cli` now enters the user namespace only for `run` and
`inspect`. `test` and `compare` start cargo, whose test binaries set up
their own namespace. `vm` runs qemu and virtiofsd as the host user.
Before, test binaries under `patchbay test` ran nested, and with this PR
they would have lost root. `run-in` also stays outside: from there the
user owns the inspect session's namespace, so `nsenter` may join it.
Before, it entered its own sibling namespace and `nsenter` failed (also
on main). `run-in` passes `--preserve-credentials` to `nsenter`, so the
command runs as the user and not as root. Where `nsenter` supports
`--keep-caps` (util-linux 2.39 or later), the command also gets the
capabilities of the namespace. With an older `nsenter`, `run-in` warns
and runs the command without capabilities.

The DNS overlay files (`/etc/hosts` and `/etc/resolv.conf` of a device)
now have mode 0644 under any umask. A root command that switches to
another user, such as `nobody`, can then read them. This fix comes from
#45.

## Breaking changes

- `init_userns()` keeps the caller's uid instead of mapping it to 0.
Commands that need uid 0 must be spawned through `as_root()`.
- Sim steps no longer run as root. Steps that need uid 0 (for example
`mount`, `chown`, or tools that check for root) need `root = true`.
`nft`, `tc`, `ip`, `ping` and low ports work without it.
- `init_userns_for_ctor()` is deprecated. It calls `init_userns()`,
ignores the error, and keeps the uid like `init_userns()`. Replace
`unsafe { patchbay::init_userns_for_ctor() }` with `let _ =
patchbay::init_userns();`, which also works from a `#[ctor]`.
- `init_userns_keep_uid()` and `init_userns_keep_uid_for_ctor()` (from
#91) are removed. No release contains them.
- `patchbay test` and `patchbay compare` no longer run cargo inside a
user namespace. Each test binary must call `init_userns()` itself, as
the testing guide shows. Before, a test binary without this call worked
under `patchbay test`.

## Impact

- Root inside the namespace is a subordinate id on the host. Files that
a root command creates outside the lab belong to it, and the user needs
`podman unshare rm` to remove them. The docs say to prefer running as
the user.
- On a host without `/etc/subuid`, there is no root. Labs work as
before.
- The NAT and hairpin tests that already flake on main flake more often
with this change. #95, now on main, fixes the cause (a forked child
briefly holding a closed probe socket).

## Testing

- `tests/userns.rs`: the uid maps to itself and 0, 1 and 65534 exist;
`as_root()` spawns run as uid 0 with the full bounding set and can
switch to `nobody`; the async variant works; plain spawns run as the
user. Root is required where the host is set up for it, unless the test
runs nested (or always with `PATCHBAY_EXPECT_ROOT`, which CI sets). The
root test runs under umask 077 and reads the DNS files as `nobody`. The
deprecated `init_userns_for_ctor()` does nothing after the bootstrap.
- `tests/userns_fallback.rs`: runs its own binary with failing helpers
first on `PATH`: both failing, and only `newgidmap` failing. Checks the
fallback, a working lab, and that the root error carries the helper's
message.
- CLI: a sim with a `root = true` step and a plain step checks both
uids.
- `patchbay-cli/tests/run_in.rs`: starts a real `inspect` session and
runs `run-in` from the initial user namespace. Checks the uid, the
network namespace and `CAP_NET_ADMIN` of the command.
- Checked by hand:
- `patchbay test -p patchbay --test userns` runs the root test for real,
with no helper noise.
- The same binary under `unshare --user` skips root with the nesting
reason.
- `patchbay vm --backend qemu up` works. Files the guest writes to
`/work`, also as guest root, are owned by the user on the host.
- `busctl --user status` and `pw-cli info 0` work from inside the
namespace.
  - `patchbay run` with failing helpers prints the fallback warning.
- `run-in` with an `nsenter` that has no `--keep-caps` warns, and runs
the command as the user without capabilities.
- The lib suite flaked in NAT and hairpin tests more often than on main.
With #95 applied on top, 14 of 14 runs passed. Merged with current main,
the workspace suite passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
`Lab::add_container` wires a new device and runs an OCI image with podman
in its network namespace. `Device::add_container` joins an existing
device instead. In TOML, a device with a `container` table does the same,
and `run` and `spawn` steps take `container = true` to run inside it.

podman runs in a user namespace nested in patchbay's, laid out like
podman's own rootless one, and all podman calls share one mount
namespace. The lab owns its containers like its devices. If the patchbay
process dies without cleanup, also on SIGKILL or Ctrl-C, a watcher shell
in a process group of its own removes the process's containers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Frando
Frando changed the base branch from feat/userns-root to feat/process-lifetime November 26, 2026 14:31

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant