mik-sdk 0.1.2

Ergonomic macros for WASI HTTP handlers - ok!, error!, json!
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
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
//! Security-related tests for the JSON parser.
//!
//! Tests for:
//! - Trailing content rejection (prevents JSON injection attacks)
//! - Depth limits (prevents stack overflow)
//! - Size limits (prevents memory exhaustion)

use super::super::*;
use crate::constants::get_max_json_size;

// =========================================================================
// HELPER FUNCTIONS
// =========================================================================

/// Generate nested JSON objects: {"a":{"a":{"a":...}}} at specified depth
fn generate_nested_objects(depth: usize) -> String {
    let mut json = String::new();
    for _ in 0..depth {
        json.push_str("{\"a\":");
    }
    json.push('1');
    for _ in 0..depth {
        json.push('}');
    }
    json
}

/// Generate nested JSON arrays: [[[[...]]]] at specified depth
fn generate_nested_arrays(depth: usize) -> String {
    let mut json = String::new();
    for _ in 0..depth {
        json.push('[');
    }
    json.push('1');
    for _ in 0..depth {
        json.push(']');
    }
    json
}

/// Generate mixed nested JSON: {"a":[{"a":[...]}]} alternating objects and arrays
fn generate_mixed_nesting(depth: usize) -> String {
    let mut json = String::new();
    for i in 0..depth {
        if i % 2 == 0 {
            json.push_str("{\"a\":");
        } else {
            json.push('[');
        }
    }
    json.push('1');
    for i in (0..depth).rev() {
        if i % 2 == 0 {
            json.push('}');
        } else {
            json.push(']');
        }
    }
    json
}

// =========================================================================
// DEPTH LIMIT TESTS - OBJECTS
// =========================================================================

#[test]
fn test_depth_limit_objects_at_19() {
    // Depth 19: should succeed (below the limit of 20)
    let json = generate_nested_objects(19);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 19 levels of object nesting should parse successfully"
    );
}

#[test]
fn test_depth_limit_objects_at_20() {
    // Depth 20: should succeed (exactly at the limit)
    let json = generate_nested_objects(20);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 20 levels of object nesting should parse successfully (at limit)"
    );
}

#[test]
fn test_depth_limit_objects_at_21() {
    // Depth 21: should fail (exceeds the limit of 20)
    let json = generate_nested_objects(21);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_none(),
        "JSON with 21 levels of object nesting should be rejected (exceeds limit)"
    );
}

// =========================================================================
// DEPTH LIMIT TESTS - ARRAYS
// =========================================================================

#[test]
fn test_depth_limit_arrays_at_19() {
    // Depth 19: should succeed (below the limit of 20)
    let json = generate_nested_arrays(19);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 19 levels of array nesting should parse successfully"
    );
}

#[test]
fn test_depth_limit_arrays_at_20() {
    // Depth 20: should succeed (exactly at the limit)
    let json = generate_nested_arrays(20);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 20 levels of array nesting should parse successfully (at limit)"
    );
}

#[test]
fn test_depth_limit_arrays_at_21() {
    // Depth 21: should fail (exceeds the limit of 20)
    let json = generate_nested_arrays(21);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_none(),
        "JSON with 21 levels of array nesting should be rejected (exceeds limit)"
    );
}

// =========================================================================
// DEPTH LIMIT TESTS - MIXED NESTING
// =========================================================================

#[test]
fn test_depth_limit_mixed_at_19() {
    // Mixed nesting at depth 19: should succeed
    let json = generate_mixed_nesting(19);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 19 levels of mixed nesting should parse successfully"
    );
}

#[test]
fn test_depth_limit_mixed_at_20() {
    // Mixed nesting at depth 20: should succeed (at limit)
    let json = generate_mixed_nesting(20);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "JSON with 20 levels of mixed nesting should parse successfully (at limit)"
    );
}

#[test]
fn test_depth_limit_mixed_at_21() {
    // Mixed nesting at depth 21: should fail (exceeds limit)
    let json = generate_mixed_nesting(21);
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_none(),
        "JSON with 21 levels of mixed nesting should be rejected (exceeds limit)"
    );
}

// =========================================================================
// DEPTH CHECK EDGE CASES
// =========================================================================

#[test]
fn test_depth_check_ignores_braces_in_strings() {
    // Braces inside strings should not count towards depth
    // This is valid JSON with depth 1, but contains many braces in strings
    let json = r#"{"key": "{{{{{{{{{{{{{{{{{{{{{{{{{{"}"#;
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "Braces inside strings should not affect depth calculation"
    );
}

#[test]
fn test_depth_check_handles_escaped_quotes() {
    // Escaped quotes inside strings should be handled correctly
    let json = r#"{"key": "value with \" escaped quote and {nested}"}"#;
    let result = try_parse(json.as_bytes());
    assert!(
        result.is_some(),
        "Escaped quotes should be handled correctly in depth check"
    );
}

#[test]
fn test_json_depth_exceeds_limit_directly() {
    // Test the internal function directly for precise boundary checks
    let json_19 = generate_nested_objects(19);
    let json_20 = generate_nested_objects(20);
    let json_21 = generate_nested_objects(21);

    assert!(
        !json_depth_exceeds_limit(json_19.as_bytes()),
        "Depth 19 should not exceed limit"
    );
    assert!(
        !json_depth_exceeds_limit(json_20.as_bytes()),
        "Depth 20 should not exceed limit (at boundary)"
    );
    assert!(
        json_depth_exceeds_limit(json_21.as_bytes()),
        "Depth 21 should exceed limit"
    );
}

#[test]
fn test_depth_check_with_escape_in_string() {
    // Escaped backslash followed by quote in string should not affect depth
    let json = br#"{"key": "value\\\"more"}"#;
    assert!(!json_depth_exceeds_limit(json));
}

#[test]
fn test_depth_check_empty_input() {
    assert!(!json_depth_exceeds_limit(&[]));
}

#[test]
fn test_depth_check_no_nesting() {
    let json = br#""just a string""#;
    assert!(!json_depth_exceeds_limit(json));
}

#[test]
fn test_depth_check_closing_without_opening() {
    // Malformed JSON - closing brace without opening
    // saturating_sub should handle this gracefully
    let json = b"}}}";
    assert!(!json_depth_exceeds_limit(json));
}

#[test]
fn test_depth_exactly_at_limit() {
    // Build JSON with exactly MAX_JSON_DEPTH levels
    let mut json = String::new();
    for _ in 0..20 {
        json.push_str("{\"a\":");
    }
    json.push('1');
    for _ in 0..20 {
        json.push('}');
    }
    // Should succeed at exactly the limit
    assert!(try_parse(json.as_bytes()).is_some());
}

#[test]
fn test_depth_one_over_limit() {
    // Build JSON with MAX_JSON_DEPTH + 1 levels
    let mut json = String::new();
    for _ in 0..21 {
        json.push_str("{\"a\":");
    }
    json.push('1');
    for _ in 0..21 {
        json.push('}');
    }
    // Should fail
    assert!(try_parse(json.as_bytes()).is_none());
}

// =========================================================================
// SIZE LIMIT TESTS
// =========================================================================

#[test]
fn test_try_parse_full_exceeds_size_limit() {
    // Create JSON larger than max size (default 1MB, configurable via MIK_MAX_JSON_SIZE)
    let max_size = get_max_json_size();
    let large = vec![b'x'; max_size + 1];
    assert!(try_parse_full(&large).is_none());
}

#[test]
fn test_try_parse_exceeds_size_limit() {
    let max_size = get_max_json_size();
    let large = vec![b' '; max_size + 1];
    assert!(try_parse(&large).is_none());
}

#[test]
fn test_json_at_size_limit() {
    // Create JSON just under the limit
    let max_size = get_max_json_size();
    let padding = "a".repeat(max_size - 20);
    let json = format!(r#"{{"x": "{padding}"}}"#);
    if json.len() <= max_size {
        assert!(try_parse(json.as_bytes()).is_some());
    }
}

// =========================================================================
// INVALID UTF-8 TESTS
// =========================================================================

#[test]
fn test_try_parse_full_invalid_utf8() {
    let invalid_utf8 = [0x80, 0x81, 0x82];
    assert!(try_parse_full(&invalid_utf8).is_none());
}

#[test]
fn test_try_parse_full_exceeds_depth_limit() {
    let json = generate_nested_objects(21);
    assert!(try_parse_full(json.as_bytes()).is_none());
}

// =========================================================================
// TRAILING CONTENT VALIDATION TESTS (Security)
// =========================================================================
// These tests verify that JSON with non-whitespace content after the
// valid JSON value is rejected. This prevents JSON injection attacks.

// === try_parse trailing content tests ===

#[test]
fn test_try_parse_rejects_trailing_garbage_object() {
    // Valid JSON followed by garbage should be rejected
    let json = br#"{"key": "value"}garbage"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject JSON with trailing non-whitespace"
    );
}

#[test]
fn test_try_parse_rejects_trailing_garbage_array() {
    let json = br"[1, 2, 3]extra";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject array with trailing content"
    );
}

