Spaces:
Sleeping

rubra-v3 / terminal_engine.py
getalvi's picture
Update terminal_engine.py
ce6222b verified
Raw History Blame Contribute Delete
14.3 kB
"""
RUBRA β€” terminal_engine.py
Secure built-in terminal with permission layer and live output streaming.
Architecture:
- TerminalSession: stateful session (working dir, env, history)
- PermissionChecker: blocks destructive operations before execution
- TerminalEngine: manages sessions, spawns processes, streams output
- Integrated into agent via tool dispatch (the agent can invoke
`terminal_run` after user approval or in auto-approved mode)
Security model (Phase 7):
DENY_ALWAYS β€” never executable, even with explicit user approval
REQUIRE_APPROVAL β€” shown to user before execution; auto-approved if
the user has set RUBRA_TERMINAL_AUTO_APPROVE=true
ALLOWED β€” safe read-only or informational commands
The RUBRA agent must call check_command() BEFORE executing and must
NOT execute if the result is DENY_ALWAYS. REQUIRE_APPROVAL commands
must surface the command to the user in the SSE stream and wait for
an explicit confirmation token before proceeding.
"""
import os
import re
import asyncio
import logging
import shlex
import uuid
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Optional, AsyncIterator, Dict
log = logging.getLogger("rubra.terminal")
# ── Permission level constants ────────────────────────────────────────────────
class PermissionLevel(Enum):
ALLOWED = "allowed"
REQUIRE_APPROVAL = "require_approval"
DENY_ALWAYS = "deny_always"
@dataclass
class CommandPermission:
level: PermissionLevel
reason: str
command: str = ""
# ── Security rules ────────────────────────────────────────────────────────────
# Each entry: (regex_pattern, PermissionLevel, human_readable_reason)
_SECURITY_RULES = [
# ALWAYS DENIED β€” catastrophic / irreversible
(r'\brm\s+(-[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*r[a-zA-Z]*f|-rf|-fr)\b',
PermissionLevel.DENY_ALWAYS, "Recursive force-delete is never allowed"),
(r'\bdd\s+if=',
PermissionLevel.DENY_ALWAYS, "Raw disk write is never allowed"),
(r'\bmkfs\b',
PermissionLevel.DENY_ALWAYS, "Filesystem creation is never allowed"),
(r':\s*\(\)\s*\{.*:\|:&\s*\}',
PermissionLevel.DENY_ALWAYS, "Fork bomb pattern detected"),
(r'>\s*/dev/sd[a-z]',
PermissionLevel.DENY_ALWAYS, "Direct device write is never allowed"),
(r'\bchmod\s+777\s+/',
PermissionLevel.DENY_ALWAYS, "Setting world-writable on / is never allowed"),
(r'curl\s+.*\|\s*(?:sudo\s+)?(?:bash|sh|zsh)',
PermissionLevel.DENY_ALWAYS, "Piping curl to shell is never allowed"),
(r'wget\s+.*\|\s*(?:sudo\s+)?(?:bash|sh|zsh)',
PermissionLevel.DENY_ALWAYS, "Piping wget to shell is never allowed"),
# REQUIRE APPROVAL β€” potentially destructive but sometimes legitimate
(r'\brm\s+', PermissionLevel.REQUIRE_APPROVAL, "File deletion requires approval"),
(r'\bsudo\s+', PermissionLevel.REQUIRE_APPROVAL, "Sudo commands require approval"),
(r'\bapt(?:-get)?\s+(?:install|remove|purge)',
PermissionLevel.REQUIRE_APPROVAL, "Package install/remove requires approval"),
(r'\bnpm\s+install\b', PermissionLevel.REQUIRE_APPROVAL, "Package install requires approval"),
(r'\bpip\s+install\b', PermissionLevel.REQUIRE_APPROVAL, "Package install requires approval"),
(r'\buv\s+add\b', PermissionLevel.REQUIRE_APPROVAL, "Package add requires approval"),
(r'\bdocker\s+(?:run|exec|rm|rmi)\b',
PermissionLevel.REQUIRE_APPROVAL, "Docker execution requires approval"),
(r'\bgit\s+push\b', PermissionLevel.REQUIRE_APPROVAL, "Git push requires approval"),
(r'\bgit\s+reset\s+--hard',
PermissionLevel.REQUIRE_APPROVAL, "Destructive git reset requires approval"),
(r'\bssh\b', PermissionLevel.REQUIRE_APPROVAL, "SSH connections require approval"),
(r'\bcurl\b|\bwget\b', PermissionLevel.REQUIRE_APPROVAL, "Network downloads require approval"),
(r'\bchown\b|\bchmod\b',PermissionLevel.REQUIRE_APPROVAL, "Permission changes require approval"),
(r'\bkill\b|\bkillall\b',PermissionLevel.REQUIRE_APPROVAL,"Process termination requires approval"),
]
# Auto-approve safe patterns β€” these override REQUIRE_APPROVAL above
_AUTO_SAFE_PATTERNS = [
r'^(?:ls|ll|la|pwd|echo|cat|head|tail|grep|find|which|type|env|printenv|'
r'python3?\s+--version|node\s+--version|npm\s+--version|git\s+(?:status|log|diff|branch|show)|'
r'pytest|python3?\s+-m\s+pytest|uvicorn\s+--help|pip\s+list|pip\s+show|'
r'uv\s+(?:run|pip\s+list)|npm\s+(?:run|list|test)|'
r'wc|sort|uniq|awk|sed|tr|cut|tee|diff|tree|du|df)\b',
]
_AUTO_SAFE_RE = [re.compile(p, re.IGNORECASE) for p in _AUTO_SAFE_PATTERNS]
# Maximum output to buffer before truncating
MAX_OUTPUT_BYTES = 512 * 1024 # 512 KB
PROCESS_TIMEOUT = 300 # 5 minutes hard cap
def check_command(command: str) -> CommandPermission:
"""
Security gate. Call BEFORE executing any command.
Returns a CommandPermission β€” caller must respect DENY_ALWAYS.
"""
cmd = command.strip()
if not cmd:
return CommandPermission(PermissionLevel.ALLOWED, "Empty command", cmd)
# Check deny-always rules first (no override possible)
for pattern, level, reason in _SECURITY_RULES:
if level == PermissionLevel.DENY_ALWAYS and re.search(pattern, cmd, re.IGNORECASE):
return CommandPermission(PermissionLevel.DENY_ALWAYS, reason, cmd)
# Check auto-safe patterns β€” skip REQUIRE_APPROVAL for known-safe commands
for safe_re in _AUTO_SAFE_RE:
if safe_re.match(cmd):
return CommandPermission(PermissionLevel.ALLOWED,
"Read-only / informational command", cmd)
# Check require-approval rules
for pattern, level, reason in _SECURITY_RULES:
if level == PermissionLevel.REQUIRE_APPROVAL and re.search(pattern, cmd, re.IGNORECASE):
auto = os.getenv("RUBRA_TERMINAL_AUTO_APPROVE", "false").lower() == "true"
if auto:
return CommandPermission(PermissionLevel.ALLOWED,
f"Auto-approved: {reason}", cmd)
return CommandPermission(PermissionLevel.REQUIRE_APPROVAL, reason, cmd)
return CommandPermission(PermissionLevel.ALLOWED, "No restrictions matched", cmd)
# ── Terminal Session ──────────────────────────────────────────────────────────
@dataclass
class TerminalSession:
session_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
working_dir: str = field(default_factory=lambda: str(Path("/tmp/rubra_terminal").resolve()))
env: Dict[str, str] = field(default_factory=dict)
history: list = field(default_factory=list)
_active_process: Optional[asyncio.subprocess.Process] = field(default=None, repr=False, compare=False)
def __post_init__(self):
Path(self.working_dir).mkdir(parents=True, exist_ok=True)
def get_env(self) -> dict:
"""Safe environment β€” inherits from os but overrides with session env."""
base = {k: v for k, v in os.environ.items()
if k not in ("GROQ_API_KEY", "OPENROUTER_KEY", "GEMINI_API_KEY",
"CEREBRAS_API_KEY", "HF_TOKEN") and not k.startswith("OPAPI")}
base.update(self.env)
base["PYTHONUNBUFFERED"] = "1"
base["TERM"] = "xterm-256color"
return base
async def kill(self):
"""Kill the current running process, if any."""
if self._active_process and self._active_process.returncode is None:
try:
self._active_process.kill()
await asyncio.wait_for(self._active_process.wait(), timeout=5)
log.info(f"[TERMINAL] Session {self.session_id}: process killed")
except Exception as e:
log.warning(f"[TERMINAL] Kill failed: {e}")
self._active_process = None
# ── Terminal Engine ───────────────────────────────────────────────────────────
class TerminalEngine:
"""
Manages terminal sessions and executes commands with live output streaming.
Singleton β€” use `terminal_engine` at module level.
"""
def __init__(self):
self._sessions: Dict[str, TerminalSession] = {}
def get_or_create_session(self, session_id: str) -> TerminalSession:
if session_id not in self._sessions:
self._sessions[session_id] = TerminalSession(session_id=session_id)
log.info(f"[TERMINAL] New session {session_id}")
return self._sessions[session_id]
def delete_session(self, session_id: str):
if session_id in self._sessions:
asyncio.create_task(self._sessions.pop(session_id).kill())
async def execute(
self,
command: str,
session_id: str,
working_dir: Optional[str] = None,
) -> AsyncIterator[dict]:
"""
Execute a command, yielding SSE-compatible dicts:
{"type": "permission_denied", "message": str}
{"type": "approval_required", "command": str, "reason": str}
{"type": "stdout", "data": str}
{"type": "stderr", "data": str}
{"type": "exit", "code": int, "elapsed_ms": int}
{"type": "error", "message": str}
Caller must be an async generator consumer, e.g. in an SSE endpoint.
"""
import time
perm = check_command(command)
if perm.level == PermissionLevel.DENY_ALWAYS:
yield {"type": "permission_denied",
"message": f"🚫 Blocked: {perm.reason}",
"command": command}
return
if perm.level == PermissionLevel.REQUIRE_APPROVAL:
yield {"type": "approval_required",
"command": command,
"reason": perm.reason,
"message": f"⚠️ This command requires approval: {perm.reason}"}
return
session = self.get_or_create_session(session_id)
cwd = working_dir or session.working_dir
Path(cwd).mkdir(parents=True, exist_ok=True)
session.history.append({"command": command, "cwd": cwd})
log.info(f"[TERMINAL] {session_id} $ {command[:80]}")
t0 = time.monotonic()
try:
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
env=session.get_env(),
limit=MAX_OUTPUT_BYTES,
)
session._active_process = proc
total_output = 0
async def read_stream(stream, stream_type: str):
nonlocal total_output
while True:
try:
line = await asyncio.wait_for(stream.readline(), timeout=60.0)
if not line:
break
total_output += len(line)
if total_output > MAX_OUTPUT_BYTES:
yield {"type": stream_type,
"data": "\n[Output truncated β€” exceeded 512KB limit]\n"}
break
yield {"type": stream_type,
"data": line.decode("utf-8", errors="replace")}
except asyncio.TimeoutError:
yield {"type": "stderr",
"data": "[No output for 60s β€” process may be waiting for input]\n"}
break
# Stream stdout and stderr concurrently
stdout_gen = read_stream(proc.stdout, "stdout")
stderr_gen = read_stream(proc.stderr, "stderr")
async def _drain(gen):
async for item in gen:
yield item
# Merge both streams β€” simple sequential approach for safety
# (true concurrent streaming requires asyncio.gather + queues)
done = False
stdout_done = False
stderr_done = False
stdout_iter = stdout_gen.__aiter__()
stderr_iter = stderr_gen.__aiter__()
while not (stdout_done and stderr_done):
if not stdout_done:
try:
item = await asyncio.wait_for(stdout_iter.__anext__(), 0.1)
yield item
except StopAsyncIteration:
stdout_done = True
except asyncio.TimeoutError:
pass
if not stderr_done:
try:
item = await asyncio.wait_for(stderr_iter.__anext__(), 0.1)
yield item
except StopAsyncIteration:
stderr_done = True
except asyncio.TimeoutError:
pass
try:
await asyncio.wait_for(proc.wait(), timeout=PROCESS_TIMEOUT)
except asyncio.TimeoutError:
proc.kill()
yield {"type": "error",
"message": f"Process timed out after {PROCESS_TIMEOUT}s β€” killed"}
elapsed_ms = int((time.monotonic() - t0) * 1000)
exit_code = proc.returncode or 0
session._active_process = None
log.info(f"[TERMINAL] {session_id} exit={exit_code} {elapsed_ms}ms")
yield {"type": "exit", "code": exit_code, "elapsed_ms": elapsed_ms}
except Exception as e:
log.error(f"[TERMINAL] {session_id} error: {e}", exc_info=True)
yield {"type": "error", "message": str(e)[:300]}
# Module-level singleton
terminal_engine = TerminalEngine()