verit 0.2.0

Exavian Veritate — zero-copy, self-describing, schema-evolvable binary serialization, safe on untrusted bytes, no unsafe, byte-identical across independent implementations.
Documentation
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
//! Fuzz-style robustness harness. Untrusted bytes are the threat model for
//! any deserializer: the reader must **never panic, hang, or read out of
//! bounds** on hostile input — every failure must surface as a typed `Error`.
//!
//! This throws tens of thousands of random and mutation-derived buffers at the
//! whole read surface (parse, schema decode, `dump_json`, and a recursive
//! reader walk) and asserts no panic escapes. It is deterministic (fixed PRNG
//! seed) so a failure reproduces exactly. Not a substitute for `cargo-fuzz`
//! under a real coverage-guided engine, but it exercises the bounds-checking,
//! depth limits, and packed popcount paths hard on every `cargo test`.

use std::panic::{catch_unwind, AssertUnwindSafe};

use verit::{
    dump_json, encode, Dt, Message, Ref, Resolver, Schema, SchemaBuilder, SchemaMode, StructReader,
    Value,
};

/// Deterministic xorshift64 — no time/entropy so failures reproduce.
struct Rng(u64);
impl Rng {
    fn next(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }
    fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
    fn byte(&mut self) -> u8 {
        (self.next() & 0xff) as u8
    }
}

// ---------------------------------------------------------------------------
// A varied corpus of *valid* messages to mutate.
// ---------------------------------------------------------------------------

fn corpus() -> Vec<(Schema, Vec<u8>)> {
    let mut out = Vec::new();

    // Kitchen sink: scalars, string, bytes, enum, nested struct, lists.
    let s1 = SchemaBuilder::new()
        .add_enum("Color", vec![(0, "Red"), (1, "Green")])
        .add_dense_struct("Point", vec![(1, "x", Dt::F64), (2, "y", Dt::F64)])
        .add_struct(
            "Rec",
            vec![
                (1, "name", Dt::Str),
                (2, "n", Dt::U64),
                (3, "blob", Dt::Bytes),
                (4, "color", Dt::named("Color")),
                (5, "at", Dt::named("Point")),
                (6, "tags", Dt::list(Dt::Str)),
                (7, "path", Dt::list(Dt::named("Point"))),
                (8, "grid", Dt::list(Dt::list(Dt::U16))),
            ],
        )
        .build("Rec")
        .unwrap();
    let v1 = Value::Struct(vec![
        (1, Value::str("hello")),
        (2, Value::U64(123456)),
        (3, Value::Bytes(vec![1, 2, 3, 4, 5])),
        (4, Value::Enum(1)),
        (
            5,
            Value::Struct(vec![(1, Value::F64(1.5)), (2, Value::F64(2.5))]),
        ),
        (6, Value::List(vec![Value::str("a"), Value::str("bb")])),
        (
            7,
            Value::List(vec![Value::Struct(vec![
                (1, Value::F64(0.0)),
                (2, Value::F64(1.0)),
            ])]),
        ),
        (
            8,
            Value::List(vec![Value::List(vec![Value::U16(7), Value::U16(8)])]),
        ),
    ]);

    // Packed wide record (exercise the popcount read path under mutation).
    let s2 = SchemaBuilder::new()
        .add_packed_struct(
            "Wide",
            vec![
                (1, "a", Dt::U8),
                (2, "b", Dt::U64),
                (3, "c", Dt::Str),
                (4, "d", Dt::U32),
                (5, "e", Dt::Bool),
                (6, "f", Dt::F64),
            ],
        )
        .build("Wide")
        .unwrap();
    let v2 = Value::Struct(vec![
        (2, Value::U64(9)),
        (3, Value::str("packed")),
        (6, Value::F64(3.25)),
    ]);

    for (s, v) in [(&s1, &v1), (&s2, &v2)] {
        for mode in [SchemaMode::Inline, SchemaMode::HashOnly] {
            out.push((s.clone(), encode(s, v, mode).unwrap()));
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Bounded recursive walk: touch every field/element without trusting counts
// or depth. Any panic here (index, overflow, unwrap) fails the test.
// ---------------------------------------------------------------------------

const MAX_DEPTH: u32 = 40;

fn walk(r: &StructReader, depth: u32, budget: &mut u32) {
    if depth > MAX_DEPTH || *budget == 0 {
        return;
    }
    // Field ids come from the reader schema; values are read from bytes.
    let ids: Vec<u16> = r.struct_def().fields.iter().map(|f| f.id).collect();
    for id in ids {
        if *budget == 0 {
            return;
        }
        *budget -= 1;
        if let Ok(Some(v)) = r.get(id) {
            walk_ref(&v, depth, budget);
        }
    }
}

fn walk_ref(v: &Ref, depth: u32, budget: &mut u32) {
    match v {
        Ref::Struct(s) => walk(s, depth + 1, budget),
        Ref::List(l) => {
            // The bulk scalar readers take a different path from `get` — one
            // range check for the whole run, and an allocation sized from the
            // element count in `to_vec_*`. A forged count must fail on
            // arithmetic there, not on an OOM kill, so every one of them is
            // exercised on hostile input alongside the per-element path.
            let _ = l.as_u8_slice();
            let _ = l.to_vec_u8();
            let _ = l.to_vec_u16();
            let _ = l.to_vec_u32();
            let _ = l.to_vec_u64();
            let _ = l.to_vec_i8();
            let _ = l.to_vec_i16();
            let _ = l.to_vec_i32();
            let _ = l.to_vec_i64();
            let _ = l.to_vec_f32();
            let _ = l.to_vec_f64();
            let mut scratch = [0f32; 16];
            let _ = l.copy_f32(&mut scratch);

            // Cap element visits: a hostile count must not turn into a huge
            // loop (each get is still bounds-checked, but we bound work too).
            let n = l.len().min(128);
            for i in 0..n {
                if *budget == 0 {
                    return;
                }
                *budget -= 1;
                if let Ok(e) = l.get(i) {
                    walk_ref(&e, depth + 1, budget);
                }
            }
        }
        _ => {}
    }
}

/// Exercise the entire read surface for one buffer. `schema` is the original
/// (for building a resolver); `None` for fully-random buffers.
fn exercise(buf: &[u8], schema: Option<&Schema>) {
    // 1. Parse + envelope accessors.
    let msg = match Message::parse(buf) {
        Ok(m) => m,
        Err(_) => return,
    };
    let _ = msg.schema_id();
    let _ = msg.root_offset();
    let _ = msg.has_inline_schema();

    // 2. Inline schema decode + self-description dump.
    let _ = msg.writer_schema();
    let _ = dump_json(buf);

    // 3. Typed walk through a resolver, if we know the original schema.
    if let Some(schema) = schema {
        if let Ok(resolver) = Resolver::identity(schema) {
            if let Ok(root) = msg.root(&resolver) {
                let mut budget = 200_000u32;
                walk(&root, 0, &mut budget);
            }
        }
    }

    // 4. Also try the message's own inline schema as the resolver source.
    if let Ok(Some(inline)) = msg.writer_schema() {
        if let Ok(resolver) = Resolver::identity(&inline) {
            if let Ok(root) = msg.root(&resolver) {
                let mut budget = 200_000u32;
                walk(&root, 0, &mut budget);
            }
        }
    }

    // 5. The bounded read surface (traversal-budget guard) must also never
    //    panic/hang — only ever a typed error, including budget exhaustion.
    //    Exercise both a generous and a deliberately tiny budget.
    if let Some(schema) = schema {
        if let Ok(resolver) = Resolver::identity(schema) {
            for limit in [msg.suggested_budget(), 4] {
                let b = verit::Budget::new(limit);
                let _ = msg.verify(&resolver, &b);
                if let Ok(root) = msg.root_bounded(&resolver, &b) {
                    let mut w = 200_000u32;
                    walk(&root, 0, &mut w);
                }
            }
        }
    }
}

fn run_guarded(input: &[u8], schema: Option<&Schema>) -> bool {
    catch_unwind(AssertUnwindSafe(|| exercise(input, schema))).is_ok()
}

#[test]
fn no_panic_on_mutated_messages() {
    let corpus = corpus();
    let mut rng = Rng(0x9E3779B97F4A7C15);
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {})); // silence caught panics

    let mut failure: Option<(Vec<u8>, usize)> = None;
    for iter in 0..40_000 {
        let (schema, base) = &corpus[rng.below(corpus.len())];
        let mut bytes = base.clone();
        // Apply 1..=6 random single-byte mutations.
        let muts = 1 + rng.below(6);
        for _ in 0..muts {
            if bytes.is_empty() {
                break;
            }
            let i = rng.below(bytes.len());
            bytes[i] = rng.byte();
        }
        // Occasionally truncate or extend to stress length handling.
        match rng.below(8) {
            0 if !bytes.is_empty() => bytes.truncate(rng.below(bytes.len())),
            1 => {
                let (n, b) = (rng.below(32), rng.byte());
                for _ in 0..n {
                    bytes.push(b);
                }
            }
            _ => {}
        }
        if !run_guarded(&bytes, Some(schema)) {
            failure = Some((bytes, iter));
            break;
        }
    }

    std::panic::set_hook(hook);
    if let Some((bytes, iter)) = failure {
        panic!("panic on mutated input at iter {iter}: {bytes:02x?}");
    }
}

#[test]
fn no_panic_on_random_bytes() {
    let mut rng = Rng(0xD1B54A32D192ED03);
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));

    let mut failure: Option<Vec<u8>> = None;
    for _ in 0..40_000 {
        let len = rng.below(96);
        let bytes: Vec<u8> = (0..len).map(|_| rng.byte()).collect();
        // Half the time, force the correct magic so more inputs reach the
        // deeper parsing/decoding paths instead of bailing at the magic check.
        let mut bytes = bytes;
        if bytes.len() >= 4 && rng.below(2) == 0 {
            bytes[0..4].copy_from_slice(b"VRT2");
        }
        // Feed the schema decoder directly too.
        let ok_schema = catch_unwind(AssertUnwindSafe(|| {
            let _ = Schema::from_canonical(&bytes);
        }))
        .is_ok();
        // The at-rest container reader is a second untrusted-input surface: a
        // hostile `.vertc` image must also only ever error, never panic/OOB.
        // Sometimes force the container magic so more inputs reach the index
        // validation instead of bailing at the magic check.
        let ok_container = catch_unwind(AssertUnwindSafe(|| {
            let mut b = bytes.clone();
            if b.len() >= 4 && rng.below(2) == 0 {
                b[0..4].copy_from_slice(b"VRTC");
            }
            #[allow(deprecated)]
            if let Ok(c) = verit::Container::parse(&b) {
                for i in 0..c.len() {
                    let _ = c.get(i);
                }
            }
        }))
        .is_ok();
        if !ok_schema || !ok_container || !run_guarded(&bytes, None) {
            failure = Some(bytes);
            break;
        }
    }

    std::panic::set_hook(hook);
    if let Some(bytes) = failure {
        panic!("panic on random input: {bytes:02x?}");
    }
}

/// A hand-built offset cycle: a struct field whose pointer loops back to its
/// own block. The lazy reader tolerates it; `dump_json`, which walks eagerly,
/// must stop at the depth limit instead of recursing forever.
#[test]
fn offset_cycle_is_bounded_not_infinite() {
    let schema = SchemaBuilder::new()
        .add_struct(
            "Node",
            vec![(1, "next", Dt::named("Node")), (2, "v", Dt::U8)],
        )
        .build("Node")
        .unwrap();
    // Root Node with `next` present and `v` present.
    let bytes = encode(
        &schema,
        &Value::Struct(vec![
            (
                1,
                Value::Struct(vec![(2, Value::U8(1))]), // a child node, no further next
            ),
            (2, Value::U8(9)),
        ]),
        SchemaMode::Inline,
    )
    .unwrap();
    // Sanity: valid form dumps fine and terminates.
    assert!(dump_json(&bytes).is_ok());

    // Now forge a cycle: point the root's `next` slot at the root block itself.
    // Find the root offset and rewrite the first u32 struct slot to it. We do
    // this by brute force over slot positions and assert dump_json never hangs
    // or panics — it returns either Ok or a DepthLimitExceeded error.
    let root_off = u32::from_le_bytes(bytes[24..28].try_into().unwrap());
    for slot in (root_off as usize..bytes.len().saturating_sub(4)).step_by(4) {
        let mut m = bytes.clone();
        m[slot..slot + 4].copy_from_slice(&root_off.to_le_bytes());
        // Must return (Ok or Err) — never hang or panic.
        let _ = dump_json(&m);
    }
}

/// A deeply-nested `list<list<list<...>>>` schema must be rejected at decode,
/// not overflow the stack.
#[test]
fn hostile_nested_schema_rejected() {
    // "VSC1", type_count=1, kind=0(struct)... build a bogus canonical schema
    // with a field whose TypeExpr is thousands of nested list markers.
    let mut s = Vec::new();
    s.extend_from_slice(b"VSC1");
    s.extend_from_slice(&1u16.to_le_bytes()); // type_count
    s.push(0); // kind: struct
    s.extend_from_slice(&1u16.to_le_bytes()); // name len
    s.push(b'S'); // name
    s.extend_from_slice(&1u16.to_le_bytes()); // field_count
    s.extend_from_slice(&1u16.to_le_bytes()); // field id
    s.extend_from_slice(&1u16.to_le_bytes()); // field name len
    s.push(b'f'); // field name
                  // 5000 list markers, repeated — pathological nesting.
    s.resize(s.len() + 5000, 0x22);
    s.push(0x02); // finally a u8 element
    s.extend_from_slice(&0u16.to_le_bytes()); // root index
                                              // Must be a clean error, not a stack overflow.
    assert!(Schema::from_canonical(&s).is_err());
}

#[test]
fn deep_struct_reference_chain_is_bounded_not_overflow() {
    // A long *acyclic* chain of distinct structs (S0 { f: S1 }, S1 { f: S2 },
    // … Sn-1 { f: u32 }) validates fine — `from_canonical` doesn't recurse
    // across struct references — but resolving it (as `dump_json` does, via
    // `Resolver::identity`) recurses once per link. The `pair`/`compat` memo
    // stops *cycles* but not this chain, so without a depth bound a ~750 KB
    // hostile message would overflow the stack. It must surface a typed error.
    let n = 40_000usize;
    let mut b = SchemaBuilder::new();
    for i in 0..n {
        let name = format!("S{i}");
        let field = if i + 1 < n {
            (1u16, "f", Dt::named(&format!("S{}", i + 1)))
        } else {
            (1u16, "f", Dt::U32)
        };
        b = b.add_struct(&name, vec![field]);
    }
    let schema = b.build("S0").expect("chain schema builds");

    // Building an identity resolver directly must be a typed error, not a crash.
    assert!(matches!(
        Resolver::identity(&schema),
        Err(verit::Error::DepthLimitExceeded)
    ));

    // And the whole hostile-message path (`dump_json` over inline schema) must
    // return a typed error rather than aborting the process.
    let bytes =
        encode(&schema, &Value::Struct(vec![]), SchemaMode::Inline).expect("empty root encodes");
    assert!(
        bytes.len() < 1_000_000,
        "chain message stays small on the wire"
    );
    assert!(
        dump_json(&bytes).is_err(),
        "dump_json must reject a deep-chain schema, not overflow"
    );

    // A comfortably-deep chain still resolves — deeper than any real schema —
    // so the bound rejects only the pathological, not the legitimate. (Each
    // struct link costs two recursion steps: the field `compat` plus the nested
    // `pair`, so the effective struct-nesting headroom is ~half the frame cap.)
    let mut ok = SchemaBuilder::new();
    let deepish = 30usize;
    for i in 0..deepish {
        let field = if i + 1 < deepish {
            (1u16, "f", Dt::named(&format!("T{}", i + 1)))
        } else {
            (1u16, "f", Dt::U32)
        };
        ok = ok.add_struct(&format!("T{i}"), vec![field]);
    }
    let ok_schema = ok.build("T0").expect("deepish chain builds");
    assert!(
        Resolver::identity(&ok_schema).is_ok(),
        "a 30-deep struct chain (well under the limit) must still resolve"
    );
}

#[test]
fn empty_defaults_section_rejected_as_noncanonical() {
    // The encoder omits the defaults section entirely when no field has a
    // default, so a present-but-empty section (count 0) is a *second* byte
    // encoding of a default-less schema. Accepting it would break the
    // "exactly one canonical encoding per schema" invariant (and the schema
    // fuzz target's round-trip oracle). It must be rejected.
    let schema = SchemaBuilder::new()
        .add_struct("S", vec![(1, "a", Dt::U32)])
        .build("S")
        .unwrap();

    // The genuine canonical form (no section) decodes and round-trips.
    let ok = Schema::from_canonical(schema.canonical_bytes()).unwrap();
    assert_eq!(ok.canonical_bytes(), schema.canonical_bytes());

    // The same schema with a trailing empty defaults section must not decode.
    let mut noncanonical = schema.canonical_bytes().to_vec();
    noncanonical.extend_from_slice(&0u16.to_le_bytes());
    assert!(Schema::from_canonical(&noncanonical).is_err());
}

#[test]
fn noncanonical_scalar_default_bits_rejected() {
    // A scalar default must be stored in its *canonical* byte form. A `bool`
    // default has exactly two legal encodings (0x00 / 0x01); any other byte
    // (e.g. 0x02) decodes to `true` but re-encodes to 0x01, so it is a second
    // byte string for the same schema. `from_canonical` must reject it, or the
    // schema fuzz oracle (`canonical_bytes() == input`) would panic on it.
    let schema = SchemaBuilder::new()
        .add_struct("R", vec![(1, "b", Dt::Bool)])
        .set_default("R", 1, Value::Bool(true))
        .build("R")
        .unwrap();

    // Canonical bytes round-trip.
    let ok = Schema::from_canonical(schema.canonical_bytes()).unwrap();
    assert_eq!(ok.canonical_bytes(), schema.canonical_bytes());

    // The last byte is the bool default (0x01 canonical); a non-canonical
    // encoding of the same value must be rejected, not silently accepted.
    let mut noncanonical = schema.canonical_bytes().to_vec();
    let last = noncanonical.len() - 1;
    assert_eq!(noncanonical[last], 0x01);
    noncanonical[last] = 0x02;
    assert!(Schema::from_canonical(&noncanonical).is_err());
}