cc-lb-runtime-wasmtime 0.1.4

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
use cc_lb_plugin_wire::schema::WireSchema;
use cc_lb_plugin_wire::{FilterResponse, PerCandidateReason};
use cc_lb_runtime_wasmtime::{
    RuntimeSlotKey, WasmPluginWireDispatch, WasmtimeRuntime, WasmtimeRuntimeError,
};
use rkyv::rancor::Error as RkyvError;
use std::sync::Arc;

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 build_malicious_wat(wat_body: &str, initial_pages: u32) -> Vec<u8> {
    let wat = format!(
        r#"
        (module
            (memory (export "memory") {})
            (func (export "cc_lb_alloc") (param i32 i32) (result i32)
                i32.const 4096
            )
            (func (export "cc_lb_free") (param i32 i32 i32))
            {}
        )
        "#,
        initial_pages, wat_body
    );
    let mut wasm = wat::parse_str(&wat).expect("valid wat");

    // Append metadata section
    let metadata = r#"{"name":"malicious-plugin","version":"0.1.0","description":"Malicious test plugin","usage":"Testing only","hooks":{"filter":{"wire_version":1,"description":"filter hook","usage":"call filter"}}}"#;
    append_custom_section(&mut wasm, "cc_lb.plugin.v1", metadata.as_bytes());

    // Append schema section
    let fingerprint = <cc_lb_plugin_wire::v1::FilterRequest as WireSchema>::FINGERPRINT;
    append_custom_section(&mut wasm, "cc_lb.schema.filter.v1", &fingerprint);

    wasm
}

#[test]
fn test_null_ptr_behavior() {
    // Given: A malicious plugin that returns a null pointer (out_ptr = 0, out_len = 10)
    let wasm_bytes = build_malicious_wat(
        r#"
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            ;; Return out_ptr = 0, out_len = 10
            i64.const 10
        )
        "#,
        1,
    );
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));

    // When: We register the filter hook
    let result = runtime.register_filter(
        RuntimeSlotKey::global("null-ptr-test"),
        "null-ptr-test",
        &wasm_bytes,
    );

    // Then: It must fail at load time during the probe with a ProbeFailed error indicating invalid pointer
    assert!(result.is_err());
    let err = match result {
        Ok(_) => unreachable!(),
        Err(e) => e,
    };
    assert!(
        matches!(err, WasmtimeRuntimeError::ProbeFailed { .. }),
        "expected ProbeFailed, got: {:?}",
        err
    );
    let msg = err.to_string();
    assert!(
        msg.contains("guest returned invalid (ptr=0, len=10)"),
        "expected error message to mention invalid ptr=0, got: {}",
        msg
    );
}

#[test]
fn test_zero_len_behavior() {
    // Given: A malicious plugin that returns a zero length (out_ptr = 1024, out_len = 0)
    let wasm_bytes = build_malicious_wat(
        r#"
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            ;; Return out_ptr = 1024, out_len = 0
            ;; 1024 << 32 = 4398046511104
            i64.const 4398046511104
        )
        "#,
        1,
    );
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));

    // When: We register the filter hook
    let result = runtime.register_filter(
        RuntimeSlotKey::global("zero-len-test"),
        "zero-len-test",
        &wasm_bytes,
    );

    // Then: It must fail at load time during the probe with a ProbeFailed error indicating invalid length
    assert!(result.is_err());
    let err = match result {
        Ok(_) => unreachable!(),
        Err(e) => e,
    };
    assert!(
        matches!(err, WasmtimeRuntimeError::ProbeFailed { .. }),
        "expected ProbeFailed, got: {:?}",
        err
    );
    let msg = err.to_string();
    assert!(
        msg.contains("guest returned invalid (ptr=1024, len=0)"),
        "expected error message to mention invalid len=0, got: {}",
        msg
    );
}

#[test]
fn test_oob_output_behavior() {
    // Given: A malicious plugin that returns an out-of-bounds pointer/length (out_ptr = 1024, out_len = 1000000)
    let wasm_bytes = build_malicious_wat(
        r#"
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            ;; Return out_ptr = 1024, out_len = 1000000
            ;; (1024 << 32) | 1000000 = 4398047511104
            i64.const 4398047511104
        )
        "#,
        1,
    );
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));

    // When: We register the filter hook
    let result = runtime.register_filter(
        RuntimeSlotKey::global("oob-output-test"),
        "oob-output-test",
        &wasm_bytes,
    );

    // Then: It must fail at load time during the probe with a ProbeFailed error indicating out of bounds
    assert!(result.is_err());
    let err = match result {
        Ok(_) => unreachable!(),
        Err(e) => e,
    };
    assert!(
        matches!(err, WasmtimeRuntimeError::ProbeFailed { .. }),
        "expected ProbeFailed, got: {:?}",
        err
    );
    let msg = err.to_string();
    assert!(
        msg.contains("out of bounds"),
        "expected error message to mention out of bounds, got: {}",
        msg
    );
}

#[test]
fn test_ptr_len_overflow_behavior() {
    // Given: A malicious plugin that returns overflowing pointer/length (out_ptr = 0xFFFF_FFFF, out_len = 0xFFFF_FFFF)
    let wasm_bytes = build_malicious_wat(
        r#"
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            ;; Return out_ptr = 0xFFFF_FFFF, out_len = 0xFFFF_FFFF
            i64.const -1
        )
        "#,
        1,
    );
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));

    // When: We register the filter hook
    let result = runtime.register_filter(
        RuntimeSlotKey::global("overflow-test"),
        "overflow-test",
        &wasm_bytes,
    );

    // Then: It must fail at load time during the probe with a ProbeFailed error indicating either out of bounds or overflow
    assert!(result.is_err());
    let err = match result {
        Ok(_) => unreachable!(),
        Err(e) => e,
    };
    assert!(
        matches!(err, WasmtimeRuntimeError::ProbeFailed { .. }),
        "expected ProbeFailed, got: {:?}",
        err
    );
    let msg = err.to_string();
    assert!(
        msg.contains("out of bounds") || msg.contains("overflows usize"),
        "expected error message to mention out of bounds or overflow, got: {}",
        msg
    );
}

#[test]
fn test_memory_grow_before_return_behavior() {
    // Given: A plugin that calls memory.grow immediately before returning a valid pointer/length in the newly grown page
    use cc_lb_plugin_wire::{FilterResponse, PerCandidateReason};
    use rkyv::rancor::Error as RkyvError;

    let response = FilterResponse {
        results: Box::new([PerCandidateReason {
            upstream_id: Box::from("11111111-1111-1111-1111-111111111111"),
            decision: Box::from("accept"),
            reason: Box::from("grow-ok"),
        }]),
    };
    let bytes = rkyv::to_bytes::<RkyvError>(&response).expect("encode");
    let mut data_section = String::new();
    for b in bytes.iter() {
        data_section.push_str(&format!("\\{:02x}", b));
    }

    let wat_body = format!(
        r#"
        (data (i32.const 65536) "{}")
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            ;; Grow memory by 1 page (64 KiB)
            i32.const 1
            memory.grow
            drop
            
            ;; Return out_ptr = 65536, out_len = {}
            ;; (65536 << 32) | {} = {}
            i64.const {}
        )
        "#,
        data_section,
        bytes.len(),
        bytes.len(),
        (65536u64 << 32) | (bytes.len() as u64),
        (65536u64 << 32) | (bytes.len() as u64)
    );

    let wasm_bytes = build_malicious_wat(&wat_body, 2);
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));

    // When: We register the filter hook
    let slot = runtime
        .register_filter(
            RuntimeSlotKey::global("grow-test"),
            "grow-test",
            &wasm_bytes,
        )
        .expect("register filter");
    let dispatch = WasmPluginWireDispatch::from_slot(slot, runtime.config_arc());
    let result = dispatch.call_filter(&[]);

    // Then: It must succeed and return the valid FilterResponse bytes
    assert!(result.is_ok());
    let out_bytes = result.unwrap();
    assert_eq!(out_bytes, bytes.to_vec());
}

#[test]
fn test_misaligned_valid_rkyv() {
    // Given: A plugin that returns a misaligned but valid rkyv response (out_ptr = 1025, out_len = len)
    let response = FilterResponse {
        results: Box::new([PerCandidateReason {
            upstream_id: Box::from("11111111-1111-1111-1111-111111111111"),
            decision: Box::from("accept"),
            reason: Box::from("aligned-or-copy"),
        }]),
    };
    let bytes = rkyv::to_bytes::<RkyvError>(&response).expect("encode");
    let mut data_section = String::new();
    for b in bytes.iter() {
        data_section.push_str(&format!("\\{:02x}", b));
    }

    let wat_body = format!(
        r#"
        (data (i32.const 1024) "{}")
        (data (i32.const 2049) "{}")
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            local.get 1
            i32.eqz
            if (result i64)
                ;; Return out_ptr = 2049, out_len = {}
                i64.const {}
            else
                ;; Return out_ptr = 1024, out_len = {}
                i64.const {}
            end
        )
        "#,
        data_section,
        data_section,
        bytes.len(),
        (2049u64 << 32) | (bytes.len() as u64),
        bytes.len(),
        (1024u64 << 32) | (bytes.len() as u64)
    );

    let wasm_bytes = build_malicious_wat(&wat_body, 1);
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));
    let slot = runtime
        .register_filter(
            RuntimeSlotKey::global("misaligned-test"),
            "misaligned-test",
            &wasm_bytes,
        )
        .expect("register filter");
    let dispatch = WasmPluginWireDispatch::from_slot(slot, runtime.config_arc());
    let result = dispatch.call_filter(&[]);

    // Then: It must succeed via fallback copy and return the valid FilterResponse bytes
    assert!(result.is_ok());
    let out_bytes = result.unwrap();
    assert_eq!(out_bytes, bytes.to_vec());
}

#[test]
fn test_corrupt_rkyv() {
    // Given: A plugin that returns corrupt rkyv bytes (out_ptr = 1024, out_len = 32)
    let corrupt_bytes = vec![0xAA; 32];
    let mut data_section = String::new();
    for b in corrupt_bytes.iter() {
        data_section.push_str(&format!("\\{:02x}", b));
    }

    let response = FilterResponse {
        results: Box::new([PerCandidateReason {
            upstream_id: Box::from("11111111-1111-1111-1111-111111111111"),
            decision: Box::from("accept"),
            reason: Box::from("corrupt-probe-ok"),
        }]),
    };
    let valid_bytes = rkyv::to_bytes::<RkyvError>(&response).expect("encode");
    let mut valid_data_section = String::new();
    for b in valid_bytes.iter() {
        valid_data_section.push_str(&format!("\\{:02x}", b));
    }

    let wat_body = format!(
        r#"
        (data (i32.const 1024) "{}")
        (data (i32.const 2048) "{}")
        (func (export "cc_lb_filter") (param i32 i32) (result i64)
            local.get 1
            i32.eqz
            if (result i64)
                ;; Return out_ptr = 2048, out_len = 32
                ;; (2048 << 32) | 32 = 8796093022240
                i64.const 8796093022240
            else
                ;; Return out_ptr = 1024, out_len = {}
                i64.const {}
            end
        )
        "#,
        valid_data_section,
        data_section,
        valid_bytes.len(),
        (1024u64 << 32) | (valid_bytes.len() as u64)
    );

    let wasm_bytes = build_malicious_wat(&wat_body, 1);
    let runtime = Arc::new(WasmtimeRuntime::with_defaults().expect("engine build"));
    let slot = runtime
        .register_filter(
            RuntimeSlotKey::global("corrupt-test"),
            "corrupt-test",
            &wasm_bytes,
        )
        .expect("register filter");
    let dispatch = WasmPluginWireDispatch::from_slot(slot, runtime.config_arc());
    let result = dispatch.call_filter(&[]);

    // Then: It must succeed at the dispatch level (since dispatch doesn't validate rkyv),
    // but the returned bytes will fail validation when accessed.
    assert!(result.is_ok());
    let out_bytes = result.unwrap();
    assert_eq!(out_bytes, corrupt_bytes);
}