#[test]
fn test_try_parse_rejects_trailing_garbage_string() {
    let json = br#""hello"world"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject string with trailing content"
    );
}

#[test]
fn test_try_parse_rejects_trailing_garbage_number() {
    let json = br"42garbage";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject number with trailing content"
    );
}

#[test]
fn test_try_parse_rejects_trailing_garbage_boolean() {
    let json = br"truefoo";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject true with trailing content"
    );

    let json = br"falsebar";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject false with trailing content"
    );
}

#[test]
fn test_try_parse_rejects_trailing_garbage_null() {
    let json = br"nullextra";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject null with trailing content"
    );
}

#[test]
fn test_try_parse_accepts_trailing_whitespace_object() {
    // Trailing whitespace should be accepted
    let json = br#"{"key": "value"}   "#;
    assert!(
        try_parse(json).is_some(),
        "try_parse should accept JSON with trailing whitespace"
    );
}

#[test]
fn test_try_parse_accepts_trailing_whitespace_various() {
    // Various whitespace characters: space, tab, newline, carriage return
    let json = b"{\"key\": \"value\"}\n\t\r ";
    assert!(
        try_parse(json).is_some(),
        "try_parse should accept various trailing whitespace"
    );
}

#[test]
fn test_try_parse_accepts_no_trailing_content() {
    let json = br#"{"key": "value"}"#;
    assert!(try_parse(json).is_some());
}

// === try_parse_full trailing content tests ===

#[test]
fn test_try_parse_full_rejects_trailing_garbage_object() {
    let json = br#"{"key": "value"}garbage"#;
    assert!(
        try_parse_full(json).is_none(),
        "try_parse_full should reject JSON with trailing non-whitespace"
    );
}

#[test]
fn test_try_parse_full_rejects_trailing_garbage_array() {
    let json = br"[1, 2, 3]extra";
    assert!(
        try_parse_full(json).is_none(),
        "try_parse_full should reject array with trailing content"
    );
}

#[test]
fn test_try_parse_full_accepts_trailing_whitespace() {
    let json = br#"{"key": "value"}   "#;
    assert!(
        try_parse_full(json).is_some(),
        "try_parse_full should accept JSON with trailing whitespace"
    );
}

// === Edge cases ===

#[test]
fn test_try_parse_rejects_multiple_json_values() {
    // Two valid JSON objects concatenated - should reject
    let json = br#"{"a":1}{"b":2}"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject multiple concatenated JSON values"
    );
}

#[test]
fn test_try_parse_rejects_json_followed_by_json() {
    // Valid JSON followed by another valid JSON (JSONL style) - should reject
    let json = br#"{"key": "value"}
{"key2": "value2"}"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject JSONL (newline-delimited JSON)"
    );
}

#[test]
fn test_try_parse_accepts_leading_whitespace() {
    // Leading whitespace should be accepted
    let json = br#"   {"key": "value"}"#;
    assert!(
        try_parse(json).is_some(),
        "try_parse should accept JSON with leading whitespace"
    );
}

#[test]
fn test_try_parse_accepts_leading_and_trailing_whitespace() {
    let json = br#"   {"key": "value"}   "#;
    assert!(
        try_parse(json).is_some(),
        "try_parse should accept JSON with leading and trailing whitespace"
    );
}

#[test]
fn test_try_parse_rejects_comment_after_json() {
    // JSON doesn't support comments - trailing // should be rejected
    let json = br#"{"key": "value"} // comment"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject JSON followed by comment"
    );
}

#[test]
fn test_try_parse_nested_object_trailing_garbage() {
    let json = br#"{"outer": {"inner": "value"}}garbage"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject nested object with trailing garbage"
    );
}

#[test]
fn test_try_parse_nested_array_trailing_garbage() {
    let json = br"[[1, 2], [3, 4]]extra";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject nested array with trailing garbage"
    );
}

#[test]
fn test_try_parse_string_with_quotes_trailing_garbage() {
    // String containing escaped quotes, followed by garbage
    let json = br#"{"msg": "hello \"world\""}extra"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should handle escaped quotes correctly"
    );
}

#[test]
fn test_try_parse_scientific_notation_trailing_garbage() {
    let json = br#"{"n": 1.23e+10}garbage"#;
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject scientific notation with trailing garbage"
    );
}

#[test]
fn test_try_parse_negative_number_trailing_garbage() {
    let json = br"-42garbage";
    assert!(
        try_parse(json).is_none(),
        "try_parse should reject negative number with trailing garbage"
    );
}