-
Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathopa.rs
More file actions
2634 lines (2465 loc) · 85.7 KB
/
opa.rs
File metadata and controls
2634 lines (2465 loc) · 85.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
//! Embedded OPA policy engine using regorus.
//!
//! Wraps [`regorus::Engine`] to evaluate Rego policies for sandbox network
//! access decisions. The engine is loaded once at sandbox startup and queried
//! on every proxy CONNECT request.
use crate::policy::{FilesystemPolicy, LandlockCompatibility, LandlockPolicy, ProcessPolicy};
use miette::Result;
use openshell_core::proto::SandboxPolicy as ProtoSandboxPolicy;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// Baked-in rego rules for OPA policy evaluation.
/// These rules define the network access decision logic and static config
/// passthroughs. They reference `data.sandbox.*` for policy data.
const BAKED_POLICY_RULES: &str = include_str!("../data/sandbox-policy.rego");
/// Result of evaluating a network access request against OPA policy.
pub struct PolicyDecision {
pub allowed: bool,
pub reason: String,
pub matched_policy: Option<String>,
}
/// Network action returned by OPA `network_action` rule.
///
/// - `Allow`: endpoint + binary explicitly matched in a network policy
/// - `Deny`: no matching policy
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NetworkAction {
Allow { matched_policy: Option<String> },
Deny { reason: String },
}
/// Input for a network access policy evaluation.
pub struct NetworkInput {
pub host: String,
pub port: u16,
pub binary_path: PathBuf,
pub binary_sha256: String,
/// Ancestor binary paths from process tree walk (parent, grandparent, ...).
pub ancestors: Vec<PathBuf>,
/// Absolute paths extracted from `/proc/<pid>/cmdline` of the socket-owning
/// process and its ancestors. Captures script paths (e.g. `/usr/local/bin/claude`)
/// that don't appear in `/proc/<pid>/exe` because the interpreter (node) is the exe.
pub cmdline_paths: Vec<PathBuf>,
}
/// Sandbox configuration extracted from OPA data at startup.
pub struct SandboxConfig {
pub filesystem: FilesystemPolicy,
pub landlock: LandlockPolicy,
pub process: ProcessPolicy,
}
/// Embedded OPA policy engine.
///
/// Thread-safe: the inner `regorus::Engine` requires `&mut self` for
/// evaluation, so access is serialized via a `Mutex`. This is acceptable
/// because policy evaluation is fast (microseconds) and contention is low
/// (one eval per CONNECT request).
pub struct OpaEngine {
engine: Mutex<regorus::Engine>,
}
impl OpaEngine {
/// Load policy from a `.rego` rules file and data from a YAML file.
///
/// Preprocesses the YAML data to expand access presets and validate L7 config.
pub fn from_files(policy_path: &Path, data_path: &Path) -> Result<Self> {
let yaml_str = std::fs::read_to_string(data_path).map_err(|e| {
miette::miette!("failed to read YAML data from {}: {e}", data_path.display())
})?;
let mut engine = regorus::Engine::new();
engine
.add_policy_from_file(policy_path)
.map_err(|e| miette::miette!("{e}"))?;
let data_json = preprocess_yaml_data(&yaml_str)?;
engine
.add_data_json(&data_json)
.map_err(|e| miette::miette!("{e}"))?;
Ok(Self {
engine: Mutex::new(engine),
})
}
/// Load policy rules and data from strings (data is YAML).
///
/// Preprocesses the YAML data to expand access presets and validate L7 config.
pub fn from_strings(policy: &str, data_yaml: &str) -> Result<Self> {
let mut engine = regorus::Engine::new();
engine
.add_policy("policy.rego".into(), policy.into())
.map_err(|e| miette::miette!("{e}"))?;
let data_json = preprocess_yaml_data(data_yaml)?;
engine
.add_data_json(&data_json)
.map_err(|e| miette::miette!("{e}"))?;
Ok(Self {
engine: Mutex::new(engine),
})
}
/// Create OPA engine from a typed proto policy.
///
/// Uses baked-in rego rules and converts the proto's typed fields to JSON
/// data under the `sandbox` key (matching `data.sandbox.*` references in
/// the rego rules).
///
/// Expands access presets and validates L7 config.
pub fn from_proto(proto: &ProtoSandboxPolicy) -> Result<Self> {
let data_json_str = proto_to_opa_data_json(proto);
// Parse back to Value for preprocessing, then re-serialize
let mut data: serde_json::Value = serde_json::from_str(&data_json_str)
.map_err(|e| miette::miette!("internal: failed to parse proto JSON: {e}"))?;
// Validate BEFORE expanding presets
let (errors, warnings) = crate::l7::validate_l7_policies(&data);
for w in &warnings {
tracing::warn!(warning = %w, "L7 policy validation warning");
}
if !errors.is_empty() {
return Err(miette::miette!(
"L7 policy validation failed:\n{}",
errors.join("\n")
));
}
// Expand access presets to explicit rules after validation
crate::l7::expand_access_presets(&mut data);
let data_json = data.to_string();
let mut engine = regorus::Engine::new();
engine
.add_policy("policy.rego".into(), BAKED_POLICY_RULES.into())
.map_err(|e| miette::miette!("{e}"))?;
engine
.add_data_json(&data_json)
.map_err(|e| miette::miette!("{e}"))?;
Ok(Self {
engine: Mutex::new(engine),
})
}
/// Evaluate a network access request against the loaded policy.
///
/// Builds an OPA input document from the `NetworkInput`, evaluates the
/// `allow_network` rule, and returns a `PolicyDecision` with the result,
/// deny reason, and matched policy name.
pub fn evaluate_network(&self, input: &NetworkInput) -> Result<PolicyDecision> {
let ancestor_strs: Vec<String> = input
.ancestors
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let cmdline_strs: Vec<String> = input
.cmdline_paths
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let input_json = serde_json::json!({
"exec": {
"path": input.binary_path.to_string_lossy(),
"ancestors": ancestor_strs,
"cmdline_paths": cmdline_strs,
},
"network": {
"host": input.host,
"port": input.port,
}
});
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
engine
.set_input_json(&input_json.to_string())
.map_err(|e| miette::miette!("{e}"))?;
let allowed = engine
.eval_rule("data.openshell.sandbox.allow_network".into())
.map_err(|e| miette::miette!("{e}"))?;
let allowed = allowed == regorus::Value::from(true);
let reason = engine
.eval_rule("data.openshell.sandbox.deny_reason".into())
.map_err(|e| miette::miette!("{e}"))?;
let reason = value_to_string(&reason);
let matched = engine
.eval_rule("data.openshell.sandbox.matched_network_policy".into())
.map_err(|e| miette::miette!("{e}"))?;
let matched_policy = if matched == regorus::Value::Undefined {
None
} else {
Some(value_to_string(&matched))
};
Ok(PolicyDecision {
allowed,
reason,
matched_policy,
})
}
/// Evaluate a network access request and return a routing action.
///
/// Uses the OPA `network_action` rule which returns one of:
/// `"allow"` or `"deny"`.
pub fn evaluate_network_action(&self, input: &NetworkInput) -> Result<NetworkAction> {
let ancestor_strs: Vec<String> = input
.ancestors
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let cmdline_strs: Vec<String> = input
.cmdline_paths
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let input_json = serde_json::json!({
"exec": {
"path": input.binary_path.to_string_lossy(),
"ancestors": ancestor_strs,
"cmdline_paths": cmdline_strs,
},
"network": {
"host": input.host,
"port": input.port,
}
});
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
engine
.set_input_json(&input_json.to_string())
.map_err(|e| miette::miette!("{e}"))?;
let action_val = engine
.eval_rule("data.openshell.sandbox.network_action".into())
.map_err(|e| miette::miette!("{e}"))?;
let action_str = value_to_string(&action_val);
let matched = engine
.eval_rule("data.openshell.sandbox.matched_network_policy".into())
.map_err(|e| miette::miette!("{e}"))?;
let matched_policy = if matched == regorus::Value::Undefined {
None
} else {
Some(value_to_string(&matched))
};
match action_str.as_str() {
"allow" => Ok(NetworkAction::Allow { matched_policy }),
_ => {
let reason_val = engine
.eval_rule("data.openshell.sandbox.deny_reason".into())
.map_err(|e| miette::miette!("{e}"))?;
let reason = value_to_string(&reason_val);
Ok(NetworkAction::Deny { reason })
}
}
}
/// Reload policy and data from strings (data is YAML).
///
/// Designed for future gRPC hot-reload from the openshell gateway.
/// Replaces the entire engine atomically. Routes through the full
/// preprocessing pipeline (port normalization, L7 validation, preset
/// expansion) to maintain consistency with `from_strings()`.
pub fn reload(&self, policy: &str, data_yaml: &str) -> Result<()> {
let new = Self::from_strings(policy, data_yaml)?;
let new_engine = new
.engine
.into_inner()
.map_err(|_| miette::miette!("lock poisoned on new engine"))?;
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
*engine = new_engine;
Ok(())
}
/// Reload policy from a proto `SandboxPolicy` message.
///
/// Reuses the full `from_proto()` pipeline (proto-to-JSON conversion, L7
/// validation, access preset expansion) so the reload has identical
/// validation guarantees as initial load. Atomically replaces the inner
/// engine on success; on failure the previous engine is untouched (LKG).
pub fn reload_from_proto(&self, proto: &ProtoSandboxPolicy) -> Result<()> {
// Build a complete new engine through the same validated pipeline.
let new = Self::from_proto(proto)?;
let new_engine = new
.engine
.into_inner()
.map_err(|_| miette::miette!("lock poisoned on new engine"))?;
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
*engine = new_engine;
Ok(())
}
/// Query static sandbox configuration from the OPA data module.
///
/// Extracts `filesystem_policy`, `landlock`, and `process` from the Rego
/// data and converts them into the Rust policy structs used by the sandbox
/// runtime for filesystem preparation, Landlock setup, and privilege dropping.
pub fn query_sandbox_config(&self) -> Result<SandboxConfig> {
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
// Query filesystem policy
let fs_val = engine
.eval_rule("data.openshell.sandbox.filesystem_policy".into())
.map_err(|e| miette::miette!("{e}"))?;
let filesystem = parse_filesystem_policy(&fs_val);
// Query landlock policy
let ll_val = engine
.eval_rule("data.openshell.sandbox.landlock_policy".into())
.map_err(|e| miette::miette!("{e}"))?;
let landlock = parse_landlock_policy(&ll_val);
// Query process policy
let proc_val = engine
.eval_rule("data.openshell.sandbox.process_policy".into())
.map_err(|e| miette::miette!("{e}"))?;
let process = parse_process_policy(&proc_val);
Ok(SandboxConfig {
filesystem,
landlock,
process,
})
}
/// Query the L7 endpoint config for a matched policy and host:port.
///
/// After L4 evaluation allows a CONNECT, this method queries the Rego data
/// to get the full endpoint object for the matched policy. Returns the raw
/// `regorus::Value` which can be parsed by `l7::parse_l7_config()`.
pub fn query_endpoint_config(&self, input: &NetworkInput) -> Result<Option<regorus::Value>> {
let ancestor_strs: Vec<String> = input
.ancestors
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let cmdline_strs: Vec<String> = input
.cmdline_paths
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let input_json = serde_json::json!({
"exec": {
"path": input.binary_path.to_string_lossy(),
"ancestors": ancestor_strs,
"cmdline_paths": cmdline_strs,
},
"network": {
"host": input.host,
"port": input.port,
}
});
let mut engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
engine
.set_input_json(&input_json.to_string())
.map_err(|e| miette::miette!("{e}"))?;
let val = engine
.eval_rule("data.openshell.sandbox.matched_endpoint_config".into())
.map_err(|e| miette::miette!("{e}"))?;
if val == regorus::Value::Undefined {
Ok(None)
} else {
Ok(Some(val))
}
}
/// Query `allowed_ips` from the matched endpoint config for a given request.
///
/// Returns the list of CIDR/IP strings from the endpoint's `allowed_ips`
/// field, or an empty vec if the field is absent or the endpoint has no
/// match. This is used by the proxy to decide between full SSRF blocking
/// and allowlist-based IP validation.
pub fn query_allowed_ips(&self, input: &NetworkInput) -> Result<Vec<String>> {
match self.query_endpoint_config(input)? {
Some(val) => Ok(get_str_array(&val, "allowed_ips")),
None => Ok(vec![]),
}
}
/// Clone the inner regorus engine for per-tunnel L7 evaluation.
///
/// With the `arc` feature enabled, this shares compiled policy via Arc
/// and only duplicates interpreter state (~microseconds). The cloned
/// engine can be used without Mutex contention.
pub fn clone_engine_for_tunnel(&self) -> Result<regorus::Engine> {
let engine = self
.engine
.lock()
.map_err(|_| miette::miette!("OPA engine lock poisoned"))?;
Ok(engine.clone())
}
}
/// Convert a `regorus::Value` to a string, handling various types.
fn value_to_string(val: ®orus::Value) -> String {
match val {
regorus::Value::String(s) => s.to_string(),
regorus::Value::Undefined => String::new(),
other => other.to_string(),
}
}
/// Extract a string from a `regorus::Value` object field.
fn get_str(val: ®orus::Value, key: &str) -> Option<String> {
let key_val = regorus::Value::String(key.into());
match val {
regorus::Value::Object(map) => match map.get(&key_val) {
Some(regorus::Value::String(s)) => Some(s.to_string()),
_ => None,
},
_ => None,
}
}
/// Extract a bool from a `regorus::Value` object field.
fn get_bool(val: ®orus::Value, key: &str) -> Option<bool> {
let key_val = regorus::Value::String(key.into());
match val {
regorus::Value::Object(map) => match map.get(&key_val) {
Some(regorus::Value::Bool(b)) => Some(*b),
_ => None,
},
_ => None,
}
}
/// Extract a string array from a `regorus::Value` object field.
fn get_str_array(val: ®orus::Value, key: &str) -> Vec<String> {
let key_val = regorus::Value::String(key.into());
match val {
regorus::Value::Object(map) => match map.get(&key_val) {
Some(regorus::Value::Array(arr)) => arr
.iter()
.filter_map(|v| {
if let regorus::Value::String(s) = v {
Some(s.to_string())
} else {
None
}
})
.collect(),
_ => vec![],
},
_ => vec![],
}
}
fn parse_filesystem_policy(val: ®orus::Value) -> FilesystemPolicy {
FilesystemPolicy {
read_only: get_str_array(val, "read_only")
.into_iter()
.map(PathBuf::from)
.collect(),
read_write: get_str_array(val, "read_write")
.into_iter()
.map(PathBuf::from)
.collect(),
include_workdir: get_bool(val, "include_workdir").unwrap_or(true),
}
}
fn parse_landlock_policy(val: ®orus::Value) -> LandlockPolicy {
let compat = get_str(val, "compatibility").unwrap_or_default();
LandlockPolicy {
compatibility: if compat == "hard_requirement" {
LandlockCompatibility::HardRequirement
} else {
LandlockCompatibility::BestEffort
},
}
}
fn parse_process_policy(val: ®orus::Value) -> ProcessPolicy {
ProcessPolicy {
run_as_user: get_str(val, "run_as_user"),
run_as_group: get_str(val, "run_as_group"),
}
}
/// Preprocess YAML policy data: parse, normalize, validate, expand access presets, return JSON.
fn preprocess_yaml_data(yaml_str: &str) -> Result<String> {
let mut data: serde_json::Value = serde_yaml::from_str(yaml_str)
.map_err(|e| miette::miette!("failed to parse YAML data: {e}"))?;
// Normalize port → ports for all endpoints so Rego always sees "ports" array.
normalize_endpoint_ports(&mut data);
// Validate BEFORE expanding presets (catches user errors like rules+access)
let (errors, warnings) = crate::l7::validate_l7_policies(&data);
for w in &warnings {
tracing::warn!(warning = %w, "L7 policy validation warning");
}
if !errors.is_empty() {
return Err(miette::miette!(
"L7 policy validation failed:\n{}",
errors.join("\n")
));
}
// Expand access presets to explicit rules after validation
crate::l7::expand_access_presets(&mut data);
serde_json::to_string(&data).map_err(|e| miette::miette!("failed to serialize data: {e}"))
}
/// Normalize endpoint port/ports in JSON data.
///
/// YAML policies may use `port: N` (single) or `ports: [N, M]` (multi).
/// This normalizes all endpoints to have a `ports` array so Rego rules
/// only need to reference `endpoint.ports[_]`.
fn normalize_endpoint_ports(data: &mut serde_json::Value) {
let Some(policies) = data
.get_mut("network_policies")
.and_then(|v| v.as_object_mut())
else {
return;
};
for (_name, policy) in policies.iter_mut() {
let Some(endpoints) = policy.get_mut("endpoints").and_then(|v| v.as_array_mut()) else {
continue;
};
for ep in endpoints.iter_mut() {
let ep_obj = match ep.as_object_mut() {
Some(obj) => obj,
None => continue,
};
// If "ports" already exists and is non-empty, keep it.
let has_ports = ep_obj
.get("ports")
.and_then(|v| v.as_array())
.is_some_and(|a| !a.is_empty());
if !has_ports {
// Promote scalar "port" to "ports" array.
let port = ep_obj
.get("port")
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
if port > 0 {
ep_obj.insert(
"ports".to_string(),
serde_json::Value::Array(vec![serde_json::json!(port)]),
);
}
}
// Remove scalar "port" — Rego only uses "ports".
ep_obj.remove("port");
}
}
}
/// Convert typed proto policy fields to JSON suitable for `engine.add_data_json()`.
///
/// The rego rules reference `data.*` directly, so the JSON structure has
/// top-level keys matching the data expectations:
/// - `data.filesystem_policy`
/// - `data.landlock`
/// - `data.process`
/// - `data.network_policies`
fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy) -> String {
let filesystem_policy = proto.filesystem.as_ref().map_or_else(
|| {
serde_json::json!({
"include_workdir": true,
"read_only": [],
"read_write": [],
})
},
|fs| {
serde_json::json!({
"include_workdir": fs.include_workdir,
"read_only": fs.read_only,
"read_write": fs.read_write,
})
},
);
let landlock = proto.landlock.as_ref().map_or_else(
|| serde_json::json!({"compatibility": "best_effort"}),
|ll| serde_json::json!({"compatibility": ll.compatibility}),
);
let process = proto.process.as_ref().map_or_else(
|| {
serde_json::json!({
"run_as_user": "sandbox",
"run_as_group": "sandbox",
})
},
|p| {
serde_json::json!({
"run_as_user": p.run_as_user,
"run_as_group": p.run_as_group,
})
},
);
let network_policies: serde_json::Map<String, serde_json::Value> = proto
.network_policies
.iter()
.map(|(key, rule)| {
let endpoints: Vec<serde_json::Value> = rule
.endpoints
.iter()
.map(|e| {
// Normalize port/ports: ports takes precedence, then
// single port promoted to array. Rego always sees "ports".
let ports: Vec<u32> = if !e.ports.is_empty() {
e.ports.clone()
} else if e.port > 0 {
vec![e.port]
} else {
vec![]
};
let mut ep = serde_json::json!({"host": e.host, "ports": ports});
if !e.protocol.is_empty() {
ep["protocol"] = e.protocol.clone().into();
}
if !e.tls.is_empty() {
ep["tls"] = e.tls.clone().into();
}
if !e.enforcement.is_empty() {
ep["enforcement"] = e.enforcement.clone().into();
}
if !e.access.is_empty() {
ep["access"] = e.access.clone().into();
}
if !e.rules.is_empty() {
let rules: Vec<serde_json::Value> = e
.rules
.iter()
.map(|r| {
let a = r.allow.as_ref();
serde_json::json!({
"allow": {
"method": a.map_or("", |a| &a.method),
"path": a.map_or("", |a| &a.path),
"command": a.map_or("", |a| &a.command),
}
})
})
.collect();
ep["rules"] = rules.into();
}
if !e.allowed_ips.is_empty() {
ep["allowed_ips"] = e.allowed_ips.clone().into();
}
ep
})
.collect();
let binaries: Vec<serde_json::Value> = rule
.binaries
.iter()
.map(|b| serde_json::json!({"path": b.path}))
.collect();
(
key.clone(),
serde_json::json!({
"name": rule.name,
"endpoints": endpoints,
"binaries": binaries,
}),
)
})
.collect();
serde_json::json!({
"filesystem_policy": filesystem_policy,
"landlock": landlock,
"process": process,
"network_policies": network_policies,
})
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use openshell_core::proto::{
FilesystemPolicy as ProtoFs, NetworkBinary, NetworkEndpoint, NetworkPolicyRule,
ProcessPolicy as ProtoProc, SandboxPolicy as ProtoSandboxPolicy,
};
const TEST_POLICY: &str = include_str!("../data/sandbox-policy.rego");
const TEST_DATA_YAML: &str = include_str!("../testdata/sandbox-policy.yaml");
fn test_engine() -> OpaEngine {
OpaEngine::from_strings(TEST_POLICY, TEST_DATA_YAML).expect("Failed to load test policy")
}
fn test_proto() -> ProtoSandboxPolicy {
let mut network_policies = std::collections::HashMap::new();
network_policies.insert(
"claude_code".to_string(),
NetworkPolicyRule {
name: "claude_code".to_string(),
endpoints: vec![
NetworkEndpoint {
host: "api.anthropic.com".to_string(),
port: 443,
..Default::default()
},
NetworkEndpoint {
host: "statsig.anthropic.com".to_string(),
port: 443,
..Default::default()
},
],
binaries: vec![NetworkBinary {
path: "/usr/local/bin/claude".to_string(),
..Default::default()
}],
},
);
network_policies.insert(
"gitlab".to_string(),
NetworkPolicyRule {
name: "gitlab".to_string(),
endpoints: vec![NetworkEndpoint {
host: "gitlab.com".to_string(),
port: 443,
..Default::default()
}],
binaries: vec![NetworkBinary {
path: "/usr/bin/glab".to_string(),
..Default::default()
}],
},
);
ProtoSandboxPolicy {
version: 1,
filesystem: Some(ProtoFs {
include_workdir: true,
read_only: vec!["/usr".to_string(), "/lib".to_string()],
read_write: vec!["/sandbox".to_string(), "/tmp".to_string()],
}),
landlock: Some(openshell_core::proto::LandlockPolicy {
compatibility: "best_effort".to_string(),
}),
process: Some(ProtoProc {
run_as_user: "sandbox".to_string(),
run_as_group: "sandbox".to_string(),
}),
network_policies,
}
}
#[test]
fn allowed_binary_and_endpoint() {
let engine = test_engine();
// Simulates Claude Code: exe is /usr/bin/node, script is /usr/local/bin/claude
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![PathBuf::from("/usr/local/bin/claude")],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(
decision.allowed,
"Expected allow, got deny: {}",
decision.reason
);
assert_eq!(decision.matched_policy.as_deref(), Some("claude_code"));
}
#[test]
fn wrong_binary_denied() {
let engine = test_engine();
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/python3"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(!decision.allowed);
assert!(
decision.reason.contains("not allowed"),
"Expected specific deny reason, got: {}",
decision.reason
);
}
#[test]
fn wrong_endpoint_denied() {
let engine = test_engine();
let input = NetworkInput {
host: "evil.example.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(!decision.allowed);
assert!(
decision.reason.contains("endpoint"),
"Expected endpoint deny reason, got: {}",
decision.reason
);
}
#[test]
fn unknown_binary_default_deny() {
let engine = test_engine();
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 443,
binary_path: PathBuf::from("/tmp/malicious"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(!decision.allowed);
}
#[test]
fn github_policy_allows_git() {
let engine = test_engine();
let input = NetworkInput {
host: "github.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/git"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(
decision.allowed,
"Expected allow, got deny: {}",
decision.reason
);
assert_eq!(
decision.matched_policy.as_deref(),
Some("github_ssh_over_https")
);
}
#[test]
fn case_insensitive_host_matching() {
let engine = test_engine();
let input = NetworkInput {
host: "API.ANTHROPIC.COM".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![PathBuf::from("/usr/local/bin/claude")],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(
decision.allowed,
"Expected case-insensitive match, got deny: {}",
decision.reason
);
}
#[test]
fn wrong_port_denied() {
let engine = test_engine();
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 80,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(!decision.allowed);
}
#[test]
fn query_sandbox_config_extracts_filesystem() {
let engine = test_engine();
let config = engine.query_sandbox_config().unwrap();
assert!(config.filesystem.include_workdir);
assert!(config.filesystem.read_only.contains(&PathBuf::from("/usr")));
assert!(
config
.filesystem
.read_write
.contains(&PathBuf::from("/tmp"))
);
}
#[test]
fn query_sandbox_config_extracts_process() {
let engine = test_engine();
let config = engine.query_sandbox_config().unwrap();
assert_eq!(config.process.run_as_user.as_deref(), Some("sandbox"));
assert_eq!(config.process.run_as_group.as_deref(), Some("sandbox"));
}
#[test]
fn from_strings_and_from_files_produce_same_results() {
let engine = test_engine();
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![PathBuf::from("/usr/local/bin/claude")],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(decision.allowed);
}
#[test]
fn reload_replaces_policy() {
let engine = test_engine();
// Verify initial policy works
let input = NetworkInput {
host: "api.anthropic.com".into(),
port: 443,
binary_path: PathBuf::from("/usr/bin/node"),
binary_sha256: "unused".into(),
ancestors: vec![],
cmdline_paths: vec![PathBuf::from("/usr/local/bin/claude")],
};
let decision = engine.evaluate_network(&input).unwrap();
assert!(decision.allowed);
// Reload with a policy that has no network policies (deny all)
let empty_data = r"
filesystem_policy:
include_workdir: true
read_only: []
read_write: []
landlock:
compatibility: best_effort
process:
run_as_user: sandbox
run_as_group: sandbox
network_policies: {}
";
engine.reload(TEST_POLICY, empty_data).unwrap();
let decision = engine.evaluate_network(&input).unwrap();
assert!(
!decision.allowed,
"Expected deny after reload with empty policies"
);
}
#[test]
fn ancestor_binary_allowed() {
// Use github policy: binary /usr/bin/git is the policy binary.
// If the socket process is /usr/bin/python3 but its ancestor is /usr/bin/git, allow.
let engine = test_engine();
let input = NetworkInput {
host: "github.com".into(),