-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecutor_tests.rs
More file actions
855 lines (750 loc) · 28.2 KB
/
Copy pathexecutor_tests.rs
File metadata and controls
855 lines (750 loc) · 28.2 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
use serde_json::json;
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use traverse_runtime::executor::{
ArtifactType, CapabilityExecutor, ExecutorCapability, ExecutorError, NativeExecutor,
SUPPORTED_HOST_ABI_VERSION, WasmExecutionLimits, WasmExecutor, WasmModuleCacheConfig,
supported_host_abi_versions, verify_wasm_host_abi_bytes,
};
// --- NativeExecutor tests ---
static TEMPFILE_COUNTER: AtomicU64 = AtomicU64::new(0);
#[test]
fn native_executor_runs_handler() {
let executor = NativeExecutor::new(|input| {
let name = input["name"].as_str().unwrap_or("world");
Ok(json!({ "greeting": format!("hello, {name}!") }))
});
let cap = native_capability("greet");
let result = executor.execute(&cap, &json!({ "name": "traverse" }));
assert_eq!(result, Ok(json!({ "greeting": "hello, traverse!" })));
}
#[test]
fn native_executor_propagates_handler_error() -> Result<(), String> {
let executor = NativeExecutor::new(|_| Err("something went wrong".to_string()));
let cap = native_capability("fail");
let err = expect_err(
executor.execute(&cap, &json!({})),
"expected execution error",
)?;
assert_eq!(
err,
ExecutorError::ExecutionFailed("something went wrong".to_string())
);
Ok(())
}
#[test]
fn native_executor_rejects_wasm_artifact_type() -> Result<(), String> {
let executor = NativeExecutor::new(|_| Ok(json!({})));
let cap = ExecutorCapability {
capability_id: "wrong-type".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: None,
wasm_checksum: None,
host_abi_version: None,
};
let err = expect_err(executor.execute(&cap, &json!({})), "expected type error")?;
assert_eq!(err, ExecutorError::UnsupportedArtifactType);
Ok(())
}
#[test]
fn native_executor_passes_input_through() -> Result<(), String> {
let executor = NativeExecutor::new(|input| Ok(input.clone()));
let cap = native_capability("echo");
let input = json!({ "a": 1, "b": [true, false] });
let result = executor
.execute(&cap, &input)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(result, input);
Ok(())
}
// --- WasmExecutor tests ---
#[test]
fn wasm_executor_rejects_native_artifact_type() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let cap = native_capability("wrong");
let err = expect_err(executor.execute(&cap, &json!({})), "expected type error")?;
assert_eq!(err, ExecutorError::UnsupportedArtifactType);
Ok(())
}
#[test]
fn wasm_executor_errors_when_no_path_set() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let cap = ExecutorCapability {
capability_id: "no-path".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: None,
wasm_checksum: None,
host_abi_version: None,
};
let err = expect_err(
executor.execute(&cap, &json!({})),
"expected BinaryLoadFailed",
)?;
assert!(
matches!(err, ExecutorError::BinaryLoadFailed(_)),
"expected BinaryLoadFailed, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_errors_on_missing_file() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let cap = ExecutorCapability {
capability_id: "missing".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some("/nonexistent/path/module.wasm".to_string()),
wasm_checksum: None,
host_abi_version: None,
};
let err = expect_err(
executor.execute(&cap, &json!({})),
"expected BinaryLoadFailed",
)?;
assert!(
matches!(err, ExecutorError::BinaryLoadFailed(_)),
"expected BinaryLoadFailed, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_detects_checksum_mismatch() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
// Build a minimal WAT module that just returns immediately
let wat_src = r#"
(module
(memory 1)
(func $main (export "_start"))
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let tmp = tempfile_path();
std::fs::write(&tmp, &wasm_bytes).map_err(|e| format!("write temp: {e}"))?;
let cap = ExecutorCapability {
capability_id: "checksum-test".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some(tmp.clone()),
wasm_checksum: Some(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
),
host_abi_version: None,
};
let err = expect_err(
executor.execute(&cap, &json!({})),
"expected ChecksumMismatch",
)?;
std::fs::remove_file(&tmp).ok();
assert!(
matches!(err, ExecutorError::ChecksumMismatch { .. }),
"expected ChecksumMismatch, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_runs_echo_module() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
// WAT module that reads stdin and writes it back to stdout (echo)
// Uses WASI fd_read (fd=0) and fd_write (fd=1)
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "proc_exit"
(func $proc_exit (param i32)))
(memory (export "memory") 1)
(func $_start (export "_start")
;; iovec for read: ptr=8, len=4096
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 4096))
;; read stdin into offset 8
(drop (call $fd_read (i32.const 0) (i32.const 0) (i32.const 1) (i32.const 4100)))
;; nread is at memory[4100]; use it as iovec len for write
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.load (i32.const 4100)))
;; write stdout
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4104)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let input = json!({ "key": "value" });
let result = executor
.run_bytes(&wasm_bytes, &input)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(result, input, "echo module should return input unchanged");
Ok(())
}
#[test]
fn wasm_executor_rejects_invalid_json_output() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
// WAT module that writes "not-json" to stdout
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory (export "memory") 1)
(data (i32.const 16) "not-json")
(func $_start (export "_start")
;; iovec: ptr=16, len=8
(i32.store (i32.const 0) (i32.const 16))
(i32.store (i32.const 4) (i32.const 8))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let err = expect_err(
executor.run_bytes(&wasm_bytes, &json!({})),
"expected OutputDeserializationFailed",
)?;
assert!(
matches!(err, ExecutorError::OutputDeserializationFailed(_)),
"expected OutputDeserializationFailed, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_traps_infinite_loop_as_timeout() -> Result<(), String> {
let executor = WasmExecutor::with_limits(WasmExecutionLimits {
fuel_budget: 1_000,
..WasmExecutionLimits::default()
})
.map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(func $_start (export "_start")
(loop $again
br $again
)
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let err = expect_err(
executor.run_bytes(&wasm_bytes, &json!({})),
"expected Timeout",
)?;
assert!(
matches!(err, ExecutorError::Timeout(_)),
"expected Timeout, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_traps_memory_growth_as_resource_exhausted() -> Result<(), String> {
let executor = WasmExecutor::with_limits(WasmExecutionLimits {
fuel_budget: 100_000,
memory_bytes: 64 * 1024,
..WasmExecutionLimits::default()
})
.map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(memory (export "memory") 1)
(func $_start (export "_start")
(drop (memory.grow (i32.const 1)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let err = expect_err(
executor.run_bytes(&wasm_bytes, &json!({})),
"expected ResourceExhausted",
)?;
assert!(
matches!(err, ExecutorError::ResourceExhausted(_)),
"expected ResourceExhausted, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_preserves_generic_traps_as_execution_failed() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(func $_start (export "_start")
unreachable
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let err = expect_err(
executor.run_bytes(&wasm_bytes, &json!({})),
"expected ExecutionFailed",
)?;
assert!(
matches!(err, ExecutorError::ExecutionFailed(_)),
"expected ExecutionFailed, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_reuses_compiled_module_by_checksum() -> Result<(), String> {
let executor = WasmExecutor::with_limits_and_cache_config(
WasmExecutionLimits::default(),
WasmModuleCacheConfig { max_entries: 2 },
)
.map_err(|e| format!("{e:?}"))?;
let wasm_bytes = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
let first_input = json!({ "call": 1 });
let first = executor
.run_bytes(&wasm_bytes, &first_input)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(first, first_input);
let after_first = executor.module_cache_stats();
assert_eq!(after_first.entries, 1);
assert_eq!(after_first.hits, 0);
assert_eq!(after_first.misses, 1);
let second_input = json!({ "call": 2 });
let second = executor
.run_bytes(&wasm_bytes, &second_input)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(second, second_input);
let after_second = executor.module_cache_stats();
assert_eq!(after_second.entries, 1);
assert_eq!(after_second.hits, 1);
assert_eq!(after_second.misses, 1);
assert_eq!(after_second.evictions, 0);
Ok(())
}
#[test]
fn wasm_executor_cached_module_still_uses_fresh_store() -> Result<(), String> {
let executor = WasmExecutor::with_limits_and_cache_config(
WasmExecutionLimits::default(),
WasmModuleCacheConfig { max_entries: 2 },
)
.map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory (export "memory") 1)
(global $counter (mut i32) (i32.const 0))
(data (i32.const 8) "{\"count\":0}")
(func $_start (export "_start")
(global.set $counter (i32.add (global.get $counter) (i32.const 1)))
(i32.store8 (i32.const 17) (i32.add (global.get $counter) (i32.const 48)))
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 11))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let first = executor
.run_bytes(&wasm_bytes, &json!({}))
.map_err(|e| format!("{e:?}"))?;
let second = executor
.run_bytes(&wasm_bytes, &json!({}))
.map_err(|e| format!("{e:?}"))?;
assert_eq!(first, json!({ "count": 1 }));
assert_eq!(second, json!({ "count": 1 }));
assert_eq!(executor.module_cache_stats().hits, 1);
Ok(())
}
#[test]
fn wasm_executor_cache_evicts_oldest_entry_deterministically() -> Result<(), String> {
let executor = WasmExecutor::with_limits_and_cache_config(
WasmExecutionLimits::default(),
WasmModuleCacheConfig { max_entries: 1 },
)
.map_err(|e| format!("{e:?}"))?;
let first_wasm = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
let second_wat = r#"
(module
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory (export "memory") 1)
(data (i32.const 8) "{}")
(func $_start (export "_start")
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 2))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4)))
)
)
"#;
let second_wasm = wat::parse_str(second_wat).map_err(|e| format!("WAT parse: {e}"))?;
executor
.run_bytes(&first_wasm, &json!({ "cached": true }))
.map_err(|e| format!("{e:?}"))?;
executor
.run_bytes(&second_wasm, &json!({}))
.map_err(|e| format!("{e:?}"))?;
executor
.run_bytes(&first_wasm, &json!({ "cached": true }))
.map_err(|e| format!("{e:?}"))?;
let stats = executor.module_cache_stats();
assert_eq!(stats.entries, 1);
assert_eq!(stats.hits, 0);
assert_eq!(stats.misses, 3);
assert_eq!(stats.evictions, 2);
Ok(())
}
#[test]
fn wasm_executor_cache_miss_when_abi_version_differs() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let wasm_bytes = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
executor
.run_bytes(&wasm_bytes, &json!({ "abi": "1.0.0" }))
.map_err(|e| format!("{e:?}"))?;
let err = expect_err(
executor.run_bytes_with_host_abi(&wasm_bytes, &json!({}), "2.0.0"),
"expected unsupported ABI version",
)?;
assert!(matches!(err, ExecutorError::UnsupportedAbiVersion { .. }));
let stats = executor.module_cache_stats();
assert_eq!(stats.entries, 1);
assert_eq!(stats.hits, 0);
assert_eq!(stats.misses, 2);
Ok(())
}
#[test]
fn wasm_host_abi_verifier_accepts_sanctioned_stdio_imports() -> Result<(), String> {
let wasm_bytes = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
let validation = verify_wasm_host_abi_bytes(&wasm_bytes, SUPPORTED_HOST_ABI_VERSION)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(validation.abi_version, SUPPORTED_HOST_ABI_VERSION);
assert_eq!(supported_host_abi_versions(), &[SUPPORTED_HOST_ABI_VERSION]);
assert!(
validation.imports.iter().any(|import| {
import.module == "wasi_snapshot_preview1" && import.name == "fd_read"
})
);
assert!(
validation.imports.iter().any(|import| {
import.module == "wasi_snapshot_preview1" && import.name == "fd_write"
})
);
Ok(())
}
#[test]
fn wasm_host_abi_verifier_rejects_unauthorized_import_before_execution() -> Result<(), String> {
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "random_get"
(func $random_get (param i32 i32) (result i32)))
(memory (export "memory") 1)
(func $_start (export "_start")
unreachable
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let err = expect_err(
executor.run_bytes(&wasm_bytes, &json!({})),
"expected unauthorized host import",
)?;
assert_eq!(
err,
ExecutorError::UnauthorizedHostImport {
error_code: "unauthorized_host_import".to_string(),
abi_version: SUPPORTED_HOST_ABI_VERSION.to_string(),
module: "wasi_snapshot_preview1".to_string(),
name: "random_get".to_string(),
}
);
Ok(())
}
#[test]
fn wasm_host_abi_verifier_rejects_unsupported_abi_version() -> Result<(), String> {
let wasm_bytes = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let err = expect_err(
executor.run_bytes_with_host_abi(&wasm_bytes, &json!({}), "2.0.0"),
"expected unsupported ABI version",
)?;
assert_eq!(
err,
ExecutorError::UnsupportedAbiVersion {
error_code: "unsupported_abi_version".to_string(),
requested: "2.0.0".to_string(),
supported: SUPPORTED_HOST_ABI_VERSION.to_string(),
}
);
Ok(())
}
#[test]
fn wasm_host_abi_verifier_reports_malformed_binary() -> Result<(), String> {
let err = expect_err(
verify_wasm_host_abi_bytes(b"not-a-wasm-binary", SUPPORTED_HOST_ABI_VERSION),
"expected malformed WASM artifact",
)?;
assert!(
matches!(err, ExecutorError::MalformedWasmArtifact { .. }),
"expected MalformedWasmArtifact, got {err:?}"
);
Ok(())
}
// --- Debug impl coverage ---
#[test]
fn native_executor_debug_impl_is_accessible() {
let executor = NativeExecutor::new(|_| Ok(json!({})));
let dbg = format!("{executor:?}");
assert!(dbg.contains("NativeExecutor"), "Debug output: {dbg}");
}
// --- ExecutorError Display coverage ---
#[test]
fn executor_error_display_covers_all_variants() {
let cases: &[(ExecutorError, &str)] = &[
(
ExecutorError::BinaryLoadFailed("oops".to_string()),
"binary load failed: oops",
),
(
ExecutorError::ChecksumMismatch {
expected: "abc".to_string(),
actual: "def".to_string(),
},
"checksum mismatch: expected abc, got def",
),
(
ExecutorError::RuntimeSetupFailed("bad linker".to_string()),
"runtime setup failed: bad linker",
),
(
ExecutorError::MalformedWasmArtifact {
error_code: "malformed_wasm_artifact".to_string(),
detail: "bad magic".to_string(),
},
"malformed_wasm_artifact: bad magic",
),
(
ExecutorError::UnsupportedAbiVersion {
error_code: "unsupported_abi_version".to_string(),
requested: "2.0.0".to_string(),
supported: "1.0.0".to_string(),
},
"unsupported_abi_version: requested Traverse Host ABI 2.0.0, supported 1.0.0",
),
(
ExecutorError::UnauthorizedHostImport {
error_code: "unauthorized_host_import".to_string(),
abi_version: "1.0.0".to_string(),
module: "wasi_snapshot_preview1".to_string(),
name: "random_get".to_string(),
},
"unauthorized_host_import: ABI 1.0.0 does not allow import wasi_snapshot_preview1::random_get",
),
(
ExecutorError::ExecutionFailed("trapped".to_string()),
"execution failed: trapped",
),
(
ExecutorError::Timeout("fuel exhausted".to_string()),
"execution timed out: fuel exhausted",
),
(
ExecutorError::ResourceExhausted("memory cap".to_string()),
"resource exhausted: memory cap",
),
(
ExecutorError::OutputDeserializationFailed("not json".to_string()),
"output deserialization failed: not json",
),
(
ExecutorError::UnsupportedArtifactType,
"unsupported artifact type for this executor",
),
];
for (err, expected_msg) in cases {
assert_eq!(
format!("{err}"),
*expected_msg,
"Display mismatch for {err:?}"
);
}
}
#[test]
fn wasm_executor_full_execute_path_via_disk() -> Result<(), String> {
// Tests the execute() code path (file I/O + optional checksum) end-to-end.
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "proc_exit"
(func $proc_exit (param i32)))
(memory (export "memory") 1)
(func $_start (export "_start")
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 4096))
(drop (call $fd_read (i32.const 0) (i32.const 0) (i32.const 1) (i32.const 4100)))
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.load (i32.const 4100)))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4104)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
let tmp = tempfile_path();
std::fs::write(&tmp, &wasm_bytes).map_err(|e| format!("write: {e}"))?;
let cap = ExecutorCapability {
capability_id: "disk-echo".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some(tmp.clone()),
wasm_checksum: None, // no checksum — exercises the skip-checksum branch
host_abi_version: None,
};
let input = json!({ "disk": true });
let result = executor.execute(&cap, &input).map_err(|e| format!("{e:?}"));
std::fs::remove_file(&tmp).ok();
assert_eq!(result, Ok(input));
Ok(())
}
#[test]
fn wasm_executor_execute_with_matching_checksum_succeeds() -> Result<(), String> {
// Exercises the checksum-match success branch in execute() — skipped by run_bytes() tests.
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let wat_src = r#"
(module
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory (export "memory") 1)
(data (i32.const 8) "{}")
(func $_start (export "_start")
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 2))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4)))
)
)
"#;
let wasm_bytes = wat::parse_str(wat_src).map_err(|e| format!("WAT parse: {e}"))?;
// Compute the correct SHA-256 checksum so the checksum-match branch is taken.
let mut hasher = Sha256::new();
hasher.update(&wasm_bytes);
let checksum: String = hasher
.finalize()
.iter()
.fold(String::new(), |mut acc, byte| {
let _ = write!(acc, "{byte:02x}");
acc
});
let tmp = tempfile_path();
std::fs::write(&tmp, &wasm_bytes).map_err(|e| format!("write: {e}"))?;
let cap = ExecutorCapability {
capability_id: "checksum-ok".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some(tmp.clone()),
wasm_checksum: Some(checksum),
host_abi_version: Some("1.0.0".to_string()),
};
let result = executor
.execute(&cap, &json!({}))
.map_err(|e| format!("{e:?}"));
std::fs::remove_file(&tmp).ok();
assert_eq!(result, Ok(json!({})));
Ok(())
}
#[test]
fn wasm_executor_cached_module_does_not_bypass_checksum_mismatch() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
let wasm_bytes = wat::parse_str(echo_wat()).map_err(|e| format!("WAT parse: {e}"))?;
let mut hasher = Sha256::new();
hasher.update(&wasm_bytes);
let checksum: String = hasher
.finalize()
.iter()
.fold(String::new(), |mut acc, byte| {
let _ = write!(acc, "{byte:02x}");
acc
});
let tmp = tempfile_path();
std::fs::write(&tmp, &wasm_bytes).map_err(|e| format!("write: {e}"))?;
let cap = ExecutorCapability {
capability_id: "checksum-cache".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some(tmp.clone()),
wasm_checksum: Some(checksum),
host_abi_version: Some("1.0.0".to_string()),
};
let input = json!({ "cache": true });
let result = executor
.execute(&cap, &input)
.map_err(|e| format!("{e:?}"))?;
assert_eq!(result, input);
assert_eq!(executor.module_cache_stats().entries, 1);
std::fs::write(&tmp, b"not-the-same-wasm").map_err(|e| format!("overwrite: {e}"))?;
let err = expect_err(
executor.execute(&cap, &json!({})),
"expected checksum mismatch",
)?;
std::fs::remove_file(&tmp).ok();
assert!(
matches!(err, ExecutorError::ChecksumMismatch { .. }),
"expected ChecksumMismatch, got {err:?}"
);
Ok(())
}
#[test]
fn wasm_executor_invalid_binary_triggers_runtime_setup_failed() -> Result<(), String> {
let executor = WasmExecutor::new().map_err(|e| format!("{e:?}"))?;
// Write garbage bytes — not a valid WASM module
let tmp = tempfile_path();
std::fs::write(&tmp, b"not-a-wasm-binary").map_err(|e| format!("write: {e}"))?;
let cap = ExecutorCapability {
capability_id: "bad-binary".to_string(),
artifact_type: ArtifactType::Wasm,
wasm_binary_path: Some(tmp.clone()),
wasm_checksum: None,
host_abi_version: None,
};
let err = expect_err(executor.execute(&cap, &json!({})), "expected error")?;
std::fs::remove_file(&tmp).ok();
assert!(
matches!(err, ExecutorError::MalformedWasmArtifact { .. }),
"expected MalformedWasmArtifact, got {err:?}"
);
Ok(())
}
// --- helpers ---
fn native_capability(id: &str) -> ExecutorCapability {
ExecutorCapability {
capability_id: id.to_string(),
artifact_type: ArtifactType::Native,
wasm_binary_path: None,
wasm_checksum: None,
host_abi_version: None,
}
}
fn tempfile_path() -> String {
let suffix = TEMPFILE_COUNTER.fetch_add(1, Ordering::Relaxed);
format!(
"/tmp/traverse-test-{}-{suffix}.wasm",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
)
}
fn echo_wat() -> &'static str {
r#"
(module
(import "wasi_snapshot_preview1" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(import "wasi_snapshot_preview1" "proc_exit"
(func $proc_exit (param i32)))
(memory (export "memory") 1)
(func $_start (export "_start")
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.const 4096))
(drop (call $fd_read (i32.const 0) (i32.const 0) (i32.const 1) (i32.const 4100)))
(i32.store (i32.const 0) (i32.const 8))
(i32.store (i32.const 4) (i32.load (i32.const 4100)))
(drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 4104)))
)
)
"#
}
/// Assert that `result` is `Err`, returning the error value or a descriptive `String` failure.
fn expect_err<T: std::fmt::Debug, E>(result: Result<T, E>, msg: &str) -> Result<E, String> {
match result {
Err(e) => Ok(e),
Ok(v) => Err(format!("{msg}: got Ok({v:?})")),
}
}