-
Notifications
You must be signed in to change notification settings - Fork 616
Expand file tree
/
Copy pathtest_sandbox_policy.py
More file actions
1843 lines (1628 loc) · 67.7 KB
/
test_sandbox_policy.py
File metadata and controls
1843 lines (1628 loc) · 67.7 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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from openshell._proto import datamodel_pb2, sandbox_pb2
if TYPE_CHECKING:
from collections.abc import Callable
from openshell import Sandbox
# =============================================================================
# Policy helpers
# =============================================================================
_BASE_FILESYSTEM = sandbox_pb2.FilesystemPolicy(
include_workdir=True,
read_only=["/usr", "/lib", "/etc", "/app", "/var/log"],
read_write=["/sandbox", "/tmp"],
)
_BASE_LANDLOCK = sandbox_pb2.LandlockPolicy(compatibility="best_effort")
_BASE_PROCESS = sandbox_pb2.ProcessPolicy(run_as_user="sandbox", run_as_group="sandbox")
# Standard proxy address inside the sandbox network namespace
_PROXY_HOST = "10.200.0.1"
_PROXY_PORT = 3128
def _base_policy(
network_policies: dict[str, sandbox_pb2.NetworkPolicyRule] | None = None,
) -> sandbox_pb2.SandboxPolicy:
"""Build a sandbox policy with standard filesystem/process/landlock settings."""
return sandbox_pb2.SandboxPolicy(
version=1,
filesystem=_BASE_FILESYSTEM,
landlock=_BASE_LANDLOCK,
process=_BASE_PROCESS,
network_policies=network_policies or {},
)
def _policy_for_python_proxy_tests() -> sandbox_pb2.SandboxPolicy:
return _base_policy(
network_policies={
"python": sandbox_pb2.NetworkPolicyRule(
name="python",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.openai.com", port=443)
],
binaries=[
sandbox_pb2.NetworkBinary(path="/sandbox/.uv/python/**/python*")
],
)
},
)
# =============================================================================
# Shared test function factories
#
# cloudpickle serializes module-level functions by reference (module + name).
# The sandbox doesn't have this module, so deserialization fails. These
# factories return closures that cloudpickle serializes by value instead.
# =============================================================================
def _proxy_connect():
"""Return a closure that sends a raw CONNECT and returns the status line."""
def fn(host, port):
import socket
conn = socket.create_connection(("10.200.0.1", 3128), timeout=10)
try:
conn.sendall(
f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}\r\n\r\n".encode()
)
return conn.recv(256).decode("latin1")
finally:
conn.close()
return fn
def _proxy_connect_then_http():
"""Return a closure that CONNECTs, does TLS + HTTP, returns JSON string."""
def fn(host, port, method="GET", path="/"):
import json as _json
import socket
import ssl
conn = socket.create_connection(("10.200.0.1", 3128), timeout=30)
try:
conn.sendall(
f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}\r\n\r\n".encode()
)
connect_resp = conn.recv(256).decode("latin1")
if "200" not in connect_resp:
return _json.dumps(
{"connect_status": connect_resp.strip(), "http_status": 0}
)
sock = conn
if port == 443:
import os
ctx = ssl.create_default_context()
ca_file = os.environ.get("SSL_CERT_FILE")
if ca_file:
ctx.load_verify_locations(ca_file)
sock = ctx.wrap_socket(conn, server_hostname=host)
sock.settimeout(15)
request = (
f"{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
)
sock.sendall(request.encode())
# Read response. The L7 relay loops back to parse the next
# request after relaying, so neither side closes — read until
# we have headers, then drain body with a short timeout.
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(4096)
if not chunk:
break
data += chunk
# Drain body with short timeout
sock.settimeout(2)
while len(data) < 65536:
try:
chunk = sock.recv(4096)
if not chunk:
break
data += chunk
except (socket.timeout, TimeoutError):
break
response = data.decode("latin1", errors="replace")
status_line = response.split("\r\n")[0] if response else ""
status_code = (
int(status_line.split()[1]) if len(status_line.split()) >= 2 else 0
)
header_end = response.find("\r\n\r\n")
headers_raw = response[:header_end] if header_end > 0 else ""
body = response[header_end + 4 :] if header_end > 0 else ""
return _json.dumps(
{
"connect_status": connect_resp.strip(),
"http_status": status_code,
"headers": headers_raw,
"body": body,
}
)
finally:
conn.close()
return fn
def _read_openshell_log():
"""Return a closure that reads the openshell log file(s).
Since the sandbox uses a rolling file appender, logs are written to
date-stamped files like ``/var/log/openshell.YYYY-MM-DD.log`` instead
of a single ``/var/log/openshell.log``. This helper globs for all
matching files so tests work with both the legacy and rolling layouts.
"""
def fn():
import glob
logs = []
for path in sorted(glob.glob("/var/log/openshell*.log*")):
try:
with open(path) as f:
logs.append(f.read())
except (FileNotFoundError, PermissionError):
pass
return "\n".join(logs)
return fn
def _forward_proxy_with_server():
"""Return a closure that starts an HTTP server and sends a forward proxy request.
The closure starts a minimal HTTP server on the given port inside the sandbox,
then sends a plain HTTP forward proxy request (non-CONNECT) through the sandbox
proxy and returns the raw response.
"""
def fn(proxy_host, proxy_port, target_host, target_port):
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
body = b"forward-proxy-ok"
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass # suppress log output
srv = HTTPServer(("0.0.0.0", int(target_port)), Handler)
threading.Thread(target=srv.handle_request, daemon=True).start()
time.sleep(0.5)
conn = socket.create_connection((proxy_host, int(proxy_port)), timeout=10)
try:
req = (
f"GET http://{target_host}:{target_port}/test HTTP/1.1\r\n"
f"Host: {target_host}:{target_port}\r\n\r\n"
)
conn.sendall(req.encode())
data = b""
conn.settimeout(5)
try:
while True:
chunk = conn.recv(4096)
if not chunk:
break
data += chunk
except socket.timeout:
pass
return data.decode("latin1")
finally:
conn.close()
srv.server_close()
return fn
def _forward_proxy_raw():
"""Return a closure that sends a forward proxy request (no server needed).
For testing deny cases — sends the request and returns whatever the proxy
responds with.
"""
def fn(proxy_host, proxy_port, target_url):
import socket
from urllib.parse import urlparse
conn = socket.create_connection((proxy_host, int(proxy_port)), timeout=10)
try:
parsed = urlparse(target_url)
host_header = parsed.netloc or parsed.hostname
req = f"GET {target_url} HTTP/1.1\r\nHost: {host_header}\r\n\r\n"
conn.sendall(req.encode())
return conn.recv(4096).decode("latin1")
finally:
conn.close()
return fn
def test_policy_applies_to_exec_commands(
sandbox: Callable[..., Sandbox],
) -> None:
def current_user() -> str:
import os
import pwd
return pwd.getpwuid(os.getuid()).pw_name
def write_allowed_files() -> str:
from pathlib import Path
Path("/sandbox/allowed.txt").write_text("ok")
Path("/tmp/allowed.txt").write_text("ok")
return "ok"
spec = datamodel_pb2.SandboxSpec(policy=_policy_for_python_proxy_tests())
with sandbox(spec=spec, delete_on_exit=True) as policy_sandbox:
user_result = policy_sandbox.exec_python(current_user)
assert user_result.exit_code == 0, user_result.stderr
assert user_result.stdout.strip() == "sandbox"
file_result = policy_sandbox.exec_python(write_allowed_files)
assert file_result.exit_code == 0, file_result.stderr
assert file_result.stdout.strip() == "ok"
def test_policy_blocks_unauthorized_proxy_connect(
sandbox: Callable[..., Sandbox],
) -> None:
spec = datamodel_pb2.SandboxSpec(policy=_policy_for_python_proxy_tests())
with sandbox(spec=spec, delete_on_exit=True) as policy_sandbox:
proxy_result = policy_sandbox.exec_python(
_proxy_connect(), args=("example.com", 443)
)
assert proxy_result.exit_code == 0, proxy_result.stderr
assert "403" in proxy_result.stdout
# =============================================================================
# L4 Tests -- Connection-level OPA policy (host:port + binary identity)
# =============================================================================
#
# L4-1: No network policies -> all CONNECT requests denied
# L4-2: Wildcard binary (/**) + specific endpoint -> any binary can connect
# but non-listed endpoints still denied
# L4-3: Binary-restricted policy -> matched binary allowed, others denied
# L4-4: Correct endpoint, wrong port -> denied
# L4-5: Multiple disjoint policies -> cross-policy access denied
# L4-6: Non-CONNECT HTTP method -> rejected with 405
# L4-7: Log fields are structured correctly (action, binary, policy, engine)
# =============================================================================
def test_l4_no_policy_denies_all(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-1: No matching endpoint in any network policy -> CONNECT denied.
We need at least one network policy so the proxy and network namespace
start (empty network_policies disables networking entirely, including
socket syscalls). The policy allows python->example.com:443 but
api.anthropic.com:443 should still be denied.
"""
policy = _base_policy(
network_policies={
"other": sandbox_pb2.NetworkPolicyRule(
name="other",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="example.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_wildcard_binary_allows_any_binary(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-2: Wildcard binary glob allows python (and anything else) to connect."""
policy = _base_policy(
network_policies={
"wildcard": sandbox_pb2.NetworkPolicyRule(
name="wildcard",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.anthropic.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# Python can reach the allowed endpoint
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
assert result.exit_code == 0, result.stderr
assert "200" in result.stdout
# Non-listed endpoint is still denied
result = sb.exec_python(_proxy_connect(), args=("example.com", 443))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_binary_restricted_denies_wrong_binary(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-3: Policy restricted to specific binary denies others.
Policy allows /usr/bin/curl -> api.anthropic.com:443.
Python (exec_python uses python) should be denied.
"""
policy = _base_policy(
network_policies={
"curl_only": sandbox_pb2.NetworkPolicyRule(
name="curl_only",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.anthropic.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/usr/bin/curl")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# Python is NOT the allowed binary -> denied
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_wrong_port_denied(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-4: Correct host but wrong port -> denied."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.anthropic.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# Port 443 -> allowed
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
assert result.exit_code == 0, result.stderr
assert "200" in result.stdout
# Port 80 -> denied
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 80))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_cross_policy_denied(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-5: Multiple disjoint policies -> cross-policy access denied.
Policy A: python -> api.anthropic.com:443
Policy B: curl -> example.com:443
Python should NOT reach example.com (that's curl's policy).
"""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.anthropic.com", port=443),
],
binaries=[
sandbox_pb2.NetworkBinary(path="/sandbox/.uv/python/**/python*")
],
),
"other": sandbox_pb2.NetworkPolicyRule(
name="other",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="example.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/usr/bin/curl")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# Python -> its own policy endpoint: allowed
result = sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
assert result.exit_code == 0, result.stderr
assert "200" in result.stdout
# Python -> curl's policy endpoint: denied
result = sb.exec_python(_proxy_connect(), args=("example.com", 443))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_non_connect_method_rejected(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-6: Non-CONNECT HTTP method -> rejected with 403."""
def send_get_to_proxy() -> str:
import socket
conn = socket.create_connection(("10.200.0.1", 3128), timeout=10)
try:
conn.sendall(
b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n\r\n"
)
return conn.recv(256).decode("latin1")
finally:
conn.close()
policy = _base_policy(
network_policies={
"any": sandbox_pb2.NetworkPolicyRule(
name="any",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="example.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(send_get_to_proxy)
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_l4_log_fields(
sandbox: Callable[..., Sandbox],
) -> None:
"""L4-7: CONNECT log contains structured fields for allow and deny."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="api.anthropic.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# Generate an allow
sb.exec_python(_proxy_connect(), args=("api.anthropic.com", 443))
# Generate a deny
sb.exec_python(_proxy_connect(), args=("example.com", 443))
log_result = sb.exec_python(_read_openshell_log())
assert log_result.exit_code == 0, log_result.stderr
log = log_result.stdout
# Verify structured fields in allow line
assert "action=allow" in log or 'action="allow"' in log or "action=allow" in log
assert "dst_host=api.anthropic.com" in log or "dst_host" in log
assert "engine=opa" in log or 'engine="opa"' in log
# Verify deny line exists
assert "action=deny" in log or 'action="deny"' in log
# =============================================================================
# SSRF Tests -- Internal IP rejection (defense-in-depth)
#
# The proxy resolves DNS before connecting and rejects any destination that
# resolves to a loopback, RFC1918 private, or link-local address. These
# tests verify the check works even when OPA policy explicitly allows the
# internal endpoint.
#
# SSRF-1: Loopback (127.0.0.1) blocked despite OPA allow
# SSRF-2: Cloud metadata (169.254.169.254) blocked despite OPA allow
# SSRF-3: Log shows "internal address" block reason
# =============================================================================
def test_ssrf_blocks_loopback_despite_policy_allow(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-1: CONNECT to 127.0.0.1 blocked even with explicit OPA allow."""
policy = _base_policy(
network_policies={
"internal": sandbox_pb2.NetworkPolicyRule(
name="internal",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="127.0.0.1", port=80),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("127.0.0.1", 80))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_ssrf_blocks_metadata_endpoint_despite_policy_allow(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-2: CONNECT to 169.254.169.254 blocked even with explicit OPA allow."""
policy = _base_policy(
network_policies={
"metadata": sandbox_pb2.NetworkPolicyRule(
name="metadata",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="169.254.169.254", port=80),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("169.254.169.254", 80))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout
def test_ssrf_log_shows_internal_address_block(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-3: Proxy log includes 'internal address' reason when SSRF check fires."""
policy = _base_policy(
network_policies={
"internal": sandbox_pb2.NetworkPolicyRule(
name="internal",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="127.0.0.1", port=80),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
sb.exec_python(_proxy_connect(), args=("127.0.0.1", 80))
log_result = sb.exec_python(_read_openshell_log())
assert log_result.exit_code == 0, log_result.stderr
log = log_result.stdout
assert "internal address" in log.lower(), (
f"Expected 'internal address' in proxy log, got:\n{log}"
)
# =============================================================================
# SSRF Tests -- allowed_ips (CIDR-based private IP access)
#
# When an endpoint has `allowed_ips`, the proxy validates resolved IPs against
# the CIDR allowlist instead of blanket-blocking all private IPs.
# Loopback and link-local remain always-blocked regardless.
#
# SSRF-4: Private IP allowed with allowed_ips (mode 2: host + IPs)
# SSRF-5: Private IP allowed with allowed_ips (mode 3: IPs only, no host)
# SSRF-6: Private IP still blocked without allowed_ips (default behavior)
# SSRF-7: Loopback always blocked even with allowed_ips covering 127.0.0.0/8
# =============================================================================
def test_ssrf_allowed_ips_permits_private_ip(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-4: CONNECT to private IP succeeds when allowed_ips covers it.
Uses 10.200.0.1 (the proxy's own host-side veth IP) as the target.
The connection attempt will fail at the TCP level (nothing listening on
port 19999) but the proxy should return 200 Connection Established
instead of 403, proving the SSRF check passed.
"""
policy = _base_policy(
network_policies={
"internal": sandbox_pb2.NetworkPolicyRule(
name="internal",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="10.200.0.1",
port=19999,
allowed_ips=["10.200.0.0/24"],
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("10.200.0.1", 19999))
assert result.exit_code == 0, result.stderr
# Should get 200 (connection established) — not 403.
# The actual TCP connection may fail but the SSRF check passed.
assert "403" not in result.stdout, (
"Expected SSRF check to pass with allowed_ips, but got 403"
)
def test_ssrf_allowed_ips_hostless_permits_private_ip(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-5: CONNECT to private IP succeeds with hostless allowed_ips (mode 3).
An endpoint with no host but with allowed_ips matches any hostname on the
given port. The resolved IP must be in the allowlist.
"""
policy = _base_policy(
network_policies={
"private_net": sandbox_pb2.NetworkPolicyRule(
name="private_net",
endpoints=[
sandbox_pb2.NetworkEndpoint(
# No host — matches any hostname on this port
port=19999,
allowed_ips=["10.200.0.0/24"],
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("10.200.0.1", 19999))
assert result.exit_code == 0, result.stderr
assert "403" not in result.stdout, (
"Expected SSRF check to pass with hostless allowed_ips, but got 403"
)
def test_ssrf_private_ip_blocked_without_allowed_ips(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-6: Private IP blocked when endpoint has no allowed_ips (default)."""
policy = _base_policy(
network_policies={
"internal": sandbox_pb2.NetworkPolicyRule(
name="internal",
endpoints=[
# No allowed_ips — private IP should be blocked
sandbox_pb2.NetworkEndpoint(host="10.200.0.1", port=19999),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("10.200.0.1", 19999))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout, (
"Expected private IP to be blocked without allowed_ips"
)
def test_ssrf_loopback_blocked_even_with_allowed_ips(
sandbox: Callable[..., Sandbox],
) -> None:
"""SSRF-7: Loopback always blocked even when allowed_ips covers 127.0.0.0/8."""
policy = _base_policy(
network_policies={
"internal": sandbox_pb2.NetworkPolicyRule(
name="internal",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="127.0.0.1",
port=80,
allowed_ips=["127.0.0.0/8"],
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(_proxy_connect(), args=("127.0.0.1", 80))
assert result.exit_code == 0, result.stderr
assert "403" in result.stdout, (
"Expected loopback to be blocked even with allowed_ips"
)
# =============================================================================
# L7 Tests -- TLS termination HTTPS inspection (Phase 2: tls=terminate)
#
# These tests use api.anthropic.com:443 as a real HTTPS endpoint since the
# sandbox already has proxy connectivity. The ephemeral CA is trusted via
# SSL_CERT_FILE injected into the sandbox environment.
#
# L7-T1: TLS terminate + access=full allows HTTPS requests through
# L7-T2: TLS terminate + access=read-only denies HTTPS POST (enforce)
# L7-T3: TLS terminate + enforcement=audit logs but allows HTTPS POST
# L7-T4: TLS terminate with explicit path rules
# L7-T5: CA trust store is injected (SSL_CERT_FILE, NODE_EXTRA_CA_CERTS)
# L7-T6: L7 deny response is valid JSON with expected fields
# L7-T7: L7 request logging includes structured fields
# L7-T8: Port 443 + protocol=rest without tls=terminate warns (L7 not evaluated)
# =============================================================================
def test_l7_tls_full_access_allows_all(
sandbox: Callable[..., Sandbox],
) -> None:
"""L7-T1: TLS terminate + access=full allows HTTPS GET through."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="api.anthropic.com",
port=443,
protocol="rest",
tls="terminate",
enforcement="enforce",
access="full",
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "GET", "/v1/models"),
)
assert result.exit_code == 0, result.stderr
resp = json.loads(result.stdout)
assert "200" in resp["connect_status"]
# Upstream returns a real response (likely 401 without auth, but not 403 from proxy)
assert resp["http_status"] != 0
assert resp["http_status"] != 403 # Not a proxy deny
def test_l7_tls_read_only_denies_post(
sandbox: Callable[..., Sandbox],
) -> None:
"""L7-T2: TLS terminate + access=read-only denies HTTPS POST (enforce)."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="api.anthropic.com",
port=443,
protocol="rest",
tls="terminate",
enforcement="enforce",
access="read-only",
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# GET should be allowed through (read-only permits GET)
get_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "GET", "/v1/models"),
)
assert get_result.exit_code == 0, get_result.stderr
get_resp = json.loads(get_result.stdout)
assert get_resp["http_status"] != 403 # Not proxy denied
# POST should be denied by the proxy with 403
post_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "POST", "/v1/messages"),
)
assert post_result.exit_code == 0, post_result.stderr
post_resp = json.loads(post_result.stdout)
assert post_resp["http_status"] == 403
assert "policy_denied" in post_resp["body"]
def test_l7_tls_audit_mode_allows_but_logs(
sandbox: Callable[..., Sandbox],
) -> None:
"""L7-T3: TLS terminate + enforcement=audit logs but allows HTTPS POST."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="api.anthropic.com",
port=443,
protocol="rest",
tls="terminate",
enforcement="audit",
access="read-only",
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# POST goes through in audit mode (not denied)
post_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "POST", "/v1/messages"),
)
assert post_result.exit_code == 0, post_result.stderr
post_resp = json.loads(post_result.stdout)
# Should NOT be 403 from proxy -- traffic is forwarded
assert post_resp["http_status"] != 403
# Log should contain audit decision
log_result = sb.exec_python(_read_openshell_log())
assert log_result.exit_code == 0, log_result.stderr
log = log_result.stdout
assert "l7_decision=audit" in log or 'l7_decision="audit"' in log
def test_l7_tls_explicit_path_rules(
sandbox: Callable[..., Sandbox],
) -> None:
"""L7-T4: TLS terminate with explicit path rules."""
policy = _base_policy(
network_policies={
"anthropic": sandbox_pb2.NetworkPolicyRule(
name="anthropic",
endpoints=[
sandbox_pb2.NetworkEndpoint(
host="api.anthropic.com",
port=443,
protocol="rest",
tls="terminate",
enforcement="enforce",
rules=[
sandbox_pb2.L7Rule(
allow=sandbox_pb2.L7Allow(method="GET", path="/v1/**"),
),
],
),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
# GET /v1/models -> allowed (matches /v1/**)
get_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "GET", "/v1/models"),
)
assert get_result.exit_code == 0, get_result.stderr
get_resp = json.loads(get_result.stdout)
assert get_resp["http_status"] != 403
# POST /v1/messages -> denied (no POST rule)
post_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "POST", "/v1/messages"),
)
assert post_result.exit_code == 0, post_result.stderr
post_resp = json.loads(post_result.stdout)
assert post_resp["http_status"] == 403
# GET /v2/anything -> denied (path doesn't match /v1/**)
v2_result = sb.exec_python(
_proxy_connect_then_http(),
args=("api.anthropic.com", 443, "GET", "/v2/anything"),
)
assert v2_result.exit_code == 0, v2_result.stderr
v2_resp = json.loads(v2_result.stdout)
assert v2_resp["http_status"] == 403
def test_l7_tls_ca_trust_store_injected(
sandbox: Callable[..., Sandbox],
) -> None:
"""L7-T5: Sandbox CA is injected into trust store environment variables."""
def check_ca_env() -> str:
import json as _json
import os
return _json.dumps(
{
"SSL_CERT_FILE": os.environ.get("SSL_CERT_FILE", ""),
"NODE_EXTRA_CA_CERTS": os.environ.get("NODE_EXTRA_CA_CERTS", ""),
"REQUESTS_CA_BUNDLE": os.environ.get("REQUESTS_CA_BUNDLE", ""),
"CURL_CA_BUNDLE": os.environ.get("CURL_CA_BUNDLE", ""),
"ca_cert_exists": os.path.exists("/etc/openshell-tls/openshell-ca.pem"),
"bundle_exists": os.path.exists("/etc/openshell-tls/ca-bundle.pem"),
}
)
policy = _base_policy(
network_policies={
"any": sandbox_pb2.NetworkPolicyRule(
name="any",
endpoints=[
sandbox_pb2.NetworkEndpoint(host="example.com", port=443),
],
binaries=[sandbox_pb2.NetworkBinary(path="/**")],
),
},
)
spec = datamodel_pb2.SandboxSpec(policy=policy)
with sandbox(spec=spec, delete_on_exit=True) as sb:
result = sb.exec_python(check_ca_env)
assert result.exit_code == 0, result.stderr
env = json.loads(result.stdout)