-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer-manager.py
More file actions
102 lines (85 loc) · 3.13 KB
/
container-manager.py
File metadata and controls
102 lines (85 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python3
import docker
import secrets
from typing import Dict
from auth_service import AuthService
class ContainerManager:
def __init__(self):
self.client = docker.from_env()
self.auth_service = AuthService('private-key.pem', 'key-id')
self.active_containers: Dict[str, str] = {}
def create_sandbox(self, user_id: str, allowed_hosts: list) -> Dict:
"""Create isolated sandbox container"""
# Generate unique container ID
container_id = f"sandbox_session_{secrets.token_urlsafe(12)}"
# Generate JWT
token = self.auth_service.generate_container_token(
container_id=container_id,
user_id=user_id,
allowed_hosts=allowed_hosts,
enforce_binding=True
)
# Create container with security settings
container = self.client.containers.run(
image='sandbox-image:latest',
name=container_id,
runtime='runsc',
detach=True,
# Network isolation
network_mode='none',
# Environment variables
environment={
'CONTAINER_ID': container_id,
'HTTP_PROXY': f'http://{container_id}:jwt_{token}@proxy:8443',
'HTTPS_PROXY': f'http://{container_id}:jwt_{token}@proxy:8443',
'NO_PROXY': 'localhost,127.0.0.1'
},
# Resource limits
mem_limit='4g',
cpu_quota=200000,
pids_limit=100,
# Security options
cap_drop=['ALL'],
cap_add=['CHOWN', 'SETUID', 'SETGID', 'NET_BIND_SERVICE'],
security_opt=['no-new-privileges:true'],
# Read-only root filesystem
read_only=True,
tmpfs={'/tmp': 'size=1G,mode=1777'},
# Volumes
volumes={
f'/srv/sandbox/users/{user_id}/uploads': {
'bind': '/mnt/uploads',
'mode': 'ro'
},
f'/srv/sandbox/users/{user_id}/outputs': {
'bind': '/mnt/outputs',
'mode': 'rw'
},
'/srv/sandbox/skills': {
'bind': '/mnt/skills',
'mode': 'ro'
}
}
)
self.active_containers[container_id] = container.id
return {
'container_id': container_id,
'token': token,
'status': 'created'
}
def destroy_sandbox(self, container_id: str):
"""Destroy sandbox and cleanup"""
if container_id in self.active_containers:
container = self.client.containers.get(self.active_containers[container_id])
container.stop(timeout=5)
container.remove(force=True)
del self.active_containers[container_id]
# Usage
if __name__ == '__main__':
manager = ContainerManager()
sandbox = manager.create_sandbox(
user_id='user_123',
allowed_hosts=['api.example.com', 'github.com']
)
print(f"Created sandbox: {sandbox['container_id']}")
print(f"Token: {sandbox['token']}")