This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: bun-linux-landlock-containerless-sandbox

Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes

Mandates kernel-enforced Linux Landlock LSM confinement via Bun 1.2 FFI immediately post-bootstrap before executing untrusted workloads. Prevents lateral filesystem traversal and unauthorized network operations at the kernel level without VM or container overhead.

Prohibited Anti-Pattern: Relying on Userland Sandboxing or Process Isolation Without Kernel Landlock Enforcement

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes - Mandates kernel-enforced Linux Landlock LSM confinement via Bun 1.2 FFI immediately post-bootstrap before executing untrusted workloads. Prevents lateral filesystem traversal and unauthorized network operations at the kernel level without VM or container overhead.
globs: src/**/*.ts, worker/**/*.ts, sandbox/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-linux-landlock-containerless-sandbox"
---

# Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Relying on Userland Sandboxing or Process Isolation Without Kernel Landlock Enforcement

## System Constraints
You are a Principal Security and DevOps Architect enforcing kernel-level confinement for multi-tenant and untrusted script execution within Bun 1.2. Userland monkeypatching of 'node:fs' or 'Bun.file' is strictly prohibited as a security boundary. You must enforce the Linux Landlock Linux Security Module (LSM) through unprivileged syscalls via Bun FFI immediately after bootstrap and prior to executing dynamic user payloads.

## Strict Guidelines
- Engineers MUST ALWAYS invoke prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) before invoking landlock_restrict_self to allow unprivileged sandbox engagement.
- Engineers MUST query the host's supported Landlock ABI version via landlock_create_ruleset with LANDLOCK_CREATE_RULESET_VERSION and fail-closed if Landlock is unavailable or version is below 1.
- Services MUST complete all privileged bootstrap operations (loading dependencies, opening log channels, binding server sockets) BEFORE applying Landlock restriction.
- Code SHOULD restrict filesystem access to explicit target scratch directories using O_PATH descriptors and explicit LANDLOCK_ACCESS_FS_* bitmasks.
- Components NEVER execute untrusted customer code, dynamic imports, or worker scripts in an unconfined Bun process.

## Bad vs Good Implementations
### Vulnerable Userland Proxy Sandboxing vs. Kernel-Enforced Landlock Sandbox

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Userland sandboxing is fundamentally broken in Node.js and Bun runtimes. Untrusted scripts can bypass patched objects through global scope leaks, alternative namespace imports, or standard CJS/ESM module loaders to traverse the entire host filesystem.
```typescript
import { readFileSync } from 'node:fs';

// ANTI-PATTERN: Attempting to sandbox code via userland proxies or monkeypatching
export function executeUntrustedWorker(userCode: string, tenantId: string) {
  const restrictedFs = {
    readFileSync: (path: string) => {
      if (!path.startsWith(`/tmp/tenants/${tenantId}`)) {
        throw new Error('Access Denied');
      }
      return readFileSync(path);
    }
  };

  // CRITICAL SECURITY FLAW: Bypassed via process.binding, Bun.file, native FFI, or import('node:fs')
  const runner = new Function('fs', userCode);
  return runner(restrictedFs);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Linux Landlock LSM through Bun 1.2 FFI to create a kernel-enforced capability barrier. Even if untrusted code achieves arbitrary code execution, kernel-level path resolution blocks any access outside the designated directory regardless of runtime APIs used.
```typescript
import { cc, ptr } from 'bun:ffi';

