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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
//! WASM guard runtime and kernel integration.
//!
//! This module provides `WasmGuard` which implements `chio_kernel::Guard` and
//! `WasmGuardRuntime` which manages a collection of loaded WASM guards.
use std::sync::Mutex;
use chio_kernel::{Guard, GuardContext, KernelError, Verdict};
use tracing::{debug, warn};
use crate::abi::{GuardRequest, GuardVerdict, WasmGuardAbi};
use crate::config::WasmGuardConfig;
use crate::error::WasmGuardError;
// ---------------------------------------------------------------------------
// WasmGuard -- single WASM guard implementing chio_kernel::Guard
// ---------------------------------------------------------------------------
/// A single WASM guard module loaded into the runtime.
///
/// Wraps a `WasmGuardAbi` backend and adapts it to the kernel's `Guard` trait.
/// On any error (fuel exhaustion, traps, serialization failures) the guard
/// fails closed and returns `Verdict::Deny`.
///
/// Carries optional receipt metadata: `manifest_sha256` (set at construction
/// from the guard manifest) and `last_fuel_consumed` (updated after each
/// `evaluate()` call).
pub struct WasmGuard {
/// Guard name (from config).
name: String,
/// The loaded WASM backend, behind a Mutex for interior mutability.
backend: Mutex<Box<dyn WasmGuardAbi>>,
/// Whether this guard is advisory-only (non-blocking).
advisory: bool,
/// SHA-256 hex digest of the guard manifest, if loaded from a manifest.
manifest_sha256: Option<String>,
/// Fuel consumed during the most recent `evaluate()` call.
last_fuel_consumed: Mutex<Option<u64>>,
}
impl WasmGuard {
/// Create a new WASM guard from a loaded backend.
///
/// `manifest_sha256` is the hex-encoded SHA-256 digest of the guard's
/// manifest file, used for receipt metadata. Pass `None` when loading
/// without a manifest (e.g. in tests).
pub fn new(
name: String,
backend: Box<dyn WasmGuardAbi>,
advisory: bool,
manifest_sha256: Option<String>,
) -> Self {
Self {
name,
backend: Mutex::new(backend),
advisory,
manifest_sha256,
last_fuel_consumed: Mutex::new(None),
}
}
/// Returns `true` if this guard is advisory-only.
#[must_use]
pub fn is_advisory(&self) -> bool {
self.advisory
}
/// Returns the SHA-256 hex digest of the guard manifest, if set.
#[must_use]
pub fn manifest_sha256(&self) -> Option<&str> {
self.manifest_sha256.as_deref()
}
/// Returns the fuel consumed during the most recent `evaluate()` call,
/// or `None` if no evaluation has occurred or the backend does not track
/// fuel.
#[must_use]
pub fn last_fuel_consumed(&self) -> Option<u64> {
self.last_fuel_consumed.lock().ok().and_then(|guard| *guard)
}
/// Returns a JSON object containing receipt metadata from the most
/// recent evaluation: `fuel_consumed` and `manifest_sha256`.
#[must_use]
pub fn guard_evidence_metadata(&self) -> serde_json::Value {
serde_json::json!({
"fuel_consumed": self.last_fuel_consumed(),
"manifest_sha256": self.manifest_sha256.as_deref(),
})
}
pub(crate) fn build_request(ctx: &GuardContext<'_>) -> GuardRequest {
use chio_guards::ToolAction;
let scopes = ctx
.scope
.grants
.iter()
.map(|g| format!("{}:{}", g.server_id, g.tool_name))
.collect();
let action = chio_guards::extract_action(&ctx.request.tool_name, &ctx.request.arguments);
let (action_type, extracted_path, extracted_target) = match &action {
ToolAction::FileAccess(path) => (Some("file_access".into()), Some(path.clone()), None),
ToolAction::FileWrite(path, _) => (Some("file_write".into()), Some(path.clone()), None),
ToolAction::NetworkEgress(host, _) => {
(Some("network_egress".into()), None, Some(host.clone()))
}
ToolAction::ShellCommand(_) => (Some("shell_command".into()), None, None),
ToolAction::McpTool(_, _) => (Some("mcp_tool".into()), None, None),
ToolAction::Patch(path, _) => (Some("patch".into()), Some(path.clone()), None),
ToolAction::CodeExecution { language, .. } => {
(Some("code_execution".into()), None, Some(language.clone()))
}
ToolAction::BrowserAction { verb, target } => (
Some("browser_action".into()),
None,
target.clone().or_else(|| Some(verb.clone())),
),
ToolAction::DatabaseQuery { database, .. } => {
(Some("database_query".into()), None, Some(database.clone()))
}
ToolAction::ExternalApiCall { service, endpoint } => (
Some("external_api_call".into()),
None,
Some(format!("{service}:{endpoint}")),
),
ToolAction::MemoryWrite { store, key } => (
Some("memory_write".into()),
None,
Some(format!("{store}/{key}")),
),
ToolAction::MemoryRead { store, key } => (
Some("memory_read".into()),
None,
Some(match key {
Some(k) => format!("{store}/{k}"),
None => store.clone(),
}),
),
ToolAction::Unknown => (Some("unknown".into()), None, None),
};
let filesystem_roots = ctx
.session_filesystem_roots
.map(|roots| roots.to_vec())
.unwrap_or_default();
GuardRequest {
tool_name: ctx.request.tool_name.clone(),
server_id: ctx.server_id.clone(),
agent_id: ctx.agent_id.clone(),
arguments: ctx.request.arguments.clone(),
scopes,
action_type,
extracted_path,
extracted_target,
filesystem_roots,
matched_grant_index: ctx.matched_grant_index,
}
}
}
impl std::fmt::Debug for WasmGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WasmGuard")
.field("name", &self.name)
.field("advisory", &self.advisory)
.finish()
}
}
impl Guard for WasmGuard {
fn name(&self) -> &str {
&self.name
}
fn evaluate(&self, ctx: &GuardContext) -> Result<Verdict, KernelError> {
let request = Self::build_request(ctx);
let mut backend = self
.backend
.lock()
.map_err(|e| KernelError::Internal(format!("WASM guard mutex poisoned: {e}")))?;
let result = backend.evaluate(&request);
let fuel = backend.last_fuel_consumed();
drop(backend); // explicit drop after reading fuel
// Store fuel consumed for receipt metadata
if let Ok(mut fuel_lock) = self.last_fuel_consumed.lock() {
*fuel_lock = fuel;
}
match result {
Ok(GuardVerdict::Allow) => {
debug!(guard = %self.name, "WASM guard allowed request");
Ok(Verdict::Allow)
}
Ok(GuardVerdict::Deny { reason }) => {
let reason_str = reason.as_deref().unwrap_or("denied by WASM guard");
if self.advisory {
debug!(
guard = %self.name,
reason = %reason_str,
"WASM advisory guard denied (non-blocking)"
);
Ok(Verdict::Allow)
} else {
warn!(
guard = %self.name,
reason = %reason_str,
"WASM guard denied request"
);
Ok(Verdict::Deny)
}
}
Err(e) => {
// Fail closed: any error during WASM execution denies.
warn!(
guard = %self.name,
error = %e,
"WASM guard error -- failing closed"
);
if self.advisory {
Ok(Verdict::Allow)
} else {
Ok(Verdict::Deny)
}
}
}
}
}
// ---------------------------------------------------------------------------
// WasmGuardRuntime -- manages multiple WASM guards
// ---------------------------------------------------------------------------
/// Runtime that manages a collection of loaded WASM guard modules.
///
/// Guards are sorted by priority (lower = earlier) before evaluation.
pub struct WasmGuardRuntime {
guards: Vec<WasmGuard>,
}
impl WasmGuardRuntime {
/// Create a new empty runtime.
pub fn new() -> Self {
Self { guards: Vec::new() }
}
/// Register a pre-loaded WASM guard.
pub fn add_guard(&mut self, guard: WasmGuard) {
self.guards.push(guard);
}
/// Load a WASM guard from a configuration entry and a backend factory.
///
/// The `factory` closure receives the raw WASM bytes and fuel limit,
/// and must return a loaded `WasmGuardAbi` implementation.
pub fn load_guard<F>(
&mut self,
config: &WasmGuardConfig,
factory: F,
) -> Result<(), WasmGuardError>
where
F: FnOnce(&[u8], u64) -> Result<Box<dyn WasmGuardAbi>, WasmGuardError>,
{
let wasm_bytes = std::fs::read(&config.path).map_err(|e| WasmGuardError::ModuleLoad {
path: config.path.clone(),
reason: e.to_string(),
})?;
// WGSEC-03: Pre-check module size before passing to the factory
if wasm_bytes.len() > config.max_module_size {
return Err(WasmGuardError::ModuleTooLarge {
size: wasm_bytes.len(),
limit: config.max_module_size,
});
}
let backend = factory(&wasm_bytes, config.fuel_limit)?;
self.guards.push(WasmGuard::new(
config.name.clone(),
backend,
config.advisory,
None, // manifest_sha256 -- Plan 02 will pass the real value
));
Ok(())
}
/// Return the number of loaded guards.
#[must_use]
pub fn guard_count(&self) -> usize {
self.guards.len()
}
/// Return an iterator over the loaded guards as `&dyn Guard`.
pub fn guards(&self) -> impl Iterator<Item = &WasmGuard> {
self.guards.iter()
}
/// Convert this runtime into a vector of boxed `Guard` trait objects
/// suitable for registering on the kernel.
pub fn into_guards(self) -> Vec<Box<dyn Guard>> {
self.guards
.into_iter()
.map(|g| Box::new(g) as Box<dyn Guard>)
.collect()
}
}
impl Default for WasmGuardRuntime {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Mock backend for testing
// ---------------------------------------------------------------------------
/// A mock WASM guard backend for testing.
///
/// Returns a fixed verdict for every invocation.
pub struct MockWasmBackend {
verdict: GuardVerdict,
loaded: bool,
}
impl MockWasmBackend {
/// Create a mock backend that always allows.
pub fn allowing() -> Self {
Self {
verdict: GuardVerdict::Allow,
loaded: false,
}
}
/// Create a mock backend that always denies with the given reason.
pub fn denying(reason: &str) -> Self {
Self {
verdict: GuardVerdict::Deny {
reason: Some(reason.to_string()),
},
loaded: false,
}
}
}
impl WasmGuardAbi for MockWasmBackend {
fn load_module(&mut self, _wasm_bytes: &[u8], _fuel_limit: u64) -> Result<(), WasmGuardError> {
self.loaded = true;
Ok(())
}
fn evaluate(&mut self, _request: &GuardRequest) -> Result<GuardVerdict, WasmGuardError> {
if !self.loaded {
return Err(WasmGuardError::BackendUnavailable);
}
Ok(self.verdict.clone())
}
fn backend_name(&self) -> &str {
"mock"
}
}
// ---------------------------------------------------------------------------
// Wasmtime backend (behind feature flag)
// ---------------------------------------------------------------------------
#[cfg(feature = "wasmtime-runtime")]
pub mod wasmtime_backend {
//! Wasmtime-based WASM guard backend.
//!
//! Requires the `wasmtime-runtime` feature.
use std::collections::HashMap;
use std::sync::Arc;
use super::*;
use crate::host::{create_shared_engine, register_host_functions, WasmHostState};
use wasmtime::{Engine, Linker, Memory, Module, Store};
use crate::host::MAX_MEMORY_BYTES;
/// Default maximum module size in bytes (10 MiB).
const DEFAULT_MAX_MODULE_SIZE: usize = 10 * 1024 * 1024;
// -------------------------------------------------------------------
// Dual-mode format detection
// -------------------------------------------------------------------
/// Detected format of a .wasm binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WasmFormat {
/// Traditional core WASM module (raw evaluate ABI).
CoreModule,
/// Component Model component (WIT-based ABI).
Component,
}
/// Inspect the first bytes of a WASM binary to determine its format.
///
/// Uses `wasmparser::Parser` for authoritative detection. Returns `Err` if
/// the bytes are neither a valid core module nor a component.
pub fn detect_wasm_format(bytes: &[u8]) -> Result<WasmFormat, WasmGuardError> {
if wasmparser::Parser::is_component(bytes) {
Ok(WasmFormat::Component)
} else if wasmparser::Parser::is_core_wasm(bytes) {
Ok(WasmFormat::CoreModule)
} else {
Err(WasmGuardError::UnrecognizedFormat)
}
}
/// Create the appropriate WASM guard backend based on binary format detection.
///
/// Inspects `wasm_bytes` to determine whether it is a core module or Component
/// Model component, then returns a loaded backend ready for `evaluate()` calls.
///
/// - Core modules route to `WasmtimeBackend` (raw ABI with host functions).
/// - Components route to `ComponentBackend` (WIT-based, type-safe bindings).
pub fn create_backend(
engine: Arc<Engine>,
wasm_bytes: &[u8],
fuel_limit: u64,
config: HashMap<String, String>,
) -> Result<Box<dyn crate::abi::WasmGuardAbi>, WasmGuardError> {
let format = detect_wasm_format(wasm_bytes)?;
match format {
WasmFormat::CoreModule => {
let mut backend = WasmtimeBackend::with_engine_and_config(engine, config);
backend.load_module(wasm_bytes, fuel_limit)?;
Ok(Box::new(backend))
}
WasmFormat::Component => {
let mut backend = crate::component::ComponentBackend::with_engine(engine);
backend.load_module(wasm_bytes, fuel_limit)?;
Ok(Box::new(backend))
}
}
}
/// Load a WASM guard enforcing the Phase 1.3 signing policy.
///
/// Reads `wasm_path` from disk, verifies that the signature sidecar
/// (`wasm_path + ".sig"`) is present and valid per
/// [`crate::manifest::verify_guard_signature`], then checks the SHA-256
/// hash against the manifest declaration before instantiating the
/// backend via [`create_backend`].
///
/// Errors are fail-closed: any signature, hash, or format problem
/// rejects the guard before any guest code runs. Operators may set
/// `manifest.allow_unsigned = true` (with `signer_public_key = None`)
/// to permit unsigned modules, in which case a WARN is logged.
pub fn load_signed_guard(
engine: Arc<Engine>,
wasm_path: &str,
fuel_limit: u64,
manifest: &crate::manifest::GuardManifest,
) -> Result<Box<dyn crate::abi::WasmGuardAbi>, WasmGuardError> {
let wasm_bytes = std::fs::read(wasm_path).map_err(|e| WasmGuardError::ModuleLoad {
path: wasm_path.to_string(),
reason: e.to_string(),
})?;
// Signing policy (Phase 1.3) -- fail-closed.
crate::manifest::verify_guard_signature(wasm_path, &wasm_bytes, manifest)?;
// Hash attestation from the manifest.
crate::manifest::verify_wasm_hash(&wasm_bytes, &manifest.wasm_sha256)?;
create_backend(engine, &wasm_bytes, fuel_limit, manifest.config.clone())
}
// -------------------------------------------------------------------
// WasmtimeBackend
// -------------------------------------------------------------------
/// WASM guard backend powered by Wasmtime.
///
/// Uses a shared [`Arc<Engine>`] and creates a fresh
/// [`Store<WasmHostState>`] per `evaluate()` call. Host functions
/// (`chio.log`, `chio.get_config`, `chio.get_time_unix_secs`) are registered
/// on the Linker before module instantiation.
pub struct WasmtimeBackend {
engine: Arc<Engine>,
module: Option<Module>,
fuel_limit: u64,
config: HashMap<String, String>,
max_memory_bytes: usize,
max_module_size: usize,
last_fuel_consumed: Option<u64>,
}
impl WasmtimeBackend {
/// Create a new Wasmtime backend with its own shared engine.
///
/// For backward compatibility; callers that want to share an engine
/// across multiple guards should use [`with_engine`] instead.
pub fn new() -> Result<Self, WasmGuardError> {
let engine = create_shared_engine()?;
Ok(Self {
engine,
module: None,
fuel_limit: 0,
config: HashMap::new(),
max_memory_bytes: MAX_MEMORY_BYTES,
max_module_size: DEFAULT_MAX_MODULE_SIZE,
last_fuel_consumed: None,
})
}
/// Create a Wasmtime backend with a pre-existing shared engine.
///
/// This is the recommended constructor when loading multiple guards:
/// create one `Arc<Engine>` via [`create_shared_engine()`] and pass it
/// to each backend.
pub fn with_engine(engine: Arc<Engine>) -> Self {
Self {
engine,
module: None,
fuel_limit: 0,
config: HashMap::new(),
max_memory_bytes: MAX_MEMORY_BYTES,
max_module_size: DEFAULT_MAX_MODULE_SIZE,
last_fuel_consumed: None,
}
}
/// Create a Wasmtime backend with a shared engine and guard-specific
/// config that will be accessible to guests via `chio.get_config`.
pub fn with_engine_and_config(
engine: Arc<Engine>,
config: HashMap<String, String>,
) -> Self {
Self {
engine,
module: None,
fuel_limit: 0,
config,
max_memory_bytes: MAX_MEMORY_BYTES,
max_module_size: DEFAULT_MAX_MODULE_SIZE,
last_fuel_consumed: None,
}
}
/// Set custom resource limits for module size and memory.
///
/// Builder-style method for configuring security boundaries.
#[must_use]
pub fn with_limits(mut self, max_memory_bytes: usize, max_module_size: usize) -> Self {
self.max_memory_bytes = max_memory_bytes;
self.max_module_size = max_module_size;
self
}
}
impl Default for WasmtimeBackend {
fn default() -> Self {
match Self::new() {
Ok(b) => b,
Err(_) => Self {
engine: Arc::new(Engine::default()),
module: None,
fuel_limit: 0,
config: HashMap::new(),
max_memory_bytes: MAX_MEMORY_BYTES,
max_module_size: DEFAULT_MAX_MODULE_SIZE,
last_fuel_consumed: None,
},
}
}
}
impl WasmGuardAbi for WasmtimeBackend {
fn load_module(
&mut self,
wasm_bytes: &[u8],
fuel_limit: u64,
) -> Result<(), WasmGuardError> {
// WGSEC-03: Reject oversized modules before compilation
if wasm_bytes.len() > self.max_module_size {
return Err(WasmGuardError::ModuleTooLarge {
size: wasm_bytes.len(),
limit: self.max_module_size,
});
}
let module = Module::new(&self.engine, wasm_bytes)
.map_err(|e| WasmGuardError::Compilation(e.to_string()))?;
// WGSEC-02: Validate that all imports come from the "chio" namespace
for import in module.imports() {
if import.module() != "chio" {
return Err(WasmGuardError::ImportViolation {
module: import.module().to_string(),
name: import.name().to_string(),
});
}
}
self.module = Some(module);
self.fuel_limit = fuel_limit;
Ok(())
}
fn evaluate(&mut self, request: &GuardRequest) -> Result<GuardVerdict, WasmGuardError> {
let module = self
.module
.as_ref()
.ok_or(WasmGuardError::BackendUnavailable)?;
// WGSEC-01: Create a fresh Store with configurable memory limit
let host_state =
WasmHostState::with_memory_limit(self.config.clone(), self.max_memory_bytes);
let mut store = Store::new(&self.engine, host_state);
store.limiter(|state| &mut state.limits);
store
.set_fuel(self.fuel_limit)
.map_err(|e| WasmGuardError::Trap(e.to_string()))?;
// Create a Linker with host functions registered
let mut linker: Linker<WasmHostState> = Linker::new(&self.engine);
register_host_functions(&mut linker)?;
let instance = linker
.instantiate(&mut store, module)
.map_err(|e| WasmGuardError::Trap(e.to_string()))?;
// Serialize request to JSON
let request_json = serde_json::to_vec(request)
.map_err(|e| WasmGuardError::Serialization(e.to_string()))?;
// Get guest memory
let memory = instance
.get_memory(&mut store, "memory")
.ok_or_else(|| WasmGuardError::MissingExport("memory".to_string()))?;
// Probe for optional chio_alloc guest export
let chio_alloc_fn = instance
.get_typed_func::<i32, i32>(&mut store, "chio_alloc")
.ok();
let request_len: i32 = request_json.len() as i32;
let request_ptr: i32 = if let Some(ref alloc_fn) = chio_alloc_fn {
match alloc_fn.call(&mut store, request_len) {
Ok(ptr) => {
// Validate returned pointer is in bounds
let mem_size = memory.data_size(&store);
if ptr >= 0
&& (ptr as usize).saturating_add(request_len as usize) <= mem_size
{
ptr
} else {
// Out-of-bounds pointer -- fall back to offset 0
tracing::warn!(
ptr = ptr,
request_len = request_len,
mem_size = mem_size,
"chio_alloc returned out-of-bounds pointer, falling back to offset 0"
);
0
}
}
Err(e) => {
// chio_alloc call failed -- fall back to offset 0
tracing::warn!(
error = %e,
"chio_alloc call failed, falling back to offset 0"
);
0
}
}
} else {
// No chio_alloc export -- use legacy offset-0 protocol
0
};
// Write request into guest memory at the resolved offset
memory
.write(&mut store, request_ptr as usize, &request_json)
.map_err(|e| WasmGuardError::Memory(e.to_string()))?;
// Call the evaluate function
let evaluate_fn = instance
.get_typed_func::<(i32, i32), i32>(&mut store, "evaluate")
.map_err(|e| WasmGuardError::MissingExport(format!("evaluate: {e}")))?;
let result = evaluate_fn
.call(&mut store, (request_ptr, request_len))
.map_err(|e| {
// Check if this was a fuel exhaustion
let msg = e.to_string();
if msg.contains("fuel") {
let consumed = self
.fuel_limit
.saturating_sub(store.get_fuel().unwrap_or(0));
// Record fuel even on exhaustion
self.last_fuel_consumed = Some(consumed);
WasmGuardError::FuelExhausted {
consumed,
limit: self.fuel_limit,
}
} else {
WasmGuardError::Trap(msg)
}
})?;
// Track fuel consumed for receipt metadata
let remaining = store.get_fuel().unwrap_or(0);
let consumed = self.fuel_limit.saturating_sub(remaining);
self.last_fuel_consumed = Some(consumed);
let verdict = match result {
crate::abi::VERDICT_ALLOW => Ok(GuardVerdict::Allow),
crate::abi::VERDICT_DENY => {
// Probe for structured chio_deny_reason export
let deny_reason_fn = instance
.get_typed_func::<(i32, i32), i32>(&mut store, "chio_deny_reason")
.ok();
let reason = if let Some(ref reason_fn) = deny_reason_fn {
read_structured_deny_reason(reason_fn, &memory, &mut store)
} else {
// Fallback to legacy offset-64K NUL-terminated string
read_deny_reason(&memory, &store)
};
Ok(GuardVerdict::Deny { reason })
}
_ => {
// Unexpected return value -- fail closed
Err(WasmGuardError::Trap(format!(
"unexpected return value from evaluate: {result}"
)))
}
};
// Drain the log buffer and emit via tracing for host-side visibility
for (level, msg) in &store.data().logs {
match level {
0 => tracing::trace!(target: "wasm_guard", "{msg}"),
1 => tracing::debug!(target: "wasm_guard", "{msg}"),
2 => tracing::info!(target: "wasm_guard", "{msg}"),
3 => tracing::warn!(target: "wasm_guard", "{msg}"),
4 => tracing::error!(target: "wasm_guard", "{msg}"),
_ => {}
}
}
verdict
}
fn backend_name(&self) -> &str {
"wasmtime"
}
fn last_fuel_consumed(&self) -> Option<u64> {
self.last_fuel_consumed
}
}
/// Read a structured deny reason from the guest via the `chio_deny_reason`
/// export. The host calls `chio_deny_reason(buf_ptr, buf_len)` with a
/// buffer region in guest memory. The guest writes a JSON-encoded
/// [`GuestDenyResponse`](crate::abi::GuestDenyResponse) into the buffer
/// and returns the number of bytes written (or a negative/zero value on
/// error).
///
/// All error paths return `None` (fail closed with no reason rather than
/// crashing).
fn read_structured_deny_reason(
reason_fn: &wasmtime::TypedFunc<(i32, i32), i32>,
memory: &Memory,
store: &mut Store<WasmHostState>,
) -> Option<String> {
const DENY_BUF_OFFSET: i32 = 65536;
const DENY_BUF_LEN: i32 = 4096;
// Call the guest's chio_deny_reason function
let bytes_written = match reason_fn.call(&mut *store, (DENY_BUF_OFFSET, DENY_BUF_LEN)) {
Ok(n) if n > 0 && n <= DENY_BUF_LEN => n,
Ok(_) => return None, // 0 or negative or too large
Err(_) => return None, // call failed -- no reason
};
// Read the response from guest memory
let mut buf = vec![0u8; bytes_written as usize];
if memory
.read(store, DENY_BUF_OFFSET as usize, &mut buf)
.is_err()
{
return None;
}
// Try to parse as JSON GuestDenyResponse
match serde_json::from_slice::<crate::abi::GuestDenyResponse>(&buf) {
Ok(resp) => Some(resp.reason),
Err(_) => {
// Not valid JSON -- try as plain UTF-8 string
std::str::from_utf8(&buf)
.ok()
.map(|s| s.trim_end_matches('\0').to_string())
.filter(|s| !s.is_empty())
}
}
}
/// Try to read a deny reason string from the guest memory region after
/// the request data. The guest may write a NUL-terminated UTF-8 string
/// starting at a well-known offset (64 KiB).
fn read_deny_reason(memory: &Memory, store: &Store<WasmHostState>) -> Option<String> {
const DENY_REASON_OFFSET: usize = 65536;
const MAX_REASON_LEN: usize = 4096;
let data = memory.data(store);
if data.len() <= DENY_REASON_OFFSET {
return None;
}
let region = &data[DENY_REASON_OFFSET..];
let end = region
.iter()
.take(MAX_REASON_LEN)
.position(|&b| b == 0)
.unwrap_or(region.len().min(MAX_REASON_LEN));
if end == 0 {
return None;
}
std::str::from_utf8(®ion[..end]).ok().map(String::from)
}
// -------------------------------------------------------------------
// Phase 5.6: Policy-driven loading with placeholders and capability
// intersection.
// -------------------------------------------------------------------
use crate::manifest::GuardManifest;
use crate::placeholders::{resolve_placeholders_in_json, PlaceholderEnv, PlaceholderError};
use sha2::Digest;
/// Names of `chio.*` host functions Chio currently exposes to guests.
///
/// Operators can pass a subset of this list as `policy_allowed_host_fns`
/// to [`load_guards_from_policy`] to restrict which capabilities any
/// custom guard may request.
pub const KNOWN_HOST_FUNCTIONS: &[&str] =
&["chio.log", "chio.get_config", "chio.get_time_unix_secs"];
/// A single WASM guard declared in the policy YAML.
///
/// This is the Chio-side equivalent of ClawdStrike's `custom.rs` plugin
/// entry: it names the module, points at its `.wasm` bytes (either on
/// disk or inline), declares the host-function capabilities the guard
/// needs, and carries a JSON config blob that may contain `${ENV_VAR}`
/// placeholders.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PolicyCustomGuard {
/// Human-readable guard name. Used for logs, receipts, and to identify
/// the guard in the pipeline.
pub name: String,
/// Semantic version of the guard. Must match the signature sidecar's
/// `version` field when signing is enabled.
#[serde(default = "default_guard_version")]
pub version: String,
/// Source of the `.wasm` bytes. Either a filesystem path or inline
/// bytes.
#[serde(flatten)]
pub module: PolicyModuleSource,
/// Host functions this guard requests access to (e.g. `chio.log`).
/// Capabilities not present in the policy-allowed allowlist cause
/// loading to fail closed.
#[serde(default)]
pub capabilities: Vec<String>,
/// Guard configuration. String leaves may contain `${VAR}` or
/// `${VAR:-default}` placeholders that are resolved at load time
/// against the injected [`PlaceholderEnv`].
#[serde(default)]
pub config: serde_json::Value,
/// Fuel budget per `evaluate()` call.
#[serde(default = "default_policy_fuel_limit")]
pub fuel_limit: u64,
/// Guard priority (lower values run first).
#[serde(default = "default_policy_priority")]
pub priority: u32,
/// If true, denials are downgraded to `Verdict::Allow` and merely
/// logged (consistent with [`WasmGuard::is_advisory`]).
#[serde(default)]
pub advisory: bool,
/// Hex-encoded Ed25519 public key of the trusted signer. Enforced via
/// the Phase 1.3 signing path ([`crate::manifest::verify_guard_signature`]).
/// When set the `.wasm.sig` sidecar MUST exist.
#[serde(default)]
pub signer_public_key: Option<String>,
/// Explicit opt-out for unsigned modules. Matches the field of the
/// same name on [`GuardManifest`]. Ignored when `signer_public_key`
/// is set.
#[serde(default)]
pub allow_unsigned: bool,
}
/// Source of the `.wasm` bytes for a [`PolicyCustomGuard`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PolicyModuleSource {
/// Load the module from disk. The signature sidecar (if any) lives
/// at `module_path + ".sig"`.
Path {
/// Filesystem path to the `.wasm` file.
module_path: String,
},
/// Inline raw WASM bytes. Useful for tests and for embedding small
/// modules in a policy file.
Inline {
/// Raw WASM bytes.
module_bytes: Vec<u8>,
},
}
impl PolicyModuleSource {
/// Borrow the module path, if this source is backed by a file.
pub fn path(&self) -> Option<&str> {
match self {
Self::Path { module_path } => Some(module_path.as_str()),
Self::Inline { .. } => None,
}
}
}
fn default_guard_version() -> String {
"0.0.0".to_string()
}
fn default_policy_fuel_limit() -> u64 {
crate::config::DEFAULT_FUEL_LIMIT
}
fn default_policy_priority() -> u32 {
1000
}
/// Top-level `custom_guards:` section of a policy document.
///
/// Consumed by [`load_guards_from_policy`]. Deliberately defined here in
/// `chio-wasm-guards` so that chio-policy can hand this struct off without
/// taking a dependency on the reverse direction.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct PolicyCustomGuards {
/// Ordered list of guard declarations.
#[serde(default)]
pub modules: Vec<PolicyCustomGuard>,
}
/// Errors returned by [`load_guards_from_policy`].
///
/// Kept distinct from [`WasmGuardError`] so callers can tell a policy
/// wiring problem (missing capability, unresolved placeholder, bad
/// signature) apart from a pure runtime failure.
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
/// The guard requested a host function that is not in the policy's
/// allowed allowlist. Fail-closed.
#[error(
"guard {guard:?} requested capability {capability:?} which is not permitted by policy"
)]
CapabilityDenied {
/// The guard name for which the check failed.
guard: String,
/// The offending capability string.
capability: String,
},
/// The guard's WASM module imports a host function from the `chio`
/// namespace that was not declared in its `capabilities` list.
#[error("guard {guard:?} module imports {import:?} which is not declared in capabilities")]
UndeclaredHostImport {
/// The guard name.
guard: String,
/// The import the module requires (e.g. `chio.log`).
import: String,
},
/// A placeholder in the guard config could not be resolved.
#[error("placeholder resolution failed for guard {guard:?}: {source}")]
Placeholder {
/// The guard name.
guard: String,
/// Underlying placeholder error.
#[source]
source: PlaceholderError,
},
/// The guard config was not a JSON object (the backend expects a map
/// of string keys to string values after placeholder expansion).
#[error("guard {guard:?} config must be a JSON object, got {kind}")]
ConfigShape {
/// The guard name.
guard: String,
/// Describes the actual JSON kind that was found.
kind: &'static str,
},
/// A resolved config value at key `key` was not a string after
/// placeholder expansion; the current host ABI only accepts strings.
#[error("guard {guard:?} config value at {key:?} must resolve to a string")]
ConfigNotString {
/// The guard name.
guard: String,
/// The config key that produced the non-string value.
key: String,
},
/// Underlying WASM guard runtime error.
#[error(transparent)]
Runtime(#[from] WasmGuardError),
}
/// Handle returned by [`load_guards_from_policy`].
///
/// Wraps a fully loaded [`WasmGuard`] alongside metadata describing the
/// capabilities that were ultimately granted to the module. Callers can
/// feed `into_guard()` (or `into_guards()` on a collection) directly into
/// [`crate::build_guard_pipeline`] or register with `WasmGuardRuntime`.
#[derive(Debug)]
pub struct WasmGuardHandle {
guard: WasmGuard,
granted_capabilities: Vec<String>,
priority: u32,
}
impl WasmGuardHandle {
/// Consume the handle and return the inner [`WasmGuard`].
pub fn into_guard(self) -> WasmGuard {
self.guard
}
/// Borrow the inner guard.
pub fn guard(&self) -> &WasmGuard {
&self.guard
}
/// Capabilities that were granted to the guard (the intersection of
/// requested and policy-allowed host functions).
pub fn granted_capabilities(&self) -> &[String] {
&self.granted_capabilities
}
/// Guard priority (lower runs first).
pub fn priority(&self) -> u32 {
self.priority
}
}
/// Load every guard declared in `policy` and return a vector of handles.
///
/// Steps for each entry, in order:
///
/// 1. **Capability intersection.** Every entry in `guard.capabilities`
/// must also appear in `policy_allowed_host_fns`. If any requested
/// capability is missing, loading fails with
/// [`LoadError::CapabilityDenied`]. An empty `capabilities` list is
/// allowed and means the guard opts into no host functions.
///
/// 2. **Placeholder resolution.** String leaves in `guard.config` are
/// rewritten via [`resolve_placeholders_in_json`] against `env`.
/// Undefined placeholders without a `:-default` fail closed.
///
/// 3. **Signature verification.** If the guard declares
/// `signer_public_key` (or `allow_unsigned = false` with no key), the
/// Phase 1.3 signing path ([`crate::manifest::verify_guard_signature`])
/// is invoked. For on-disk modules the `.wasm.sig` sidecar is
/// consulted; for inline modules only `allow_unsigned = true` is
/// accepted (there is no sidecar to check).
///
/// 4. **Import check.** The module is compiled and its imports are
/// inspected: any `chio.*` import not in the guard's `capabilities`
/// list is rejected ([`LoadError::UndeclaredHostImport`]). This
/// enforces capability intersection at the module boundary, not just
/// at the policy layer.
///
/// 5. **Backend construction.** A [`WasmtimeBackend`] is instantiated
/// with the resolved config map and the supplied `engine`.
///
/// Returned handles are sorted by priority (lower first), matching the
/// ordering used by [`crate::load_wasm_guards`].
pub fn load_guards_from_policy(
policy: &PolicyCustomGuards,
env: &dyn PlaceholderEnv,
policy_allowed_host_fns: &[String],
engine: Arc<Engine>,
) -> Result<Vec<WasmGuardHandle>, LoadError> {
let mut handles: Vec<WasmGuardHandle> = Vec::with_capacity(policy.modules.len());
// Sort a copy of the entries so lower priority runs first, non-advisory
// before advisory at the same priority. Priority is the primary key;
// advisory is only a tie-breaker. Matches `load_wasm_guards` in
// `wiring.rs` so policy-driven and config-driven loading produce the
// same evaluation order.
let mut sorted: Vec<PolicyCustomGuard> = policy.modules.clone();
sorted.sort_by_key(|g| (g.priority, g.advisory as u8));
for guard_spec in &sorted {
// 1. Capability intersection (fail closed on any un-allowed capability).
for requested in &guard_spec.capabilities {
if !policy_allowed_host_fns.iter().any(|a| a == requested) {
return Err(LoadError::CapabilityDenied {
guard: guard_spec.name.clone(),
capability: requested.clone(),
});
}
}
let granted: Vec<String> = guard_spec.capabilities.clone();
// 2. Placeholder resolution on the config JSON.
let resolved_config =
resolve_placeholders_in_json(&guard_spec.config, env).map_err(|source| {
LoadError::Placeholder {
guard: guard_spec.name.clone(),
source,
}
})?;
let config_map = json_object_to_string_map(&resolved_config, &guard_spec.name)?;
// 3. Obtain bytes and enforce Phase 1.3 signing.
let wasm_bytes = match &guard_spec.module {
PolicyModuleSource::Path { module_path } => {
let bytes = std::fs::read(module_path).map_err(|e| {
LoadError::Runtime(WasmGuardError::ModuleLoad {
path: module_path.clone(),
reason: e.to_string(),
})
})?;
// Build a transient GuardManifest describing just the
// identity + signer, so we can reuse the Phase 1.3
// sidecar verification path.
let transient_manifest = GuardManifest {
name: guard_spec.name.clone(),
version: guard_spec.version.clone(),
abi_version: "1".to_string(),
wasm_path: module_path.clone(),
wasm_sha256: hex::encode(sha2::Sha256::digest(&bytes)),
config: std::collections::HashMap::new(),
signer_public_key: guard_spec.signer_public_key.clone(),
allow_unsigned: guard_spec.allow_unsigned,
};
crate::manifest::verify_guard_signature(
module_path,
&bytes,
&transient_manifest,
)
.map_err(LoadError::Runtime)?;
bytes
}
PolicyModuleSource::Inline { module_bytes } => {
// Inline modules have no sidecar. Require allow_unsigned.
if guard_spec.signer_public_key.is_some() {
return Err(LoadError::Runtime(WasmGuardError::SignatureVerification(
format!(
"guard {:?} has signer_public_key but inline module_bytes have no sidecar",
guard_spec.name
),
)));
}
if !guard_spec.allow_unsigned {
return Err(LoadError::Runtime(WasmGuardError::SignatureVerification(
format!(
"guard {:?} inline module_bytes require allow_unsigned=true",
guard_spec.name
),
)));
}
module_bytes.clone()
}
};
// 4. Compile and check imports against the granted capability set.
verify_module_imports_within_capabilities(&engine, &wasm_bytes, guard_spec, &granted)?;
// 5. Construct the backend + guard.
let mut backend =
WasmtimeBackend::with_engine_and_config(engine.clone(), config_map.clone());
backend
.load_module(&wasm_bytes, guard_spec.fuel_limit)
.map_err(LoadError::Runtime)?;
let manifest_sha = hex::encode(sha2::Sha256::digest(&wasm_bytes));
let guard = WasmGuard::new(
guard_spec.name.clone(),
Box::new(backend),
guard_spec.advisory,
Some(manifest_sha),
);
handles.push(WasmGuardHandle {
guard,
granted_capabilities: granted,
priority: guard_spec.priority,
});
}
Ok(handles)
}
/// Coerce a resolved JSON config into the string-to-string map the host
/// ABI exposes via `chio.get_config`.
///
/// Only the top-level object's string values are preserved; nested
/// objects / arrays cause `ConfigNotString` because the `chio.get_config`
/// host function returns UTF-8 bytes by key.
fn json_object_to_string_map(
value: &serde_json::Value,
guard_name: &str,
) -> Result<std::collections::HashMap<String, String>, LoadError> {
use serde_json::Value;
let mut out = std::collections::HashMap::new();
match value {
Value::Object(map) => {
for (k, v) in map {
match v {
Value::String(s) => {
out.insert(k.clone(), s.clone());
}
Value::Null => {
// Skip nulls -- treat as "unset".
}
Value::Bool(b) => {
out.insert(k.clone(), b.to_string());
}
Value::Number(n) => {
out.insert(k.clone(), n.to_string());
}
_ => {
return Err(LoadError::ConfigNotString {
guard: guard_name.to_string(),
key: k.clone(),
});
}
}
}
Ok(out)
}
Value::Null => Ok(out),
Value::Array(_) => Err(LoadError::ConfigShape {
guard: guard_name.to_string(),
kind: "array",
}),
Value::Bool(_) => Err(LoadError::ConfigShape {
guard: guard_name.to_string(),
kind: "bool",
}),
Value::Number(_) => Err(LoadError::ConfigShape {
guard: guard_name.to_string(),
kind: "number",
}),
Value::String(_) => Err(LoadError::ConfigShape {
guard: guard_name.to_string(),
kind: "string",
}),
}
}
/// Compile the module and ensure every `chio.*` import is in the granted
/// capabilities list.
///
/// Modules loaded as components (WIT) are exempt from this check because
/// they do not declare core imports the same way.
fn verify_module_imports_within_capabilities(
engine: &Engine,
wasm_bytes: &[u8],
guard_spec: &PolicyCustomGuard,
granted: &[String],
) -> Result<(), LoadError> {
// Only core modules expose the `chio.*` imports; skip components.
if detect_wasm_format(wasm_bytes).unwrap_or(WasmFormat::CoreModule)
!= WasmFormat::CoreModule
{
return Ok(());
}
let module = Module::new(engine, wasm_bytes)
.map_err(|e| LoadError::Runtime(WasmGuardError::Compilation(e.to_string())))?;
for import in module.imports() {
if import.module() == "chio" {
let qualified = format!("chio.{}", import.name());
if !granted.iter().any(|g| g == &qualified) {
return Err(LoadError::UndeclaredHostImport {
guard: guard_spec.name.clone(),
import: qualified,
});
}
}
}
Ok(())
}
// -----------------------------------------------------------------------
// Tests for wasmtime_backend
// -----------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::abi::GuardRequest;
fn make_guard_request() -> GuardRequest {
GuardRequest {
tool_name: "test_tool".to_string(),
server_id: "test_server".to_string(),
agent_id: "agent-1".to_string(),
arguments: serde_json::json!({"key": "value"}),
scopes: vec!["test_server:test_tool".to_string()],
action_type: None,
extracted_path: None,
extracted_target: None,
filesystem_roots: Vec::new(),
matched_grant_index: None,
}
}
// -------------------------------------------------------------------
// chio_alloc tests
// -------------------------------------------------------------------
#[test]
fn chio_alloc_used_when_exported() {
// WAT module with chio_alloc that returns 1024.
// evaluate checks that ptr == 1024 and returns ALLOW only if so.
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "chio_alloc") (param $size i32) (result i32)
;; Always allocate at offset 1024
(i32.const 1024)
)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return ALLOW (0) only if ptr == 1024, else DENY (1)
(if (result i32) (i32.eq (local.get $ptr) (i32.const 1024))
(then (i32.const 0))
(else (i32.const 1))
)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
assert!(
result.is_allow(),
"expected ALLOW (chio_alloc should have been used), got: {result:?}"
);
}
#[test]
fn no_chio_alloc_uses_offset_zero() {
// WAT module WITHOUT chio_alloc.
// evaluate checks that ptr == 0 and returns ALLOW only if so.
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return ALLOW (0) only if ptr == 0, else DENY (1)
(if (result i32) (i32.eqz (local.get $ptr))
(then (i32.const 0))
(else (i32.const 1))
)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
assert!(
result.is_allow(),
"expected ALLOW (offset 0 fallback should be used without chio_alloc), got: {result:?}"
);
}
#[test]
fn chio_alloc_oob_falls_back() {
// WAT module with chio_alloc that returns 999_999_999 (out-of-bounds).
// evaluate checks that ptr == 0 (proving fallback occurred).
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "chio_alloc") (param $size i32) (result i32)
;; Return absurdly large pointer
(i32.const 999999999)
)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return ALLOW (0) only if ptr == 0 (fallback), else DENY (1)
(if (result i32) (i32.eqz (local.get $ptr))
(then (i32.const 0))
(else (i32.const 1))
)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
assert!(
result.is_allow(),
"expected ALLOW (OOB chio_alloc should fall back to offset 0), got: {result:?}"
);
}
#[test]
fn chio_alloc_negative_falls_back() {
// WAT module with chio_alloc that returns -1 (negative pointer).
// evaluate checks that ptr == 0 (proving fallback occurred).
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "chio_alloc") (param $size i32) (result i32)
;; Return negative pointer
(i32.const -1)
)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return ALLOW (0) only if ptr == 0 (fallback), else DENY (1)
(if (result i32) (i32.eqz (local.get $ptr))
(then (i32.const 0))
(else (i32.const 1))
)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
assert!(
result.is_allow(),
"expected ALLOW (negative chio_alloc should fall back to offset 0), got: {result:?}"
);
}
// -------------------------------------------------------------------
// chio_deny_reason tests
// -------------------------------------------------------------------
#[test]
fn chio_deny_reason_structured() {
// WAT module with chio_deny_reason that writes a JSON GuestDenyResponse
// into the provided buffer and returns the byte count.
//
// The JSON {"reason":"blocked by policy"} is stored using escaped
// quotes in the WAT data segment at offset 512.
// chio_deny_reason copies it to buf_ptr using memory.copy.
let json_bytes = br#"{"reason":"blocked by policy"}"#;
let json_len = json_bytes.len(); // 30
// Build WAT data segment using \xx hex escapes to avoid quote issues
let hex_data: String = json_bytes.iter().map(|b| format!("\\{b:02x}")).collect();
let wat = format!(
r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
;; Store the JSON response at offset 512 using hex escapes
(data (i32.const 512) "{hex_data}")
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return DENY (1)
(i32.const 1)
)
(func (export "chio_deny_reason") (param $buf_ptr i32) (param $buf_len i32) (result i32)
;; Copy JSON from offset 512 to buf_ptr using memory.copy
(memory.copy
(local.get $buf_ptr) ;; dest
(i32.const 512) ;; src
(i32.const {json_len}) ;; len
)
;; Return number of bytes written
(i32.const {json_len})
)
)
"#
);
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
match &result {
GuardVerdict::Deny { reason } => {
assert_eq!(
reason.as_deref(),
Some("blocked by policy"),
"expected structured deny reason from chio_deny_reason"
);
}
_ => panic!("expected Deny verdict, got: {result:?}"),
}
}
#[test]
fn chio_deny_reason_fallback_legacy() {
// WAT module WITHOUT chio_deny_reason export.
// Has a NUL-terminated string at offset 65536 ("legacy reason\0").
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(data (i32.const 65536) "legacy reason\00")
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return DENY (1)
(i32.const 1)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
match &result {
GuardVerdict::Deny { reason } => {
assert_eq!(
reason.as_deref(),
Some("legacy reason"),
"expected legacy deny reason from offset 64K"
);
}
_ => panic!("expected Deny verdict, got: {result:?}"),
}
}
#[test]
fn chio_deny_reason_invalid_returns_none() {
// WAT module with chio_deny_reason that returns -1 (error).
// The host should fall back to None reason.
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return DENY (1)
(i32.const 1)
)
(func (export "chio_deny_reason") (param $buf_ptr i32) (param $buf_len i32) (result i32)
;; Return -1 (error)
(i32.const -1)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
match &result {
GuardVerdict::Deny { reason } => {
assert_eq!(
reason, &None,
"expected None reason when chio_deny_reason returns -1"
);
}
_ => panic!("expected Deny verdict, got: {result:?}"),
}
}
// -------------------------------------------------------------------
// Security enforcement tests (WGSEC-01, WGSEC-02, WGSEC-03)
// -------------------------------------------------------------------
#[test]
fn module_too_large_rejected() {
// Set a very small max_module_size and provide bytes exceeding it
let mut backend = WasmtimeBackend::new()
.unwrap()
.with_limits(16 * 1024 * 1024, 100);
let big_bytes = vec![0u8; 200];
let result = backend.load_module(&big_bytes, 1_000_000);
match result {
Err(WasmGuardError::ModuleTooLarge { size, limit }) => {
assert_eq!(size, 200);
assert_eq!(limit, 100);
}
other => panic!("expected ModuleTooLarge, got: {other:?}"),
}
}
#[test]
fn module_within_size_accepted() {
// Use a small valid WAT module with default limits (10 MiB)
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 1)
(func (export "evaluate") (param i32 i32) (result i32)
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
let result = backend.load_module(wat.as_bytes(), 1_000_000);
assert!(result.is_ok(), "expected Ok, got: {result:?}");
}
#[test]
fn import_validation_rejects_wasi() {
// WAT module that imports from wasi_snapshot_preview1 (forbidden)
let wat = r#"
(module
(import "wasi_snapshot_preview1" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory (export "memory") 1)
(func (export "evaluate") (param i32 i32) (result i32)
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
let result = backend.load_module(wat.as_bytes(), 1_000_000);
match result {
Err(WasmGuardError::ImportViolation { module, name }) => {
assert_eq!(module, "wasi_snapshot_preview1");
assert_eq!(name, "fd_write");
}
other => panic!("expected ImportViolation, got: {other:?}"),
}
}
#[test]
fn import_validation_accepts_chio_only() {
// WAT module that imports only from "chio" namespace
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 1)
(func (export "evaluate") (param i32 i32) (result i32)
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
let result = backend.load_module(wat.as_bytes(), 1_000_000);
assert!(
result.is_ok(),
"expected Ok for chio-only imports, got: {result:?}"
);
}
#[test]
fn memory_growth_beyond_limit_traps() {
// WAT module that tries to grow memory by 1000 pages (64 MB)
// with a very small limit (2 pages = 128 KiB)
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 1)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Try to grow memory by 1000 pages -- should trap
(drop (memory.grow (i32.const 1000)))
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new()
.unwrap()
.with_limits(2 * 64 * 1024, 10 * 1024 * 1024);
backend.load_module(wat.as_bytes(), 10_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req);
assert!(
result.is_err(),
"expected error (trap) when memory.grow exceeds limit, got: {result:?}"
);
}
#[test]
fn memory_growth_within_limit_works() {
// WAT module that grows memory by 1 page with default 16 MiB limit
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 1)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Grow memory by 1 page (64 KiB) -- should succeed
(drop (memory.grow (i32.const 1)))
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 10_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req);
assert!(
result.is_ok(),
"expected Ok when memory.grow is within limit, got: {result:?}"
);
}
#[test]
fn deny_no_reason_at_all() {
// WAT module without chio_deny_reason and no string at offset 64K.
// Memory is zeroed so read_deny_reason will find a NUL at position 0.
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
;; Return DENY (1)
(i32.const 1)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let result = backend.evaluate(&req).unwrap();
match &result {
GuardVerdict::Deny { reason } => {
assert_eq!(
reason, &None,
"expected None reason when no deny reason mechanism is available"
);
}
_ => panic!("expected Deny verdict, got: {result:?}"),
}
}
// -------------------------------------------------------------------
// Fuel tracking tests
// -------------------------------------------------------------------
#[test]
fn wasmtime_fuel_consumed_after_evaluate() {
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
assert!(
backend.last_fuel_consumed().is_none(),
"fuel should be None before any evaluation"
);
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let req = make_guard_request();
let _ = backend.evaluate(&req).unwrap();
let fuel = backend.last_fuel_consumed();
assert!(fuel.is_some(), "fuel should be Some after evaluation");
assert!(fuel.unwrap() > 0, "fuel consumed should be > 0");
}
#[test]
fn wasmtime_fuel_consumed_tracked_on_wasm_guard() {
let wat = r#"
(module
(import "chio" "log" (func $log (param i32 i32 i32)))
(import "chio" "get_config" (func $get_config (param i32 i32 i32 i32) (result i32)))
(import "chio" "get_time_unix_secs" (func $get_time (result i64)))
(memory (export "memory") 2)
(func (export "evaluate") (param $ptr i32) (param $len i32) (result i32)
(i32.const 0)
)
)
"#;
let mut backend = WasmtimeBackend::new().unwrap();
backend.load_module(wat.as_bytes(), 1_000_000).unwrap();
let guard = WasmGuard::new(
"fuel-test".to_string(),
Box::new(backend),
false,
Some("deadbeef".to_string()),
);
// Before evaluation
assert!(guard.last_fuel_consumed().is_none());
assert_eq!(guard.manifest_sha256(), Some("deadbeef"));
// After evaluation -- use abi-level evaluate via mock context
let req = make_guard_request();
{
let mut be = guard.backend.lock().unwrap();
let _ = be.evaluate(&req).unwrap();
let fuel = be.last_fuel_consumed();
drop(be);
if let Ok(mut fl) = guard.last_fuel_consumed.lock() {
*fl = fuel;
}
}
assert!(guard.last_fuel_consumed().is_some());
assert!(guard.last_fuel_consumed().unwrap() > 0);
// manifest_sha256 unchanged after evaluate
assert_eq!(guard.manifest_sha256(), Some("deadbeef"));
// guard_evidence_metadata returns both values
let evidence = guard.guard_evidence_metadata();
assert!(evidence["fuel_consumed"].as_u64().unwrap() > 0);
assert_eq!(evidence["manifest_sha256"], "deadbeef");
}
// -------------------------------------------------------------------
// Format detection tests
// -------------------------------------------------------------------
#[test]
fn detect_core_module_magic_bytes() {
// Core WASM magic: \0asm followed by version 1
let core_bytes = b"\x00asm\x01\x00\x00\x00";
let format = detect_wasm_format(core_bytes);
assert!(format.is_ok());
assert_eq!(format.unwrap(), WasmFormat::CoreModule);
}
#[test]
fn detect_component_magic_bytes() {
// Component magic: \0asm followed by component layer encoding
let component_bytes = b"\x00asm\x0d\x00\x01\x00";
let format = detect_wasm_format(component_bytes);
assert!(format.is_ok());
assert_eq!(format.unwrap(), WasmFormat::Component);
}
#[test]
fn detect_invalid_bytes() {
let garbage = b"not wasm at all";
let format = detect_wasm_format(garbage);
assert!(format.is_err());
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use chio_core::capability::ChioScope;
use chio_kernel::{GuardContext, ToolCallRequest};
fn make_test_request() -> ToolCallRequest {
ToolCallRequest {
request_id: "req-1".to_string(),
capability: chio_core::capability::CapabilityToken::sign(
chio_core::capability::CapabilityTokenBody {
id: "cap-1".to_string(),
issuer: chio_core::crypto::Keypair::generate().public_key(),
subject: chio_core::crypto::Keypair::generate().public_key(),
scope: ChioScope::default(),
issued_at: 0,
expires_at: u64::MAX,
delegation_chain: vec![],
},
&chio_core::crypto::Keypair::generate(),
)
.unwrap(),
tool_name: "test_tool".to_string(),
server_id: "test_server".to_string(),
agent_id: "agent-1".to_string(),
arguments: serde_json::json!({"key": "value"}),
dpop_proof: None,
governed_intent: None,
approval_token: None,
model_metadata: None,
federated_origin_kernel_id: None,
}
}
#[test]
fn mock_allow_backend() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new("test-allow".to_string(), Box::new(backend), false, None);
let request = make_test_request();
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let result = guard.evaluate(&ctx);
assert!(matches!(result, Ok(Verdict::Allow)));
}
#[test]
fn mock_deny_backend() {
let mut backend = MockWasmBackend::denying("blocked by test");
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new("test-deny".to_string(), Box::new(backend), false, None);
let request = make_test_request();
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let result = guard.evaluate(&ctx);
assert!(matches!(result, Ok(Verdict::Deny)));
}
#[test]
fn advisory_guard_allows_on_deny() {
let mut backend = MockWasmBackend::denying("advisory denial");
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new("test-advisory".to_string(), Box::new(backend), true, None);
assert!(guard.is_advisory());
let request = make_test_request();
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
// Advisory guards should allow even when the backend denies
let result = guard.evaluate(&ctx);
assert!(matches!(result, Ok(Verdict::Allow)));
}
#[test]
fn runtime_manages_multiple_guards() {
let mut runtime = WasmGuardRuntime::new();
assert_eq!(runtime.guard_count(), 0);
let mut b1 = MockWasmBackend::allowing();
b1.load_module(b"fake", 1000).unwrap();
runtime.add_guard(WasmGuard::new("g1".to_string(), Box::new(b1), false, None));
let mut b2 = MockWasmBackend::denying("no");
b2.load_module(b"fake", 1000).unwrap();
runtime.add_guard(WasmGuard::new("g2".to_string(), Box::new(b2), false, None));
assert_eq!(runtime.guard_count(), 2);
let boxed = runtime.into_guards();
assert_eq!(boxed.len(), 2);
}
#[test]
fn guard_request_serialization() {
let req = GuardRequest {
tool_name: "read_file".to_string(),
server_id: "fs-server".to_string(),
agent_id: "agent-42".to_string(),
arguments: serde_json::json!({"path": "/etc/passwd"}),
scopes: vec!["fs-server:read_file".to_string()],
action_type: None,
extracted_path: None,
extracted_target: None,
filesystem_roots: Vec::new(),
matched_grant_index: None,
};
let json = serde_json::to_string(&req).unwrap();
let deserialized: GuardRequest = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.tool_name, "read_file");
assert_eq!(deserialized.scopes.len(), 1);
}
#[test]
fn guard_verdict_helpers() {
let allow = GuardVerdict::Allow;
assert!(allow.is_allow());
assert!(!allow.is_deny());
let deny = GuardVerdict::Deny {
reason: Some("bad".to_string()),
};
assert!(!deny.is_allow());
assert!(deny.is_deny());
}
#[test]
fn unloaded_mock_fails() {
let mut backend = MockWasmBackend::allowing();
// Do NOT call load_module
let req = GuardRequest {
tool_name: "t".to_string(),
server_id: "s".to_string(),
agent_id: "a".to_string(),
arguments: serde_json::Value::Null,
scopes: vec![],
action_type: None,
extracted_path: None,
extracted_target: None,
filesystem_roots: Vec::new(),
matched_grant_index: None,
};
let result = backend.evaluate(&req);
assert!(result.is_err());
}
// -------------------------------------------------------------------
// build_request enrichment tests
// -------------------------------------------------------------------
fn make_test_request_with(tool_name: &str, arguments: serde_json::Value) -> ToolCallRequest {
ToolCallRequest {
request_id: "req-1".to_string(),
capability: chio_core::capability::CapabilityToken::sign(
chio_core::capability::CapabilityTokenBody {
id: "cap-1".to_string(),
issuer: chio_core::crypto::Keypair::generate().public_key(),
subject: chio_core::crypto::Keypair::generate().public_key(),
scope: ChioScope::default(),
issued_at: 0,
expires_at: u64::MAX,
delegation_chain: vec![],
},
&chio_core::crypto::Keypair::generate(),
)
.unwrap(),
tool_name: tool_name.to_string(),
server_id: "test_server".to_string(),
agent_id: "agent-1".to_string(),
arguments,
dpop_proof: None,
governed_intent: None,
approval_token: None,
model_metadata: None,
federated_origin_kernel_id: None,
}
}
#[test]
fn build_request_action_type_file_access() {
let request =
make_test_request_with("read_file", serde_json::json!({"path": "/etc/passwd"}));
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let req = WasmGuard::build_request(&ctx);
assert_eq!(req.action_type.as_deref(), Some("file_access"));
}
#[test]
fn build_request_extracted_path_for_file_access() {
let request =
make_test_request_with("read_file", serde_json::json!({"path": "/etc/passwd"}));
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let req = WasmGuard::build_request(&ctx);
assert_eq!(req.extracted_path.as_deref(), Some("/etc/passwd"));
}
#[test]
fn build_request_action_type_network_egress() {
let request = make_test_request_with(
"fetch",
serde_json::json!({"url": "https://example.com/api"}),
);
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let req = WasmGuard::build_request(&ctx);
assert_eq!(req.action_type.as_deref(), Some("network_egress"));
assert_eq!(req.extracted_target.as_deref(), Some("example.com"));
assert!(
req.extracted_path.is_none(),
"network_egress should not set extracted_path"
);
}
#[test]
fn build_request_filesystem_roots_from_context() {
let request = make_test_request_with(
"read_file",
serde_json::json!({"path": "/home/user/file.txt"}),
);
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let roots = vec!["/home".to_string(), "/tmp".to_string()];
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: Some(&roots),
matched_grant_index: None,
};
let req = WasmGuard::build_request(&ctx);
assert_eq!(
req.filesystem_roots,
vec!["/home".to_string(), "/tmp".to_string()]
);
}
#[test]
fn build_request_matched_grant_index_from_context() {
let request =
make_test_request_with("read_file", serde_json::json!({"path": "/etc/passwd"}));
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: Some(3),
};
let req = WasmGuard::build_request(&ctx);
assert_eq!(req.matched_grant_index, Some(3));
}
#[test]
fn build_request_action_type_unknown_for_unrecognized_tool() {
let request = make_test_request_with("test_tool", serde_json::json!({"key": "value"}));
let scope = ChioScope::default();
let agent_id = "agent-1".to_string();
let server_id = "test_server".to_string();
let ctx = GuardContext {
request: &request,
scope: &scope,
agent_id: &agent_id,
server_id: &server_id,
session_filesystem_roots: None,
matched_grant_index: None,
};
let req = WasmGuard::build_request(&ctx);
// "test_tool" is not a recognized filesystem/network/shell tool,
// so extract_action returns McpTool (fallback) which we map to "mcp_tool"
assert_eq!(req.action_type.as_deref(), Some("mcp_tool"));
}
// -------------------------------------------------------------------
// Receipt metadata tests (manifest_sha256, fuel_consumed, evidence)
// -------------------------------------------------------------------
#[test]
fn wasm_guard_stores_manifest_sha256() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new(
"test-hash".to_string(),
Box::new(backend),
false,
Some("abcdef0123456789".to_string()),
);
assert_eq!(guard.manifest_sha256(), Some("abcdef0123456789"));
}
#[test]
fn wasm_guard_manifest_sha256_none_when_unset() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new("test-no-hash".to_string(), Box::new(backend), false, None);
assert!(guard.manifest_sha256().is_none());
}
#[test]
fn wasm_guard_last_fuel_consumed_none_before_evaluate() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new("test-fuel".to_string(), Box::new(backend), false, None);
assert!(guard.last_fuel_consumed().is_none());
}
#[test]
fn mock_backend_last_fuel_consumed_returns_none() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let req = GuardRequest {
tool_name: "t".to_string(),
server_id: "s".to_string(),
agent_id: "a".to_string(),
arguments: serde_json::Value::Null,
scopes: vec![],
action_type: None,
extracted_path: None,
extracted_target: None,
filesystem_roots: Vec::new(),
matched_grant_index: None,
};
let _ = backend.evaluate(&req).unwrap();
assert!(
backend.last_fuel_consumed().is_none(),
"mock backend should not track fuel"
);
}
#[test]
fn guard_evidence_metadata_returns_json_structure() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new(
"test-evidence".to_string(),
Box::new(backend),
false,
Some("sha256hex".to_string()),
);
let evidence = guard.guard_evidence_metadata();
assert!(evidence.is_object());
assert!(evidence.get("fuel_consumed").is_some());
assert!(
evidence["fuel_consumed"].is_null(),
"fuel should be null before evaluate"
);
assert_eq!(evidence["manifest_sha256"], "sha256hex");
}
#[test]
fn guard_evidence_metadata_null_when_no_manifest() {
let mut backend = MockWasmBackend::allowing();
backend.load_module(b"fake", 1000).unwrap();
let guard = WasmGuard::new(
"test-evidence-null".to_string(),
Box::new(backend),
false,
None,
);
let evidence = guard.guard_evidence_metadata();
assert!(evidence["manifest_sha256"].is_null());
}
}