Add --publish: the one ingress control

Everything else in the file gates egress, which left an everyday request unanswered: the
agent starts a dev server inside the sandbox and a human wants to look at it. This puts a
listener on the host that forwards into the container, so a browser, curl or an API
tester reaches the server the sandboxed process runs.

`--publish [ADDR:]HOST:CONTAINER`, config `publish` and AISB_PUBLISH, repeatable, with the
cost named in the flag: it is ingress, so whatever that server serves is reachable from
the address it binds. The default address is 127.0.0.1 because a bare podman -p binds
every interface (measured) -- a port committed in a repo config must not quietly be a port
on the LAN. publish_addr changes the default machine-wide; a spec with a non-loopback
address warns on every run. The grammar is smaller than podman's on purpose: one port per
entry, no ranges, no /udp, no `*` -- this list is reviewed line by line, and typing
0.0.0.0 is the whole warning. An address means three parts, so `127.0.0.1:8000` is refused
rather than guessed. No -p alias: that flag belongs to the harness (claude -p prints).

Fail closed, as elsewhere: --net none cannot forward a port and podman discards the
mapping while starting the container anyway, so "it ran" would mean "nothing is
listening"; a host port already in use is named before the container starts, not after a
build; pick_port() will not hand the gate a port this run publishes. The container is
labelled with the ports it was given, and doctor reports them.

Inside, publish_rules() accepts tcp on the published ports in the input chain and never
the output one. Measured (docs/networking.md): pasta delivers the connection over
loopback, so that rule counts 0 packets on the reference host; it is there for a host or a
bridge network that delivers on the interface, and so that `nft list table inet aisb`
answers "what can reach this container". The ports are validated again inside the
entrypoint, because a ruleset is not somewhere to splice an unvalidated string. And the
measurement that makes a configured preview look broken: a server bound to 127.0.0.1
inside answers inside and refuses the published port outside, so dev servers must bind
0.0.0.0 -- both skills say so in the change that writes the port.

Tests. Unit: the grammar and every port list that looks right and is not, config/env/flag
precedence and dedup, the canonical spec in --print-policy, the `# ingress:` header, the
flags reaching the invocation before the image, egress enforcement byte-identical with a
port open, which chain the rule lands in and that a non-numeric port never reaches nft as
code. e2e (tests/e2e/13_publish.sh): one real container with enforce=nft where the host
gets its 200 and the same run still refuses a domain outside the allowlist at 403, the
server runs as uid 1000 with no capabilities so it cannot widen its own port, and the host
listener is gone when the container exits.

