feat(security): контейнерная изоляция Claude CLI (Docker sandbox)
Claude Code теперь работает внутри Docker-контейнера: - Видит ТОЛЬКО /data (рабочая папка сметчика) - Хостовая ФС недоступна (/home/mcp-user, .env, SSH ключи) - Лимиты: --memory=512m --cpus=1 - Auth через mount .claude/ (rw для session-env) - Образ: smeta-claude-sandbox (node:22-slim + python + openpyxl + claude-code) - Старый bridge сохранён как claude_bridge_direct.py Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
+47
-32
@@ -1,4 +1,4 @@
|
||||
"""Bridge between FastAPI and Claude Code CLI subprocess."""
|
||||
"""Bridge using Docker container for Claude CLI isolation."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
@@ -6,16 +6,20 @@ import os
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
CLAUDE_BIN = os.environ.get(
|
||||
"CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude")
|
||||
)
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
APP_DIR = Path(__file__).parent
|
||||
CLAUDE_CONFIG_DIR = os.environ.get(
|
||||
"CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")
|
||||
)
|
||||
# Docker host gateway for xray proxy
|
||||
DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1")
|
||||
XRAY_PORT = os.environ.get("XRAY_PORT", "10809")
|
||||
|
||||
# Session tracking: (username, tab_id) -> claude session_id (#12)
|
||||
# Session tracking: (username, tab_id) -> claude session_id
|
||||
_sessions: dict[tuple[str, str], str] = {}
|
||||
|
||||
# Concurrency limit (#11 DoS)
|
||||
# Concurrency limit
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
|
||||
@@ -37,7 +41,6 @@ def clear_session(username: str, tab_id: str):
|
||||
_sessions.pop((username, tab_id), None)
|
||||
|
||||
|
||||
# Whitelist of allowed file extensions (#6)
|
||||
ALLOWED_EXTENSIONS = {
|
||||
".xlsx", ".xls", ".docx", ".doc", ".pdf",
|
||||
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
|
||||
@@ -48,53 +51,65 @@ def is_allowed_file(filename: str) -> bool:
|
||||
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
# Minimal env for subprocess (#7 — don't leak all env vars)
|
||||
def _build_claude_env() -> dict[str, str]:
|
||||
env = {
|
||||
"HOME": os.environ.get("HOME", "/home/mcp-user"),
|
||||
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
||||
"LANG": os.environ.get("LANG", "en_US.UTF-8"),
|
||||
"HTTPS_PROXY": os.environ.get("HTTPS_PROXY", "http://127.0.0.1:10809"),
|
||||
"HTTP_PROXY": os.environ.get("HTTP_PROXY", "http://127.0.0.1:10809"),
|
||||
}
|
||||
# Claude Code needs XDG dirs
|
||||
for k in ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "NODE_PATH"):
|
||||
if k in os.environ:
|
||||
env[k] = os.environ[k]
|
||||
return env
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
message: str,
|
||||
username: str,
|
||||
tab_id: str = "default",
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Run claude CLI, yield SSE-formatted events."""
|
||||
"""Run claude in Docker container, yield SSE-formatted events."""
|
||||
async with _semaphore:
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
session_id = get_session_id(username, tab_id)
|
||||
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
cmd = [
|
||||
CLAUDE_BIN, "-p", message,
|
||||
# Build claude args
|
||||
claude_args = [
|
||||
"-p", message,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
]
|
||||
if instructions.exists():
|
||||
cmd.extend(["--append-system-prompt-file", str(instructions)])
|
||||
# Mount instructions file into container
|
||||
claude_args.extend([
|
||||
"--append-system-prompt-file", "/instructions.md"
|
||||
])
|
||||
if session_id:
|
||||
cmd.extend(["--resume", session_id])
|
||||
claude_args.extend(["--resume", session_id])
|
||||
|
||||
env = _build_claude_env()
|
||||
# Docker command
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
# Resource limits
|
||||
"--memory=512m",
|
||||
"--cpus=1",
|
||||
"--network=host", # access xray on host
|
||||
# Mount work directory as /data
|
||||
"-v", f"{work_dir.resolve()}:/data",
|
||||
# Mount Claude auth — full dir rw (Claude needs session-env/)
|
||||
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
|
||||
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
|
||||
# Mount instructions
|
||||
]
|
||||
if instructions.exists():
|
||||
cmd.extend(["-v", f"{instructions.resolve()}:/instructions.md:ro"])
|
||||
|
||||
# Environment
|
||||
cmd.extend([
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
# Working directory
|
||||
"-w", "/data",
|
||||
# Image + claude args
|
||||
DOCKER_IMAGE,
|
||||
])
|
||||
cmd.extend(claude_args)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=str(work_dir),
|
||||
env=env,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Bridge between FastAPI and Claude Code CLI subprocess."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
CLAUDE_BIN = os.environ.get(
|
||||
"CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude")
|
||||
)
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
APP_DIR = Path(__file__).parent
|
||||
|
||||
# Session tracking: (username, tab_id) -> claude session_id (#12)
|
||||
_sessions: dict[tuple[str, str], str] = {}
|
||||
|
||||
# Concurrency limit (#11 DoS)
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
return _sessions.get((username, tab_id))
|
||||
|
||||
|
||||
def set_session_id(username: str, tab_id: str, sid: str):
|
||||
_sessions[(username, tab_id)] = sid
|
||||
|
||||
|
||||
def clear_session(username: str, tab_id: str):
|
||||
_sessions.pop((username, tab_id), None)
|
||||
|
||||
|
||||
# Whitelist of allowed file extensions (#6)
|
||||
ALLOWED_EXTENSIONS = {
|
||||
".xlsx", ".xls", ".docx", ".doc", ".pdf",
|
||||
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
|
||||
}
|
||||
|
||||
|
||||
def is_allowed_file(filename: str) -> bool:
|
||||
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
# Minimal env for subprocess (#7 — don't leak all env vars)
|
||||
def _build_claude_env() -> dict[str, str]:
|
||||
env = {
|
||||
"HOME": os.environ.get("HOME", "/home/mcp-user"),
|
||||
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
||||
"LANG": os.environ.get("LANG", "en_US.UTF-8"),
|
||||
"HTTPS_PROXY": os.environ.get("HTTPS_PROXY", "http://127.0.0.1:10809"),
|
||||
"HTTP_PROXY": os.environ.get("HTTP_PROXY", "http://127.0.0.1:10809"),
|
||||
}
|
||||
# Claude Code needs XDG dirs
|
||||
for k in ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "NODE_PATH"):
|
||||
if k in os.environ:
|
||||
env[k] = os.environ[k]
|
||||
return env
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
message: str,
|
||||
username: str,
|
||||
tab_id: str = "default",
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Run claude CLI, yield SSE-formatted events."""
|
||||
async with _semaphore:
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
session_id = get_session_id(username, tab_id)
|
||||
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
cmd = [
|
||||
CLAUDE_BIN, "-p", message,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
]
|
||||
if instructions.exists():
|
||||
cmd.extend(["--append-system-prompt-file", str(instructions)])
|
||||
if session_id:
|
||||
cmd.extend(["--resume", session_id])
|
||||
|
||||
env = _build_claude_env()
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
cwd=str(work_dir),
|
||||
env=env,
|
||||
)
|
||||
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
etype = event.get("type", "")
|
||||
|
||||
if etype == "assistant":
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
text = block["text"]
|
||||
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
|
||||
elif block.get("type") == "tool_use":
|
||||
name = block.get("name", "")
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n"
|
||||
|
||||
elif etype == "result":
|
||||
sid = event.get("session_id", "")
|
||||
if sid:
|
||||
set_session_id(username, tab_id, sid)
|
||||
result_text = event.get("result", "")
|
||||
yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n"
|
||||
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
|
||||
"""List files in user's work directory."""
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
files = []
|
||||
for f in sorted(work_dir.iterdir()):
|
||||
if f.is_file() and not f.name.startswith("."):
|
||||
files.append({
|
||||
"name": f.name,
|
||||
"size": f.stat().st_size,
|
||||
})
|
||||
return files
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM node:22-slim
|
||||
|
||||
# Python + libs for file processing
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
python3 python3-pip python3-venv && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip3 install --break-system-packages --no-cache-dir \
|
||||
openpyxl python-docx pymupdf pandas
|
||||
|
||||
# Claude Code CLI
|
||||
RUN npm install -g @anthropic-ai/claude-code
|
||||
|
||||
# Worker user with same UID as host mcp-user (for .claude auth files)
|
||||
RUN useradd -m -s /bin/bash -u 1002 worker
|
||||
USER worker
|
||||
WORKDIR /data
|
||||
|
||||
ENTRYPOINT ["claude"]
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Bridge using Docker container for Claude CLI isolation."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
APP_DIR = Path(__file__).parent.parent # one level up from sandbox/
|
||||
CLAUDE_CONFIG_DIR = os.environ.get(
|
||||
"CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")
|
||||
)
|
||||
# Docker host gateway for xray proxy
|
||||
DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1")
|
||||
XRAY_PORT = os.environ.get("XRAY_PORT", "10809")
|
||||
|
||||
# Session tracking: (username, tab_id) -> claude session_id
|
||||
_sessions: dict[tuple[str, str], str] = {}
|
||||
|
||||
# Concurrency limit
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
return _sessions.get((username, tab_id))
|
||||
|
||||
|
||||
def set_session_id(username: str, tab_id: str, sid: str):
|
||||
_sessions[(username, tab_id)] = sid
|
||||
|
||||
|
||||
def clear_session(username: str, tab_id: str):
|
||||
_sessions.pop((username, tab_id), None)
|
||||
|
||||
|
||||
ALLOWED_EXTENSIONS = {
|
||||
".xlsx", ".xls", ".docx", ".doc", ".pdf",
|
||||
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
|
||||
}
|
||||
|
||||
|
||||
def is_allowed_file(filename: str) -> bool:
|
||||
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
message: str,
|
||||
username: str,
|
||||
tab_id: str = "default",
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Run claude in Docker container, yield SSE-formatted events."""
|
||||
async with _semaphore:
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
session_id = get_session_id(username, tab_id)
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
# Build claude args
|
||||
claude_args = [
|
||||
"-p", message,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
]
|
||||
if instructions.exists():
|
||||
# Mount instructions file into container
|
||||
claude_args.extend([
|
||||
"--append-system-prompt-file", "/instructions.md"
|
||||
])
|
||||
if session_id:
|
||||
claude_args.extend(["--resume", session_id])
|
||||
|
||||
# Docker command
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
# Resource limits
|
||||
"--memory=512m",
|
||||
"--cpus=1",
|
||||
"--network=host", # access xray on host
|
||||
# Mount work directory as /data
|
||||
"-v", f"{work_dir.resolve()}:/data",
|
||||
# Mount Claude auth (read-only)
|
||||
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude:ro",
|
||||
# Mount instructions
|
||||
]
|
||||
if instructions.exists():
|
||||
cmd.extend(["-v", f"{instructions.resolve()}:/instructions.md:ro"])
|
||||
|
||||
# Environment
|
||||
cmd.extend([
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
# Working directory
|
||||
"-w", "/data",
|
||||
# Image + claude args
|
||||
DOCKER_IMAGE,
|
||||
])
|
||||
cmd.extend(claude_args)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
etype = event.get("type", "")
|
||||
|
||||
if etype == "assistant":
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
text = block["text"]
|
||||
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
|
||||
elif block.get("type") == "tool_use":
|
||||
name = block.get("name", "")
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n"
|
||||
|
||||
elif etype == "result":
|
||||
sid = event.get("session_id", "")
|
||||
if sid:
|
||||
set_session_id(username, tab_id, sid)
|
||||
result_text = event.get("result", "")
|
||||
yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n"
|
||||
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
await proc.wait()
|
||||
|
||||
|
||||
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
|
||||
"""List files in user's work directory."""
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
files = []
|
||||
for f in sorted(work_dir.iterdir()):
|
||||
if f.is_file() and not f.name.startswith("."):
|
||||
files.append({
|
||||
"name": f.name,
|
||||
"size": f.stat().st_size,
|
||||
})
|
||||
return files
|
||||
Reference in New Issue
Block a user