cc-lb-runtime-wasmtime 0.1.1

Wasmtime-based plugin runtime for cc-lb. Host-side wasm plugin admission + dispatch.
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
//! Load-time wasm inspection — metadata + fingerprint validation gate.
//!
//! The host walks raw `.wasm` bytes with `wasmparser` to enforce three
//! invariants before the module ever sees the wasmtime engine:
//!
//! 1. **Imports allow-list.** Stage 1 still disallows _every_ host
//!    import. The only legal direction of communication is host → guest
//!    via the declared exports.
//! 2. **Required exports per declared hook.** Every module requires
//!    `memory`, `cc_lb_alloc`, `cc_lb_free`. On top of that each hook
//!    listed in `cc_lb.plugin.v1` requires its matching export.
//!    Signature validation is deferred to instantiate-time via
//!    `instance.get_typed_func`.
//! 3. **Schema fingerprints.** Each declared hook ships a
//!    `cc_lb.schema.<hook>.v<N>` custom section holding the 32-byte
//!    [`cc_lb_plugin_wire::WireSchema::FINGERPRINT`] for the matching
//!    host wire type.
//!
//! `wasmtime::Module::custom_sections` does NOT round-trip through
//! `precompile_module → Module::deserialize`, so this inspection runs
//! against the raw `.wasm` bytes.
//!
//! Section + tag names are sourced from
//! [`cc_lb_plugin_wire::schema`] so the host, the
//! `cc-lb-pdk-wasmtime-macros` codegen, and this gate share a single
//! source of truth.

use std::collections::{BTreeMap, HashMap, HashSet};

use crate::error::WasmtimeRuntimeError;
use cc_lb_plugin_wire::metadata::PluginMetadata;
use cc_lb_plugin_wire::schema::{HookKind, WireSchema, WireVersion, host_supported_versions};
use wasmparser::{ExternalKind, Parser, Payload};

const PLUGIN_META_SECTION: &str = "cc_lb.plugin.v1";
const REQUIRED_MEMORY_EXPORT: &str = "memory";
const ALWAYS_REQUIRED_FUNC_EXPORTS: &[&str] = &["cc_lb_alloc", "cc_lb_free"];

/// Outcome of [`inspect_wasm`].
#[derive(Debug, Clone)]
pub struct ModuleInspection {
    pub metadata: PluginMetadata,
    pub hook_versions: BTreeMap<HookKind, WireVersion>,
    pub hook_fingerprints: BTreeMap<HookKind, [u8; 32]>,
}

impl ModuleInspection {
    /// Primary fingerprint — first declared hook fingerprint. Kept for
    /// callers that still persist the historical single schema hash.
    pub fn primary_schema_hash(&self) -> [u8; 32] {
        self.hook_fingerprints
            .values()
            .next()
            .copied()
            .expect("PluginMetadata::parse guarantees at least one hook")
    }
}

/// Walk `wasm` bytes once, enforcing the structural invariants in the
/// module docs. The check is purely structural and never executes guest
/// code.
pub fn inspect_wasm(kind: HookKind, wasm: &[u8]) -> Result<ModuleInspection, WasmtimeRuntimeError> {
    let mut observed_sections: HashMap<String, [u8; 32]> = HashMap::new();
    let mut plugin_metadata: Option<Vec<u8>> = None;
    let mut found_func_exports: HashSet<String> = HashSet::new();
    let mut found_memory_export = false;

    for payload in Parser::new(0).parse_all(wasm) {
        let payload = payload.map_err(|e| WasmtimeRuntimeError::ModuleRejected {
            reason: format!("wasm parse error: {e}"),
        })?;

        match payload {
            Payload::ImportSection(imports) => {
                let count = imports.into_iter().count();
                if count > 0 {
                    return Err(WasmtimeRuntimeError::ModuleRejected {
                        reason: format!(
                            "plugin module imports {count} item(s); Stage 1 disallows every host import",
                        ),
                    });
                }
            }
            Payload::ExportSection(exports) => {
                for export in exports {
                    let export = export.map_err(|e| WasmtimeRuntimeError::ModuleRejected {
                        reason: format!("invalid export entry: {e}"),
                    })?;
                    match export.kind {
                        ExternalKind::Func => {
                            found_func_exports.insert(export.name.to_owned());
                        }
                        ExternalKind::Memory if export.name == REQUIRED_MEMORY_EXPORT => {
                            found_memory_export = true;
                        }
                        _ => {}
                    }
                }
            }
            Payload::CustomSection(section) => {
                let name = section.name();
                if name == PLUGIN_META_SECTION {
                    plugin_metadata = Some(section.data().to_vec());
                    continue;
                }
                if name.starts_with("cc_lb.schema.") {
                    let data = section.data();
                    if data.len() != 32 {
                        return Err(WasmtimeRuntimeError::ModuleRejected {
                            reason: format!(
                                "`{name}` section is {} bytes; expected 32",
                                data.len()
                            ),
                        });
                    }
                    let mut buf = [0u8; 32];
                    buf.copy_from_slice(data);
                    observed_sections.insert(name.to_owned(), buf);
                }
            }
            _ => {}
        }
    }

    let metadata = plugin_metadata
        .as_deref()
        .ok_or_else(|| WasmtimeRuntimeError::ModuleRejected {
            reason: format!("missing required `{PLUGIN_META_SECTION}` custom section"),
        })
        .and_then(|bytes| {
            PluginMetadata::parse(bytes).map_err(|error| WasmtimeRuntimeError::ModuleRejected {
                reason: format!("invalid `{PLUGIN_META_SECTION}` metadata: {error}"),
            })
        })?;

    if !metadata.hooks.contains_key(kind.as_str()) {
        return Err(WasmtimeRuntimeError::ModuleRejected {
            reason: format!(
                "metadata does not declare required `{}` hook for this slot",
                kind.as_str()
            ),
        });
    }

    if !found_memory_export {
        return Err(WasmtimeRuntimeError::ModuleRejected {
            reason: format!("missing required export `{REQUIRED_MEMORY_EXPORT}` (Memory)"),
        });
    }
    for needed in ALWAYS_REQUIRED_FUNC_EXPORTS {
        if !found_func_exports.contains(*needed) {
            return Err(WasmtimeRuntimeError::ModuleRejected {
                reason: format!("missing required function export `{needed}`"),
            });
        }
    }

    let mut hook_versions = BTreeMap::new();
    let mut hook_fingerprints = BTreeMap::new();
    for (hook_name, hook_metadata) in &metadata.hooks {
        let hook =
            HookKind::parse(hook_name).ok_or_else(|| WasmtimeRuntimeError::ModuleRejected {
                reason: format!("unknown hook `{hook_name}` in metadata"),
            })?;
        let wire_version = WireVersion::from_u8(hook_metadata.wire_version).ok_or_else(|| {
            WasmtimeRuntimeError::ModuleRejected {
                reason: format!(
                    "hook `{}` declares unsupported wire version {}",
                    hook.as_str(),
                    hook_metadata.wire_version
                ),
            }
        })?;
        if !host_supported_versions(hook).contains(&wire_version) {
            return Err(WasmtimeRuntimeError::ModuleRejected {
                reason: format!(
                    "host does not support hook `{}` wire version {}",
                    hook.as_str(),
                    wire_version.as_u8()
                ),
            });
        }
        let needed_export = hook.export_name();
        if !found_func_exports.contains(needed_export) {
            return Err(WasmtimeRuntimeError::ModuleRejected {
                reason: format!(
                    "missing required function export `{needed_export}` for declared hook `{}`",
                    hook.as_str()
                ),
            });
        }

        let section_name = schema_section_name(hook, wire_version);
        let observed = observed_sections
            .get(&section_name)
            .copied()
            .ok_or_else(|| WasmtimeRuntimeError::ModuleRejected {
                reason: format!(
                    "missing `{section_name}` custom section for declared hook `{}`",
                    hook.as_str()
                ),
            })?;
        let expected = expected_fingerprint(hook, wire_version);
        if observed != expected {
            return Err(WasmtimeRuntimeError::ModuleRejected {
                reason: format!(
                    "`{section_name}` hash mismatch (host expects {} but plugin shipped {})",
                    hex32(&expected),
                    hex32(&observed),
                ),
            });
        }
        hook_versions.insert(hook, wire_version);
        hook_fingerprints.insert(hook, observed);
    }

    Ok(ModuleInspection {
        metadata,
        hook_versions,
        hook_fingerprints,
    })
}

pub(crate) fn schema_section_name(hook: HookKind, version: WireVersion) -> String {
    format!("{}.{}", hook.section_prefix(), version.as_str())
}

pub(crate) fn expected_fingerprint(hook: HookKind, version: WireVersion) -> [u8; 32] {
    match (hook, version) {
        (HookKind::Filter, WireVersion::V1) => {
            <cc_lb_plugin_wire::v1::FilterRequest as WireSchema>::FINGERPRINT
        }
        (HookKind::Shape, WireVersion::V1) => {
            <cc_lb_plugin_wire::v1::ShapeRequest as WireSchema>::FINGERPRINT
        }
        (HookKind::Observe, WireVersion::V1) => {
            <cc_lb_plugin_wire::v1::ObserveEvent as WireSchema>::FINGERPRINT
        }
    }
}

fn hex32(bytes: &[u8; 32]) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(64);
    for b in bytes {
        let _ = write!(out, "{b:02x}");
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn filter_section_bytes() -> Vec<u8> {
        expected_fingerprint(HookKind::Filter, WireVersion::V1).to_vec()
    }
    fn shape_section_bytes() -> Vec<u8> {
        expected_fingerprint(HookKind::Shape, WireVersion::V1).to_vec()
    }
    fn observe_section_bytes() -> Vec<u8> {
        expected_fingerprint(HookKind::Observe, WireVersion::V1).to_vec()
    }

    fn metadata_section(hook: &str) -> Vec<u8> {
        format!(
            r#"{{"name":"x","version":"0.0.1","description":"test plugin","usage":"test usage","hooks":{{"{hook}":{{"wire_version":1,"description":"{hook} hook","usage":"call {hook}"}}}}}}"#
        )
        .into_bytes()
    }

    fn wat_with_custom_sections(wat: &str, sections: &[(&str, &[u8])]) -> Vec<u8> {
        let mut module = wat::parse_str(wat).expect("valid wat");
        for (name, data) in sections {
            append_custom_section(&mut module, name, data);
        }
        module
    }

    fn append_custom_section(module: &mut Vec<u8>, name: &str, data: &[u8]) {
        let mut payload = Vec::new();
        encode_leb128(&mut payload, name.len() as u64);
        payload.extend_from_slice(name.as_bytes());
        payload.extend_from_slice(data);

        module.push(0);
        encode_leb128(module, payload.len() as u64);
        module.extend_from_slice(&payload);
    }

    fn encode_leb128(buf: &mut Vec<u8>, mut value: u64) {
        loop {
            let mut byte = (value & 0x7f) as u8;
            value >>= 7;
            if value != 0 {
                byte |= 0x80;
            }
            buf.push(byte);
            if value == 0 {
                break;
            }
        }
    }

    fn filter_plugin_wat() -> &'static str {
        r#"
        (module
            (memory (export "memory") 1)
            (func (export "cc_lb_alloc") (param i32 i32) (result i32) i32.const 0)
            (func (export "cc_lb_free") (param i32 i32 i32))
            (func (export "cc_lb_filter") (param i32 i32) (result i64) i64.const 0)
        )
        "#
    }

    fn shape_plugin_wat() -> &'static str {
        r#"
        (module
            (memory (export "memory") 1)
            (func (export "cc_lb_alloc") (param i32 i32) (result i32) i32.const 0)
            (func (export "cc_lb_free") (param i32 i32 i32))
            (func (export "cc_lb_shape") (param i32 i32) (result i64) i64.const 0)
        )
        "#
    }

    fn observe_plugin_wat() -> &'static str {
        r#"
        (module
            (memory (export "memory") 1)
            (func (export "cc_lb_alloc") (param i32 i32) (result i32) i32.const 0)
            (func (export "cc_lb_free") (param i32 i32 i32))
            (func (export "cc_lb_observe") (param i32 i32) (result i64) i64.const 0)
        )
        "#
    }

    #[test]
    fn accepts_filter_plugin() {
        let bytes = wat_with_custom_sections(
            filter_plugin_wat(),
            &[
                (
                    &schema_section_name(HookKind::Filter, WireVersion::V1),
                    &filter_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("filter")),
            ],
        );
        let inspection = inspect_wasm(HookKind::Filter, &bytes).expect("filter plugin OK");
        assert_eq!(inspection.metadata.name, "x");
        assert_eq!(inspection.hook_fingerprints.len(), 1);
        assert_eq!(inspection.primary_schema_hash().len(), 32);
        assert_eq!(inspection.hook_versions[&HookKind::Filter], WireVersion::V1);
    }

    #[test]
    fn accepts_shape_plugin_with_shape_section() {
        let bytes = wat_with_custom_sections(
            shape_plugin_wat(),
            &[
                (
                    &schema_section_name(HookKind::Shape, WireVersion::V1),
                    &shape_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("shape")),
            ],
        );
        let inspection = inspect_wasm(HookKind::Shape, &bytes).expect("shape plugin OK");
        assert_eq!(inspection.hook_versions[&HookKind::Shape], WireVersion::V1);
    }

    #[test]
    fn accepts_observe_plugin() {
        let bytes = wat_with_custom_sections(
            observe_plugin_wat(),
            &[
                (
                    &schema_section_name(HookKind::Observe, WireVersion::V1),
                    &observe_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("observe")),
            ],
        );
        let inspection = inspect_wasm(HookKind::Observe, &bytes).expect("observe plugin OK");
        assert_eq!(
            inspection.hook_versions[&HookKind::Observe],
            WireVersion::V1
        );
    }

    #[test]
    fn rejects_filter_without_schema_section() {
        let bytes = wat_with_custom_sections(
            filter_plugin_wat(),
            &[("cc_lb.plugin.v1", &metadata_section("filter"))],
        );
        let err = inspect_wasm(HookKind::Filter, &bytes).expect_err("missing section");
        let msg = format!("{err}");
        assert!(msg.contains("cc_lb.schema.filter.v1"), "got: {msg}");
    }

    #[test]
    fn rejects_filter_wrong_hash() {
        let bytes = wat_with_custom_sections(
            filter_plugin_wat(),
            &[
                (
                    &schema_section_name(HookKind::Filter, WireVersion::V1),
                    &[0u8; 32],
                ),
                ("cc_lb.plugin.v1", &metadata_section("filter")),
            ],
        );
        let err = inspect_wasm(HookKind::Filter, &bytes).expect_err("bad hash");
        let msg = format!("{err}");
        assert!(msg.contains("hash mismatch"), "got: {msg}");
    }

    #[test]
    fn rejects_imports_for_any_kind() {
        let bytes = wat_with_custom_sections(
            r#"
            (module
                (import "env" "host_log" (func (param i32 i32)))
                (memory (export "memory") 1)
                (func (export "cc_lb_alloc") (param i32 i32) (result i32) i32.const 0)
                (func (export "cc_lb_free") (param i32 i32 i32))
                (func (export "cc_lb_filter") (param i32 i32) (result i64) i64.const 0)
            )
            "#,
            &[
                (
                    &schema_section_name(HookKind::Filter, WireVersion::V1),
                    &filter_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("filter")),
            ],
        );
        let err = inspect_wasm(HookKind::Filter, &bytes).expect_err("import rejected");
        let msg = format!("{err}");
        assert!(msg.contains("disallows every host import"), "got: {msg}");
    }

    #[test]
    fn rejects_missing_alloc_or_free() {
        let bytes = wat_with_custom_sections(
            r#"
            (module
                (memory (export "memory") 1)
                (func (export "cc_lb_alloc") (param i32 i32) (result i32) i32.const 0)
                (func (export "cc_lb_filter") (param i32 i32) (result i64) i64.const 0)
            )
            "#,
            &[
                (
                    &schema_section_name(HookKind::Filter, WireVersion::V1),
                    &filter_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("filter")),
            ],
        );
        let err = inspect_wasm(HookKind::Filter, &bytes).expect_err("missing free");
        let msg = format!("{err}");
        assert!(msg.contains("cc_lb_free"), "got: {msg}");
    }

    #[test]
    fn filter_module_rejected_for_shape_slot() {
        // A filter-only plugin presented to a Shape slot must be
        // rejected — the shape exports and sections are simply absent.
        let bytes = wat_with_custom_sections(
            filter_plugin_wat(),
            &[
                (
                    &schema_section_name(HookKind::Filter, WireVersion::V1),
                    &filter_section_bytes(),
                ),
                ("cc_lb.plugin.v1", &metadata_section("filter")),
            ],
        );
        let err = inspect_wasm(HookKind::Shape, &bytes).expect_err("kind mismatch");
        let msg = format!("{err}");
        assert!(
            msg.contains("does not declare required `shape`"),
            "got: {msg}"
        );
    }
}