Skip to content

About

A Rust-based security control plane for AI agents, featuring policy-enforced command execution, isolated Linux Docker sandboxes, MCP integration, persistent audit logging, and Prometheus observability.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Agent Execution Control Plane

Policy-enforced, sandboxed execution gateway for AI agents and automated tooling.

License: Apache-2.0 Language: Rust Unsafe Code MCP: rmcp 3.12 CI

agent-execution-control-plane sits between AI agents and the operating system. Every HTTP or Model Context Protocol (MCP) execution request is authenticated, structurally validated, evaluated against a deterministic default-deny policy engine, bounded by administrative resource ceilings, executed inside an isolated Linux container, persisted to a SQLite audit ledger, and cleaned up deterministically.


Visual Overview

System Startup & Readiness Isolated Sandbox Execution
System Startup and Readiness Successful Isolated Execution
Configuration validation, structured JSON startup logs, /healthz, and /readyz on Ubuntu ARM64 with rootless Docker. Policy-approved /bin/cat /workspace/hello.txt execution inside an ephemeral container (COMPLETED, cleaned, zero leftover containers).

Problem Statement

Granting AI agents direct shell or host access exposes systems to prompt-injection command execution, credential exfiltration, arbitrary filesystem reads/writes, symlink escapes, fork bombs, and orphaned background processes. Simple shell-string blacklists are brittle and easily bypassed.

This project replaces unrestricted host execution with an explicit security gateway:

  • Commands are structured (executable + args[]) rather than shell-interpolated strings.
  • Authorization is default-deny and decoupled from agent identity.
  • Limits (CPU, memory, PIDs, temporary disk, output bytes, concurrency, and timeouts) are enforced independently of agent requests.
  • HTTP and MCP transports share the exact same ControlPlaneService enforcement pipeline.

Core Capabilities

  • Controlled HTTP Execution API: POST /v1/executions (sync or ?mode=async), GET /v1/executions, GET /v1/executions/{id}, POST /v1/executions/{id}/cancel, POST /v1/executions/validate, POST /v1/policy/evaluate, GET /v1/agent/whoami.
  • Default-Deny Policy Engine: Global executable denylists, per-agent executable & argument regex allowlists/denylists, container image allowlists, per-rule environment key allowlists, network denial (none default), human approval_id gates, workspace path canonicalization + symlink-escape detection, and explainable ALLOW/DENY traces.
  • Explicit Execution State Machine: Enforced transitions across RECEIVED → VALIDATING → AUTHORIZED → STARTING → RUNNING → COMPLETED alongside REJECTED, FAILED, TIMED_OUT, CANCELLED, and CLEANUP_FAILED.
  • Hardened Linux Container Isolation (bollard): Non-root 65532:65532, ReadOnlyRootfs, noexec,nosuid,nodev bounded /tmp tmpfs, CapDrop: ALL, no-new-privileges:true, custom ARM64/AMD64 seccomp-BPF profile, network_mode: none, cgroups v2 CPU/memory/swap/PIDs limits, ulimits, and guaranteed container cleanup.
  • Official MCP Gateway (rmcp): Supports Streamable HTTP (/mcp, protected by bearer authentication, loopback host allowlist, and strict Origin rejection) and stdio (mcp-stdio subcommand) exposing execute_command, inspect_execution, cancel_execution, list_execution_history, and validate_policy.
  • Persistent SQLite Audit Ledger: sqlx-backed WAL SQLite persistence (executions and execution_transitions), storing decisions, lifecycle transitions, bounded outputs, and env key names only (never secret values).
  • Observability & Operational Health: /healthz, /readyz, structured JSON/pretty tracing logs with x-request-id, and Prometheus /metrics.

Architecture

