AI agents are moving from simple chat interfaces to systems that can execute code, call APIs, process files, browse information, and perform multi-step tasks.
That flexibility creates a security problem.
A normal application usually controls exactly what code runs and which resources it can access. An AI agent is different because its behavior can be influenced by model output, external content, user instructions, and dynamically selected tools.
If an agent can execute arbitrary code inside the same environment as the main application, a small mistake can become a serious security incident.
A safer architecture separates the agent's execution environment from the host application.
This article explains how to design a secure hosted AI agent architecture using isolated runtime environments, with practical .NET examples and production-oriented security considerations.
Introduction
Consider an AI coding agent that receives this request:
Analyze the uploaded project,
run the tests,
fix failing tests,
and generate a report.
The agent may need to:
Read project files.
Inspect source code.
Execute commands.
Install dependencies.
Run tests.
Generate output files.
Return a summary.
Giving the agent unrestricted access to the application server is dangerous.
Instead, use an architecture such as:
User
|
v
Agent Application
|
Tool / Task Planner
|
v
Runtime Controller
|
+-----------+-----------+
| |
v v
Isolated Runtime A Isolated Runtime B
| |
Files Processes
Network Commands
Packages Temporary Data
| |
+-----------+-----------+
|
v
Sanitized Results
The central idea is simple:
The agent should not automatically share the trust boundary of the host application.
Why Agent Isolation Matters
Traditional applications usually execute predetermined code paths.
An agent can generate or select actions dynamically.
For example:
User
|
v
LLM
|
+--> Read file
|
+--> Execute command
|
+--> Call API
|
+--> Create file
|
+--> Run program
Every additional capability increases the attack surface.
Potential risks include:
Arbitrary command execution
Malicious file access
Credential theft
Network abuse
Resource exhaustion
Dependency attacks
Prompt injection
Data exfiltration
Cross-tenant access
Persistent malicious artifacts
Isolation does not eliminate these risks, but it provides an additional security boundary.
What Is an Isolated Runtime?
An isolated runtime is a controlled execution environment where agent-generated operations can run without having unrestricted access to the host system.
Depending on the security requirements, this could be based on:
Containers
Virtual machines
MicroVMs
Sandboxed runtimes
Dedicated worker processes
Restricted operating-system environments
The important characteristic is not the technology name.
It is the security boundary around execution.
Separate Control Plane and Execution Plane
A production architecture should separate agent orchestration from code execution.
Control Plane
-------------------------
Agent API
Authentication
Authorization
Task Management
Policy Engine
Audit Logs
Runtime Controller
|
v
Execution Plane
-------------------------
Isolated Runtime
Temporary Files
Processes
Network
Tools
The control plane decides what is allowed.
The execution plane performs what has been authorized.
This separation makes security policies easier to enforce.
A Basic .NET Architecture
A .NET application can represent an agent task with a simple model.
public sealed record AgentTask(
string TaskId,
string TenantId,
string Instructions,
IReadOnlyList<string> AllowedTools);
The application should not send arbitrary instructions directly to a runtime.
Instead, first validate the task.
public interface IAgentPolicy
{
Task<PolicyDecision> EvaluateAsync(
AgentTask task,
CancellationToken cancellationToken);
}
The policy layer can decide whether execution is permitted.
public sealed record PolicyDecision(
bool Allowed,
string? Reason);
Then:
var decision = await policy.EvaluateAsync(
task,
cancellationToken);
if (!decision.Allowed)
{
throw new InvalidOperationException(
decision.Reason ?? "Execution denied.");
}
This creates a clear authorization boundary before runtime execution.
Never Trust Model Output
One of the most important principles for agent security is:
LLM output is data, not authorization.
Suppose the model generates:
{
"tool": "execute_command",
"command": "dotnet test"
}
The application should not assume that because the model selected the tool, execution is allowed.
Instead:
LLM Decision
|
v
Policy Validation
|
v
Tool Authorization
|
v
Runtime Restrictions
|
v
Execution
The model can request an operation.
The application decides whether the operation is permitted.
Define Explicit Tool Permissions
Avoid giving every agent access to every tool.
For example:
public enum AgentTool
{
ReadFile,
WriteFile,
RunTests,
ExecuteProcess,
HttpRequest
}
A policy can define which tools are available.
var allowedTools = new HashSet<AgentTool>
{
AgentTool.ReadFile,
AgentTool.RunTests
};
If the agent requests:
ExecuteProcess
the policy layer can reject it.
This is more secure than relying on prompt instructions such as:
Do not execute dangerous commands.
Prompts are not security boundaries.
Runtime Resource Limits
An isolated environment should have explicit resource limits.
At minimum, consider:
CPU
Memory
Disk
Process Count
Execution Time
Network Connections
File Size
Output Size
For example:
Maximum execution time: 2 minutes
Maximum memory: controlled limit
Maximum workspace size: controlled limit
Maximum output: controlled limit
The exact values should be based on the workload rather than arbitrary defaults.
Resource limits protect both security and reliability.
Execution Timeout
Every agent operation should have a timeout.
using var timeout =
new CancellationTokenSource(
TimeSpan.FromMinutes(2));
await runtime.ExecuteAsync(
task,
timeout.Token);
Without a timeout, an agent could accidentally or intentionally start a process that never terminates.
Examples include:
Infinite loops
Long-running builds
Waiting processes
Interactive commands
Recursive scripts
Timeouts provide an important containment mechanism.
Filesystem Isolation
The agent should not automatically access the host filesystem.
Instead, provide a dedicated workspace:
Runtime
|
+-- /workspace
| +-- source
| +-- output
| +-- temp
|
+-- /runtime
|
+-- restricted system files
The workspace should be temporary whenever possible.
For example:
var workspace =
Path.Combine(
Path.GetTempPath(),
$"agent-{task.TaskId}");
Directory.CreateDirectory(workspace);
After execution:
Directory.Delete(
workspace,
recursive: true);
Production systems should also handle cleanup when execution fails.
Path Traversal Protection
File tools need additional protection.
An agent might attempt to access:
../../secrets.txt
or:
/etc/passwd
The application should resolve the path and verify that it remains inside the allowed workspace.
var fullPath =
Path.GetFullPath(
Path.Combine(workspace, requestedPath));
var root =
Path.GetFullPath(workspace);
if (!fullPath.StartsWith(
root,
StringComparison.OrdinalIgnoreCase))
{
throw new UnauthorizedAccessException(
"Path is outside the workspace.");
}
The exact implementation should also account for platform-specific path behavior and symbolic links.
Filesystem authorization should happen before opening the file.
Network Isolation
Network access is one of the most frequently overlooked agent risks.
Imagine an agent can execute:
curl https://internal-service
or connect to a private database.
A compromised agent could potentially use that capability for data exfiltration or internal service discovery.
Use an explicit network policy.
For example:
Internet
|
X
Agent Runtime
Approved API
|
v
Controlled Gateway
Rather than giving the runtime unrestricted outbound access, route approved network operations through controlled services.
Allowlisting External Services
If an agent needs an API, define exactly which destinations are allowed.
Conceptually:
var allowedHosts = new HashSet<string>(
StringComparer.OrdinalIgnoreCase)
{
"api.example.internal"
};
Before making a request:
if (!allowedHosts.Contains(
requestUri.Host))
{
throw new SecurityException(
"Destination is not allowed.");
}
Join the conversation! Your thoughts help the community grow.