tsbox run: overlayfs, unshare, chroot
The image is on disk after lesson 3: a few directories of files, one per layer. tsbox run has to turn them into a
root file system the process can write to, hide the host from it, and do all of that as a normal user. The first
attempt assembled one long shell string, and a container command containing $(whoami) ran on the host before the
container existed.
The split from functional core, imperative shell is what makes this lesson testable on a Mac.
The core is planRun(spec, paths): it returns data (directories, mounts in order, flags) and never touches the disk. A
second pure function, toUnshareArgv(plan), renders that plan as an argv. The shell, a dozen lines, creates the
directories and spawns the argv. Only the shell needs Linux.
Rootless: user namespaces
Section titled “Rootless: user namespaces”Containers need root-like powers inside: mounting file systems, changing the hostname, being pid 1. Running tsbox as real root would make every container escape a full host compromise. A user namespace gives a process its own idea of user ids. Inside, the process is uid 0; outside, the kernel maps that to your ordinary uid, so “root” in the container owns nothing on the host except what you own.
unshare --user --map-root-user id -u # prints 0, while you are still a normal user--map-root-user writes a one-line map, “inside 0 is outside me, count 1”. With only one uid mapped, a container that
wants several users (the www-data and postgres of real images) cannot have them. Podman solves that with the
newuidmap helper and the ranges in /etc/subuid: a second step for later. This lesson keeps the single mapping.
Namespaces and unshare
Section titled “Namespaces and unshare”unshare runs a program in new namespaces. Each flag hides one part of the host:
| Flag | Namespace | What the container no longer shares |
|---|---|---|
--user |
user | uids and gids (see above) |
--mount |
mount | the mount table: mounts made inside stay inside |
--pid |
pid | process ids: the container sees itself as pid 1 |
--fork |
needed with --pid: the child, not unshare, becomes pid 1 |
|
--uts |
uts | the hostname |
--ipc |
ipc | shared memory and message queues |
The network namespace (--net) is left out on purpose, and the container shares the host’s network. A private
network without root needs a user-space helper (slirp4netns, pasta), a lesson of its own.
overlayfs: layers you can write to
Section titled “overlayfs: layers you can write to”Layers are read-only and shared between containers. A container must still be able to write. overlayfs stacks directories into one view:
lowerdir: the read-only layers, top layer first, separated by:.upperdir: a directory that receives every write, and deletions as marker files.workdir: scratch space the kernel needs on the same file system asupperdir.- the mount target: the merged view, which becomes the container’s root.
mount -t overlay overlay -o lowerdir=/layers/app:/layers/base,upperdir=$C/upper,workdir=$C/work $C/mergedRemoving the container is rm -r $C, and the layers are untouched. Two details are easy to get wrong. The lowerdir
list is split on : and the option string on ,, so a layer path containing either one breaks the mount
(or, if it came from a manifest, injects an option). The kernel documents a backslash escape for :, but the plan
rejects both characters outright, which is safer than escaping. And order matters: reverse the layers and an
old file shadows the new one.
Mounting overlayfs as a normal user inside a user namespace works on recent kernels (5.11 is the version usually cited) with the
userxattr option. On older kernels use fuse-overlayfs, a user-space program that does the same job, and paths.overlay
chooses between them. Detecting which one works is a capability check that lesson 8 turns into a startup decision.
chroot, and why pivot_root is better
Section titled “chroot, and why pivot_root is better”After the mounts, the process needs merged as its /. chroot does that: it changes the root directory for one
program. It is simple and enough for this lesson, but it has known escapes for a process that is root inside the
container. Real runtimes use pivot_root, which moves the old root under a directory (put_old) and makes the new one the root of the mount namespace.
The runtime then unmounts the old root, so the host tree is gone rather than just out of reach. Inside the new mount namespace we also mount a fresh proc
(so ps shows only the container’s processes) and a tmpfs on /dev.
The plan
Section titled “The plan”type Mount = | { readonly _tag: "Overlay"; readonly driver: "kernel" | "fuse"; readonly lower: readonly string[]; readonly upper: string; readonly work: string; readonly target: string } | { readonly _tag: "Proc"; readonly target: string } | { readonly _tag: "Tmpfs"; readonly target: string; readonly options: string }
interface RunPlan { readonly rootfs: string readonly dirs: readonly string[] // created first, in order readonly mounts: readonly Mount[] // applied in order: the overlay must exist before /proc is mounted inside it readonly flags: readonly string[] // unshare flags readonly env: readonly string[] readonly cmd: readonly string[]}
declare const plan: RunPlanfor (const mount of plan.mounts) { switch (mount._tag) { case "Overlay": console.log(mount.lower.join(":")) break case "Proc": case "Tmpfs": console.log(mount.target) break }}A plan is the container’s recipe as a value. A test compares it with toEqual; a future tsbox run --dry-run prints it;
and the code that finally executes it has no decisions left to make.
Rendering without injection
Section titled “Rendering without injection”unshare takes the mount commands as a script for sh -c. Two rules keep data out of code:
- Every path and env entry that appears in the script goes through
shellQuote: wrap in single quotes, and write each'inside as'\''(close the quote, an escaped quote, reopen). Inside single quotes the shell interprets nothing. - The container command is not in the script. It is passed after the script as arguments and used as
"$@".sh -c script name a b cmakes$0 = nameand$@ = a b c, with no re-parsing, the same pattern as lesson 1.
function shellQuote(text: string): string { return `'${text.replaceAll("'", `'\\''`)}'`}
const cmd = ["sh", "-c", "echo $(whoami); 'rm' -rf /"]const script = `exec chroot '/containers/web-1/merged' "$@"`const argv = ["unshare", "--user", "--map-root-user", "--mount", "--", "sh", "-c", script, "tsbox-init", ...cmd]console.log(shellQuote("it's"), argv.length) // 'it'\''s' 12env -i before chroot clears the host’s environment, so the container sees only the variables in the spec
(plus a default PATH): a host AWS_SECRET_ACCESS_KEY must not leak in. Names are checked against
[A-Za-z_][A-Za-z0-9_]* first, because a name containing = or a space would change the meaning of the entry.
Run it for real
Section titled “Run it for real”The shell is small. In podman machine ssh (a Fedora CoreOS VM, Linux, with bun installed there) get a root file
system, run the plan, then look from the inside. The Alpine mini root file system is a single tarball:
podman machine sshmkdir -p ~/layers/alpine && cd ~/layers/alpinecurl -L https://dl-cdn.alpinelinux.org/alpine/v3.20/releases/aarch64/alpine-minirootfs-3.20.3-aarch64.tar.gz | tar -xzUse x86_64 in the URL on an Intel machine. Then the shell, in shell.ts next to your main.ts:
import { mkdirSync } from "node:fs"import { planRun, toUnshareArgv } from "./main.ts"
const spec = { id: "demo", image: "alpine", cmd: ["sh", "-c", "id -u; hostname; ps; echo hi > /note; ls /"], env: {}, limits: {} }const home = process.env.HOMEconst planned = planRun(spec, { root: `${home}/containers`, layers: [`${home}/layers/alpine`], overlay: "kernel" })if (!planned.ok) throw new Error(planned.error)
for (const dir of planned.value.dirs) mkdirSync(dir, { recursive: true })const child = Bun.spawn(toUnshareArgv(planned.value), { stdin: "inherit", stdout: "inherit", stderr: "inherit" })process.exit(await child.exited)bun shell.tsls ~/containers/demo/upper # the "note" file is here; ~/layers/alpine is unchangedExpect 0 for the uid, the hostname of the VM or localhost (we did not change it), and a ps with only a handful of
processes. If mount fails with “wrong fs type” or “permission denied”, the kernel cannot mount overlayfs unprivileged:
install fuse-overlayfs and pass overlay: "fuse". The mount points /proc and /dev must exist in the image: the Alpine mini root file system has them. Nothing here can be proven on macOS: do not expect unshare to exist there.
Exercise
Section titled “Exercise”Local. Copy the starter into the Relay project as main.ts, and the tests next to it. They run anywhere: they only
compare data. The starter wraps strings in double quotes and joins the command into one string, so
nothing is quoted and the plan is ignored.
Implement planRun (validation order is in the starter), shellQuote and toUnshareArgv. The tests check the plan
exactly, the argv exactly (kernel and fuse variants), hostile commands and paths, sorted env, and every error message.
// `tsbox run` must start a container without root. The functional core turns a ContainerSpec into a// RunPlan (plain data: directories, mounts in order, namespace flags, env), and `toUnshareArgv` turns// the plan into the argv of one `unshare` call. A thin shell (shown on the lesson page) creates the// directories and spawns that argv on Linux. Tests here only check data, so they run on macOS.// The first draft built one big shell string: a command containing `$(...)` ran on the HOST.//// Rules:// - planRun(spec, paths) returns Result; errors, checked in this order:// `invalid container id: <id>` (ids match /^[a-z0-9][a-z0-9_-]{0,62}$/), "empty command",// "image has no layers", "layer path cannot contain ':' or ',': <path>" (they would corrupt the// overlay lowerdir list), `invalid env name: <name>` (names match /^[A-Za-z_][A-Za-z0-9_]*$/).// - dirs, in order: <root>/<id>, then upper, work, merged inside it. rootfs is the merged dir.// - mounts, in order: Overlay (lower = paths.layers as given, top layer first; driver = paths.overlay)// on merged, Proc on merged/proc, Tmpfs on merged/dev with options "mode=755".// - flags: --user --map-root-user --mount --pid --fork --uts --ipc, in that order.// - env: "NAME=value" sorted by name, with a default PATH of// /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin that spec.env may override.// - toUnshareArgv(plan) = ["unshare", ...flags, "--", "sh", "-c", script, "tsbox-init", ...cmd].// The script has these lines joined by "\n", every path and env entry wrapped by shellQuote:// set -eu// mount -t overlay overlay -o '<lowerdir=a:b,upperdir=U,workdir=W,userxattr>' '<merged>'// (driver "fuse": fuse-overlayfs -o '<lowerdir=a:b,upperdir=U,workdir=W>' '<merged>', no userxattr)// mount -t proc proc '<merged>/proc'// mount -t tmpfs -o 'mode=755' tmpfs '<merged>/dev'// exec env -i '<NAME=value>' ... chroot '<merged>' "$@"// The command is NEVER part of the script text: it arrives as "$@".// - shellQuote(text): wrap in single quotes; each ' inside becomes '\''.export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export interface ContainerSpec { readonly id: string readonly image: string readonly cmd: readonly string[] readonly env: Readonly<Record<string, string>> readonly limits: { readonly memoryBytes?: number; readonly cpuQuota?: number; readonly pids?: number }}
export interface RunPaths { readonly root: string readonly layers: readonly string[] readonly overlay: "kernel" | "fuse"}
export type Mount = | { readonly _tag: "Overlay" readonly driver: "kernel" | "fuse" readonly lower: readonly string[] readonly upper: string readonly work: string readonly target: string } | { readonly _tag: "Proc"; readonly target: string } | { readonly _tag: "Tmpfs"; readonly target: string; readonly options: string }
export interface RunPlan { readonly rootfs: string readonly dirs: readonly string[] readonly mounts: readonly Mount[] readonly flags: readonly string[] readonly env: readonly string[] readonly cmd: readonly string[]}
export function planRun(_spec: ContainerSpec, _paths: RunPaths): Result<RunPlan, string> { throw new Error("not implemented")}
export function shellQuote(text: string): string { return `"${text}"`}
export function toUnshareArgv(plan: RunPlan): string[] { return ["unshare", "--user", "sh", "-c", plan.cmd.join(" ")]}import { expect, test } from "bun:test"import { planRun, shellQuote, toUnshareArgv } from "./main.ts"import type { ContainerSpec, RunPaths } from "./main.ts"
const spec: ContainerSpec = { id: "web-1", image: "alpine:3.20", cmd: ["echo", "hello world"], env: { ZED: "last", APP_MODE: "prod" }, limits: {},}const paths: RunPaths = { root: "/home/u/.local/share/tsbox/containers", layers: ["/store/layers/app", "/store/layers/base"], overlay: "kernel",}const dir = "/home/u/.local/share/tsbox/containers/web-1"
function planOf(s: ContainerSpec, p: RunPaths) { const plan = planRun(s, p) if (!plan.ok) throw new Error(plan.error) return plan.value}
test("the plan creates upper, work and merged under the container directory, in order", () => { const plan = planOf(spec, paths) expect(plan.dirs).toEqual([dir, `${dir}/upper`, `${dir}/work`, `${dir}/merged`]) expect(plan.rootfs).toBe(`${dir}/merged`)})
test("mounts come in order: overlay first, then proc and dev inside it", () => { expect(planOf(spec, paths).mounts).toEqual([ { _tag: "Overlay", driver: "kernel", lower: ["/store/layers/app", "/store/layers/base"], upper: `${dir}/upper`, work: `${dir}/work`, target: `${dir}/merged`, }, { _tag: "Proc", target: `${dir}/merged/proc` }, { _tag: "Tmpfs", target: `${dir}/merged/dev`, options: "mode=755" }, ])})
test("rootless flags: a user namespace mapping us to root, plus mount, pid, uts and ipc", () => { expect(planOf(spec, paths).flags).toEqual(["--user", "--map-root-user", "--mount", "--pid", "--fork", "--uts", "--ipc"])})
test("env is sorted by name and gets a default PATH that the spec can override", () => { expect(planOf(spec, paths).env).toEqual([ "APP_MODE=prod", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "ZED=last", ]) expect(planOf({ ...spec, env: { PATH: "/opt/bin" } }, paths).env).toEqual(["PATH=/opt/bin"])})
test("the unshare argv, exactly", () => { const argv = toUnshareArgv(planOf(spec, paths)) const script = [ "set -eu", `mount -t overlay overlay -o 'lowerdir=/store/layers/app:/store/layers/base,upperdir=${dir}/upper,workdir=${dir}/work,userxattr' '${dir}/merged'`, `mount -t proc proc '${dir}/merged/proc'`, `mount -t tmpfs -o 'mode=755' tmpfs '${dir}/merged/dev'`, `exec env -i 'APP_MODE=prod' 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' 'ZED=last' chroot '${dir}/merged' "$@"`, ].join("\n") expect(argv).toEqual([ "unshare", "--user", "--map-root-user", "--mount", "--pid", "--fork", "--uts", "--ipc", "--", "sh", "-c", script, "tsbox-init", "echo", "hello world", ])})
test("fuse-overlayfs is used when the kernel overlay is not available", () => { const argv = toUnshareArgv(planOf(spec, { ...paths, overlay: "fuse" })) const script = argv[argv.indexOf("-c") + 1] ?? "" expect(script.split("\n")[1]).toBe( `fuse-overlayfs -o 'lowerdir=/store/layers/app:/store/layers/base,upperdir=${dir}/upper,workdir=${dir}/work' '${dir}/merged'`, ) expect(script.includes("userxattr")).toBe(false)})
test("the command is passed as arguments, never spliced into the script", () => { const nasty = ["sh", "-c", "echo $(whoami); 'rm' -rf /"] const argv = toUnshareArgv(planOf({ ...spec, cmd: nasty }, paths)) const script = argv[argv.indexOf("-c") + 1] ?? "" expect(script.includes("whoami")).toBe(false) expect(argv.slice(-4)).toEqual(["tsbox-init", ...nasty])})
test("paths and env values with quotes are quoted, not interpreted", () => { expect(shellQuote("it's here")).toBe(`'it'\\''s here'`) const odd = toUnshareArgv(planOf({ ...spec, env: { MSG: "a'b; reboot" } }, { ...paths, root: "/data/my dir" })) const script = odd[odd.indexOf("-c") + 1] ?? "" expect(script.includes(`'MSG=a'\\''b; reboot'`)).toBe(true) expect(script.includes(`'/data/my dir/web-1/merged/proc'`)).toBe(true)})
test("bad input is an error value, not a plan", () => { expect(planRun({ ...spec, id: "../etc" }, paths)).toEqual({ ok: false, error: "invalid container id: ../etc" }) expect(planRun({ ...spec, cmd: [] }, paths)).toEqual({ ok: false, error: "empty command" }) expect(planRun(spec, { ...paths, layers: [] })).toEqual({ ok: false, error: "image has no layers" }) expect(planRun(spec, { ...paths, layers: ["/a,b"] })).toEqual({ ok: false, error: "layer path cannot contain ':' or ',': /a,b", }) expect(planRun({ ...spec, env: { "BAD-NAME": "x" } }, paths)).toEqual({ ok: false, error: "invalid env name: BAD-NAME" })})- Rootless means a user namespace: root inside, your uid outside.
unshareflags choose what to hide: mounts, pids, hostname, ipc. Networking needs a helper and is left out.- overlayfs stacks read-only
lowerdirs (top first) under a writableupperdir, and the merged view is the root. chrootis enough here;pivot_rootis what real runtimes use.- Build the recipe as data (
RunPlan), render it with quoted paths and the command as"$@", then execute it in a thin shell.
Further reading
Section titled “Further reading”- Overlay Filesystem (Linux kernel): lowerdir, upperdir and workdir.
- unshare(1): the namespace flags used here.
- pivot_root(2): how real runtimes switch the root.