flowchart TD
    Agent["AI Agent / MCP Client"] -->|"HTTPS / HTTP + Bearer Token"| API["Axum HTTP Router (/v1/*, /mcp)"]
    AgentLocal["Local MCP Host"] -->|"stdin/stdout JSON-RPC + AECP_AGENT_TOKEN"| MCPStdio["MCP stdio Transport (rmcp)"]

    API --> Auth["AgentRegistry (Constant-Time SHA-256 Auth)"]
    MCPStdio --> Auth

    Auth --> Service["ControlPlaneService (Single Enforcement Path)"]
    Service --> Validator["Structural Request Validator"]
    Validator --> Policy["PolicyEngine + PathGuard (Default-Deny)"]
    Policy -->|"ALLOW + Clamped Plan"| ExecMgr["ExecutionManager (Semaphore, State Machine, Timers)"]
    Policy -->|"DENY"| Audit["SQLite AuditStore (sqlx WAL)"]

    ExecMgr --> Runtime["SandboxRuntime Trait"]
    Runtime --> Docker["DockerSandboxRuntime (bollard + seccomp-BPF)"]
    Docker --> Container["Ephemeral Linux Container (non-root, ro-rootfs, net=none)"]

    ExecMgr --> Audit
    ExecMgr --> Metrics["ControlPlaneMetrics (Prometheus /metrics)"]
    ExecMgr --> Logs["Structured Tracing (stderr)"]
Loading

Execution Lifecycle

stateDiagram-v2
    [*] --> RECEIVED
    RECEIVED --> VALIDATING
    VALIDATING --> REJECTED: Policy DENY
    VALIDATING --> AUTHORIZED: Policy ALLOW
    AUTHORIZED --> STARTING: Semaphore permit acquired
    AUTHORIZED --> CANCELLED: Cancelled while queued
    STARTING --> RUNNING: Container prepared & started
    STARTING --> FAILED: Prepare error
    STARTING --> TIMED_OUT: Prepare deadline exceeded
    STARTING --> CANCELLED: Cancelled during prepare
    RUNNING --> COMPLETED: Exit code 0
    RUNNING --> FAILED: Non-zero exit / OOM / runtime error
    RUNNING --> TIMED_OUT: Deadline exceeded -> SIGKILL
    RUNNING --> CANCELLED: Cancel API / SIGTERM -> SIGKILL
    COMPLETED --> CLEANUP_FAILED: Container removal error
    FAILED --> CLEANUP_FAILED: Container removal error
    TIMED_OUT --> CLEANUP_FAILED: Container removal error
    CANCELLED --> CLEANUP_FAILED: Container removal error
Loading

Security Architecture

  • Trust Boundaries: Untrusted HTTP/MCP inputs (Zone 0) are authenticated and structurally checked at ingress (Zone 1), authorized deterministically by PolicyEngine (Zone 1), orchestrated by ExecutionManager (Zone 2), dispatched to the container engine (Zone 3) over a dedicated Unix socket never mounted into any container, and executed inside a disposable unprivileged sandbox (Zone 4).
  • Memory Safety: #![forbid(unsafe_code)] is enforced at the crate root.
  • Path & Symlink Defense: src/policy/path_guard.rs rejects .. traversal, NUL/control bytes, forbidden host prefixes (/etc, /proc, /sys, /dev, /var/run/docker.sock, /run/docker.sock), symlinked workspace roots, and symlinks resolving outside canonical_root.
  • Credential Hygiene: Bearer tokens are stored and compared only as SHA-256 digests (subtle::ConstantTimeEq). Environment variables like LD_PRELOAD and DYLD_INSERT_LIBRARIES are rejected unconditionally; approved env variable values are omitted from HTTP validation responses, structured logs, and SQLite audit rows.
  • Detailed Analysis: See THREAT_MODEL.md, ARCHITECTURE.md, and SECURITY.md.

Repository Structure