// Compile and bind Linux Landlock LSM confinement via Bun FFI
const { symbols: { restrict_process_to_dir } } = cc({
  source: `
    #define _GNU_SOURCE
    #include <linux/landlock.h>
    #include <sys/prctl.h>
    #include <sys/syscall.h>
    #include <fcntl.h>
    #include <unistd.h>

    #ifndef SYS_landlock_create_ruleset
    #define SYS_landlock_create_ruleset 444
    #define SYS_landlock_add_rule 445
    #define SYS_landlock_restrict_self 446
    #endif

    int restrict_process_to_dir(const char* allowed_dir) {
      int abi = syscall(SYS_landlock_create_ruleset, NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
      if (abi < 1) return -1; // Fail-closed: Landlock unsupported

      struct landlock_ruleset_attr attr = {
        .handled_access_fs = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE |
                             LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR
      };

      int ruleset_fd = syscall(SYS_landlock_create_ruleset, &attr, sizeof(attr), 0);
      if (ruleset_fd < 0) return -2;

      int target_fd = open(allowed_dir, O_PATH | O_CLOEXEC);
      if (target_fd < 0) { close(ruleset_fd); return -3; }

      struct landlock_path_beneath_attr path_attr = {
        .allowed_access = attr.handled_access_fs,
        .parent_fd = target_fd
      };

      int rule_res = syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_PATH_BENEATH, &path_attr, 0);
      close(target_fd);
      if (rule_res < 0) { close(ruleset_fd); return -4; }

      if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) { close(ruleset_fd); return -5; }
      int res = syscall(SYS_landlock_restrict_self, ruleset_fd, 0);
      close(ruleset_fd);
      return res;
    }
  `,
  symbols: {
    restrict_process_to_dir: { args: ['cstring'], returns: 'int' }
  }
});

export function bootstrapTenantSandbox(tenantScratchDir: string): void {
  const dirBuffer = Buffer.from(tenantScratchDir + '\0');
  const result = restrict_process_to_dir(ptr(dirBuffer));
  
  if (result !== 0) {
    throw new Error(`Failed to apply Landlock sandbox guardrail. Code: ${result}`);
  }
  // Process is now permanently locked into tenantScratchDir at the Linux kernel level
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes

Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes defines an industrial-grade behavioral standard for devops engineering. Mandates kernel-enforced Linux Landlock LSM confinement via Bun 1.2 FFI immediately post-bootstrap before executing untrusted workloads. Prevents lateral filesystem traversal and unauthorized network operations at the kernel level without VM or container overhead. 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: Relying on Userland Sandboxing or Process Isolation Without Kernel Landlock Enforcement 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 DriftRelying on Userland Sandboxing or Process Isolation Without Kernel Landlock EnforcementCritical
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 invoke prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) before invoking landlock_restrict_self to allow unprivileged sandbox engagement.

Engineers MUST ALWAYS invoke prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) before invoking landlock_restrict_self to allow unprivileged sandbox engagement.

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 query the host's supported Landlock ABI version via landlock_create_ruleset with LANDLOCK_CREATE_RULESET_VERSION and fail-closed if Landlock is unavailable or version is below 1.

Engineers MUST query the host's supported Landlock ABI version via landlock_create_ruleset with LANDLOCK_CREATE_RULESET_VERSION and fail-closed if Landlock is unavailable or version is below 1.

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

Services MUST complete all privileged bootstrap operations (loading dependencies, opening log channels, binding server sockets) BEFORE applying Landlock restriction.

Services MUST complete all privileged bootstrap operations (loading dependencies, opening log channels, binding server sockets) BEFORE applying Landlock restriction.

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

Code SHOULD restrict filesystem access to explicit target scratch directories using O_PATH descriptors and explicit LANDLOCK_ACCESS_FS_* bitmasks.

Code SHOULD restrict filesystem access to explicit target scratch directories using O_PATH descriptors and explicit LANDLOCK_ACCESS_FS_* bitmasks.

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

Components NEVER execute untrusted customer code, dynamic imports, or worker scripts in an unconfined Bun process.

Components NEVER execute untrusted customer code, dynamic imports, or worker scripts in an unconfined Bun process.

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 Kernel-Enforced Linux Landlock LSM Sandboxing for Bun 1.2 Runtimes critical for AI coding assistants?

Mandates kernel-enforced Linux Landlock LSM confinement via Bun 1.2 FFI immediately post-bootstrap before executing untrusted workloads. Prevents lateral filesystem traversal and unauthorized network operations at the kernel level without VM or container overhead. 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 (Relying on Userland Sandboxing or Process Isolation Without Kernel Landlock Enforcement) 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

Kernel-Enforced