-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecureexec_engine.py
More file actions
188 lines (164 loc) · 7.45 KB
/
secureexec_engine.py
File metadata and controls
188 lines (164 loc) · 7.45 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
"""
SecureExecAPI Engine — Sandboxed tool execution with IAM-gated dry-run.
Full commercial API: x402 + MPP payment gate, ERC-8004 identity, proof_hash audit trail.
dryRun=True DEFAULT in v1. ALWAYS calls EP to validate agent before execution.
ALWAYS fails open on EP timeout.
"""
import os
import time
import json
import uuid
import hashlib
import logging
import requests
import psycopg2
from datetime import datetime, timezone
logging.basicConfig(
filename=os.getenv('LOG_FILE', '/tmp/secureexec.log'),
level=logging.INFO,
format='%(asctime)s %(message)s'
)
DB = os.getenv('DATABASE_URL', 'dbname=achilles_db user=achilles password=olympus2026 host=localhost')
EP_URL = os.getenv('EP_GUARD_URL', 'https://achillesalpha.onrender.com/ep/validate')
TIMEOUT_S = 3
def get_internal_agent_ids():
return [v for k, v in os.environ.items() if k.endswith('_AGENT_ID') and v]
def is_internal_agent(agent_id):
return agent_id in get_internal_agent_ids()
ALLOWED_TOOLS = {
'http_get': 'HTTP GET request to a URL',
'json_parse': 'Parse and validate JSON payload',
'schema_validate': 'Validate data against a schema',
'math_compute': 'Perform mathematical computation',
'string_transform': 'String manipulation and formatting',
'data_filter': 'Filter and sort a dataset',
'mock_api_call': 'Simulate an API call (dry-run only)',
'hash_generate': 'Generate hash of input data',
'timestamp_parse': 'Parse and convert timestamps',
'regex_match': 'Test regex pattern against input',
}
BLOCKED_TOOLS = [
'shell_exec', 'bash', 'python_exec', 'sql_write', 'file_write',
'metasploit', 'sqlmap', 'nmap_write', 'deploy', 'kubectl', 'docker_exec'
]
def get_db():
return psycopg2.connect(DB)
def generate_proof_hash(payload):
try:
return '0x' + hashlib.sha256(
json.dumps(payload, sort_keys=True).encode()
).hexdigest()
except Exception:
return '0x' + hashlib.sha256(str(time.time()).encode()).hexdigest()
def validate_with_ep(agent_id, tool_name, dry_run):
try:
r = requests.post(
EP_URL,
json={'agent_id': agent_id, 'plan': {'action': 'tool_exec', 'tool': tool_name, 'dry_run': dry_run}},
timeout=TIMEOUT_S
)
result = r.json()
return result.get('valid', True), result.get('proof_hash')
except Exception as e:
logging.warning(f"EP timeout/error: {e} — failing open")
return True, None
def simulate_tool(tool_name, args):
if tool_name in BLOCKED_TOOLS:
return {'output': f"Tool '{tool_name}' requires on-chain EP approval — blocked in v1", 'exitCode': 403, 'simulated': True, 'blocked': True}
simulations = {
'http_get': lambda a: {'status': 200, 'body': f"Simulated GET {a.get('url','?')}", 'headers': {}},
'json_parse': lambda a: {'valid': True, 'keys': list(a.get('data', {}).keys()), 'type': 'object'},
'schema_validate': lambda a: {'valid': True, 'errors': [], 'schema': a.get('schema', {})},
'math_compute': lambda a: {'result': 0, 'expression': a.get('expression', '0')},
'string_transform':lambda a: {'result': str(a.get('input', '')).upper()},
'data_filter': lambda a: {'filtered': a.get('data', [])[:a.get('limit', 10)], 'count': len(a.get('data', []))},
'mock_api_call': lambda a: {'status': 200, 'body': {'success': True, 'endpoint': a.get('endpoint', '?')}, 'latencyMs': 45},
'hash_generate': lambda a: {'hash': hashlib.sha256(str(a.get('input', '')).encode()).hexdigest(), 'algorithm': 'sha256'},
'timestamp_parse': lambda a: {'parsed': datetime.now(timezone.utc).isoformat(), 'unix': int(time.time())},
'regex_match': lambda a: {'matched': True, 'pattern': a.get('pattern', ''), 'input': a.get('input', '')},
}
sim_fn = simulations.get(tool_name)
if sim_fn:
try:
return {'output': sim_fn(args or {}), 'exitCode': 0, 'simulated': True}
except Exception as e:
return {'output': f"Simulation error: {e}", 'exitCode': 1, 'simulated': True}
return {'output': f"Tool '{tool_name}' executed in simulation mode", 'exitCode': 0, 'simulated': True}
def log_call(agent_id, tool_name, dry_run, status, iam_approved,
proof_hash, latency_ms, payment_protocol=None):
try:
conn = get_db()
cur = conn.cursor()
cur.execute("""
INSERT INTO secureexec_calls
(caller_agent_id, tool_name, dry_run, status, iam_approved,
proof_hash, latency_ms, payment_protocol)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
""", (agent_id, tool_name, dry_run, status, iam_approved,
proof_hash, latency_ms, payment_protocol))
conn.commit()
conn.close()
except Exception as e:
logging.warning(f"log_call failed: {e}")
def exec_tool(agent_id, tool, dry_run=True, context=None, payment_protocol=None):
"""
Core execution. dryRun=True always in v1.
ALWAYS validates with EP. ALWAYS generates proof_hash.
ALWAYS logs to Postgres. ALWAYS fails open.
"""
start = time.time()
tool_name = tool.get('name', 'unknown')
args = tool.get('args', {})
job_id = str(uuid.uuid4())
dry_run = True # Force in v1
try:
iam_approved, ep_proof = validate_with_ep(agent_id, tool_name, dry_run)
result = simulate_tool(tool_name, args)
latency_ms = int((time.time() - start) * 1000)
proof_hash = ep_proof or generate_proof_hash({
'jobId': job_id, 'agentId': agent_id,
'tool': tool_name, 'ts': time.time()
})
status = 'blocked' if result.get('blocked') else 'completed'
response = {
'jobId': job_id,
'tool': tool_name,
'dryRun': dry_run,
'status': status,
'result': result,
'iamApproved': iam_approved,
'proofHash': proof_hash,
'paymentProtocol': payment_protocol,
'latencyMs': latency_ms,
'timestamp': datetime.now(timezone.utc).isoformat(),
'schemaVersion': 'v1'
}
log_call(agent_id, tool_name, dry_run, status, iam_approved,
proof_hash, latency_ms, payment_protocol)
logging.info(f"[{agent_id}] tool={tool_name} status={status} latency={latency_ms}ms payment={payment_protocol}")
return response
except Exception as e:
latency_ms = int((time.time() - start) * 1000)
logging.error(f"exec_tool failed: {e}")
proof_hash = generate_proof_hash({'error': str(e), 'ts': time.time()})
log_call(agent_id, tool_name, True, 'error', False, proof_hash, latency_ms)
return {
'jobId': job_id, 'tool': tool_name, 'dryRun': True,
'status': 'error',
'result': {'output': 'Execution error — fallback', 'exitCode': 1, 'simulated': True},
'iamApproved': False, 'proofHash': proof_hash,
'latencyMs': latency_ms,
'timestamp': datetime.now(timezone.utc).isoformat(),
'schemaVersion': 'v1', 'fallback': True
}
def list_tools():
return {'allowed': ALLOWED_TOOLS, 'blocked_in_v1': BLOCKED_TOOLS, 'schemaVersion': 'v1'}
if __name__ == '__main__':
print("SecureExecAPI smoke test...")
result = exec_tool(
agent_id='achilles',
tool={'name': 'http_get', 'args': {'url': 'https://example.com'}},
dry_run=True
)
print(json.dumps(result, indent=2))