agent-execution-control-plane/
├── .github/workflows/ci.yml            # fmt, clippy, Linux AMD64/ARM64 tests, Docker E2E, cargo-audit/deny, gitleaks
├── .gitignore                          # Excludes /target/, .env*, *.db*, *.log, .DS_Store
├── Cargo.toml                          # Single-crate manifest with unsafe_code = "forbid"
├── Cargo.lock                          # Pinned dependency graph
├── LICENSE                             # Apache-2.0 license
├── README.md                           # Project overview, architecture, usage, and verification evidence
├── ARCHITECTURE.md                     # Component design, state machine, gVisor/Firecracker evaluation
├── THREAT_MODEL.md                     # Trust zones, threat mitigations, and residual risks
├── SECURITY.md                         # Privilege requirements, hardening checklist, vulnerability reporting
├── CONTRIBUTING.md                     # Build/test workflow and security invariants
├── config/
│   ├── control-plane.example.toml      # Validated example configuration (non-production token hash)
│   └── seccomp-default.json            # Default-errno Linux seccomp-BPF allowlist (ARM64 & AMD64)
├── migrations/
│   └── 0001_initial_audit_schema.sql   # SQLite schema for executions & transition audit log
├── src/
│   ├── main.rs                         # Binary entrypoint (serve, mcp-stdio, validate-config, graceful shutdown)
│   ├── lib.rs                          # Crate root (#![forbid(unsafe_code)])
│   ├── config.rs                       # Strict TOML config, env overrides, fail-closed startup validation
│   ├── domain.rs                       # Core domain types, structural validation, error-to-HTTP mapping
│   ├── auth.rs                         # Constant-time SHA-256 bearer token authentication
│   ├── control_plane.rs                # Unified ControlPlaneService shared by HTTP and MCP
│   ├── api.rs                          # Axum router, health/readiness/metrics endpoints, auth middleware
│   ├── observability.rs                # Prometheus metrics collector & /metrics renderer
│   ├── policy/
│   │   ├── mod.rs                      # PolicyDecision, PolicyExplanation, ApprovedExecutionPlan
│   │   ├── engine.rs                   # Default-deny rule engine & resource clamping
│   │   └── path_guard.rs               # Host workspace canonicalization & symlink-escape protection
│   ├── execution/
│   │   ├── mod.rs                      # ExecutionManager (concurrency semaphore, timeouts, cancel, cleanup)
│   │   └── state_machine.rs            # Explicit ExecutionState transitions & ExecutionRecord
│   ├── sandbox/
│   │   ├── mod.rs                      # SandboxRuntime trait, CancelSignal, UnavailableSandboxRuntime
│   │   └── docker.rs                   # Bollard Docker Engine adapter (seccomp, cgroups v2, cap_drop, ro-rootfs)
│   ├── mcp/
│   │   ├── mod.rs                      # Streamable HTTP & stdio MCP transport wiring (rmcp)
│   │   └── tools.rs                    # 5 MCP tools delegating strictly to ControlPlaneService
│   └── audit/
│       └── mod.rs                      # SQLx SQLite WAL audit store & migration runner
├── tests/
│   ├── support/fake_sandbox.rs         # Deterministic SandboxRuntime test double
│   ├── api_foundation.rs               # HTTP health, auth, validation, and policy-enforcement tests
│   ├── security_policy.rs              # Path traversal, symlink escape, env/arg/network/approval tests
│   ├── execution_lifecycle.rs          # State machine, timeout, cancel, concurrency, cleanup failure tests
│   ├── mcp_integration.rs              # MCP Streamable HTTP auth, tool schema, policy & cancel tests
│   ├── audit_observability.rs          # SQLite restart persistence, secret-scrubbing & /metrics tests
│   └── docker_linux_e2e.rs             # Real Linux container containment suite (gated on AECP_DOCKER_TEST=1)
└── docs/assets/screenshots/            # Genuine Linux runtime Terminal screenshots

Technology Stack

Responsibility Crate / Tool
Language Rust (2024 edition, rustc 1.100.x, #![forbid(unsafe_code)])
Async Runtime tokio
HTTP Server axum (0.8), tower-http (0.6)
Serialization & Config serde, serde_json, toml
Policy Regex Matching regex
Linux Container Runtime bollard (0.21, Docker Engine API 1.53)
MCP Gateway rmcp (3.12), schemars (1.2)
Persistent Audit Store sqlx (0.9, SQLite WAL)
Observability tracing, tracing-subscriber, metrics, metrics-exporter-prometheus (0.18)
Cryptography & IDs sha2, subtle, uuid, chrono

Installation & Prerequisites

Linux (Production / Full Isolation Verification)

  • Rust stable toolchain (1.88+) with C toolchain (gcc, pkg-config) for bundled SQLite compilation
  • Docker Engine (24+) with cgroups v2 and seccomp enabled (rootless Docker recommended)
  • Pre-pulled approved container image (e.g., docker pull alpine:3.20)

macOS (Development & Control-Plane Testing)

  • Rust stable toolchain (rustup, cargo, clippy, rustfmt)
  • Note: macOS runs unit, policy, lifecycle, MCP, and SQLite tests natively; real Linux container isolation (docker_linux_e2e) requires a Linux host or an Ubuntu ARM64 Lima VM.

Configuration

Copy and customize config/control-plane.example.toml:

  • [server]: bind_address, max_request_body_bytes, request_timeout_secs
  • [logging]: level (trace|debug|info|warn|error), format (json|pretty)
  • [runtime]: kind ("docker" | "unavailable"), docker_socket (e.g., unix:///run/user/1000/docker.sock for rootless Docker), seccomp_profile_path, container_user (must be non-root, e.g., "65532:65532")
  • [audit]: database_url (e.g., "sqlite://./data/aecp-audit.db")
  • [limits]: hard ceilings (default_timeout_ms, max_timeout_ms, max_args, max_arg_bytes, max_env_vars, max_env_value_bytes, max_output_bytes, max_concurrent_executions, default_profile, max_profile)
  • [policy]: default_network ("none"), default_image, allowed_images, denied_executables, [[policy.workspaces]], [[policy.rules]], approved_approval_ids
  • [[agents]]: id, display_name, token_sha256, enabled, max_profile, allowed_permissions

Supported environment overrides:

  • AECP_CONFIG: path to TOML config when --config is omitted
  • AECP_BIND_ADDR: overrides server.bind_address
  • AECP_LOG_LEVEL: overrides logging.level
  • AECP_LOG_FORMAT: overrides logging.format (json or pretty)
  • AECP_AGENT_TOKEN / AECP_AGENT_ID: required credentials for mcp-stdio mode

Running the System

# 1. Build release binary
cargo build --release

# 2. Validate configuration (fails closed on invalid security invariants)
./target/release/agent-execution-control-plane validate-config --config config/control-plane.example.toml

# 3. Ensure approved sandbox image is present locally
docker pull alpine:3.20

# 4. Start HTTP + Streamable HTTP MCP control plane
./target/release/agent-execution-control-plane serve --config /path/to/your-config.toml

# 5. Optional: Run local stdio MCP gateway
AECP_AGENT_TOKEN="your-agent-token" ./target/release/agent-execution-control-plane mcp-stdio --config /path/to/your-config.toml

Real Execution Examples

Submit a policy-approved sandbox execution

curl -s -X POST http://127.0.0.1:8080/v1/executions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "executable": "/bin/cat",
    "args": ["/workspace/hello.txt"],
    "working_dir": "/workspace",
    "mounts": [{"container_path": "/workspace", "read_write": false}],
    "requested_permissions": ["read_workspace"]
  }' | jq .

Observed response on Ubuntu 26.04 ARM64 with rootless Docker:

{
  "execution_id": "d28c0e3a-1281-4dd0-9a3c-0d8710924b35",
  "agent_id": "agent-inspector",
  "state": "COMPLETED",
  "executable": "/bin/cat",
  "args": ["/workspace/hello.txt"],
  "image": "alpine:3.20",
  "rule_id": "allow-cat-workspace",
  "policy_verdict": "ALLOW",
  "exit_code": 0,
  "oom_killed": false,
  "stdout": "Hello from policy-enforced Linux sandbox workspace!\n",
  "cleanup_status": "cleaned"
}

Policy rejection (403 Forbidden)

curl -s -X POST http://127.0.0.1:8080/v1/executions \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"executable": "/bin/sh", "args": ["-c", "id"]}' | jq .

Screenshots

Policy Rejection (Denied Executable, Path Traversal & MCP Denial)

Policy Rejection HTTP 403 policy denial for /bin/sh, HTTP 400 structural path-traversal rejection (..), and MCP validate_policy denial for /usr/bin/curl.

Persistent Execution Audit & SQLite Storage

Execution Audit GET /v1/executions alongside direct SQLite inspection confirming both COMPLETED and REJECTED records persist without storing sensitive env values.

Prometheus Observability Metrics

Observability Metrics Live GET /metrics output tracking policy decisions, execution outcomes, active count, cleanup failures, audit errors, and duration quantiles.


Testing and Verification

Test Commands

cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test

Verified Results

Suite / Check Environment Outcome
cargo fmt --check & cargo clippy --all-targets -- -D warnings macOS aarch64-apple-darwin (rustc 1.100.0) Passed (0 warnings)
Unit tests (src/lib.rs: config, auth, domain, state machine) macOS & Ubuntu 26.04 ARM64 12 passed, 0 failed
HTTP API foundation (tests/api_foundation.rs) macOS & Ubuntu 26.04 ARM64 4 passed, 0 failed
Security policy & symlink guard (tests/security_policy.rs) macOS & Ubuntu 26.04 ARM64 5 passed, 0 failed
Execution lifecycle (tests/execution_lifecycle.rs) macOS & Ubuntu 26.04 ARM64 5 passed, 0 failed
MCP Streamable HTTP (tests/mcp_integration.rs) macOS & Ubuntu 26.04 ARM64 2 passed, 0 failed
SQLite audit & Prometheus (tests/audit_observability.rs) macOS & Ubuntu 26.04 ARM64 1 passed, 0 failed
Real Linux rootless Docker E2E (tests/docker_linux_e2e.rs) Ubuntu 26.04 ARM64 (Linux 7.0.0, rootless Docker + systemd cgroups v2) Passed (UID 65532, RO rootfs, /tmp noexec, CapEff=0, NoNewPrivs=1, Seccomp=2, network=none, timeout kill, pids_limit=16, memory_mb=32 OOM kill, zero leaked containers)
Binary hardening & release exposure audit (REA) Release Mach-O (arm64) & Linux ELF (aarch64) ELF: PIE, NX, Full RELRO (BIND_NOW), stack protector, fortify, no RPATH/RUNPATH; Mach-O: MH_PIE, non-exec stack, ___stack_chk_fail, 0 exposed secrets/debug companions

Limitations

  • Shared Linux Kernel: Docker containers (even rootless with seccomp and CapDrop: ALL) share the host Linux kernel; container escapes via kernel vulnerabilities are not fully eliminated.
  • Linux AMD64 Runtime Not Locally Executed: Local verification ran on macOS arm64 and Ubuntu 26.04 aarch64 (ARM64) VM; AMD64 execution is covered in CI (ubuntu-24.04) rather than executed locally on Apple Silicon.
  • Host Workspace TOCTOU: path_guard canonicalizes and checks symlinks immediately before container creation; untrusted processes with write access to a bind-mounted host workspace could race between validation and mount. Keep workspaces read_only = true and isolated from untrusted host writers.
  • Static Approval List: policy.approved_approval_ids is configured statically in TOML rather than via an interactive out-of-band approval API.

Roadmap

  • Add gVisor (runsc) runtime selection and evaluate a Firecracker microVM SandboxRuntime backend for hostile multi-tenant workloads.
  • Interactive out-of-band human approval workflow (PENDING_APPROVAL state + signed webhook/CLI approval endpoint).
  • OIDC / mTLS agent identity federation alongside static SHA-256 bearer tokens.
  • Per-execution read-only/ephemeral container rootfs hash attestation.

Contributing

See CONTRIBUTING.md.

License

Licensed under the Apache License, Version 2.0.

About

A Rust-based security control plane for AI agents, featuring policy-enforced command execution, isolated Linux Docker sandboxes, MCP integration, persistent audit logging, and Prometheus observability.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages