forked from moltis-org/moltis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.rs
More file actions
1288 lines (1138 loc) · 40 KB
/
Copy pathtests.rs
File metadata and controls
1288 lines (1138 loc) · 40 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
#![allow(clippy::unwrap_used, clippy::expect_used)]
use {
super::*,
std::sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
struct TestBroadcaster {
called: AtomicBool,
session_key: std::sync::Mutex<Option<String>>,
}
impl TestBroadcaster {
fn new() -> Self {
Self {
called: AtomicBool::new(false),
session_key: std::sync::Mutex::new(None),
}
}
}
#[tokio::test]
async fn limited_output_handles_multibyte_boundary() {
let input = format!("{}л{}", "a".repeat(1999), "z".repeat(10));
let output = read_output_limited(input.as_bytes(), 2000).await.unwrap();
assert!(output.contains("[output truncated]"));
assert!(!output.contains('л'));
}
#[tokio::test]
async fn limited_output_caps_lossy_utf8_expansion() {
const LIMIT: usize = 10;
const MARKER: &str = "\n... [output truncated]";
let input = [0xff_u8; 100];
let output = read_output_limited(input.as_slice(), LIMIT).await.unwrap();
assert!(output.ends_with(MARKER));
assert!(output.len() <= LIMIT + MARKER.len());
}
#[async_trait]
impl ApprovalBroadcaster for TestBroadcaster {
async fn broadcast_request(
&self,
_request_id: &str,
_command: &str,
session_key: Option<&str>,
) -> Result<()> {
self.called.store(true, Ordering::SeqCst);
*self.session_key.lock().unwrap() = session_key.map(ToOwned::to_owned);
Ok(())
}
}
#[tokio::test]
async fn test_exec_echo() {
let result = exec_command("echo hello", &ExecOpts::default())
.await
.unwrap();
assert_eq!(result.stdout.trim(), "hello");
assert_eq!(result.exit_code, 0);
}
#[test]
fn host_exec_injects_the_resolved_moltis_data_dir() {
let mut env = vec![("MOLTIS_DATA_DIR".to_owned(), "stale".to_owned())];
inject_moltis_data_dir(&mut env, true);
assert_eq!(env, vec![(
"MOLTIS_DATA_DIR".to_owned(),
moltis_config::data_dir().to_string_lossy().into_owned(),
)]);
}
#[test]
fn host_exec_injects_the_resolved_managed_files_dir() {
let mut env = vec![("MOLTIS_FILES_DIR".to_owned(), "stale".to_owned())];
inject_moltis_files_dir(
&mut env,
Some(
moltis_config::managed_files_dir()
.to_string_lossy()
.into_owned(),
),
);
assert_eq!(env, vec![(
"MOLTIS_FILES_DIR".to_owned(),
moltis_config::managed_files_dir()
.to_string_lossy()
.into_owned(),
)]);
}
#[test]
fn sandbox_exec_injects_the_guest_managed_files_dir() {
let mut env = Vec::new();
inject_moltis_files_dir(&mut env, Some(crate::sandbox::SANDBOX_FILES_DIR.to_owned()));
assert_eq!(env, vec![(
"MOLTIS_FILES_DIR".to_owned(),
crate::sandbox::SANDBOX_FILES_DIR.to_owned(),
)]);
}
#[test]
fn unsupported_sandbox_omits_the_managed_files_dir() {
let mut env = vec![("MOLTIS_FILES_DIR".to_owned(), "stale".to_owned())];
inject_moltis_files_dir(&mut env, None);
assert!(env.is_empty());
}
#[tokio::test]
async fn test_exec_stderr() {
let result = exec_command("echo err >&2", &ExecOpts::default())
.await
.unwrap();
assert_eq!(result.stderr.trim(), "err");
}
#[tokio::test]
async fn test_exec_exit_code() {
let result = exec_command("exit 42", &ExecOpts::default()).await.unwrap();
assert_eq!(result.exit_code, 42);
}
#[tokio::test]
async fn test_exec_timeout() {
let opts = ExecOpts {
timeout: Duration::from_millis(100),
..Default::default()
};
let result = exec_command("sleep 10", &opts).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_exec_timeout_kills_before_later_side_effect() {
let temp_dir = tempfile::tempdir().unwrap();
let marker = temp_dir.path().join("should-not-exist");
let command = format!("(sleep 1; touch '{}') & wait", marker.display());
let opts = ExecOpts {
timeout: Duration::from_millis(50),
..Default::default()
};
assert!(exec_command(&command, &opts).await.is_err());
tokio::time::sleep(Duration::from_millis(1100)).await;
assert!(!marker.exists(), "timed-out descendant continued running");
}
#[tokio::test]
async fn test_exec_tool() {
let temp_dir = tempfile::tempdir().unwrap();
let tool = ExecTool {
working_dir: Some(temp_dir.path().to_path_buf()),
..Default::default()
};
let result = tool
.execute(serde_json::json!({ "command": "echo hello" }))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "hello");
assert_eq!(result["exit_code"], 0);
}
#[tokio::test]
async fn test_exec_tool_empty_working_dir() {
let temp_dir = tempfile::tempdir().unwrap();
let tool = ExecTool {
working_dir: Some(temp_dir.path().to_path_buf()),
..Default::default()
};
let result = tool
.execute(serde_json::json!({ "command": "pwd", "working_dir": "" }))
.await
.unwrap();
assert_eq!(result["exit_code"], 0);
assert!(!result["stdout"].as_str().unwrap().trim().is_empty());
}
#[tokio::test]
async fn test_exec_tool_uses_internal_working_dir_default() {
let temp_dir = tempfile::tempdir().unwrap();
let tool = ExecTool::default();
let result = tool
.execute(serde_json::json!({
"command": "pwd",
"_working_dir": temp_dir.path(),
}))
.await
.unwrap();
let reported = std::fs::canonicalize(result["stdout"].as_str().unwrap().trim()).unwrap();
assert_eq!(reported, temp_dir.path().canonicalize().unwrap());
}
#[tokio::test]
async fn test_exec_tool_safe_command_no_approval_needed() {
let mgr = Arc::new(ApprovalManager::default());
let bc = Arc::new(TestBroadcaster::new());
let bc_dyn: Arc<dyn ApprovalBroadcaster> = Arc::clone(&bc) as _;
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_approval(Arc::clone(&mgr), bc_dyn);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({ "command": "echo safe" }))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "safe");
assert!(!bc.called.load(Ordering::SeqCst));
}
#[tokio::test]
async fn test_exec_tool_approval_approved() {
let mgr = Arc::new(ApprovalManager::default());
let bc = Arc::new(TestBroadcaster::new());
let bc_dyn: Arc<dyn ApprovalBroadcaster> = Arc::clone(&bc) as _;
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_approval(Arc::clone(&mgr), bc_dyn);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let mgr2 = Arc::clone(&mgr);
let handle = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(50)).await;
let ids = mgr2.pending_ids().await;
let id = ids.first().unwrap().clone();
mgr2.resolve(
&id,
ApprovalDecision::Approved,
Some("curl http://example.com"),
)
.await;
});
let result = tool
.execute(serde_json::json!({
"command": "curl http://example.com",
"_session_key": "session:abc"
}))
.await;
handle.await.unwrap();
assert!(bc.called.load(Ordering::SeqCst));
assert_eq!(
bc.session_key.lock().unwrap().as_deref(),
Some("session:abc")
);
let _ = result;
}
#[tokio::test]
async fn test_exec_tool_approval_denied() {
let mgr = Arc::new(ApprovalManager::default());
let bc = Arc::new(TestBroadcaster::new());
let bc_dyn: Arc<dyn ApprovalBroadcaster> = Arc::clone(&bc) as _;
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_approval(Arc::clone(&mgr), bc_dyn);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let mgr2 = Arc::clone(&mgr);
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(50)).await;
let ids = mgr2.pending_ids().await;
let id = ids.first().unwrap().clone();
mgr2.resolve(&id, ApprovalDecision::Denied, None).await;
});
let result = tool
.execute(serde_json::json!({ "command": "rm -rf /" }))
.await;
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("denied"));
}
#[tokio::test]
async fn test_exec_tool_with_sandbox() {
use crate::sandbox::{NoSandbox, SandboxScope};
let sandbox: Arc<dyn Sandbox> = Arc::new(NoSandbox);
let id = SandboxId {
scope: SandboxScope::Session,
key: "test-session".into(),
};
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_sandbox(sandbox, id);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({ "command": "echo sandboxed" }))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "sandboxed");
assert_eq!(result["exit_code"], 0);
}
struct RetryRecoverySandbox {
ensure_ready_calls: AtomicUsize,
cleanup_calls: AtomicUsize,
exec_calls: AtomicUsize,
cleanup_should_fail: bool,
failures_before_success: usize,
}
impl RetryRecoverySandbox {
fn new(cleanup_should_fail: bool, failures_before_success: usize) -> Self {
Self {
ensure_ready_calls: AtomicUsize::new(0),
cleanup_calls: AtomicUsize::new(0),
exec_calls: AtomicUsize::new(0),
cleanup_should_fail,
failures_before_success,
}
}
}
#[async_trait]
impl Sandbox for RetryRecoverySandbox {
fn backend_name(&self) -> &'static str {
"docker"
}
async fn ensure_ready(&self, _id: &SandboxId, _image_override: Option<&str>) -> Result<()> {
self.ensure_ready_calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn exec(&self, _id: &SandboxId, _command: &str, _opts: &ExecOpts) -> Result<ExecResult> {
let call = self.exec_calls.fetch_add(1, Ordering::SeqCst);
if call < self.failures_before_success {
return Ok(ExecResult {
stdout: String::new(),
stderr: "Error: internalError: \"failed to create process in container\" (cause: \"invalidState: \\\"cannot exec: container is not running\\\"\")".to_string(),
exit_code: 1,
});
}
Ok(ExecResult {
stdout: "recovered".to_string(),
stderr: String::new(),
exit_code: 0,
})
}
async fn cleanup(&self, _id: &SandboxId) -> Result<()> {
self.cleanup_calls.fetch_add(1, Ordering::SeqCst);
if self.cleanup_should_fail {
return Err(Error::message("cleanup failed"));
}
Ok(())
}
}
#[derive(Default)]
struct CaptureWorkingDirSandbox {
last_working_dir: std::sync::Mutex<Option<PathBuf>>,
}
#[async_trait]
impl Sandbox for CaptureWorkingDirSandbox {
fn backend_name(&self) -> &'static str {
"docker"
}
fn provides_fs_isolation(&self) -> bool {
true
}
async fn ensure_ready(&self, _id: &SandboxId, _image_override: Option<&str>) -> Result<()> {
Ok(())
}
async fn exec(&self, _id: &SandboxId, _command: &str, opts: &ExecOpts) -> Result<ExecResult> {
let mut guard = self
.last_working_dir
.lock()
.unwrap_or_else(|e| e.into_inner());
*guard = opts.working_dir.clone();
Ok(ExecResult {
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
})
}
async fn cleanup(&self, _id: &SandboxId) -> Result<()> {
Ok(())
}
}
#[derive(Default)]
struct NonWaitingSandbox {
ensure_ready_calls: AtomicUsize,
image: std::sync::Mutex<Option<String>>,
}
#[async_trait]
impl Sandbox for NonWaitingSandbox {
fn backend_name(&self) -> &'static str {
"docker"
}
fn provides_fs_isolation(&self) -> bool {
true
}
async fn ensure_ready(&self, _id: &SandboxId, image_override: Option<&str>) -> Result<()> {
self.ensure_ready_calls.fetch_add(1, Ordering::SeqCst);
*self.image.lock().unwrap_or_else(|e| e.into_inner()) =
image_override.map(ToOwned::to_owned);
Ok(())
}
async fn exec(&self, _id: &SandboxId, _command: &str, _opts: &ExecOpts) -> Result<ExecResult> {
Ok(ExecResult {
stdout: "ok".to_string(),
stderr: String::new(),
exit_code: 0,
})
}
async fn cleanup(&self, _id: &SandboxId) -> Result<()> {
Ok(())
}
}
struct FailingIsolatedSandbox;
#[async_trait]
impl Sandbox for FailingIsolatedSandbox {
fn backend_name(&self) -> &'static str {
"docker"
}
fn provides_fs_isolation(&self) -> bool {
true
}
fn is_isolated(&self) -> bool {
true
}
async fn ensure_ready(&self, _id: &SandboxId, _image_override: Option<&str>) -> Result<()> {
Err(Error::message("ensure_ready failed"))
}
async fn exec(&self, _id: &SandboxId, _command: &str, _opts: &ExecOpts) -> Result<ExecResult> {
Err(Error::message("no active sandbox"))
}
async fn cleanup(&self, _id: &SandboxId) -> Result<()> {
Ok(())
}
}
#[derive(Default)]
struct SyncUploadFailingSandbox {
ensure_ready_calls: AtomicUsize,
write_file_calls: AtomicUsize,
}
#[async_trait]
impl Sandbox for SyncUploadFailingSandbox {
fn backend_name(&self) -> &'static str {
"docker"
}
fn provides_fs_isolation(&self) -> bool {
true
}
fn is_isolated(&self) -> bool {
true
}
async fn ensure_ready(&self, _id: &SandboxId, _image_override: Option<&str>) -> Result<()> {
self.ensure_ready_calls.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn exec(&self, _id: &SandboxId, _command: &str, _opts: &ExecOpts) -> Result<ExecResult> {
Ok(ExecResult {
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
})
}
async fn write_file(
&self,
_id: &SandboxId,
_file_path: &str,
_content: &[u8],
) -> Result<Option<serde_json::Value>> {
self.write_file_calls.fetch_add(1, Ordering::SeqCst);
Err(Error::message("upload failed"))
}
async fn cleanup(&self, _id: &SandboxId) -> Result<()> {
Ok(())
}
}
#[tokio::test]
async fn test_exec_tool_retries_container_not_running_with_cleanup() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(RetryRecoverySandbox::new(false, 1));
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "retry-session".into(),
};
let result = ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({ "command": "echo hi" }))
.await
.unwrap();
assert_eq!(result["exit_code"], 0);
assert_eq!(result["stdout"].as_str().unwrap(), "recovered");
assert_eq!(sandbox.ensure_ready_calls.load(Ordering::SeqCst), 2);
assert_eq!(sandbox.cleanup_calls.load(Ordering::SeqCst), 1);
assert_eq!(sandbox.exec_calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn test_exec_tool_retries_container_not_running_when_cleanup_fails() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(RetryRecoverySandbox::new(true, 1));
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "retry-cleanup-fail-session".into(),
};
let result = ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({ "command": "echo hi" }))
.await
.unwrap();
assert_eq!(result["exit_code"], 0);
assert_eq!(result["stdout"].as_str().unwrap(), "recovered");
assert_eq!(sandbox.ensure_ready_calls.load(Ordering::SeqCst), 2);
assert_eq!(sandbox.cleanup_calls.load(Ordering::SeqCst), 1);
assert_eq!(sandbox.exec_calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn test_exec_tool_stops_after_max_container_retries() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(RetryRecoverySandbox::new(
false,
MAX_SANDBOX_RECOVERY_RETRIES + 1,
));
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "retry-max-session".into(),
};
let result = ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({ "command": "echo hi" }))
.await
.unwrap();
assert_eq!(result["exit_code"], 1);
assert!(is_container_not_running_exec_error(
result["stderr"].as_str().unwrap_or_default()
));
assert_eq!(
sandbox.ensure_ready_calls.load(Ordering::SeqCst),
MAX_SANDBOX_RECOVERY_RETRIES + 1
);
assert_eq!(
sandbox.cleanup_calls.load(Ordering::SeqCst),
MAX_SANDBOX_RECOVERY_RETRIES
);
assert_eq!(
sandbox.exec_calls.load(Ordering::SeqCst),
MAX_SANDBOX_RECOVERY_RETRIES + 1
);
}
#[tokio::test]
async fn test_exec_tool_cleanup_no_sandbox() {
let tool = ExecTool::default();
tool.cleanup().await.unwrap();
}
#[tokio::test]
async fn test_exec_tool_cleanup_with_sandbox() {
use crate::sandbox::{NoSandbox, SandboxScope};
let sandbox: Arc<dyn Sandbox> = Arc::new(NoSandbox);
let id = SandboxId {
scope: SandboxScope::Session,
key: "cleanup-test".into(),
};
let tool = ExecTool::default().with_sandbox(sandbox, id);
tool.cleanup().await.unwrap();
}
struct TestEnvProvider;
#[async_trait]
impl EnvVarProvider for TestEnvProvider {
async fn get_env_vars(&self) -> Vec<(String, secrecy::Secret<String>)> {
vec![(
"TEST_INJECTED".into(),
secrecy::Secret::new("hello_from_env".into()),
)]
}
}
#[tokio::test]
async fn test_exec_tool_with_env_provider() {
let provider: Arc<dyn EnvVarProvider> = Arc::new(TestEnvProvider);
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_env_provider(provider);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({ "command": "echo $TEST_INJECTED" }))
.await
.unwrap();
// The value is redacted in output.
assert_eq!(result["stdout"].as_str().unwrap().trim(), "[REDACTED]");
}
#[tokio::test]
async fn test_env_var_redaction_base64_exfiltration() {
let provider: Arc<dyn EnvVarProvider> = Arc::new(TestEnvProvider);
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_env_provider(provider);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({ "command": "echo $TEST_INJECTED | base64" }))
.await
.unwrap();
let stdout = result["stdout"].as_str().unwrap().trim();
assert!(
!stdout.contains("aGVsbG9fZnJvbV9lbnY"),
"base64 of secret should be redacted, got: {stdout}"
);
}
#[tokio::test]
async fn test_env_var_redaction_hex_exfiltration() {
let provider: Arc<dyn EnvVarProvider> = Arc::new(TestEnvProvider);
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_env_provider(provider);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({ "command": "printf '%s' \"$TEST_INJECTED\" | xxd -p" }))
.await
.unwrap();
let stdout = result["stdout"].as_str().unwrap().trim();
assert!(
!stdout.contains("68656c6c6f5f66726f6d5f656e76"),
"hex of secret should be redacted, got: {stdout}"
);
}
#[tokio::test]
async fn test_env_var_redaction_file_exfiltration() {
let provider: Arc<dyn EnvVarProvider> = Arc::new(TestEnvProvider);
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_env_provider(provider);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({
"command": "f=$(mktemp); echo $TEST_INJECTED > $f; cat $f; rm $f"
}))
.await
.unwrap();
let stdout = result["stdout"].as_str().unwrap().trim();
assert_eq!(stdout, "[REDACTED]", "file read-back should be redacted");
}
#[test]
fn test_redaction_needles() {
let needles = redaction_needles("secret123");
// Raw value
assert!(needles.contains(&"secret123".to_string()));
// base64
assert!(needles.iter().any(|n| n.contains("c2VjcmV0MTIz")));
// hex
assert!(needles.iter().any(|n| n.contains("736563726574313233")));
}
#[test]
fn test_is_container_not_running_exec_error() {
assert!(is_container_not_running_exec_error(
"Error: internalError: \"failed to create process in container\" (cause: \"invalidState: \\\"cannot exec: container is not running\\\"\")"
));
assert!(is_container_not_running_exec_error(
"cannot exec: container is not running"
));
assert!(is_container_not_running_exec_error(
"Error: invalidState: \"container codex-stop-12016 is not running\""
));
assert!(is_container_not_running_exec_error(
"Error: internalError: \"failed to create process in container\" (cause: \"invalidState: \\\"no sandbox client exists: container is stopped\\\"\")"
));
// notFound errors from get/inspect failures
assert!(is_container_not_running_exec_error(
"Error: notFound: \"get failed: container moltis-sandbox-main not found\""
));
assert!(is_container_not_running_exec_error(
"container not found: moltis-sandbox-session-abc"
));
assert!(!is_container_not_running_exec_error(
"permission denied: operation not permitted"
));
}
#[tokio::test]
async fn test_exec_tool_with_sandbox_router_off() {
use crate::sandbox::{NoSandbox, SandboxConfig, SandboxRouter};
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig::default(),
Arc::new(NoSandbox),
));
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_sandbox_router(router);
tool.working_dir = Some(temp_dir.path().to_path_buf());
// No session key → defaults to "main", mode=Off → direct exec.
let result = tool
.execute(serde_json::json!({ "command": "echo direct" }))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "direct");
}
#[tokio::test]
async fn test_exec_tool_with_sandbox_router_session_key() {
use crate::sandbox::{NoSandbox, SandboxConfig, SandboxRouter};
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig::default(),
Arc::new(NoSandbox),
));
// Override to enable sandbox for this session (NoSandbox backend → still executes directly).
router.set_override("session:abc", true).await;
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_sandbox_router(router);
tool.working_dir = Some(temp_dir.path().to_path_buf());
let result = tool
.execute(serde_json::json!({
"command": "echo routed",
"_session_key": "session:abc"
}))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "routed");
}
#[tokio::test]
async fn test_exec_tool_with_sandbox_router_does_not_wait_for_background_image_build() {
use crate::sandbox::{DEFAULT_SANDBOX_IMAGE, SandboxConfig, SandboxRouter};
let sandbox = Arc::new(NonWaitingSandbox::default());
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig::default(),
sandbox_dyn,
));
router.building_flag.store(true, Ordering::Relaxed);
let result = tokio::time::timeout(
Duration::from_millis(100),
ExecTool::default()
.with_sandbox_router(router)
.execute(serde_json::json!({
"command": "printf ok",
"_session_key": "session:blocking-build"
})),
)
.await
.expect("exec must not wait for the background sandbox image build")
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "ok");
assert_eq!(result["exit_code"], 0);
assert_eq!(sandbox.ensure_ready_calls.load(Ordering::SeqCst), 1);
assert_eq!(
sandbox
.image
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_deref(),
Some(DEFAULT_SANDBOX_IMAGE)
);
}
#[tokio::test]
async fn test_exec_tool_marks_synced_when_isolated_ensure_ready_fails() {
use crate::sandbox::{SandboxConfig, SandboxRouter};
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig::default(),
Arc::new(FailingIsolatedSandbox),
));
let session_key = "session:ensure-ready-fails";
let result = ExecTool::default()
.with_sandbox_router(Arc::clone(&router))
.execute(serde_json::json!({
"command": "printf ok",
"_session_key": session_key
}))
.await;
assert!(result.is_err());
assert!(router.is_synced(session_key).await);
assert_eq!(
router.sync_failure(session_key).await.as_deref(),
Some("ensure_ready failed")
);
assert!(router.mark_preparing_once(session_key).await);
assert!(!router.is_synced(session_key).await);
assert!(router.sync_failure(session_key).await.is_none());
}
#[tokio::test]
async fn test_exec_tool_clears_prepared_session_when_sync_in_fails() {
use crate::sandbox::{SandboxConfig, SandboxRouter};
let host_workspace = tempfile::tempdir().unwrap();
std::fs::write(host_workspace.path().join("input.txt"), "needs upload").unwrap();
let sandbox = Arc::new(SyncUploadFailingSandbox::default());
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig {
shared_home_dir: Some(host_workspace.path().to_path_buf()),
..Default::default()
},
Arc::clone(&sandbox) as Arc<dyn Sandbox>,
));
let session_key = "session:sync-in-fails";
let result = ExecTool::default()
.with_sandbox_router(Arc::clone(&router))
.execute(serde_json::json!({
"command": "printf ok",
"_session_key": session_key
}))
.await;
assert!(result.is_err());
assert_eq!(sandbox.ensure_ready_calls.load(Ordering::SeqCst), 1);
assert_eq!(sandbox.write_file_calls.load(Ordering::SeqCst), 1);
assert!(router.is_synced(session_key).await);
assert_eq!(
router.sync_failure(session_key).await.as_deref(),
Some("upload failed")
);
assert!(router.mark_preparing_once(session_key).await);
assert!(!router.is_synced(session_key).await);
assert!(router.sync_failure(session_key).await.is_none());
}
/// Regression test: when SandboxMode=All (the default) but the backend is
/// NoSandbox (no container runtime), the exec tool must NOT use
/// /home/sandbox as the working directory. It should fall back to the host
/// data directory and execute successfully.
#[tokio::test]
async fn test_exec_tool_no_container_backend_with_sandbox_mode_all() {
use crate::sandbox::{NoSandbox, SandboxConfig, SandboxRouter};
// Default config has mode=All, so is_sandboxed() returns true for
// every session. But the backend is NoSandbox ("none") — no Docker.
let router = Arc::new(SandboxRouter::with_backend(
SandboxConfig::default(),
Arc::new(NoSandbox),
));
// No explicit working_dir — the tool must NOT default to /home/sandbox.
let tool = ExecTool::default().with_sandbox_router(router);
let result = tool
.execute(serde_json::json!({ "command": "echo works" }))
.await
.unwrap();
assert_eq!(result["stdout"].as_str().unwrap().trim(), "works");
assert_eq!(result["exit_code"], 0);
}
#[tokio::test]
async fn test_exec_tool_sandbox_rewrites_host_absolute_working_dir() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(CaptureWorkingDirSandbox::default());
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "rewrite-host-abs-path".into(),
};
ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({
"command": "echo test",
"working_dir": "/Users/fabien"
}))
.await
.unwrap();
let captured = sandbox
.last_working_dir
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
// Absolute paths outside the sandbox are passed through — the backend
// handles remapping to its own workspace if needed.
assert_eq!(captured, Some(PathBuf::from("/Users/fabien")));
}
#[tokio::test]
async fn test_exec_tool_sandbox_resolves_relative_working_dir_under_home() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(CaptureWorkingDirSandbox::default());
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "rewrite-relative-path".into(),
};
ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({
"command": "echo test",
"working_dir": "project"
}))
.await
.unwrap();
let captured = sandbox
.last_working_dir
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
assert_eq!(captured, Some(PathBuf::from("/home/sandbox/project")));
}
#[tokio::test]
async fn test_exec_tool_sandbox_keeps_in_sandbox_absolute_working_dir() {
use crate::sandbox::SandboxScope;
let sandbox = Arc::new(CaptureWorkingDirSandbox::default());
let sandbox_dyn: Arc<dyn Sandbox> = Arc::clone(&sandbox) as _;
let id = SandboxId {
scope: SandboxScope::Session,
key: "keep-sandbox-abs-path".into(),
};
ExecTool::default()
.with_sandbox(sandbox_dyn, id)
.execute(serde_json::json!({
"command": "echo test",
"working_dir": "/home/sandbox/work"
}))
.await
.unwrap();
let captured = sandbox
.last_working_dir
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
assert_eq!(captured, Some(PathBuf::from("/home/sandbox/work")));
}
#[tokio::test]
async fn test_exec_command_bad_working_dir_error_message() {
let opts = ExecOpts {
working_dir: Some(PathBuf::from("/nonexistent_dir_12345")),
..Default::default()
};
let err = exec_command("echo hello", &opts).await.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("/nonexistent_dir_12345"),
"error should mention the bad directory, got: {msg}"
);
assert!(
msg.contains("working directory"),
"error should mention 'working directory', got: {msg}"
);
}
#[tokio::test]
async fn test_completion_callback_fires() {
let called = Arc::new(AtomicBool::new(false));
let called_clone = Arc::clone(&called);
let cb: ExecCompletionFn = Arc::new(move |event| {
assert_eq!(event.command, "echo callback");
assert_eq!(event.exit_code, 0);
assert!(event.stdout_preview.contains("callback"));
called_clone.store(true, Ordering::SeqCst);
});
let temp_dir = tempfile::tempdir().unwrap();
let mut tool = ExecTool::default().with_completion_callback(cb);