Securing AI Agent Tool Boundaries and Ephemeral Build Sandboxes
Practical defense-in-depth patterns for AI coding agents and web builders: MCP filesystem confinement, immutable build harnesses, networkless ephemeral sandboxes, and dedicated preview domains.
Table of Contents
- →Treat every prompt, repository file, and AI-generated build script as hostile input by confining MCP tools to canonicalized workspace roots and separating editable source from immutable build configs.
- →Run untrusted compile steps inside ephemeral
--network=none --read-onlysandboxes backed by gVisor or strict seccomp profiles, then extract only static build artifacts. - →Host live user previews on a dedicated preview apex domain completely separate from your main SaaS domain so browser Same-Origin Policy and cookie boundaries enforce isolation by default.
AI coding agents and prompt-to-app platforms invert the classic developer-tools trust model. Instead of a trusted engineer editing local code on a single-tenant laptop, an autonomous loop reads untrusted prompts, pulls third-party documentation, invokes Model Context Protocol (MCP) tools, writes code, and triggers package builds on shared infrastructure.
Once an agent can both read external content and call local tools or build containers, indirect prompt injection becomes a code-execution vector. Hardening these systems requires four physical enforcement boundaries that hold even when the model is completely tricked into acting adversarially.
1. Confinement at the MCP Tool Boundary
Many agent regressions happen inside thin filesystem, browser, or command-wrapper tools that validate arguments with string prefix checks (strings.HasPrefix(path, workspaceRoot)) before handing paths to the operating system.
String checks break quickly under real filesystem semantics:
- Prefix collisions: Checking
HasPrefix(target, "/srv/work/proj1")accidentally matches/srv/work/proj10/secrets.envunless a trailing path separator is enforced. - Symlink escapes: A workspace file created by the agent (or cloned from an external repository) can point to
/etc/passwdor a host credential file outside the project root. A naive lexicalfilepath.Cleannever notices the symlink target. - Post-validation TOCTOU swaps: Validating a path at step 1 and opening it at step 2 allows a concurrent tool or build process to swap a benign directory for a symlink in between.
A resilient tool boundary resolves canonical real paths, enforces filepath.Rel containment, rejects symlinks explicitly with O_NOFOLLOW or Lstat, and binds every tool session to a single scoped directory with zero ambient host credentials:
realRoot, err := filepath.EvalSymlinks(absRoot)
if err != nil {
return ErrAccessDenied
}
linfo, err := os.Lstat(absTarget)
if err != nil || linfo.Mode()&os.ModeSymlink != 0 {
return ErrAccessDenied
}
realTarget, err := filepath.EvalSymlinks(absTarget)
if err != nil {
return ErrAccessDenied
}
rel, err := filepath.Rel(realRoot, realTarget)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || filepath.IsAbs(rel) {
return ErrAccessDenied
}
2. Immutable Build Configs and Dependency Hygiene
Giving an AI agent unrestricted write access to the entire project root lets a single prompt injection poison the build pipeline itself. Modifying vite.config.ts, next.config.js, Makefile, or adding a postinstall hook in package.json turns a harmless frontend preview build into arbitrary command execution during compilation.
Separate agent-editable code from host-owned build infrastructure:
| Surface | Writable by Agent? | Security Control |
|---|---|---|
Application Source (src/, public/) | Yes | Static size caps, symlink rejection, strict extension allowlist |
Build Harness (vite.config, tsconfig, Dockerfile) | No (Read-only) | Mounted read-only from host-signed template before every build |
Dependency Tree (node_modules, lockfile) | No (Pre-baked) | Pre-installed inside immutable base image; runtime installs run with --ignore-scripts or offline cache |
| Build Secrets & Deploy Tokens | Never mounted | Injected only into the separate host-side artifact publisher after the sandbox exits |
Pre-baking an approved component and dependency layer into a digest-pinned builder image both eliminates npm install supply-chain execution during user builds and cuts cold-build latency dramatically.
3. Ephemeral --network=none --read-only Sandboxes With gVisor or Seccomp
Compilation should be treated as a pure, untrusted function: bytes of source code go in, static HTML/JS/CSS bundles come out, and the execution container is destroyed immediately afterward.
Even with rootless UIDs and dropped Linux capabilities, a shared kernel still exposes a large syscall surface. Hardening the build container narrows both kernel attack surface and data-exfiltration paths:
docker run --rm \
--runtime=runsc \
--network=none \
--read-only \
--user 1000:1000 \
--cap-drop=ALL \
--security-opt=no-new-privileges:true \
--pids-limit=96 \
--memory=768m \
--cpus=1.0 \
--tmpfs /tmp:rw,noexec,nosuid,nodev,size=128m \
-v /srv/builds/<job_id>/src:/workspace/src:ro \
-v /srv/builds/<job_id>/out:/workspace/out:rw \
builder-template@sha256:<pinned_digest> \
npm run build -- --outDir /workspace/out
Key properties of this execution model:
- Zero egress (
--network=none): Even if malicious build code executes during bundling, it cannot open outbound sockets to exfiltrate environment state, scan internal RFC 1918 networks, or query cloud metadata services. - Immutable root filesystem (
--read-only): Scratch files live strictly in a boundednoexec,nosuid,nodevtmpfsmount, preventing dropped binaries from executing and capping disk exhaustion. - Reduced kernel surface (
--runtime=runsc/ seccomp): Running builds under gVisor (runsc) intercepts syscalls in a user-space Go kernel rather than passing them straight to the host Linux kernel; where gVisor is unavailable, apply a tight custom seccomp profile blockingptrace,bpf,io_uring, and user-namespace escalation. - Artifact-only extraction: Once the container exits, the control plane copies only verified static assets (
.html,.js,.css,.svg,.png,.woff2) while rejecting symlinks, dotfiles, and oversized bundles before publishing.
4. Dedicated Preview Domains for Browser Origin Isolation
Container isolation protects your server, but once a user opens an AI-generated preview in their browser, JavaScript inside that preview runs with whatever browser origin authority your routing design grants it.
Serving untrusted user sites under paths on your primary SaaS domain (such as app.example.com/preview/<id>) shares the exact same browser origin with your authenticated control plane. A single XSS gadget, overlooked cookie scope, or permissive Service Worker scope can pivot from a preview tab straight into a victim's logged-in account.
The clean architectural fix is moving all user-generated previews onto a dedicated, isolated preview apex domain that has zero relation to your primary product domain (for instance, serving previews at <project-slug>.<preview-apex> while your console lives on example.com):
- Hard eTLD+1 boundary: Browsers isolate
document.cookie,localStorage,IndexedDB, Service Workers, andSameSitecookie transmission across distinct registrable domains automatically. - Zero credential leakage: Control-plane session cookies scoped to
example.comare never attached by the browser to requests hitting the separate preview apex, even if an attacker crafts arbitraryfetch()calls inside generated JavaScript. - Per-project subdomain separation: Giving each generated project its own unique subdomain under the preview apex prevents one untrusted preview from reading another tenant's client-side storage or registering a parent-origin Service Worker.
- Strict edge headers: Pair dedicated preview origins with
X-Content-Type-Options: nosniff,Referrer-Policy: no-referrer,X-Robots-Tag: noindex, nofollow, and sandboxed CSP rules on SVG assets.
Building an AI coding agent, MCP server, or multi-tenant sandbox platform and want an independent offensive review of your container, tool, and browser isolation boundaries? Contact the DomainFA Security Desk or email [email protected].
Why Automated Scanners Miss Business Logic and Authorization Bugs
Why dependency and signature scanners stay green even when state-machine bypasses, sibling-route authorization gaps, and accounting invariant breaks sit in production code.
Cloudflare Nameservers vs. Native Registrar DNS: Which Setup Fits Your Stack
When to delegate your domain to Cloudflare nameservers versus keeping authoritative DNS on DomainFA Native NS, and how to move zones with zero downtime.