
I Gave My Coding Agents Root Access: The Guardrail Architecture That Stopped Them From Deleting My Database
How to safely give AI coding agents root access using a layered guardrail architecture — sandboxing, permission brokers, destructive-command firewalls, and rollback.
I gave my coding agents root access. It was the scariest and most productive decision I've made as a systems engineer. The scariest part wasn't the agents themselves — it was the moment one of them, mid-refactor, decided to run DROP TABLE users on a production replica. That command never executed. What stopped it wasn't luck or a well-timed Ctrl+C. It was a four-layer guardrail architecture I'd built the week before, designed specifically to contain the blast radius of an autonomous agent with superuser privileges.
This article is a deep-dive into that architecture. I'll walk through the threat model, the four layers I implemented, the exact code that powers each layer, and the incident that proved the design worked. If you're running AI coding agents (Claude Code, Cursor, Copilot, Aider, or a custom agent) with elevated permissions, this is the playbook for making it safe.
- 1. The Threat Model: Why Root Access + Agents = Disaster
- 2. The Guardrail Architecture: A Four-Layer Overview
- 3. Layer 1: The Sandbox — Filesystem, Network, and Process Isolation
- 4. Layer 2: The Permission Broker — A Policy Engine for Every Tool Call
- 5. Layer 3: The Destructive-Command Firewall — Catching the
DROP TABLE - 6. Layer 4: Audit Trail and Rollback — Undoing the Unthinkable
- 7. The Incident: How the Guardrails Saved the Database
- 8. Hardening and Production Considerations
- Frequently Asked Questions
1. The Threat Model: Why Root Access + Agents = Disaster
Coding agents are obedient. That's their superpower and their fatal flaw. A human engineer has a survival instinct — when you type rm -rf /, a small part of your brain screams "no." An LLM doesn't have that instinct. It has a goal, a context window, and a toolset. If the goal is "refactor the auth module" and the context suggests the users table is obsolete, the agent will happily construct and execute DROP TABLE users with zero hesitation.
When you grant that agent root access, you remove the last natural barrier. The agent can now:
- Delete or overwrite any file —
/etc/passwd,nginx.conf, your.envfile, the entirenode_modulesdirectory. - Modify system configuration — rewrite
iptables, change SSH keys, altersysctlsettings. - Talk to any network endpoint — exfiltrate secrets, hit internal APIs, or connect to a production database.
- Kill any process — including your CI runner, your database server, or the agent itself.
- Install arbitrary packages — pulling in compromised dependencies or executing post-install scripts.
I classified the failure modes into three severity tiers:
| Severity | Example | Blast Radius |
|---|---|---|
| Critical | DROP TABLE, rm -rf /, git push --force to main | Irreversible, potentially catastrophic |
| High | ALTER TABLE, npm install --global, chmod 777 on a config file | Reversible but time-consuming to fix |
| Moderate | git commit with wrong files, kill on a non-critical process | Annoying, recoverable with audit log |
The goal of the guardrail architecture isn't to prevent the agent from doing anything — that defeats the purpose. The goal is to contain the blast radius so that even when the agent makes a mistake, the damage is bounded, auditable, and reversible.
2. The Guardrail Architecture: A Four-Layer Overview
The architecture I built is a series of four independent layers, each one wrapping the agent's execution environment. The key design principle is defense in depth: if one layer fails, the next one catches the mistake. The layers are:
┌─────────────────────────────────────────────────────────────┐
│ Agent (LLM + Tools) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ LAYER 1: Sandbox (bwrap / namespaces / seccomp) │
│ - Filesystem isolation (read-only root, tmpfs overlay) │
│ - Network isolation (loopback only, no external egress) │
│ - Process isolation (PID namespace, no host visibility) │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ LAYER 2: Permission Broker (policy engine) │
│ - Intercepts every tool call before execution │
│ - Checks path, command, network, and permission │
│ - Returns allow / deny / ask with a structured reason │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ LAYER 3: Destructive-Command Firewall (regex ruleset) │
│ - Pattern-matches against known dangerous commands │
│ - Blocks critical operations regardless of policy │
│ - Logs the full command and context │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ LAYER 4: Audit Trail & Rollback (snapshot + undo) │
│ - Records every mutation with a pre-image │
│ - Maintains a Git-style snapshot before each mutation │
│ - Enables automated rollback to the last safe state │
└──────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────▼──────────────────────────────────┐
│ Target System (filesystem, DB, network, processes) │
└─────────────────────────────────────────────────────────────┘
Each layer is independent and fail-closed. If Layer 1's sandbox breaks, the agent can't run at all. If Layer 2's permission broker has a bug, it defaults to deny. If Layer 3's firewall can't parse a command, it blocks it. If Layer 4's audit trail fails to write, the mutation is aborted. This is the opposite of "fail-open," which would let the agent run unconstrained in the event of an error.
3. Layer 1: The Sandbox — Filesystem, Network, and Process Isolation
The sandbox is the first and most important layer. It's a hard boundary that the agent cannot cross, no matter what it tries. I used bubblewrap (bwrap) on Linux, which leverages kernel namespaces and seccomp to create an isolated environment. Here's the core invocation I use:
#!/usr/bin/env bash
# sandbox-run.sh — wraps a command in a strict sandbox
set -euo pipefail
# 1. Create a tmpfs for the agent's writable workspace
WORKSPACE=$(mktemp -d /tmp/agent-workspace.XXXXXX)
# 2. Set up the sandbox
bwrap \
--die-with-parent \
--ro-bind /usr /usr \
--ro-bind /lib /lib \
--ro-bind /lib64 /lib64 \
--ro-bind /bin /bin \
--ro-bind /etc /etc \
--ro-bind /opt /opt \
--ro-bind /sbin /sbin \
--ro-bind /var /var \
--tmpfs /tmp \
--bind "$WORKSPACE" /workspace \
--chdir /workspace \
--unshare-all \
--share-net \
--new-session \
--proc /proc \
--dev /dev \
--setenv PATH "/usr/local/bin:/usr/bin:/bin" \
--setenv HOME "/workspace" \
-- "$@"
What this does:
--ro-bindmounts the system directories as read-only. The agent can read/etc,/usr,/bin, but it can't modify a single file in them.--tmpfs /tmpgives the agent a fresh, empty temp directory. It can't see or touch anything outside its workspace.--bind "$WORKSPACE" /workspaceis the only writable directory. The agent is confined to this tmpfs-backed workspace.--unshare-allcreates new namespaces for PID, mount, UTS, IPC, and network. The agent can't see host processes, and its network is isolated.--share-net— I'll explain this in a second. It's a deliberate exception.
The Network Question
A strict sandbox would use --unshare-net to give the agent a completely isolated network namespace with no egress. But that breaks the agent's ability to fetch packages, hit APIs, or connect to the database — which is often the whole point of giving it root access. So I made a deliberate trade-off:
- Allow loopback only by default (
--unshare-net+ a loopback interface inside the namespace). The agent can talk to local services (e.g., a local Postgres) but can't reach the internet. - Allow egress to a whitelist of domains via a proxy or network namespace routing. I use
--share-netwith a seccomp filter that blocks outbound connections to non-whitelisted IPs.
For the purposes of this article, I'll show the loopback-only variant, which is the safest default:
# Strict network isolation: loopback only, no external egress
bwrap \
--unshare-net \
--ro-bind /usr /usr \
--ro-bind /lib /lib \
--ro-bind /bin /bin \
--ro-bind /etc /etc \
--tmpfs /tmp \
--bind "$WORKSPACE" /workspace \
--chdir /workspace \
--unshare-all \
--new-session \
--proc /proc \
--dev /dev \
--setenv PATH "/usr/local/bin:/usr/bin:/bin" \
--setenv HOME "/workspace" \
-- "$@"
If you need external network access for package installation, you can add a seccomp filter that only allows connect() to specific IPs/ports. I'll cover that in the hardening section.
4. Layer 2: The Permission Broker — A Policy Engine for Every Tool Call
The sandbox handles filesystem and process isolation, but it doesn't know what the agent is trying to do. That's the permission broker's job. It intercepts every tool call the agent makes — bash, read_file, write_file, edit_file, run_command — and evaluates it against a policy before allowing execution.
I implemented this as a TypeScript module that sits between the agent's tool layer and the shell. The policy is defined in YAML for readability:
# policy.yaml — the permission broker's ruleset
version: 1
# Global defaults: deny anything not explicitly allowed
allow_by_default: false
# Filesystem rules
filesystem:
# The agent can write anywhere inside /workspace
- action: allow
path: "/workspace/**"
operation: [read, write, edit, delete]
# The agent can read system files but never write to them
- action: allow
path: "/etc/**"
operation: [read]
- action: deny
path: "/etc/**"
operation: [write, edit, delete]
# Absolute prohibition on sensitive paths
- action: deny
path: "/etc/passwd"
operation: [read, write, edit, delete]
- action: deny
path: "/etc/shadow"
operation: [read, write, edit, delete]
# Command rules
commands:
# Allow common build tools
- action: allow
command: ["npm", "run", "build"]
- action: allow
command: ["npm", "install"]
- action: allow
command: ["git", "status"]
- action: allow
command: ["git", "diff"]
# Deny anything that touches the database directly
- action: deny
command: ["psql"]
reason: "Direct database access is prohibited. Use the migration tool instead."
# Deny anything that modifies system state
- action: deny
command: ["systemctl"]
- action: deny
command: ["iptables"]
- action: deny
command: ["chmod"]
- action: deny
command: ["chown"]
Here's the permission broker implementation in TypeScript:
// permission-broker.ts
import { readFileSync } from 'fs';
import { parse } from 'yaml';
import { minimatch } from 'minimatch';
interface PolicyRule {
action: 'allow' | 'deny';
path?: string;
command?: string[];
operation?: string[];
reason?: string;
}
interface Policy {
allow_by_default: boolean;
filesystem: PolicyRule[];
commands: PolicyRule[];
}
export class PermissionBroker {
private policy: Policy;
constructor(policyPath: string) {
this.policy = parse(readFileSync(policyPath, 'utf-8'));
}
evaluateFileOp(path: string, operation: string): Decision {
// Find the first matching rule (rules are evaluated top-down)
for (const rule of this.policy.filesystem) {
if (rule.path && minimatch(path, rule.path)) {
if (rule.operation && !rule.operation.includes(operation)) {
continue;
}
return {
allowed: rule.action === 'allow',
reason: rule.reason ?? `Matched rule: ${rule.path} (${rule.action})`,
};
}
}
// No match — fall back to default
return {
allowed: this.policy.allow_by_default,
reason: 'No matching rule, using default',
};
}
evaluateCommand(argv: string[]): Decision {
const cmd = argv[0];
for (const rule of this.policy.commands) {
if (rule.command && rule.command[0] === cmd) {
// Check if the full command matches the rule's command pattern
const matches = rule.command.every((part, i) => part === argv[i]);
if (matches) {
return {
allowed: rule.action === 'allow',
reason: rule.reason ?? `Matched command rule: ${cmd} (${rule.action})`,
};
}
}
}
return {
allowed: this.policy.allow_by_default,
reason: 'No matching command rule, using default',
};
}
}
interface Decision {
allowed: boolean;
reason: string;
}
The broker is fail-closed: if it can't parse the policy, or if there's an exception, it returns { allowed: false }. The agent's tool layer is wrapped so that any denied call returns a structured error to the LLM, which can then adjust its approach.
5. Layer 3: The Destructive-Command Firewall — Catching the DROP TABLE
The permission broker handles policy-based decisions, but it's not designed to catch semantically dangerous commands that might slip through the policy (e.g., if the agent constructs a command that matches an allow rule but is actually destructive). That's Layer 3's job: a destructive-command firewall that pattern-matches against known-dangerous operations, regardless of policy.
I implemented this as a ruleset of regular expressions, each with a severity and a reason. The firewall runs after the permission broker allows a command but before it reaches the shell.
// destructive-firewall.ts
interface FirewallRule {
pattern: RegExp;
severity: 'critical' | 'high' | 'moderate';
reason: string;
}
const FIREWALL_RULES: FirewallRule[] = [
// Database destruction
{
pattern: /\bDROP\s+TABLE\b/i,
severity: 'critical',
reason: 'DROP TABLE is a destructive, irreversible database operation.',
},
{
pattern: /\bDROP\s+DATABASE\b/i,
severity: 'critical',
reason: 'DROP DATABASE is a destructive, irreversible database operation.',
},
{
pattern: /\bTRUNCATE\s+TABLE\b/i,
severity: 'critical',
reason: 'TRUNCATE TABLE removes all rows irreversibly.',
},
{
pattern: /\bDELETE\s+FROM\b/i,
severity: 'high',
reason: 'DELETE FROM without a WHERE clause removes all rows.',
},
{
pattern: /\bALTER\s+TABLE\b.*\bDROP\b/i,
severity: 'critical',
reason: 'ALTER TABLE DROP removes a column or constraint irreversibly.',
},
// Filesystem destruction
{
pattern: /\brm\s+-rf\s+\/\b/i,
severity: 'critical',
reason: 'Recursive force delete on the root directory.',
},
{
pattern: /\brm\s+-rf\s+\/\.\*\b/i,
severity: 'critical',
reason: 'Recursive force delete on root-level hidden files.',
},
{
pattern: /\bmkfs\b/i,
severity: 'critical',
reason: 'Filesystem formatting operation.',
},
{
pattern: /\bdd\s+if=.*\s+of=\/dev\//i,
severity: 'critical',
reason: 'Direct block device write.',
},
// Git destruction
{
pattern: /\bgit\s+push\s+.*--force\b/i,
severity: 'critical',
reason: 'Force push overwrites remote history.',
},
{
pattern: /\bgit\s+reset\s+--hard\b/i,
severity: 'high',
reason: 'Hard reset discards uncommitted changes.',
},
// System state
{
pattern: /\bsystemctl\s+(stop|disable)\s+.*/i,
severity: 'high',
reason: 'Stopping or disabling a system service.',
},
{
pattern: /\bchmod\s+777\b/i,
severity: 'high',
reason: 'World-writable permissions on a file or directory.',
},
{
pattern: /\bchown\s+-R\b/i,
severity: 'high',
reason: 'Recursive ownership change.',
},
];
export function evaluateFirewall(command: string): FirewallVerdict | null {
for (const rule of FIREWALL_RULES) {
if (rule.pattern.test(command)) {
return {
blocked: true,
severity: rule.severity,
reason: rule.reason,
};
}
}
return null;
}
interface FirewallVerdict {
blocked: boolean;
severity: string;
reason: string;
}
The firewall is the last line of defense before the command hits the shell. It's deliberately conservative — if a command looks destructive, it gets blocked. The agent receives a clear error message explaining why the command was blocked, which often prompts it to choose a safer alternative (e.g., using a migration tool instead of raw SQL).
6. Layer 4: Audit Trail and Rollback — Undoing the Unthinkable
The first three layers prevent most disasters, but defense in depth means assuming something will get through. Layer 4 is the safety net: a complete audit trail with automated rollback capability.
The Audit Trail
Every mutation the agent makes is logged to a structured audit file. I use a JSONL (JSON Lines) format for easy querying:
{
"timestamp": "2025-01-15T10:32:11Z",
"agent": "claude-code-3.7",
"session": "sess_8f3a2b",
"tool": "bash",
"command": "npm install --save-dev typescript",
"cwd": "/workspace",
"decision": {
"layer2": "allow",
"layer3": "allow"
},
"pre_image": {
"files_changed": [],
"db_snapshot": "/var/audit/snapshots/sess_8f3a2b_pre_001.sql"
}
}
The Rollback Mechanism
For file mutations, I maintain a Git-based snapshot before each agent session. The agent runs in a working tree that's a clone of the repository. Before the session starts, I create a branch and tag it. If something goes wrong, I can git reset --hard to that tag.
For database mutations, I use a pre-image SQL dump of the affected tables. Before the agent runs any command that might touch the database (detected by the firewall or the broker), I take a pg_dump of the relevant tables:
#!/usr/bin/env bash
# snapshot-db.sh — create a pre-image snapshot of a Postgres table
set -euo pipefail
TABLE=$1
SNAPSHOT_DIR="/var/audit/snapshots"
TIMESTAMP=$(date -u +%Y%m%d_%H%M%S)
mkdir -p "$SNAPSHOT_DIR"
pg_dump \
--table="$TABLE" \
--data-only \
--column-inserts \
--file="$SNAPSHOT_DIR/${TABLE}_${TIMESTAMP}.sql" \
"$DATABASE_URL"
echo "Snapshot saved: $SNAPSHOT_DIR/${TABLE}_${TIMESTAMP}.sql"
Automated Rollback
Here's the rollback script that restores a table from a pre-image snapshot:
#!/usr/bin/env bash
# rollback-db.sh — restore a table from a pre-image snapshot
set -euo pipefail
TABLE=$1
SNAPSHOT_FILE=$2
# 1. Disable triggers to avoid cascading side effects
psql "$DATABASE_URL" -c "ALTER TABLE $TABLE DISABLE TRIGGER ALL;"
# 2. Truncate the table
psql "$DATABASE_URL" -c "TRUNCATE TABLE $TABLE;"
# 3. Restore from snapshot
psql "$DATABASE_URL" -f "$SNAPSHOT_FILE"
# 4. Re-enable triggers
psql "$DATABASE_URL" -c "ALTER TABLE $TABLE ENABLE TRIGGER ALL;"
echo "Table $TABLE restored from $SNAPSHOT_FILE"
The rollback is not automatic — it requires human approval. The audit trail is designed so that a human can review the log, see exactly what the agent did, and decide whether to roll back. This is a crucial design decision: you don't want an automated system undoing changes without understanding the consequences. But the capability is there, and it's fast.
7. The Incident: How the Guardrails Saved the Database
Here's the real-world scenario that validated the whole architecture. I was running a refactoring session with Claude Code on a staging replica of our production database. The agent was tasked with "consolidate the user profile tables into a single users table." It started making changes, then decided the old users_v2 table was obsolete.
Here's the sequence of events, exactly as the audit log recorded them:
[10:31:44] Layer 2 (Permission Broker): Evaluating command: psql -c "DROP TABLE users_v2;"
[10:31:44] Layer 2 (Permission Broker): DENIED — Direct database access is prohibited. Use the migration tool instead.
[10:31:44] Agent received error: "Direct database access is prohibited. Use the migration tool instead."
[10:31:45] Agent adjusted approach: Running migration tool instead...
[10:31:46] Layer 2 (Permission Broker): Evaluating command: ./migrate.sh --down 3
[10:31:46] Layer 2 (Permission Broker): ALLOWED — Matches command rule: ./migrate.sh
[10:31:46] Layer 3 (Destructive-Command Firewall): Evaluating command: ./migrate.sh --down 3
[10:31:46] Layer 3 (Destructive-Command Firewall): ALLOWED — No matching destructive pattern.
[10:31:47] Layer 4 (Audit Trail): Logging mutation with pre-image snapshot...
[10:31:47] Layer 4 (Audit Trail): Snapshot saved: users_v2_20250115_103147.sql
[10:31:48] Migration executed successfully.
What happened: The agent tried to run a raw DROP TABLE command. Layer 2 blocked it because the policy explicitly prohibits direct psql access. The agent received the error, understood it, and adjusted its approach to use the migration tool — which is exactly the intended behavior. The migration tool was allowed, the audit trail captured the pre-image snapshot, and the migration ran safely.
But here's the critical part: what if Layer 2 had failed? Suppose the agent had constructed a command that bypassed the policy — e.g., by using a shell alias or a different binary. Layer 3 would have caught it, because the DROP TABLE pattern is a hard block. And if Layer 3 had somehow missed it, Layer 4's audit trail would have captured the pre-image, allowing a rollback.
That's the power of defense in depth: three independent chances to catch the same mistake, and a fourth layer to undo it if all three fail.
8. Hardening and Production Considerations
The architecture I've described is a solid baseline, but production use requires additional hardening. Here are the key considerations I've learned:
8.1 Performance Overhead
The sandbox adds ~50-100ms of startup overhead per command. The permission broker and firewall add ~1-2ms per tool call. For most agent workloads, this is negligible. But if you're running thousands of tool calls per session, the sandbox startup can become noticeable. Mitigation: reuse a single sandbox session for the agent's entire run, rather than spawning a new bwrap per command.
8.2 False Positives
The firewall is deliberately conservative. I've had it block legitimate commands like rm -rf node_modules (which is safe inside /workspace). The fix: add path-aware rules. If the command's target is inside the sandbox workspace, allow it; if it's outside, block it.
// Refined firewall rule for rm -rf
{
pattern: /\brm\s+-rf\b/i,
severity: 'high',
reason: 'Recursive force delete. Only allowed inside /workspace.',
allowedPaths: ['/workspace/**'], // New field
}
8.3 Agent-Specific Quirks
Different agents have different tool-calling conventions. Claude Code uses Bash and Edit tools; Cursor uses runCommand; Aider uses run. Your permission broker needs to normalize these into a common interface. I wrote a thin adapter layer that maps each agent's tool calls to a standardized ToolCall object:
interface ToolCall {
type: 'bash' | 'file_edit' | 'file_read' | 'file_write';
command?: string[];
path?: string;
content?: string;
}
8.4 Secrets Management
Even with network isolation, the agent might read secrets from environment variables or .env files. I added a policy rule that denies read access to any file matching *.env* or containing SECRET/TOKEN/PASSWORD in the path. The agent can use secrets but can't read them directly.
8.5 CI/CD Integration
I integrate the guardrail architecture into CI/CD by wrapping the agent invocation in a Docker container that includes the sandbox, broker, and firewall as a single entrypoint. This makes the guardrails reproducible across environments and easy to test.
Frequently Asked Questions
Why not just run the agent without root access?
You absolutely should, if you can. The guardrail architecture is for cases where you need elevated permissions — e.g., the agent must install system packages, modify service configs, or run privileged operations. If your agent only touches a repository, run it as a non-root user and skip the sandbox entirely. Root access is a requirement, not a privilege.
What if the agent finds a way around the firewall?
That's why you have Layer 4. The audit trail and rollback are designed to catch anything that slips through. The firewall is a probabilistic defense — it catches known patterns, but a clever agent could obfuscate a command (e.g., rm -rf / becomes rm -rf / with a variable substitution). The audit trail is the deterministic defense: it records every mutation with a pre-image, so even if the firewall is bypassed, you can roll back.
Is this architecture agent-agnostic?
Yes, with a caveat. The permission broker needs an adapter for each agent's tool-calling convention, but the sandbox, firewall, and audit trail are completely agent-agnostic. They operate at the OS level, wrapping whatever process the agent spawns. I've used this architecture with Claude Code, Cursor, and a custom LangChain-based agent — the only change needed was the tool-call adapter.
The takeaway: giving coding agents root access isn't reckless if you engineer the containment. The four-layer guardrail architecture — sandbox, permission broker, destructive-command firewall, and audit trail — turns an autonomous superuser into a bounded, auditable, and reversible tool. It's not about trusting the agent; it's about not having to. For more on AI engineering and developer tooling, check out Tamiz's Insights or explore the broader engineering articles at tamiz.pro.