This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-posix-spawn-cgroup-sandboxing-standard

Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard

Enforces strict process isolation for child processes executed via Bun 1.2 by prohibiting raw shell interpolation, preventing process descriptor leakage, and enforcing structured command arrays. Mandates explicit environment variable sanitization, unprivileged user execution, and cgroup v2/namespace resource boundaries to prevent command injection and host resource exhaustion.

Prohibited Anti-Pattern: Arbitrary Shell Interpolation and Ambient Process State Inheritance via Bun.spawn/Bun.$

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard - Enforces strict process isolation for child processes executed via Bun 1.2 by prohibiting raw shell interpolation, preventing process descriptor leakage, and enforcing structured command arrays. Mandates explicit environment variable sanitization, unprivileged user execution, and cgroup v2/namespace resource boundaries to prevent command injection and host resource exhaustion.
globs: src/**/*.{ts,tsx,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-posix-spawn-cgroup-sandboxing-standard"
---

# Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Arbitrary Shell Interpolation and Ambient Process State Inheritance via Bun.spawn/Bun.$

## System Constraints
You are a Principal Systems & Security Architect enforcing strict POSIX spawn isolation and Linux cgroup/namespace sandboxing rules for Bun 1.2 runtimes. You must prohibit any invocation of dynamic shell command execution (such as `sh -c`, `bash -c`, or unescaped `Bun.$` template literals) and enforce structured, array-based `Bun.spawn` calls. Ensure that child processes never inherit the host process environment, ambient credentials, or open file descriptors by requiring strict environment allowlisting, explicit stdio mapping, unprivileged UID/GID execution contexts, and kernel-level resource limits.

## Strict Guidelines
- Engineers MUST ALWAYS pass arguments as an explicit, validated array of strings (`string[]`) directly to `Bun.spawn` rather than invoking shell interpreters (`sh`, `bash`, `cmd.exe`) or using dynamic string concatenation.
- Engineers MUST NEVER use `Bun.$` with unsanitized dynamic user input or ambient host context where untrusted execution boundaries are required.
- Engineers MUST ALWAYS sanitize the execution environment by passing an explicit `env` allowlist map to `Bun.spawn`; implicit inheritance of `process.env` containing cloud credentials or secrets is strictly forbidden.
- Services MUST ALWAYS explicitly bind standard I/O streams using 'pipe', 'ignore', or allocated `FileHandle` instances; inherited ambient file descriptors (FD leakage) MUST be closed.
- Subprocesses executing untrusted or semi-trusted tasks MUST be executed under unprivileged UID/GID contexts or bounded via Linux cgroup v2 limits (`memory.max`, `pids.max`) and namespace wrappers (e.g., `bwrap` or `nsenter`).
- Engineers MUST ALWAYS attach an `AbortSignal` with an explicit timeout to prevent lingering zombie processes or resource exhaustion from blocked I/O loops.

## Bad vs Good Implementations
### Subprocess Execution: Shell Interpolation & Host Credential Leak vs. Isolated POSIX Spawn

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invokes an intermediate shell (`sh -c`) with string interpolation, allowing arbitrary command execution if `inputScript` contains metacharacters. It also inherits all environment secrets from `process.env`, inherits parent file descriptors, and lacks timeout or memory ceiling constraints.
```typescript
import { $ } from "bun";

// CRITICAL VULNERABILITY: Shell interpolation leads to command injection,
// process inherits process.env (AWS keys, DB tokens), and unconstrained memory/PIDs.
export async function executeUserPipeline(inputScript: string, targetPath: string) {
  const result = await $`sh -c "./processor.sh ${inputScript} --out ${targetPath}"`.text();
  return result;
}
```

#### Production Standard (Correct)
> **Standard**: Uses direct array execution via `Bun.spawn` without a shell interpreter, isolates filesystem and kernel namespaces using Bubblewrap (`bwrap`), strips sensitive ambient environment variables, isolates stdio streams, and enforces a rigid execution timeout via `AbortSignal`.
```typescript
import { spawn } from "bun";

interface ExecutionOptions {
  readonly timeoutMs?: number;
  readonly maxBufferBytes?: number;
}

// PRODUCTION INVARIANT: Direct POSIX spawn without shell, strict env isolation, and AbortController
export async function executeUserPipelineSafe(
  scriptArg: string,
  targetPath: string,
  options: ExecutionOptions = {}
): Promise<string> {
  const { timeoutMs = 10_000, maxBufferBytes = 10 * 1024 * 1024 } = options;
  const ac = new AbortController();
  const timeoutId = setTimeout(() => ac.abort(new Error("Subprocess timed out")), timeoutMs);

  // Strict argument validation to ensure path safety
  if (!/^[a-zA-Z0-9_-]+$/.test(scriptArg)) {
    throw new TypeError("Invalid script argument identifier");
  }

  try {
    const proc = spawn([
      "/usr/bin/bwrap", // Linux unprivileged user namespace / cgroup sandbox wrapper
      "--ro-bind", "/usr", "/usr",
      "--ro-bind", "/lib", "/lib",
      "--ro-bind", "/lib64", "/lib64",
      "--tmpfs", "/tmp",
      "--unshare-all",
      "--die-with-parent",
      "--",
      "/usr/local/bin/processor",
      scriptArg,
      "--out",
      targetPath
    ], {
      // Mandatory: Disallow ambient process.env inheritance
      env: {
        PATH: "/usr/local/bin:/usr/bin",
        NODE_ENV: "production",
        TMPDIR: "/tmp"
      },
      stdin: "ignore",
      stdout: "pipe",
      stderr: "pipe",
      signal: ac.signal,
    });

    const stdoutPromise = new Response(proc.stdout).text();
    const stderrPromise = new Response(proc.stderr).text();
    const [exitCode, stdout, stderr] = await Promise.all([
      proc.exited,
      stdoutPromise,
      stderrPromise
    ]);

    if (exitCode !== 0) {
      throw new Error(`Process exited with code ${exitCode}: ${stderr.slice(0, 1024)}`);
    }

    if (stdout.length > maxBufferBytes) {
      throw new RangeError("Subprocess output exceeded memory safety threshold");
    }

    return stdout;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard

Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict process isolation for child processes executed via Bun 1.2 by prohibiting raw shell interpolation, preventing process descriptor leakage, and enforcing structured command arrays. Mandates explicit environment variable sanitization, unprivileged user execution, and cgroup v2/namespace resource boundaries to prevent command injection and host resource exhaustion. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Arbitrary Shell Interpolation and Ambient Process State Inheritance via Bun.spawn/Bun.$ Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftArbitrary Shell Interpolation and Ambient Process State Inheritance via Bun.spawn/Bun.$Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS pass arguments as an explicit, validated array of strings (`string[]`) directly to `Bun.spawn` rather than invoking shell interpreters (`sh`, `bash`, `cmd.exe`) or using dynamic string concatenation.

Engineers MUST ALWAYS pass arguments as an explicit, validated array of strings (`string[]`) directly to `Bun.spawn` rather than invoking shell interpreters (`sh`, `bash`, `cmd.exe`) or using dynamic string concatenation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER use `Bun.$` with unsanitized dynamic user input or ambient host context where untrusted execution boundaries are required.

Engineers MUST NEVER use `Bun.$` with unsanitized dynamic user input or ambient host context where untrusted execution boundaries are required.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ALWAYS sanitize the execution environment by passing an explicit `env` allowlist map to `Bun.spawn`

Engineers MUST ALWAYS sanitize the execution environment by passing an explicit `env` allowlist map to `Bun.spawn`; implicit inheritance of `process.env` containing cloud credentials or secrets is strictly forbidden.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ALWAYS explicitly bind standard I/O streams using 'pipe', 'ignore', or allocated `FileHandle` instances

Services MUST ALWAYS explicitly bind standard I/O streams using 'pipe', 'ignore', or allocated `FileHandle` instances; inherited ambient file descriptors (FD leakage) MUST be closed.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Subprocesses executing untrusted or semi-trusted tasks MUST be executed under unprivileged UID/GID contexts or bounded via Linux cgroup v2 limits (`memory.max`, `pids.max`) and namespace wrappers (e.g., `bwrap` or `nsenter`).

Subprocesses executing untrusted or semi-trusted tasks MUST be executed under unprivileged UID/GID contexts or bounded via Linux cgroup v2 limits (`memory.max`, `pids.max`) and namespace wrappers (e.g., `bwrap` or `nsenter`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Engineers MUST ALWAYS attach an `AbortSignal` with an explicit timeout to prevent lingering zombie processes or resource exhaustion from blocked I/O loops.

Engineers MUST ALWAYS attach an `AbortSignal` with an explicit timeout to prevent lingering zombie processes or resource exhaustion from blocked I/O loops.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Bun 1.2 Subprocess POSIX Spawn & Cgroup Sandboxing Isolation Standard critical for AI coding assistants?

Enforces strict process isolation for child processes executed via Bun 1.2 by prohibiting raw shell interpolation, preventing process descriptor leakage, and enforcing structured command arrays. Mandates explicit environment variable sanitization, unprivileged user execution, and cgroup v2/namespace resource boundaries to prevent command injection and host resource exhaustion. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Arbitrary Shell Interpolation and Ambient Process State Inheritance via Bun.spawn/Bun.$) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Bun