Implement Agent Sandboxing and Safety Constraints

Medium
Agents

Agent Code Sandboxing

Agents that execute code must do so in a sandboxed environment to prevent security breaches.

Task

Implement CodeSandbox that:

  1. Validates code statically for dangerous patterns before execution.
  2. Executes Python code in a restricted globals environment.
  3. Enforces time and memory limits.
  4. Logs all execution attempts.

Constraints

  • Block: os.system, subprocess, __import__, eval, exec, open, file I/O.
  • Execution timeout: configurable, default 5s.
  • Return structured result with success, output, error, and execution time.

Examples

Example 1:
Input: sb = CodeSandbox(SandboxConstraints()) sb.validate_code('import os; os.system("rm -rf /")')
Output: ['Blocked pattern: os.system', 'Blocked pattern: import']
Explanation: Both patterns are in the blocked list.

Starter Code

import subprocess
import resource
from typing import Dict, Any, List

class SandboxConstraints:
    def __init__(self):
        self.allowed_modules: List[str] = []
        self.blocked_patterns: List[str] = ['os.system', 'subprocess', '__import__', 'eval', 'exec']
        self.max_execution_time: float = 5.0  # seconds
        self.max_memory_mb: int = 128
        self.allow_network: bool = False

class CodeSandbox:
    def __init__(self, constraints: SandboxConstraints):
        self.constraints = constraints
        self.execution_log: list = []

    def validate_code(self, code: str) -> List[str]:
        # TODO: Static analysis - return list of violations
        pass

    def execute(self, code: str, timeout: float = None) -> Dict:
        # TODO: Execute in restricted environment
        # Return: {'success': bool, 'output': str, 'error': str, 'time': float}
        pass

    def _build_restricted_globals(self) -> Dict:
        # TODO: Build safe globals dict
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews