chio-wasm-guards 0.1.2

WASM guard runtime for Chio -- load and execute .wasm guard modules with fuel metering
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
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use arc_swap::ArcSwap;
use chio_kernel::{Guard, GuardContext, GuardDecision, KernelError};
use tracing::{debug, warn};

use crate::abi::{GuardRequest, GuardVerdict, WasmGuardAbi};
use crate::epoch::EpochId;
use crate::metrics::{classify_deny_reason_class, REASON_CLASS_MALFORMED};
use crate::observability::{
    guard_digest_or_unknown, guard_evaluate_span, DEFAULT_GUARD_VERSION, RELOAD_APPLIED,
    VERDICT_ALLOW, VERDICT_DENY, VERDICT_ERROR,
};

use super::evidence::LastEvaluationEvidence;
use super::module::LoadedModule;

/// A single WASM guard module loaded into the runtime.
///
/// Wraps a swappable `LoadedModule` 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) plus the module epoch used by the most recent
/// `evaluate()` call.
pub struct WasmGuard {
    /// Guard name (from config).
    name: String,
    /// Guard semantic version from policy or manifest metadata.
    version: String,
    /// Current loaded module epoch.
    loaded: ArcSwap<LoadedModule>,
    /// Serializes module swaps with rollback baseline capture.
    reload_lock: Mutex<()>,
    /// Next epoch identifier reserved for future module swaps.
    next_epoch_id: AtomicU64,
    /// Latest reload sequence observed for this guard.
    reload_seq: AtomicU64,
    /// Whether this guard is advisory-only (non-blocking).
    advisory: bool,
    /// Evidence metadata captured from the most recent `evaluate()` call.
    last_evaluation_evidence: Mutex<Option<LastEvaluationEvidence>>,
}

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::new_with_metadata(
            name,
            DEFAULT_GUARD_VERSION.to_string(),
            backend,
            advisory,
            manifest_sha256,
        )
    }

    /// Create a new WASM guard with explicit guard metadata.
    pub fn new_with_metadata(
        name: String,
        version: String,
        backend: Box<dyn WasmGuardAbi>,
        advisory: bool,
        manifest_sha256: Option<String>,
    ) -> Self {
        Self {
            name,
            version,
            loaded: ArcSwap::from_pointee(LoadedModule::new(
                backend,
                EpochId::INITIAL,
                manifest_sha256,
            )),
            reload_lock: Mutex::new(()),
            next_epoch_id: AtomicU64::new(1),
            reload_seq: AtomicU64::new(0),
            advisory,
            last_evaluation_evidence: Mutex::new(None),
        }
    }

    /// Returns `true` if this guard is advisory-only.
    #[must_use]
    pub fn is_advisory(&self) -> bool {
        self.advisory
    }

    /// Returns the guard semantic version attached to tracing metadata.
    #[must_use]
    pub fn guard_version(&self) -> &str {
        &self.version
    }

    /// Returns the SHA-256 hex digest of the guard manifest, if set.
    #[must_use]
    pub fn manifest_sha256(&self) -> Option<String> {
        self.loaded
            .load()
            .manifest_sha256()
            .map(ToString::to_string)
    }

    /// Return a snapshot of the currently loaded module.
    #[must_use]
    pub fn loaded_module(&self) -> Arc<LoadedModule> {
        self.loaded.load_full()
    }

    /// Return the epoch identifier of the currently loaded module.
    #[must_use]
    pub fn current_epoch_id(&self) -> EpochId {
        self.loaded.load().epoch_id()
    }

    /// Return the latest observed reload sequence for this guard.
    #[must_use]
    pub fn current_reload_seq(&self) -> u64 {
        self.reload_seq.load(Ordering::SeqCst)
    }

    /// Record the latest reload sequence for evaluation spans.
    ///
    /// Only the successful hot-reload apply path calls this, so the reload
    /// counter uses the documented `applied` outcome (matching the
    /// `RELOAD_APPLIED` span and the descriptor's declared outcome values) rather
    /// than an undeclared `ok` series.
    pub fn record_reload_seq(&self, reload_seq: u64) {
        self.reload_seq.store(reload_seq, Ordering::SeqCst);
        chio_metrics_spec::runtime::families::GUARD_RELOAD.incr(&[&self.name, RELOAD_APPLIED]);
    }

    /// Reserve and return the next monotonic epoch identifier.
    ///
    /// Returns `None` if the counter is already exhausted.
    pub fn reserve_next_epoch_id(&self) -> Option<EpochId> {
        let next = self
            .next_epoch_id
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
                current.checked_add(1)
            })
            .ok()?;
        Some(EpochId::new(next))
    }

    /// Replace the current loaded module with a new backend and return its
    /// assigned epoch identifier.
    pub fn replace_loaded_module(
        &self,
        backend: Box<dyn WasmGuardAbi>,
        manifest_sha256: Option<String>,
    ) -> Option<EpochId> {
        self.replace_loaded_module_with_previous(backend, manifest_sha256)
            .map(|(_, epoch_id)| epoch_id)
    }

    /// Replace the loaded module and return the previous module snapshot.
    pub fn replace_loaded_module_with_previous(
        &self,
        backend: Box<dyn WasmGuardAbi>,
        manifest_sha256: Option<String>,
    ) -> Option<(Arc<LoadedModule>, EpochId)> {
        let _reload_guard = match self.reload_lock.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        let previous = self.loaded.load_full();
        let epoch_id = self.reserve_next_epoch_id()?;
        self.loaded.store(Arc::new(LoadedModule::new(
            backend,
            epoch_id,
            manifest_sha256,
        )));
        previous.clear_instance_pre_cache();
        if let Ok(mut evidence_lock) = self.last_evaluation_evidence.lock() {
            *evidence_lock = None;
        }
        Some((previous, epoch_id))
    }

    /// Restore a previously loaded module snapshot.
    ///
    /// Used by the hot-reload watchdog to roll back a published epoch without
    /// recompiling the prior module.
    pub fn restore_loaded_module(&self, module: Arc<LoadedModule>) {
        let _reload_guard = match self.reload_lock.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        let previous = self.loaded.load_full();
        self.loaded.store(module);
        previous.clear_instance_pre_cache();
        if let Ok(mut evidence_lock) = self.last_evaluation_evidence.lock() {
            *evidence_lock = None;
        }
    }

    /// 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_evaluation_evidence
            .lock()
            .ok()
            .and_then(|guard| guard.as_ref().and_then(|evidence| evidence.fuel_consumed))
    }

    /// 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 {
        if let Ok(evidence) = self.last_evaluation_evidence.lock() {
            if let Some(evidence) = evidence.as_ref() {
                return serde_json::json!({
                    "epoch_id": evidence.epoch_id.get(),
                    "fuel_consumed": evidence.fuel_consumed,
                    "manifest_sha256": evidence.manifest_sha256,
                });
            }
        }
        let loaded = self.loaded.load();
        serde_json::json!({
            "epoch_id": loaded.epoch_id().get(),
            "fuel_consumed": null,
            "manifest_sha256": loaded.manifest_sha256(),
        })
    }

    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_type, extracted_path, extracted_target) =
            match chio_guards::extract_action_checked(
                &ctx.request.tool_name,
                &ctx.request.arguments,
            ) {
                Ok(action) => 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),
                },
                Err(err) => (Some("malformed_arguments".into()), None, Some(err.field)),
            };

        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("version", &self.version)
            .field("advisory", &self.advisory)
            .finish()
    }
}

/// Emit the per-evaluation guard families: verdict count, evaluation duration,
/// and fuel consumed. Called from every verdict arm so allow, deny, and error
/// all record.
fn emit_guard_eval_metrics(guard_id: &str, verdict: &str, elapsed: std::time::Duration, fuel: u64) {
    use chio_metrics_spec::runtime::families;
    families::GUARD_VERDICT.incr(&[guard_id, verdict]);
    families::GUARD_EVAL_DURATION.observe(&[guard_id, verdict], elapsed.as_secs_f64());
    families::GUARD_FUEL_CONSUMED.incr_by(&[guard_id], fuel);
}

impl Guard for WasmGuard {
    fn name(&self) -> &str {
        &self.name
    }

    fn evaluate(&self, ctx: &GuardContext) -> Result<GuardDecision, KernelError> {
        let eval_started = std::time::Instant::now();
        let request = Self::build_request(ctx);
        if request.action_type.as_deref() == Some("malformed_arguments") {
            warn!(
                guard = %self.name,
                tool_name = %request.tool_name,
                field = %request.extracted_target.as_deref().unwrap_or("unknown"),
                "WASM guard host action extraction failed, failing closed"
            );
            // Record the fail-closed deny so malformed-argument denials are
            // observable in the verdict/deny/duration families instead of
            // silently returning before the metrics path. The bounded `malformed`
            // reason class keeps cardinality finite.
            emit_guard_eval_metrics(&self.name, VERDICT_DENY, eval_started.elapsed(), 0);
            chio_metrics_spec::runtime::families::GUARD_DENY
                .incr(&[&self.name, REASON_CLASS_MALFORMED]);
            return Ok(GuardDecision::deny(Vec::new()));
        }

        let loaded = self.loaded.load_full();
        let span = guard_evaluate_span(
            &self.name,
            &self.version,
            guard_digest_or_unknown(loaded.manifest_sha256()),
            loaded.epoch_id().get(),
            self.current_reload_seq(),
            None,
        );
        let _span_guard = span.enter();

        let (result, fuel) = match loaded.evaluate(&request) {
            Ok(value) => value,
            Err(err) => {
                span.record("verdict", VERDICT_ERROR);
                emit_guard_eval_metrics(&self.name, VERDICT_ERROR, eval_started.elapsed(), 0);
                return Err(err);
            }
        };

        if let Ok(mut evidence_lock) = self.last_evaluation_evidence.lock() {
            *evidence_lock = Some(LastEvaluationEvidence {
                epoch_id: loaded.epoch_id(),
                manifest_sha256: loaded.manifest_sha256().map(ToString::to_string),
                fuel_consumed: fuel,
            });
        }

        match result {
            Ok(GuardVerdict::Allow) => {
                span.record("verdict", VERDICT_ALLOW);
                emit_guard_eval_metrics(
                    &self.name,
                    VERDICT_ALLOW,
                    eval_started.elapsed(),
                    fuel.unwrap_or(0),
                );
                debug!(
                    guard = %self.name,
                    epoch_id = loaded.epoch_id().get(),
                    "WASM guard allowed request"
                );
                Ok(GuardDecision::allow())
            }
            Ok(GuardVerdict::Deny { reason }) => {
                let reason_str = reason.as_deref().unwrap_or("denied by WASM guard");
                span.record("verdict", VERDICT_DENY);
                emit_guard_eval_metrics(
                    &self.name,
                    VERDICT_DENY,
                    eval_started.elapsed(),
                    fuel.unwrap_or(0),
                );
                // Classify the guard-provided reason into a bounded reason class
                // so `chio_guard_deny_total{reason_class}` cannot explode series
                // cardinality on free-form strings, and so the breakdown reflects
                // WHY the guard denied rather than the enforcement mode.
                let reason_class = classify_deny_reason_class(reason.as_deref());
                chio_metrics_spec::runtime::families::GUARD_DENY.incr(&[&self.name, reason_class]);
                if self.advisory {
                    debug!(
                        guard = %self.name,
                        epoch_id = loaded.epoch_id().get(),
                        reason = %reason_str,
                        "WASM advisory guard denied (non-blocking)"
                    );
                    Ok(GuardDecision::allow())
                } else {
                    warn!(
                        guard = %self.name,
                        epoch_id = loaded.epoch_id().get(),
                        reason = %reason_str,
                        "WASM guard denied request"
                    );
                    Ok(GuardDecision::deny(Vec::new()))
                }
            }
            Err(e) => {
                // Fail closed: any error during WASM execution denies.
                span.record("verdict", VERDICT_ERROR);
                emit_guard_eval_metrics(
                    &self.name,
                    VERDICT_ERROR,
                    eval_started.elapsed(),
                    fuel.unwrap_or(0),
                );
                warn!(
                    guard = %self.name,
                    epoch_id = loaded.epoch_id().get(),
                    error = %e,
                    "WASM guard error, failing closed"
                );
                if self.advisory {
                    Ok(GuardDecision::allow())
                } else {
                    Ok(GuardDecision::deny(Vec::new()))
                }
            }
        }
    }
}