13 KiB
Security Hardening Design
Date: 2026-04-03 Issues: #69, #70, #74, #75 Approach: Hybrid — Core boundaries + Middleware policies
Overview
OpenACP has multiple critical security vulnerabilities across agent filesystem access, process execution, agent installation, plugin system, and tunnel subsystem. This design addresses all 15 remaining vulnerabilities in a single branch using a hybrid approach: core enforces hard boundaries (cannot be bypassed), security plugin handles configurable policies.
Current State (Vulnerabilities)
| Area | Critical | High | Medium |
|---|---|---|---|
| Agent filesystem/process (#69) | 2 | 3 | 1 |
| Agent installation (#70) | 2 | 2 | 2 |
| Plugin system (#74) | 1 | 0 | 0 |
| Tunnel system (#75) | 1 | 3 | 0 |
| Total | 5 | 8 | 3 |
Already fixed (not in scope): shell injection (#74), plugin crash handling (#74), execSync blocking (#74), timing attack (#75), process leak (#75).
Section 1: Workspace Sandbox (Core)
PathGuard Module
File: src/core/security/path-guard.ts
PathGuard validates all file operations against workspace boundaries. It receives cwd (immutable from session), allowedPaths (from config), and .openacpignore patterns.
Interface:
interface PathGuardOptions {
cwd: string;
allowedPaths: string[];
ignorePatterns: string[]; // from .openacpignore + defaults
}
class PathGuard {
constructor(options: PathGuardOptions);
validatePath(targetPath: string, operation: 'read' | 'write'): { allowed: boolean; reason: string };
}
Validation logic:
- Normalize path via
path.resolve(), resolve symlinks viafs.realpathSync() - Check path starts with
cwdor any entry inallowedPaths— if not → reject - Check path against
.openacpignorepatterns — if match → reject - Return
{ allowed: true }
.openacpignore
Located at {cwd}/.openacpignore. Syntax identical to .gitignore (use ignore npm package).
Built-in default patterns (always applied, even without file):
.env*
*.key
*.pem
.ssh/
.aws/
.openacp/
**/credentials*
**/secrets*
**/*.secret
User patterns in .openacpignore are merged on top of defaults. Agent cannot write to .openacpignore itself (hardcoded in PathGuard).
Core Enforcement Points
agent-instance.ts:566-579→readTextFile(): callpathGuard.validatePath(path, 'read')beforereadTextFileWithRange()agent-instance.ts:581-594→writeTextFile(): callpathGuard.validatePath(path, 'write')beforefs.writeFileagent-instance.ts:699-703→ attachment file reading: callpathGuard.validatePath(path, 'read')beforefs.promises.readFile()terminal-manager.ts:40-123→createTerminal(): validatecwdparam is within allowed boundariesread-text-file.ts:7-17→readTextFileWithRange(): add PathGuard check (this is the underlying utility used by readTextFile)- On reject → return error to agent (no crash, agent sees "file restricted" message)
API/SSE Path Redaction
Agent output streamed via SSE or returned via API should not leak absolute file paths outside workspace:
viewer-routes.ts:40-63→/api/file/:idand/api/diff/:id: replace absolutefilePathwith workspace-relative path (stripcwdprefix)workspace.ts:14-19→/workspaceendpoint: already requiressessions:readscope, acceptable to expose workspace directory to authenticated clients- SSE
agent:eventpayloads: no additional filtering needed (tool outputs may reference paths, but the sandbox prevents actual access)
Config
workspace: {
security: {
allowedPaths: string[] // default: [] — cwd only
envWhitelist: string[] // default: see Section 2
}
}
Section 2: Environment Variable Filtering (Core)
EnvFilter Module
File: src/core/security/env-filter.ts
function filterEnv(
processEnv: Record<string, string>,
agentEnv?: Record<string, string>,
whitelist?: string[]
): Record<string, string>;
Logic:
- Start with empty object
- Copy only whitelisted keys from
process.env(supports glob patterns likeLC_*) - Merge
agentEnvon top (agent-defined vars from agent config) - Return filtered env
Default whitelist:
const DEFAULT_ENV_WHITELIST = [
"PATH", "HOME", "SHELL", "LANG", "LC_*", "TERM", "USER", "LOGNAME",
"TMPDIR", "XDG_*", "NODE_ENV", "EDITOR"
];
Admin extends via workspace.security.envWhitelist in config.
Enforcement Points
agent-instance.ts:197— replace{ ...process.env, ...agentDef.env }withfilterEnv(process.env, agentDef.env)terminal-manager.ts:78— replace{ ...process.env, ...env }withfilterEnv(process.env, env)- Tunnel provider spawn calls (ngrok.ts, bore.ts, cloudflare.ts, tailscale.ts) — these inherit parent env implicitly via
spawn()without explicitenvoption. Addenv: filterEnv(process.env, providerEnv)to each spawn call.
Backward Compatibility
Default whitelist covers all vars needed for normal agent operation. If an agent needs a specific var, admin adds it to config.
Section 3: Auto-Approve Fix + Permission Hardening (Core)
Fix Auto-Approve Bypass
Remove the description-based auto-approve in session-bridge.ts:365-396.
Current PermissionRequest type (core/types.ts:44-48) only has id, description, options — no toolId field. Two options:
Option chosen: Instead of adding toolId to the ACP protocol type, simplify by removing auto-approve entirely. The bypass was originally added for convenience but creates a security hole. Permission requests should always go through the normal approval flow (user approval or bypass mode for headless API).
// BEFORE (vulnerable):
if (request.description.toLowerCase().includes("openacp")) { ... }
// AFTER (secure):
// Remove the entire description-based auto-approve block.
// Auto-approve is only available via explicit bypass mode (which requires sessions:dangerous scope).
This is the safest approach — no string matching, no toolId dependency, no way for agents to self-approve.
Headless API Bypass Protection
POST /sessions/:id/dangerous→ require new scopesessions:dangerous(separate fromsessions:write)- Log warning when bypass is enabled
Workspace Path Sanitization
Fix resolveWorkspace() in config.ts:
resolveWorkspace(input?: string): string {
if (!input) return expandAndCreate(this.config.workspace.baseDir);
// Named workspace only — no absolute paths, no traversal
const name = input.replace(/[^a-zA-Z0-9_-]/g, '');
if (name !== input) throw new Error(`Invalid workspace name: "${input}"`);
return expandAndCreate(path.join(this.config.workspace.baseDir, name));
}
Reject absolute paths, ~ paths, and .. traversal. Only allow simple named workspaces.
Section 4: Agent Installation Security (Core)
Checksum Verification
Registry adds sha256 field per binary target. New download flow:
- Download with size limit
- Verify SHA-256 hash
- Validate tar contents (list before extract)
- Extract
const buffer = await downloadWithSizeLimit(archiveUrl, MAX_DOWNLOAD_SIZE);
if (expectedHash) {
const actualHash = crypto.createHash('sha256').update(buffer).digest('hex');
if (actualHash !== expectedHash) {
throw new Error(`Integrity check failed: expected ${expectedHash}, got ${actualHash}`);
}
}
If registry has no hash → log warning, allow install (backward compat) but display warning to user.
Download Size Limit
MAX_DOWNLOAD_SIZE = 500 * 1024 * 1024(500MB)readResponseWithProgress()aborts whenreceived > MAX_DOWNLOAD_SIZE
Validate-Before-Extract (Fix TOCTOU)
Use tar -tf to list archive contents before extraction:
- Reject entries containing
.. - Reject absolute paths
- Reject symlinks pointing outside destDir
- Only proceed with
tar -xzfif all entries pass
Uninstall Path Validation
const agentsDir = path.resolve(expandHome("~/.openacp/agents"));
const realPath = path.resolve(agent.binaryPath);
if (!realPath.startsWith(agentsDir + path.sep)) {
throw new Error(`Refusing to delete path outside agents directory: ${realPath}`);
}
File Permissions
agents.jsonand registry cache → write withmode: 0o600mkdirSyncfor agents dir →mode: 0o700
Shared with install-binary.ts (Tunnel Binaries)
Same patterns apply: size limit, tar content validation before extract, checksum when available.
Section 5: Plugin System Hardening
npm --ignore-scripts
Add flag to all npm install calls:
plugin-installer.ts:67→ add--ignore-scriptswizard.ts:304→ add--ignore-scriptsto setup wizard npm installwizard.ts:357→ add--ignore-scriptsto setup wizard npm install
await execAsync(`npm install ${packageName} --prefix "${dir}" --save --ignore-scripts`, {
timeout: 60000,
});
Prevents all postinstall/preinstall RCE across all npm install paths.
Plugin Scope Restriction (Configurable)
// Config
plugins: {
trustedScopes: string[] // default: ["@openacp"]
}
- If
trustedScopesis non-empty → only allow packages from those scopes - If empty → allow any (backward compat)
- Warn user when installing packages outside trusted scope
Plugin Permission Audit Logging
Log each plugin access to ctx.core (configManager, sessionManager, adapters). Security plugin can subscribe to plugin:coreAccess events for monitoring.
Section 6: Tunnel Security
Auth Default On
- Tunnel viewer routes →
auth: trueby default - On first tunnel start → auto-generate random token:
crypto.randomBytes(32).toString('hex') - Token stored in tunnel config, displayed to user at tunnel creation
- User must explicit set
auth.enabled: falsefor public access
XSS Sanitization
Fix file-viewer.ts:158-164. Current code already loads DOMPurify from CDN (cdn.jsdelivr.net/npm/dompurify@3.2.4) but has two issues:
- Falls back to unsanitized
innerHTMLif DOMPurify fails to load - External CDN dependency can be compromised or unavailable
Fix:
- Remove CDN dependency for DOMPurify
- Implement inline
sanitizeHtml()function directly in the template string (this is a server-rendered template, not a separate JS file) - The sanitizer strips
<script>tags,on*event attributes,javascript:URIs - Allows safe tags:
p,h1-h6,ul,ol,li,a,code,pre,blockquote,em,strong,img - Fallback when
markedis unavailable already escapes HTML correctly (line 162-163) — no change needed there
Credentials via Environment Variables
Replace CLI arguments with env vars:
| Provider | Before | After |
|---|---|---|
| ngrok | --authtoken TOKEN |
env: { NGROK_AUTHTOKEN: token } |
| bore | --secret SECRET |
env: { BORE_SECRET: secret } |
| openacp | --token TOKEN |
env: { CLOUDFLARE_TUNNEL_TOKEN: token } |
Process args no longer contain secrets → ps aux safe.
Section 7: Testing Strategy
New Test Files
| File | Covers |
|---|---|
src/core/security/__tests__/path-guard.test.ts |
PathGuard: cwd boundary, allowedPaths, .openacpignore, symlink escape, .. traversal, default deny patterns |
src/core/security/__tests__/env-filter.test.ts |
EnvFilter: whitelist, glob patterns, agent env merge, secrets not leaked |
src/core/agents/__tests__/agent-installer-security.test.ts |
Checksum verify, size limit abort, tar content validation, uninstall path validation |
src/plugins/tunnel/__tests__/tunnel-security.test.ts |
Auth default on, XSS sanitization, credentials in env not args |
Updated Test Files
| File | Updates |
|---|---|
src/core/sessions/__tests__/session-bridge-autoapprove.test.ts |
Verify description-based bypass no longer works, only toolId whitelist |
src/core/plugin/__tests__/plugin-installer.test.ts |
Verify --ignore-scripts flag present, trusted scope rejection |
Key Test Scenarios
PathGuard:
- Allow read file within cwd
- Reject read file outside cwd (
/etc/passwd,~/.ssh/id_rsa) - Reject path traversal (
cwd + "/../../../etc/passwd") - Reject symlink pointing outside cwd
- Reject
.openacpignorematched files (.env,*.key) - Allow file in
allowedPathsconfig - Default deny patterns apply even without
.openacpignorefile - Agent cannot write to
.openacpignoreitself
EnvFilter:
- Only whitelisted vars passed through
- Glob patterns work (
LC_*matchesLC_ALL) AWS_SECRET_ACCESS_KEYnot leaked- Agent-defined vars merged correctly
Auto-approve:
- Description containing "openacp" NO LONGER auto-approves
- Auto-approve block is fully removed (no string matching, no toolId)
- Only bypass mode (requiring
sessions:dangerousscope) can skip permissions
Installer:
- Mismatched SHA-256 rejects install
- Download > 500MB aborted
- Tar with
../entries rejected BEFORE extraction - Uninstall path outside
~/.openacp/agents/rejected
Plugin:
npm installincludes--ignore-scripts(plugin-installer.ts AND wizard.ts)- Untrusted scope warns/rejects per config
API path redaction:
/api/file/:idreturns workspace-relative path, not absolute/api/diff/:idreturns workspace-relative path, not absolute
Tunnel:
- Auth enabled by default (viewer routes require token)
- Markdown XSS payloads sanitized
- Credentials passed via env vars, not CLI args