LLM-Generated: true
This commit is contained in:
2026-10-30 22:53:57 -04:00
parent ac2f310d10
commit 144e322391
21 changed files with 993 additions and 79 deletions
+7 -5
View File
@@ -83,14 +83,14 @@ Not for an explanation, unless the user asked about the machine and agrees:
| topic | fact |
|---|---|
| precedence | built-in default < `~/.config/ai-sandbox/{config,allow}` < `./.ai-sandbox/{config,allow}` < `AISB_*` < CLI. `allow/env/mount/install/label` accumulate; other keys replace |
| precedence | built-in default < `~/.config/ai-sandbox/{config,allow}` < `./.ai-sandbox/{config,allow}` < `AISB_*` < CLI. `allow/env/mount/install/label/publish` accumulate; other keys replace |
| arg parsing | stops at the first positional or unknown flag; the rest goes **to the harness**. `--` replaces the command. `--strict-args` makes an unknown flag an error |
| default net | `allow`, and an empty allowlist in `allow` mode is a hard error, never a silent free-for-all |
| enforcement | two stacked controls: an in-container `inet aisb` nft table with `policy drop` on output, installed by the entrypoint as root before it `setpriv`s to uid 1000 with no capabilities, plus a squid gate on the host loopback that filters by domain at CONNECT |
| refusals | exit **77** ruleset could not be installed; **78** policy file missing in the container. Both are the sandbox working; `--allow-unenforced` is the named escape hatch |
| gate ports | squid relays only **80, 443, 8443**; `--allow domain:8080` is not what it looks like. IP/CIDR entries are direct netfilter rules instead (default ports 80,443) |
| host services | `100.64.0.1` (config: `gate_addr`) inside the container *is* the host's loopback; only the gate's port is reachable through it unless you `--allow 100.64.0.1:<port>` |
| inbound | there is no publish flag, and in `--net allow` the generated ruleset's input chain is `policy drop` too, so a `-p` pushed through `extra_args` is dropped inside. That last half is a reading of `gen_rules()`, not a measurement — probe it (right-sandbox's `references/port-and-loopback.md`) before promising a preview URL |
| inbound | `--publish [ADDR:]HOST:CONTAINER` (config `publish`, `AISB_PUBLISH`): forwards a host port into the container. Bound to **127.0.0.1** unless the spec names an address (podman's bare `-p` binds every interface, measured), one port per entry, an address needs three parts, `--net none` refuses instead of starting with nothing listening, a busy host port is named before the build. The server must listen on `0.0.0.0` **inside**: a loopback-only server answers inside and refuses the published port (measured). Ingress only — egress enforcement is untouched in the same run |
| filesystem | cwd mounted rw **at its host path** (falls back to `/project` with a message when the host path would bury `/tmp`, `/usr`, `/etc`, `/var`, `/opt`, `/run`, the container home, or `/`); nothing else is mounted except the `.agents` share and the read-only policy mount at `/run/aisb` |
| the container user | uid/gid 1000, the image's own `sandbox` account, `$HOME` = its home (`--userns=keep-id`, so files the agent writes are owned by *you* on the host). Skills land at `~/.agents` on both sides and they are different directories |
| skills | host `~/.agents` → the container's `~/.agents` (`agents_dest`) **read-only**, no flag makes it writable; `--no-agents` to withhold it, `--agents-dir` for another directory. Its contents are readable by whatever runs in there |
@@ -105,9 +105,11 @@ Not for an explanation, unless the user asked about the machine and agrees:
Say it plainly, then give the closest real thing:
* "publish a port" → no; run the server on the host (the mount is your disk), or one named
`--net full` preview run with `AISB_EXTRA_ARGS=-p …` and an explicit warning that that run has no
egress policy.
* "publish a port on my network so my phone can see it" → not as a committed setting.
`--publish 0.0.0.0:18080:8000` exists and warns on every run, because that is the sandbox becoming
a server on the LAN; `publish = 8000` (loopback) is the setting a repo file should carry. The old
answer — `AISB_EXTRA_ARGS=-p …` with `--net full` — buys nothing that `--publish` does not, and it
costs the egress policy.
* "make the sandbox able to write my skills" → no, by design: a skill is an instruction you follow
later on the host. Author it in the project and move it yourself.
* "let the pipeline push from inside the sandbox" → no: an agent that can push can ship what you are
@@ -7,8 +7,8 @@ not** — grep for these in the installed script (`readlink -f "$(command -v ai-
| question | read |
|---|---|
| "what does `--x` do / does it exist" | `usage()` (grouped by NETWORK / FILESYSTEM / ENVIRONMENT / IMAGE / PI CONFIG / LIMITS / RUN / ESCAPE HATCHES / SUBCOMMANDS), `parse_args()`, and `KNOWN_OPTS` + `suggest()` for the accepted set |
| "which config keys are legal" | `cfg_read_kv()` — the `case` lists them, the accumulate list is `cfg_accum_keys` (`allow env mount install label`). Anything else warns `unknown key` and is ignored |
| "what does `--x` do / does it exist" | `usage()` (grouped by NETWORK / PORTS (INGRESS) / FILESYSTEM / ENVIRONMENT / IMAGE / PI CONFIG / LIMITS / RUN / ESCAPE HATCHES / SUBCOMMANDS), `parse_args()`, and `KNOWN_OPTS` + `suggest()` for the accepted set |
| "which config keys are legal" | `cfg_read_kv()` — the `case` lists them, the accumulate list is `cfg_accum_keys` (`allow env mount install label publish`). Anything else warns `unknown key` and is ignored |
| "what wins, my flag or the file" | `resolve_opts()` — every line is `${OPT_x:-${AISB_X:-$(cfgv x default)}}`: CLI, then env, then config, then default. `load_config()` shows the file order |
| "`AISB_*` variables" | the comment block above `usage()` and `--help`'s ENVIRONMENT section |
| "why did arg parsing eat my harness flag" | `parse_args()` stops at the first positional/unknown; `--` sets `COMMAND`; `--strict-args`; `default_command()`/`harness_argv()` decide what actually runs |
@@ -25,6 +25,8 @@ not** — grep for these in the installed script (`readlink -f "$(command -v ai-
| gate lifecycle / ports / reuse | `pick_port()`, `gate_up()`, `teardown()`, `cmd_gate()`; `AISB_GATE_KEEP=1`; `gate_port`/`gate_addr` | `ai-sandbox gate status` |
| `--no-gate` vs `--proxy` vs the gate | `resolve_proxy_endpoints()` — `--proxy` uses your proxy (default port 3128); `--no-gate` resolves domains once on the host, opens DNS and warns; default is the built-in gate | `--dry-run` (the `HTTP(S)_PROXY` args) |
| host-loopback / `100.64.0.1` | `build_argv()`'s `--network=pasta:--map-host-loopback,${gate_addr}` and the `NO_PROXY` defaults | `docs/networking.md`'s measurement table |
| "can I see the server the sandbox is running" / what `publish` means | `resolve_publish()` (the grammar, the loopback default `publish_addr`, the refusals), `build_argv()`'s `--publish` + `aisb.publish` label, `write_policy_files()`'s `AISB_PUBLISH_PORTS`, and `publish_rules()` in the entrypoint. `pick_port()` skips published host ports | `--dry-run`'s `# ingress:` line; `docs/networking.md` "Publishing a port"; `tests/e2e/13_publish.sh` (host reaches it, egress still refused, loopback-only server inside does not answer, busy port refuses the run) |
| "does publishing weaken the sandbox?" | It is ingress only: the output chain, the gate and the allowlist are untouched, and the mapping is decided on the host before the container starts — the command has no `CAP_NET_ADMIN` and cannot add or widen a port | `tests/unit/06_entrypoint.sh` (the rule lands in `input`, never `output`), `tests/e2e/13_publish.sh`, threat model #14 |
| "is my machine able to do this" | `cmd_doctor()`, `tests/spike_network.sh` | `ai-sandbox doctor --deep` |
## Filesystem, mounts, the working directory
@@ -89,7 +91,10 @@ not** — grep for these in the installed script (`readlink -f "$(command -v ai-
`gate up` is the explicit long-lived exception.
* **ruleset** — the `inet aisb` nft table installed inside the container's namespace: output
`policy drop` with room for loopback, established/related, ICMP, the direct IP entries, the gate's
address:port, and DNS only in `--no-gate` mode. Input `policy drop` too, so nothing is published in.
address:port, and DNS only in `--no-gate` mode. Input is `policy drop` as well, accepting loopback,
established/related, a few icmpv6 types and — since `publish` exists — the tcp ports the host
forwards in (`aisb-publish`). Measured on the reference host pasta delivers those over loopback, so
that rule carries 0 packets there and does the work on a host that delivers on the interface.
* **`POL[...]` / `P_*` / `OPT_*` / `CFG_*`** — resolved policy / resolved lists / raw CLI flags /
config-file values. Reading raw env vars elsewhere is the bug pattern; a helper called as
`X="$(helper)"` runs in a subshell, so any `POL[..]` it sets is discarded.
@@ -112,6 +117,9 @@ not** — grep for these in the installed script (`readlink -f "$(command -v ai-
| How do I let it push? | You don't, from inside. `--allow github.com` + `--env GH_TOKEN` or `--mount ~/.ssh:ro` does it, and the threat model explains the price. For pipelines, run `ai-sandbox-autophase`, which pushes on the host. |
| How do I see what the gate allowed? | `ai-sandbox gate logs` (and `gate status`, `gate down`). Don't put secrets in URLs: the gate sees what flows through it. |
| A stale container home after a rebuild? | It is the `aisb-home` volume. `ai-sandbox clean --volumes[=GLOB]`, or `--ephemeral-home` per run. |
| How do I see the dev server the sandbox runs? | `--publish 8000` (config `publish = 8000`): host `127.0.0.1:8000` → container `8000`, warned if you name a non-loopback address. The server inside must bind `0.0.0.0` — a `127.0.0.1`-only server answers inside and refuses the published port (measured). `--net none` refuses to publish, because podman drops the mapping there and starts anyway. |
| Is a published port a security hole? | It is ingress you asked for: whatever that server serves is reachable from the address it is bound to, for as long as the run lasts. Loopback by default (podman's bare `-p` binds every interface), no ranges, the agent cannot open or widen one, egress enforcement is untouched. Threat model #14. |
| How does the sandbox reach a database on my machine? | That is egress, not `publish`: `allow = 100.64.0.1:<port>` (and a `NO_PROXY` entry when it is HTTP on an unusual port). `publish` points the other way. |
| How do I refresh the base? | `ai-sandbox update --check` then `ai-sandbox update` (or `build --refresh-base`). TTL re-resolves a digest, it never downloads on a preview. |
| Do `--dry-run`/`--print-*` touch the network? | No — that determinism is deliberate. `inspect` is the one that asks the machine now. |
| Is the container root? | It starts root with `CAP_NET_ADMIN` just long enough to install the ruleset, then `setpriv` to uid 1000 with no capabilities and `no-new-privileges`. `--insecure-keep-root` is the opposite. |
+33 -13
View File
@@ -1,6 +1,6 @@
---
name: right-sandbox
description: Analyzes a project directory and writes that project's ai-sandbox policy — .ai-sandbox/allow plus .ai-sandbox/config (egress allowlist, environment variable names, bind mounts, working directory, resource limits, harness, extra image packages, access to services on the host) — so that a plain `ai-sandbox` run in the directory is the correct, reviewable invocation. Use when the user asks to set up, configure, write, fix, review or tighten ai-sandbox or the sandbox for a project, wants a .ai-sandbox config committed with the code, or asks why a sandboxed agent cannot reach a package registry, a database, a localhost port or its model gateway. Writes policy files only — never builds, never starts a container, never puts a credential value in a file.
description: Analyzes a project directory and writes that project's ai-sandbox policy — .ai-sandbox/allow plus .ai-sandbox/config (egress allowlist, environment variable names, bind mounts, published ports so a local web server can be run and previewed from the host, working directory, resource limits, harness, extra image packages, access to services on the host) — so that a plain `ai-sandbox` run in the directory is the correct, reviewable invocation. Use when the user asks to set up, configure, write, fix, review or tighten ai-sandbox or the sandbox for a project, wants a .ai-sandbox config committed with the code, wants to run a dev server or expose a port from inside the sandbox, or asks why a sandboxed agent cannot reach a package registry, a database, a localhost port or its model gateway. Writes policy files only — never builds, never starts a container, never puts a credential value in a file.
---
# right-sandbox
@@ -73,6 +73,7 @@ made deliberately.
| package installs | lockfiles (`pnpm-lock.yaml`, `uv.lock`, `Cargo.lock`, `go.sum`, `Gemfile.lock`, `pom.xml`…) | `allow` entries for the registries that ecosystem really contacts — see the table in `references/settings-map.md` |
| model gateway | `~/.pi/agent/models.json` `baseUrl` host, or the base URL the user's harness is configured with | `allow = <gateway host>`; without it a bridged pi starts and cannot answer |
| a database / queue / cache | `docker-compose*.yml` published ports, `.env` URLs, `DATABASE_URL` | `allow = 100.64.0.1:<published port>` + an env var that points the app at `100.64.0.1` — see `references/port-and-loopback.md` |
| a server the project runs, to be seen from the host (dev server, storybook, API docs, a preview the agent should be able to start *and* drive) | `scripts.dev` / `start` in `package.json`, `vite.config.*`, `manage.py runserver`, `uvicorn …`, a `Dockerfile` `EXPOSE`, the port in the project's own README | `publish = <port>` (loopback by default) — ingress, not an `allow` line. `references/port-and-loopback.md` has the bind-`0.0.0.0` requirement, which is what makes the difference between configured and working |
| a non-HTTP backend | pinned host:port (a LAN inference box, an internal API) | `allow = <ip or cidr>:<port>` (IP/CIDR become netfilter rules; domains go through the gate) |
| credential the harness needs | `.env.example`, CI `secrets.*`, `--env NAME` in the user's launcher | `env = NAME` (name only), and list what the user must export |
| reference material / sibling repo | imports or docs that read `../something` | `mount = ../something:/something:ro` |
@@ -128,6 +129,10 @@ env = @./.ai-sandbox/env
# apt packages the test suite needs that the image lacks
install = postgresql-client
# ingress: the dev server this project runs, previewable on the host at
# http://127.0.0.1:8000 (loopback only; the server binds 0.0.0.0 inside)
publish = 8000
```
`env = @path` is the config-file form of `--env-file` (`--env-file F` becomes the entry `@F`), so
@@ -150,6 +155,9 @@ to put in it.
opened**; weaker for CDNs and rotating IPs. `--proxy host:port` uses a proxy you already run
(default port 3128). Neither belongs in a committed config without a comment justifying it.
* An empty allowlist in `allow` mode is a hard error. Never "fix" that by widening net.
* `publish` is the one **ingress** key and it is not an allow entry: `allow = 100.64.0.1:5432` lets
the sandbox reach your machine, `publish = 5432:5432` lets your machine reach the sandbox. Writing
the wrong one of these is how a service ends up open on the wrong side.
## 5. Verify (no builds, no containers, no network)
@@ -176,7 +184,10 @@ Check, in this order, and fix the files instead of explaining the output:
4. `mounts=` and `agents=` are what you wrote and nothing more.
5. the dry run shows `--network pasta:--map-host-loopback,100.64.0.1`, `--cap-drop=ALL`,
`--security-opt no-new-privileges`, `--userns keep-id:…` and no secret values.
6. `--print-policy | grep -i` for each credential name from §1: the *name* may appear, a *value*
6. if you wrote `publish`: the `# ingress: publish=[…]` line shows `127.0.0.1` on every entry unless
the user asked for an address, and the project's dev command binds `0.0.0.0` — a published port
pointing at a `127.0.0.1`-only server is configured, silent and useless.
7. `--print-policy | grep -i` for each credential name from §1: the *name* may appear, a *value*
must not.
Then, with the user watching (this builds the image the first time and starts a container):
@@ -184,12 +195,14 @@ Then, with the user watching (this builds the image the first time and starts a
```bash
ai-sandbox --shell # egress, mounts, env present
ai-sandbox --net none -- make test # the offline half of the toolchain
ai-sandbox doctor # host readiness
ai-sandbox doctor # host readiness, incl. the ports it would publish
```
Probe the two or three endpoints the project actually needs from inside (`curl -sS -m 5 -o
/dev/null -w '%{http_code}\n' https://registry.npmjs.org/`) rather than assuming an allowlist entry
means a working toolchain.
means a working toolchain. If you wrote `publish`, probe the other direction too, from the host,
while a sandbox is still running (`references/port-and-loopback.md` §2 has the two-shell probe): a
published port nobody answered during the review is not a verified setting.
## 6. Report
@@ -198,19 +211,26 @@ Finish with exactly these five points, so the user can act without reading the f
1. **Files written** — paths, plus the `.gitignore` change if any.
2. **`cd <dir> && ai-sandbox`** is now the invocation (and the alias note if they use one).
3. **What they must export** first (`env =` names that are unset), and where values may go.
4. **What is deliberately not allowed** — the git remote first, then anything you declined to open
because the honest answer was "not without weakening the sandbox" (inbound port publishing is
usually on this list).
4. **What is deliberately not allowed, and what is open** — the git remote first, then anything you
declined to open because the honest answer was "not without weakening the sandbox". If you wrote
`publish`, name each port, its host address and what listens there: an open port belongs in the
report even though it was requested.
5. **What you verified and how** — the two preview commands and any live probe, with results.
## Ports, localhost, "the app must be reachable"
Read `references/port-and-loopback.md` before promising anything about ports. Short version: a
sandboxed process reaches *services on your machine* through the mapped loopback address
`100.64.0.1`, which needs an `allow` entry **and** a client that does not send that request to the
egress proxy; and a port the sandbox listens on is **not** reachable from the host in `--net allow`
mode, because the generated ruleset's input chain is `policy drop`. Verify on the machine rather
than repeating that from memory — the file has the probes.
Read `references/port-and-loopback.md` before promising anything about ports. Two directions, two
settings, and the wrong one is how a service ends up open on the wrong side:
* **the sandbox → a service on your machine**: `allow = 100.64.0.1:<port>` (the mapped loopback
address), plus a client that does not send that request to the egress proxy.
* **your machine → the sandbox**: `publish = <port>`, bound to `127.0.0.1` unless the spec names an
address. It is ingress: egress enforcement is untouched by it, and the agent inside cannot open or
widen a port of its own. The server has to bind `0.0.0.0` *inside* — that is the difference between
a configured preview and a working one, and it is measured, not folklore.
Verify on the machine rather than repeating any of this from memory: `--dry-run` shows
`# ingress: publish=[…]`, and `tests/e2e/13_publish.sh` is what the claims rest on.
## References
@@ -2,10 +2,14 @@
Two separate problems wear the same name. Get the direction right before touching a config.
| | what it is | possible in `--net allow`? |
|---|---|---|
| **outbound** | the sandboxed process reaches a service running on your machine (dev postgres, redis, a mock API, a local model server) | **yes** — one allow entry, sometimes plus a proxy bypass |
| **inbound** | your browser on the host reaches a server the sandbox started | **no** — the generated ruleset drops it; three workarounds below |
| | what it is | how | direction |
|---|---|---|---|
| **outbound** | the sandboxed process reaches a service running on your machine (dev postgres, redis, a mock API, a local model server) | `allow = 100.64.0.1:<port>` — an ordinary allow entry | egress |
| **inbound** | your browser on the host reaches a server the sandbox started | `publish = <port>` / `--publish` | ingress |
They are not the same setting and one does not imply the other. `allow = 100.64.0.1:5432` does not
open a port; `publish = 5432:5432` does not allow egress. Getting these backwards is how a database
ends up reachable from the wrong side.
Container-to-container is a third case, already measured on the reference host: two containers on a
shared user-defined network **cannot reach each other**, so do not design a sidecar proxy, a
@@ -66,54 +70,141 @@ env = DATABASE_URL=postgresql://dev@100.64.0.1:5432/app_dev
If `100.64.0.1` collides with a real network the project must reach, change `gate_addr` (and
remember the gate itself is reached at that address too).
## 2. Inbound: "I want to see the app the agent is building"
## 2. Inbound: publishing a port the sandbox listens on
There is **no publish flag** (`--publish`/`-p` are not in `parse_args()`). You can push one through
the escape hatch — `extra_args = -p 8000:8000` or `AISB_EXTRA_ARGS="-p 8000:8000"` — and then read
the ruleset the entrypoint installs: the `input` chain is `policy drop` with room only for `lo`,
`established,related` and a few icmpv6 types, so a fresh inbound connection is dropped inside the
container. Confirm on the machine instead of trusting that reading:
`--publish` (config key `publish`, repeatable) forwards a host port into the container, so a client
on the host — a browser, curl, an API tester — reaches a server the sandboxed process runs. It is
the only ingress setting in the tool, and the ruleset names the ports it opened
(`nft list table inet aisb` → the `aisb-publish` rule).
```bash
AISB_EXTRA_ARGS="-p 8000:8000" ai-sandbox --shell
# inside: python3 -m http.server 8000 &
# host: curl -sS -m 3 -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/
Shapes, and what they bind. **The default address is `127.0.0.1`**, because a bare podman `-p` binds
every interface (measured) and a port in a committed config must not quietly be a port on the LAN:
| spec | host side | container side |
|---|---|---|
| `8000` | `127.0.0.1:8000` | `8000` |
| `18080:8000` | `127.0.0.1:18080` | `8000` |
| `0.0.0.0:18080:8000` | every interface — **warns on every run** | `8000` |
| `[::1]:18080:8000` | ipv6 loopback | `8000` |
Rules the parser enforces, and the reasons to repeat them to the user:
* **One port per entry.** No ranges, no `/udp`: this list is reviewed line by line, and a range is a
line nobody reads.
* **An address means three parts.** `127.0.0.1:8000` is refused rather than guessed at.
* **`--net none` refuses to publish.** Measured: podman discards port mappings there with one line on
its own stderr and starts the container anyway, so "it ran" would mean "nothing is listening".
* **A busy host port is named before the container starts**, not after a build. Suggest
`publish = <other>:<container>` rather than telling the user to go find `ss` output.
* **No `-p` flag.** `-p` passes through to the harness (`claude -p` prints), which is deliberate.
* **No `*`.** podman's shorthand for "every interface" is refused; write `0.0.0.0`. Typing the address
is the warning.
### The one thing that makes a published port look broken
**The server has to bind `0.0.0.0` inside the container.** Measured: a server bound to
`127.0.0.1` inside answers `200` from inside and refuses the published port from the host, because
pasta delivers the connection to the container's own address, not to its loopback. So the config is
not enough — the project's dev command has to cooperate:
| stack | what the preview command needs |
|---|---|
| vite | `npm run dev -- --host 0.0.0.0` |
| Next / webpack dev servers | `--hostname 0.0.0.0` |
| Django | `runserver 0.0.0.0:8000` |
| Flask | `flask --app … run --host 0.0.0.0 -p 8000` |
| uvicorn / FastAPI | `uvicorn --host 0.0.0.0 --port 8000 …` |
| a bare static server | `python3 -m http.server 8000 --bind 0.0.0.0` |
A dev-server config file that pins `host: 127.0.0.1` (`vite.config.*`, `webpack-dev-server`,
`gunicorn -b 127.0.0.1:8000`) needs that changed, or the preview command overrides it on the command
line. Say which, or the user will conclude the sandbox is broken.
### What publishing does not do
* **It does not weaken egress.** The same run answers the host and still refuses every domain
outside the allowlist; the entrypoint still drops all capabilities before the command runs.
`tests/e2e/13_publish.sh` asserts both halves in one container, so this is not a claim to re-derive.
* **It does not let the agent open more ports.** The mapping is decided on the host before the
container starts; inside, the command has no `CAP_NET_ADMIN` and cannot add or widen one.
* **It does not survive the run.** The listener is pasta's, removed with the container. If a port is
still bound afterwards, something was started with `--keep` — `ai-sandbox ps`, `ai-sandbox clean`.
### What to write, and what not to
Loopback publishing is a legitimate project setting: it says "this project runs a server on this
port, and previewing it is part of working on it".
```ini
# .ai-sandbox/config
publish = 8000 # the app: http://127.0.0.1:8000
publish = 18080:3000 # the storybook, on a host port that is free
```
Expected on a stock host in `--net allow`: no answer. If yours answers, that is a fact worth adding
to `docs/networking.md` — measure and report it, do not build the workflow on it.
Comment each one with what runs there — a port without a name is a port a later reader cannot
remove. Do **not** commit:
What to tell the user instead, in order of preference:
* a **non-loopback** address (`0.0.0.0:…`, `192.168.x.x:…`). It warns on every run because it means
what it says: anything that can route to the machine can reach whatever the sandbox serves. If the
user genuinely needs a phone on their WiFi to reach the preview, that is a per-run flag, said out
loud, not a line in a file that outlives the run.
* `publish_addr = 0.0.0.0` in a repo config. It changes the default for every bare `publish` line in
that directory, which is the same mistake wearing a different hat. It belongs in
`~/.config/ai-sandbox/config` if anywhere.
* a port for a service the project does not actually run, "in case".
### Verify it, in this order
```bash
ai-sandbox --dry-run # '# ingress: publish=[127.0.0.1:8000:8000]' and
# '--publish 127.0.0.1:8000:8000' in the invocation
ai-sandbox --print-policy | grep '^publish=' # canonical addr:host:container, loopback unless you
# wrote an address
```
Then the only check that answers the real question, with the user watching (a real container; the
port exists only while it runs):
```bash
ai-sandbox --publish 8000 --shell
# inside: python3 -m http.server 8000 --bind 0.0.0.0 >/tmp/s.log 2>&1 &
# inside: curl -sS -o /dev/null -m2 -w 'inside=%{http_code}\n' http://127.0.0.1:8000/
# host: curl -sS -o /dev/null -m3 -w 'host=%{http_code}\n' http://127.0.0.1:8000/
```
`host=200` is the result. `host=000` with `inside=200` is the bind address, not the sandbox — go back
to the table above. A refusal naming the port means something else holds it. `--print-entrypoint |
grep -A6 'chain input'` shows the accept rule shape; on the reference host pasta forwards over
loopback, so that rule's packet counter stays at 0 while the port serves — the rule is the audit
trail and the portability guarantee, not what carries the traffic there.
### When the honest answer is still "don't publish"
1. **Run the server on the host.** The project mount *is* their disk: the agent edits, the host's
`npm run dev` / `runserver` picks it up, the browser hits a normal host port. Nothing is
published, nothing is opened, egress stays enforced. This is the answer for 90% of "preview the
app" requests.
2. **One named preview run**, when the server itself must be the sandboxed process (the agent needs
to drive it, seed it, watch its logs):
```bash
AISB_EXTRA_ARGS="-p 8000:8000" ai-sandbox --net full -- npm run dev
```
Say out loud what this is: `--net full` means that run has **no egress policy**. It is a
preview of a trusted project, not a project setting — which is why it never belongs in
`.ai-sandbox/config`.
3. **Split the loop**: the agent builds and unit-tests in the sandbox, writes a screenshotable
static export or a `make preview` target, and the human runs that target. This keeps the review
step where it belongs.
`npm run dev` / `runserver` picks it up, the browser hits a normal host port. Nothing is published
and nothing is opened. Still the right answer when the agent does not need to drive the server —
and that is most "preview the app" requests.
2. **Publish it**, when the server itself has to be the sandboxed process: the agent seeds a
database it starts, runs a migration then serves, needs to watch the server's own logs, or the
test *is* hitting the endpoint. Loopback, named in `.ai-sandbox/config`, with the bind address
fixed in the same change.
3. **Split the loop**: the agent builds and unit-tests in the sandbox, writes a static export or a
`make preview` target, and the human runs that. Keeps the review step where it belongs.
If the user genuinely needs publish-with-enforcement, the honest answer is that it is not
implemented: a `--publish PORT` would need an `input` accept rule per port in `gen_rules()`, the
port list carried in the session policy, and a threat-model line about who may connect. Offer to
write it as a change to `bin/ai-sandbox` — as its own phase, with a `tests/e2e` probe — rather than
hacking `extra_args` into a committed config and calling it secure.
If the ask is "publish it on the LAN so I can check it on my phone", that is a per-run
`--publish 0.0.0.0:18080:8000` with the warning read out, never the committed config — and if the
user wants it permanently, say plainly that the sandbox is then a server on their network.
## 3. Notes that keep coming up
* The gate binds the **host's loopback** only, on a free port at or above `gate_port` (18081);
`ai-sandbox gate status` and `gate logs` show a long-lived one.
`ai-sandbox gate status` and `gate logs` show a long-lived one. `pick_port()` skips ports this run
publishes, so a `publish = 18081` does not lose the run.
* `NO_PROXY` covering `localhost` is correct and must stay — tooling that refuses to proxy the
container's own loopback (dev databases, auth servers, vite HMR) breaks otherwise.
* `--no-gate` opens DNS inside the container; the mapped loopback address still needs its `allow`
line.
* `--net none` has no interface at all: neither direction works, which makes it the right mode for
`make test` on a toolchain that is already installed.
`make test` on a toolchain that is already installed — and the reason it refuses `--publish`.
* `ai-sandbox doctor` reports the resolved `publish` lines and warns about a non-loopback bind or a
host port already in use. It never binds anything itself.
@@ -11,9 +11,10 @@ built-in default < ~/.config/ai-sandbox/{config,allow} < ./.ai-sandbox/{conf
< AISB_* environment < command-line flag
```
`allow`, `env`, `mount`, `install`, `label` **accumulate** from every source (deduped); every other
key replaces. So a repo file cannot revoke a user-wide `allow` line — say so if the user expects a
repo config to tighten their own machine.
`allow`, `env`, `mount`, `install`, `label`, `publish` **accumulate** from every source (deduped);
every other key replaces. So a repo file cannot revoke a user-wide `allow` line — say so if the user
expects a repo config to tighten their own machine. It also cannot *un*publish a port the user's
own config opens.
## The container, for orientation
@@ -43,6 +44,7 @@ directories — the host one is bind-mounted read-only onto the container one at
| `home_cache` | `1` | `0` = throwaway tmpfs home (also `--ephemeral-home`) |
| `gate_addr` | `100.64.0.1` | the address that *means* the host's loopback inside the container |
| `gate_port` | `18081` | preferred first port; next free is used |
| `publish_addr` | `127.0.0.1` | the host address a bare `publish = 8000` binds. Machine-wide setting: put it in the user config, never in a repo file, and do not widen it for the user's convenience |
| `extra_args` | empty | appended verbatim to `podman run`, word-split. Escape hatch: do not commit it |
| `pi_config` | `1` | bridge `~/.pi/agent/{models,settings}.json` with the credential as `$VAR` |
| `pi_token_env` | `AI_API_TOKEN` | the variable the bridged config reads |
@@ -57,6 +59,7 @@ directories — the host one is bind-mounted read-only onto the container one at
| `mount` | — | repeatable; `SRC[:DEST][:ro\|rw]`, default `DEST=/mnt/<basename>` |
| `install` | — | repeatable; apt packages, each distinct set is its own image tag |
| `label` | — | repeatable; `K=V` on the container |
| `publish` | — | repeatable; **ingress**: `[ADDR:]HOST:CONTAINER` forwarded into the container. One port per entry, no ranges, no `/udp`; an address needs three parts. `8000`, `18080:3000`, `0.0.0.0:18080:3000` (LAN-visible: warned, do not commit) |
Anything else warns (`unknown key`) and is ignored.
@@ -64,6 +67,7 @@ Anything else warns (`unknown key`) and is ignored.
```
egress --net none|allow|full --allow HOST[:PORT] --allow-file F --proxy HOST:PORT --no-gate
ingress --publish [ADDR:]HOST:CONTAINER (no `-p`: that flag belongs to the harness)
files --mount SRC[:DEST][:ro] --no-cwd --workdir DIR|auto --read-only
--home-cache --ephemeral-home --agents | --no-agents --agents-dir PATH
env --env NAME --env NAME=VALUE --env-file F (F should be 0600)
@@ -128,6 +132,10 @@ fails loudly, which is the feature.
that with `--workdir /tmp/...`; the tmpfs covers it.
* The host path may not contain `:` at all — podman cannot parse such a mount spec, and
ai-sandbox refuses rather than passing the error along.
* `publish` is the only **ingress** setting there is, and it is not an allowlist entry. `allow =
100.64.0.1:5432` lets the sandbox reach a service on your machine; `publish = 5432:5432` lets your
machine reach a port inside the container. Confusing the two is how a database ends up exposed.
Read `references/port-and-loopback.md` before writing either.
* Nothing is inherited but `TERM LANG LC_ALL LC_CTYPE TZ` (plus `HOME`, set to the container home,
`AISB=1`, `AISB_SESSION`). A tool that needs `PATH`, a dotfile or anything else from your real home
needs an explicit grant.
+38 -6
View File
@@ -128,8 +128,21 @@ devports="$(grep -rIhoE --include='vite.config.*' --include='next.config.*' --in
'(--[Pp][Oo][Rr][Tt][[:space:]=]+[0-9]{4,5})|([Pp][Oo][Rr][Tt][[:space:]]*[=:][[:space:]]*"?[0-9]{4,5})' . 2>/dev/null \
| grep -oE '[0-9]{4,5}$' | sort -u | tr '\n' ' ')"
[[ -n "$devports" ]] && note "ports named in dev-server configs: $devports"
note "outbound (sandbox -> a service on this machine) is grantable: 100.64.0.1:<port>."
note "inbound (host -> a server the sandbox started) is dropped by the ruleset -- references/port-and-loopback.md"
exposed="$(files_matching Dockerfile 'Dockerfile.*' | xargs -r grep -hoiE '^EXPOSE[[:space:]]+[0-9]+' 2>/dev/null \
| grep -oE '[0-9]+' | sort -u | tr '\n' ' ')"
[[ -n "$exposed" ]] && note "EXPOSEd in the Dockerfile: $exposed"
# The address matters as much as the port: a dev server pinned to loopback answers nothing on a
# published port, so quote the project's own setting back when it says 127.0.0.1.
binds="$(grep -rIhoE --include='vite.config.*' --include='next.config.*' --include='webpack*.js' \
--include='gunicorn*' --include='Procfile' --include='settings.py' --include='*.toml' \
'(host|HOST|BIND|bind|--host|-b)[^0-9A-Za-z]{0,4}(0\.0\.0\.0|127\.0\.0\.1|\[::1\]|localhost)' . 2>/dev/null \
| grep -oE '0\.0\.0\.0|127\.0\.0\.1|\[::1\]|localhost' | sort | tr '\n' ' ')"
[[ -n "$binds" ]] && note "addresses the project's own config binds to: $binds"
note "outbound (sandbox -> a service on this machine): allow = 100.64.0.1:<port>."
note "inbound (host -> a server the sandbox runs): publish = <port> -- loopback unless an address"
note " is written in the spec. The two are not interchangeable: publish is ingress, allow is egress."
note " a published port only reaches a server listening on 0.0.0.0 inside (measured), so a config that"
note " binds loopback above needs that said in the same change. references/port-and-loopback.md"
# --------------------------------------------------------------------------- environment names
section "environment variable NAMES the project references (no values)"
@@ -174,8 +187,9 @@ fi
# --------------------------------------------------------------------------- existing policy
section "existing policy"
KV_KEYS="net harness workdir cpus memory pids tmpfs_size base_image node_version pi_version \
base_ttl_days base_auto_update selinux home_cache gate_addr gate_port extra_args pi_config \
pi_token_env pi_token_auto pi_agent_dir thinking agents agents_dir agents_dest allow env mount install label"
base_ttl_days base_auto_update selinux home_cache gate_addr gate_port publish publish_addr extra_args \
pi_config pi_token_env pi_token_auto pi_agent_dir thinking agents agents_dir agents_dest \
allow env mount install label"
for f in .ai-sandbox/config .ai-sandbox/allow; do
[[ -r "$f" ]] && found "$f ($(wc -l < "$f") lines)" || note "$f: absent"
done
@@ -193,6 +207,23 @@ if [[ -r .ai-sandbox/config ]]; then
fi
if [[ "$k" == net && "$v" == full ]]; then warn "net = full in a committed config: that is an escape hatch, not a policy"; fi
if [[ "$k" == extra_args ]]; then warn "extra_args in a committed config: the podman escape hatch -- it belongs on one command line"; fi
if [[ "$k" == publish ]]; then
case "$v" in
*/*) warn "publish = $v has a protocol suffix: one port per entry, no /udp" ;;
*-*) warn "publish = $v is a range: ai-sandbox takes one port per entry, so a reviewed line is never a block of ports" ;;
\[*) note "publish = $v -- an ipv6 bind in brackets, then host:container" ;;
*:*:*) note "publish = $v -- addr:host:container; anything not loopback is an open door and warns on every run" ;;
*:*) note "publish = $v -- host port -> container port, bound to 127.0.0.1 (the default)" ;;
*[!0-9]*) warn "publish = $v is not a port, host:container or addr:host:container -- ai-sandbox refuses it" ;;
*) note "publish = $v -- 127.0.0.1:$v -> container $v; the server must bind 0.0.0.0 inside" ;;
esac
fi
if [[ "$k" == publish_addr ]]; then
case "$v" in
127.*|localhost|::1|\[::1\]) note "publish_addr = $v -- loopback, the safe default" ;;
*) warn "publish_addr = $v in a repo config widens every bare publish line in this directory -- the user's config, if anywhere" ;;
esac
fi
done < .ai-sandbox/config
fi
if [[ -r .ai-sandbox/allow ]]; then
@@ -225,7 +256,8 @@ else
fi
section "next"
note "1. decide net / allow / env / mount / install / limits from the above (SKILL.md step 2)"
note "1. decide net / allow / env / mount / install / publish / limits from the above (SKILL.md step 2)"
note "2. write .ai-sandbox/allow and .ai-sandbox/config, commented, names only"
note "3. verify with ai-sandbox --print-policy and --dry-run (no build, no container, no network)"
note "4. then one live probe per endpoint the project really needs"
note "4. then one live probe per endpoint the project really needs -- and from the host too if you"
note " wrote publish: that port exists only while a sandbox runs, and only 0.0.0.0 inside answers it"