-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathjson_fuzz_test.go
More file actions
1712 lines (1622 loc) · 62.3 KB
/
Copy pathjson_fuzz_test.go
File metadata and controls
1712 lines (1622 loc) · 62.3 KB
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Structure-aware JSON fuzzer for the jsonparser public surface.
//
// This file implements a grammar-driven JSON generator and a set of JSON-
// aware mutation operators that target the structural boundaries where
// parser bugs live: truncation right after a ':' (the OSS-Fuzz
// sentinel_value_boundary class), truncation inside a key (truncated_mid_key),
// truncation after an unclosed '{' or '[' (truncated_mid_structure), etc.
//
// The grammar generator always emits valid JSON. The mutation operators
// then break that valid JSON at precisely the byte positions where the
// parser's state machine has to make a transition — the positions that
// blind byte-flip mutation reaches only after exponentially many trials.
//
// Assertion model (each gate maps to a known bug class):
//
// 1. NO-PANIC gate — every op recovers() clean.
// Catches: empty-key panics (SYS-REQ-111),
// truncation panics, sentinel-deref panics.
// 2. OUTPUT-VALIDITY — json.Valid(out) after Set/Delete.
// Catches: silent data corruption (SYS-REQ-110 / PR #286).
// 3. ROUND-TRIP — Get(out, path) returns the set value.
// Catches: Set/Get asymmetry, index-beyond-length data loss.
// 4. NUMERIC-ORACLE — ParseInt/ParseFloat match strconv.
// Catches: numeric edge cases (overflow, leading zeros).
//
// The gates are HONEST: no t.Skip, no soft exceptions for known bugs. If a
// gate fires, it is a real bug or a documented-open divergence (the latter
// are excluded from the OUTPUT-VALIDITY gate via pathShapeMatchesRoot,
// matching the convention in path_fuzz_test.go).
//
// Verifies: SYS-REQ-035 (no-panic on malformed/adversarial input).
// reqproof:proptest parser.Get, parser.Set, parser.Delete, parser.GetString, parser.GetInt, parser.GetFloat,
// parser.GetBoolean, parser.GetUnsafeString, parser.ArrayEach, parser.ObjectEach, parser.EachKey,
// parser.ParseInt, parser.ParseFloat
package jsonparser
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"os"
"runtime/debug"
"strconv"
"testing"
"time"
"unicode/utf8"
)
// =============================================================================
// Seed corpus (the known-dangerous inputs we've already found)
// =============================================================================
type structureAwareSeed struct {
data []byte
path []byte
}
// structureAwareSeeds is the set of inputs that exercise every previously-
// buggy code path. Each seed is annotated with the bug class it targets.
var structureAwareSeeds = []structureAwareSeed{
{[]byte(`{"a":1}`), []byte("a")}, // baseline valid object
{[]byte(`[1,2,3]`), []byte("")}, // empty key on array root (SYS-REQ-111)
{[]byte(`{"a":[{"x":1}]}`), []byte("a")}, // the D9 repro shape (array-of-object)
{[]byte(`{"a":`), []byte("a")}, // truncated at value boundary (OSS-Fuzz 4649128545288192)
{[]byte(`{"key`), []byte("key")}, // truncated mid-key
{[]byte(`{"a":[1,2`), []byte("a/[0]")}, // truncated mid-structure
{[]byte(`{"a":"\u30`), []byte("a")}, // truncated mid-escape
{[]byte(`{"a":1,"b":2}`), []byte("a")}, // duplicate-key mutation target
{[]byte(`[1,2,3]`), []byte("[0]")}, // in-range array index
{[]byte(`[1,2,3]`), []byte("[99]")}, // out-of-range index (SYS-REQ-110)
{[]byte(`{"a":[1,2,3]}`), []byte("a/[5]")}, // nested OOB index (PR #286 class)
{[]byte(`{"":1}`), []byte("")}, // object with empty key
{[]byte(`null`), []byte("a")}, // scalar root
{[]byte(``), []byte("a")}, // empty input
{[]byte(`{`), []byte("a")}, // unclosed object
{[]byte(`[}`), []byte("[0]")}, // malformed array
{[]byte(`{"a":"hello\nworld"}`), []byte("a")}, // escaped string value
{[]byte(`{"a":9223372036854775807}`), []byte("a")}, // int64 max
{[]byte(`{"a":99999999999999999999}`), []byte("a")}, // overflow boundary
{[]byte(`{"a":-0.0}`), []byte("a")}, // negative zero float
// --- UTF-8 / Unicode edge cases (parser indexes BYTES not runes) ---
{[]byte(`{"a":"\uD800\uDC00"}`), []byte("a")}, // valid surrogate pair (U+10000)
{[]byte(`{"a":"\uDBFF\uDFFF"}`), []byte("a")}, // valid surrogate pair (U+10FFFF)
{[]byte(`{"a":"\uD800"}`), []byte("a")}, // lone high surrogate (malformed)
{[]byte(`{"a":"\uDC00"}`), []byte("a")}, // lone low surrogate (malformed)
{[]byte(`{"a":"\uD800\uD800"}`), []byte("a")}, // two highs (malformed)
{[]byte(`{"a":"\u0000"}`), []byte("a")}, // escaped null
{[]byte(`{"a":"\u001F"}`), []byte("a")}, // escaped unit separator
{[]byte("{\"a\":\"x\x00y\"}"), []byte("a")}, // raw null byte (invalid JSON)
{[]byte("{\"a\":\"x\x1Fy\"}"), []byte("a")}, // raw control char (invalid JSON)
// --- Raw multibyte UTF-8 (must be raw bytes, not \u escapes) ---
{[]byte("{\"a\":\"\xC3\xA9\"}"), []byte("a")}, // 2-byte: é (U+00E9)
{[]byte("{\"a\":\"\xE4\xB8\x96\xE7\x95\x8C\"}"), []byte("a")}, // 3-byte: 世界
{[]byte("{\"a\":\"\xF0\x9F\x98\x80\"}"), []byte("a")}, // 4-byte: emoji 😀
// --- Invalid UTF-8 byte sequences (parser must reject cleanly) ---
{[]byte("{\"a\":\"x\xC0\xAFy\"}"), []byte("a")}, // overlong '/' (0xC0 0xAF)
{[]byte("{\"a\":\"x\xE0y\"}"), []byte("a")}, // truncated 3-byte (leading 0xE0)
{[]byte("{\"a\":\"x\xFFy\"}"), []byte("a")}, // never-valid byte 0xFF
{[]byte("{\"a\":\"x\xFEy\"}"), []byte("a")}, // never-valid byte 0xFE
// --- BOM (U+FEFF = 0xEF 0xBB 0xBF) ---
{[]byte("\xEF\xBB\xBF" + `{"a":1}`), []byte("a")}, // BOM at start of input
// --- Number edge cases (exponent extremes, negative zero, NaN text) ---
{[]byte(`{"a":1e999}`), []byte("a")}, // float overflow (+Inf)
{[]byte(`{"a":1e-999}`), []byte("a")}, // float underflow (0)
{[]byte(`{"a":1e308}`), []byte("a")}, // near float64 max
{[]byte(`{"a":1e-323}`), []byte("a")}, // near float64 min denormal
{[]byte(`{"a":-0}`), []byte("a")}, // negative zero int
{[]byte(`{"a":-0e0}`), []byte("a")}, // negative zero exponent
{[]byte(`{"a":Infinity}`), []byte("a")}, // invalid: Infinity text
{[]byte(`{"a":NaN}`), []byte("a")}, // invalid: NaN text
{[]byte(`{"a":-Infinity}`), []byte("a")}, // invalid: -Infinity text
{[]byte(`{"a":12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890}`), []byte("a")}, // 100+ digit integer
{[]byte(`{"a":0.12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890}`), []byte("a")}, // 100+ digit decimal
// --- All JSON escapes (including \b and \f) ---
{[]byte(`{"a":"\b\f\n\t\r\"\\\/"}`), []byte("a")}, // all 8 JSON escapes
{[]byte(`{"a":"\/\/\/\/"}`), []byte("a")}, // solidus run
}
// =============================================================================
// Deterministic RNG seeding from fuzz inputs
// =============================================================================
// newRandFromSeed derives a deterministic *rand.Rand from the fuzz inputs.
// This lets the fuzz body make structure-aware generation/mutation decisions
// that are a pure function of the engine-supplied bytes (so the engine's
// coverage feedback remains meaningful). Uses FNV-1a for speed (no allocs
// beyond the rand.Rand struct itself).
func newRandFromSeed(seeds ...[]byte) *rand.Rand {
const (
offsetBasis uint64 = 14695981039346656037
fnvPrime uint64 = 1099511628211
)
h := offsetBasis
for _, s := range seeds {
for _, b := range s {
h ^= uint64(b)
h *= fnvPrime
}
}
return rand.New(rand.NewSource(int64(h)))
}
// =============================================================================
// Recursive JSON value generator (grammar-based)
// =============================================================================
const maxGenDepth = 5
// genJSON returns a valid JSON document generated from the grammar. The
// output is always valid JSON per RFC 8259 (the corpus-sanity test asserts
// json.Valid on every generated document).
//
// Depth controls recursion: at depth >= maxGenDepth the generator emits
// only scalars to bound the output size and stress the base cases.
func genJSON(r *rand.Rand, depth int) []byte {
var buf []byte
genValue(r, depth, &buf)
return buf
}
// genValue appends one JSON value to buf, chosen from a weighted
// distribution that favors containers at shallow depth (to exercise
// nesting) and scalars at deep depth (to bound recursion).
func genValue(r *rand.Rand, depth int, buf *[]byte) {
if depth >= maxGenDepth {
// Scalars only at deep recursion.
switch r.Intn(4) {
case 0:
genString(r, buf)
case 1:
genNumber(r, buf)
case 2:
*buf = append(*buf, 't', 'r', 'u', 'e')
default:
*buf = append(*buf, 'n', 'u', 'l', 'l')
}
return
}
roll := r.Intn(20)
switch {
case roll < 6: // 30% — object
genObject(r, depth, buf)
case roll < 11: // 25% — array
genArray(r, depth, buf)
case roll < 14: // 15% — string
genString(r, buf)
case roll < 18: // 20% — number
genNumber(r, buf)
case roll == 18: // 5% — bool
if r.Intn(2) == 0 {
*buf = append(*buf, 't', 'r', 'u', 'e')
} else {
*buf = append(*buf, 'f', 'a', 'l', 's', 'e')
}
default: // 5% — null
*buf = append(*buf, 'n', 'u', 'l', 'l')
}
}
// genObject emits an object with 0–5 entries. Keys are drawn from a set
// that includes the dangerous cases: empty-string "", unicode (\uXXXX),
// long, and escaped special characters.
func genObject(r *rand.Rand, depth int, buf *[]byte) {
*buf = append(*buf, '{')
n := r.Intn(6) // 0..5 entries
for i := 0; i < n; i++ {
if i > 0 {
*buf = append(*buf, ',')
}
genKey(r, buf)
*buf = append(*buf, ':')
genValue(r, depth+1, buf)
}
*buf = append(*buf, '}')
}
// genArray emits an array with 0–5 elements (including the empty array []).
func genArray(r *rand.Rand, depth int, buf *[]byte) {
*buf = append(*buf, '[')
n := r.Intn(6) // 0..5 elements
for i := 0; i < n; i++ {
if i > 0 {
*buf = append(*buf, ',')
}
genValue(r, depth+1, buf)
}
*buf = append(*buf, ']')
}
// genKey emits a JSON object key (a double-quoted string). The key content
// is drawn from a weighted distribution that includes the cases most likely
// to expose parser bugs:
// - empty string "" (the empty-key hazard class, SYS-REQ-111)
// - unicode escapes \uXXXX (escape-parsing paths)
// - long keys (allocation paths)
// - escaped special chars (\\, \", \n, \t — escape correctness)
func genKey(r *rand.Rand, buf *[]byte) {
*buf = append(*buf, '"')
switch r.Intn(16) {
case 0: // empty string key
case 1: // single ASCII char
*buf = append(*buf, byte('a'+r.Intn(26)))
case 2: // short ASCII (1–8 chars)
for i := 0; i < 1+r.Intn(8); i++ {
*buf = append(*buf, byte('a'+r.Intn(26)))
}
case 3: // unicode escape sequence \u30XX (hiragana range)
*buf = append(*buf, '\\', 'u', '3', '0')
*buf = append(*buf, hexDigit(r), hexDigit(r))
case 4: // long key (stress allocation paths)
for i := 0; i < 20+r.Intn(30); i++ {
*buf = append(*buf, byte('a'+r.Intn(26)))
}
case 5: // escaped special chars (always valid JSON)
*buf = append(*buf, '\\', '"', '\\', '\\', '\\', 'n', '\\', 't')
case 6: // numeric-looking key
*buf = append(*buf, '0', '0', '7')
case 7: // "key" (matches common test seeds)
*buf = append(*buf, 'k', 'e', 'y')
// --- raw multibyte UTF-8 keys (parser indexes BYTES not runes) ---
case 8: // 2-byte UTF-8 raw key (Latin/Greek/Cyrillic)
var u [4]byte
n := utf8.EncodeRune(u[:], rune(0x80+r.Intn(0x780)))
*buf = append(*buf, u[:n]...)
case 9: // 3-byte UTF-8 raw key (CJK/Arabic/Hindi)
var u [4]byte
n := utf8.EncodeRune(u[:], rune(0x800+r.Intn(0xF800)))
*buf = append(*buf, u[:n]...)
case 10: // valid surrogate-pair escape key (U+10000+)
cp := 0x10000 + r.Intn(0x10FFFF-0x10000+1)
cp -= 0x10000
appendUnicodeEscape(buf, 0xD800+(cp>>10))
appendUnicodeEscape(buf, 0xDC00+(cp&0x3FF))
case 11: // lone surrogate escape key (malformed — parser must reject)
appendUnicodeEscape(buf, 0xD800+r.Intn(0x800))
case 12: // escaped control char key (\u0000 / \u001F)
appendUnicodeEscape(buf, r.Intn(0x20))
case 13: // invalid UTF-8 raw bytes in key (overlong / truncated / FF)
switch r.Intn(3) {
case 0:
*buf = append(*buf, 0xC0, 0xAF)
case 1:
*buf = append(*buf, 0xE0)
default:
*buf = append(*buf, 0xFF)
}
case 14: // BOM-prefixed key
*buf = append(*buf, 0xEF, 0xBB, 0xBF, 'k')
default: // 2-char ASCII
*buf = append(*buf, byte('a'+r.Intn(26)), byte('a'+r.Intn(26)))
}
*buf = append(*buf, '"')
}
// genString emits a JSON string value. Includes empty "", ASCII, strings
// with escape sequences, unicode escapes, and long strings.
func genString(r *rand.Rand, buf *[]byte) {
*buf = append(*buf, '"')
switch r.Intn(22) {
case 0: // empty string
case 1: // ASCII short
for i := 0; i < 1+r.Intn(8); i++ {
*buf = append(*buf, byte('a'+r.Intn(26)))
}
case 2: // escape sequences (all 8 JSON escapes incl. \b and \f)
escapes := [][]byte{[]byte(`\n`), []byte(`\t`), []byte(`\"`), []byte(`\\`), []byte(`\/`), []byte(`\r`), []byte(`\b`), []byte(`\f`)}
for i := 0; i < 1+r.Intn(4); i++ {
*buf = append(*buf, escapes[r.Intn(len(escapes))]...)
}
case 3: // unicode escape (BMP non-surrogate, hiragana range)
*buf = append(*buf, '\\', 'u', '3', '0')
*buf = append(*buf, hexDigit(r), hexDigit(r))
case 4: // long string (stress allocation)
for i := 0; i < 50+r.Intn(50); i++ {
*buf = append(*buf, byte('a'+r.Intn(26)))
}
case 5: // mixed content with escapes
*buf = append(*buf, []byte(`hello\nworld\u2603`)...)
case 6: // numeric-looking string (tests type coercion in callers)
*buf = append(*buf, '1', '2', '3', '4', '5')
case 7: // whitespace inside string (properly escaped — raw control
// bytes like 0x09 are invalid inside JSON strings per RFC 8259,
// so we emit the \t escape sequence instead of a literal tab).
*buf = append(*buf, ' ', '\\', 't')
// --- raw multibyte UTF-8 (parser indexes BYTES not runes) ---
case 8: // 2-byte UTF-8 raw (U+0080–U+07FF: accented Latin, Greek, Cyrillic)
var u [4]byte
n := utf8.EncodeRune(u[:], rune(0x80+r.Intn(0x780)))
*buf = append(*buf, u[:n]...)
case 9: // 3-byte UTF-8 raw (U+0800–U+FFFF: CJK, Arabic, Hindi)
var u [4]byte
n := utf8.EncodeRune(u[:], rune(0x800+r.Intn(0xF800)))
*buf = append(*buf, u[:n]...)
case 10: // 4-byte UTF-8 raw (U+10000+: emoji, math symbols, CJK ext.)
var u [4]byte
cp := 0x10000 + r.Intn(0x10FFFF-0x10000+1)
n := utf8.EncodeRune(u[:], rune(cp))
*buf = append(*buf, u[:n]...)
// --- surrogate-pair escapes (the escape decoder must combine these) ---
case 11: // valid surrogate pair (\uXXXX\uXXXX → U+10000..U+10FFFF)
cp := 0x10000 + r.Intn(0x10FFFF-0x10000+1)
cp -= 0x10000
appendUnicodeEscape(buf, 0xD800+(cp>>10))
appendUnicodeEscape(buf, 0xDC00+(cp&0x3FF))
case 12: // lone high surrogate (malformed — parser must reject)
appendUnicodeEscape(buf, 0xD800+r.Intn(0x400))
case 13: // lone low surrogate (malformed — parser must reject)
appendUnicodeEscape(buf, 0xDC00+r.Intn(0x400))
case 14: // two high surrogates back-to-back (malformed)
appendUnicodeEscape(buf, 0xD800+r.Intn(0x400))
appendUnicodeEscape(buf, 0xD800+r.Intn(0x400))
// --- control characters (escaped form, valid JSON) ---
case 15: // escaped null and unit separator
appendUnicodeEscape(buf, 0x00) // \u0000
appendUnicodeEscape(buf, 0x1F) // \u001F
// --- long escape runs (stress the escape decoder's allocation path) ---
case 16:
escapes := [][]byte{[]byte(`\n`), []byte(`\t`), []byte(`\"`), []byte(`\\`), []byte(`\/`), []byte(`\r`), []byte(`\b`), []byte(`\f`)}
for i := 0; i < 30+r.Intn(30); i++ {
*buf = append(*buf, escapes[r.Intn(len(escapes))]...)
}
case 17: // solidus edge cases: \/ and bare / both valid in JSON strings
*buf = append(*buf, '\\', '/', '/', '\\', '/')
// --- invalid UTF-8 byte sequences (parser must reject, never panic) ---
case 18: // overlong encoding (0xC0 0xAF = overlong '/')
*buf = append(*buf, 0xC0, 0xAF)
case 19: // truncated sequence (leading byte 0xE0 with no continuation)
*buf = append(*buf, 0xE0)
case 20: // never-valid bytes 0xFF / 0xFE
*buf = append(*buf, 0xFF, 0xFE)
case 21: // BOM (U+FEFF = 0xEF 0xBB 0xBF) inside a string — valid UTF-8, unusual
*buf = append(*buf, 0xEF, 0xBB, 0xBF)
}
*buf = append(*buf, '"')
}
// nearMaxInt64 are string representations of integers at/above the int64
// boundary. They are emitted as literal bytes (not via strconv.AppendInt)
// to avoid int64 overflow in the generator itself.
var nearMaxInt64 = []string{
"9223372036854775807", // math.MaxInt64 exactly
"9223372036854775806", // MaxInt64 - 1
"9223372036854775808", // MaxInt64 + 1 (overflows int64)
"9999999999999999999", // 19 nines (overflows)
"99999999999999999999", // 20 nines (overflows)
}
var nearMinInt64 = []string{
"-9223372036854775808", // math.MinInt64 exactly
"-9223372036854775807", // MinInt64 + 1
"-9223372036854775809", // MinInt64 - 1 (underflows)
"-9999999999999999999", // large negative (underflows)
}
// genNumber emits a JSON number. The distribution is weighted toward the
// fast-path (small ints) but includes overflow boundaries, floats, and
// intentionally-malformed values (leading zeros) that exercise the parser's
// error paths.
func genNumber(r *rand.Rand, buf *[]byte) {
switch r.Intn(20) {
case 0: // 0
*buf = append(*buf, '0')
case 1: // small positive int (1–2 digits — the fast path)
*buf = strconv.AppendInt(*buf, int64(1+r.Intn(99)), 10)
case 2: // negative small int
*buf = strconv.AppendInt(*buf, -int64(1+r.Intn(99)), 10)
case 3: // near int64 max (overflow boundary)
*buf = append(*buf, nearMaxInt64[r.Intn(len(nearMaxInt64))]...)
case 4: // near int64 min (overflow boundary)
*buf = append(*buf, nearMinInt64[r.Intn(len(nearMinInt64))]...)
case 5: // medium int
*buf = strconv.AppendInt(*buf, int64(100+r.Intn(100000)), 10)
case 6: // float (fixed notation)
*buf = strconv.AppendFloat(*buf, r.Float64()*1000, 'f', 2, 64)
case 7: // float with exponent
*buf = strconv.AppendFloat(*buf, r.Float64()*1e10, 'e', -1, 64)
case 8: // negative float
*buf = strconv.AppendFloat(*buf, -r.Float64()*1000, 'f', 2, 64)
case 9: // leading zeros (invalid JSON per RFC 8259 but tests parser leniency)
*buf = append(*buf, '0', '0', '7')
case 10: // very small float
*buf = append(*buf, []byte("0.000001")...)
// --- exponent extremes (overflow / underflow paths) ---
case 11: // float overflow → +Inf
switch r.Intn(3) {
case 0:
*buf = append(*buf, []byte("1e999")...)
case 1:
*buf = append(*buf, []byte("1e400")...)
default:
*buf = append(*buf, []byte("2.5e500")...)
}
case 12: // float underflow → 0
switch r.Intn(3) {
case 0:
*buf = append(*buf, []byte("1e-999")...)
case 1:
*buf = append(*buf, []byte("1e-400")...)
default:
*buf = append(*buf, []byte("1e-323")...) // near float64 min denormal
}
case 13: // near float64 max (1.7976931348623157e+308)
*buf = append(*buf, []byte("1.7976931348623157e+308")...)
case 14: // near float64 min denormal (5e-324)
*buf = append(*buf, []byte("5e-324")...)
// --- negative zero variants ---
case 15:
switch r.Intn(3) {
case 0:
*buf = append(*buf, '-', '0')
case 1:
*buf = append(*buf, []byte("-0.0")...)
default:
*buf = append(*buf, []byte("-0e0")...)
}
// --- very long numbers (overflow path) ---
case 16: // 100+ digit integer
*buf = append(*buf, '9')
for i := 0; i < 100+r.Intn(50); i++ {
*buf = append(*buf, '9')
}
case 17: // 100+ digit decimal
*buf = append(*buf, '0', '.')
for i := 0; i < 100+r.Intn(50); i++ {
*buf = append(*buf, '9')
}
// --- Infinity / NaN text (invalid JSON but parsers may see them) ---
case 18:
switch r.Intn(3) {
case 0:
*buf = append(*buf, []byte("Infinity")...)
case 1:
*buf = append(*buf, []byte("NaN")...)
default:
*buf = append(*buf, []byte("-Infinity")...)
}
default: // single-digit positive
*buf = strconv.AppendInt(*buf, int64(r.Intn(10)), 10)
}
}
// hexDigit returns a single lowercase hexadecimal digit byte.
func hexDigit(r *rand.Rand) byte {
d := r.Intn(16)
if d < 10 {
return byte('0' + d)
}
return byte('a' + d - 10)
}
// hexChars is the lowercase hex alphabet used by appendUnicodeEscape.
const hexChars = "0123456789abcdef"
// appendUnicodeEscape appends a `\uXXXX` escape sequence for the given code
// point to buf. Does NOT validate cp — callers use it for both valid BMP
// code points and for lone/invalid surrogates (which the parser must reject
// cleanly). cp must fit in 20 bits (the BMP range); higher bits are masked.
func appendUnicodeEscape(buf *[]byte, cp int) {
*buf = append(*buf, '\\', 'u',
hexChars[(cp>>12)&0xF],
hexChars[(cp>>8)&0xF],
hexChars[(cp>>4)&0xF],
hexChars[cp&0xF])
}
// =============================================================================
// JSON-aware mutation operators
// =============================================================================
//
// Each operator targets a structural boundary where the parser's state
// machine has to make a transition. Truncating or corrupting at these
// positions exercises the error-recovery paths that hide the bug classes
// documented in the task spec.
//
// Every operator MUST return a new slice (never mutate the input in place)
// because the fuzz engine may reuse the input buffer across iterations.
// mutationOp is a JSON-aware mutation: it takes valid (or near-valid) JSON
// bytes and returns a mutated copy with a structural break introduced at a
// known-dangerous boundary.
type mutationOp func(r *rand.Rand, data []byte) []byte
// mutationOps is the registry of all operators. applyMutation picks one at
// random. The injectEmptyKeyComponent and injectOobArrayIndex operators
// from the spec are path-side operators and are handled separately in
// injectPathHazard.
var mutationOps = []mutationOp{
truncateAtValueBoundary,
truncateMidKey,
truncateMidStructure,
truncateMidEscape,
truncateMidElement,
duplicateKey,
byteflipAtStructuralByte,
injectInvalidUTF8,
injectLoneSurrogate,
injectUnbalancedOpen,
injectMismatchedCloser,
}
// applyMutation picks one operator at random and applies it.
func applyMutation(r *rand.Rand, data []byte) []byte {
if len(data) < 2 {
return data
}
op := mutationOps[r.Intn(len(mutationOps))]
return op(r, data)
}
// findStructuralBytes returns the positions of all bytes in data that match
// any of targets. Returns nil if none are found.
func findStructuralBytes(data []byte, targets ...byte) []int {
var pos []int
for i, b := range data {
for _, t := range targets {
if b == t {
pos = append(pos, i)
break
}
}
}
return pos
}
// truncateAtValueBoundary cuts the document right after a ':' (before the
// value starts). This is the OSS-Fuzz 4649128545288192 /
// sentinel_value_boundary class: the parser must not dereference past the
// cut when looking for the value token.
func truncateAtValueBoundary(r *rand.Rand, data []byte) []byte {
pos := findStructuralBytes(data, ':')
if len(pos) == 0 {
return data
}
cut := pos[r.Intn(len(pos))] + 1
if cut > len(data) {
cut = len(data)
}
out := make([]byte, cut)
copy(out, data[:cut])
return out
}
// truncateMidKey cuts inside a string key. The cut is placed between the
// opening '"' of a key and its closing '"'. This is the truncated_mid_key
// class: the parser's Unescape routine must detect the unterminated string.
func truncateMidKey(r *rand.Rand, data []byte) []byte {
var cuts []int
for i := 1; i < len(data); i++ {
if data[i] != '"' {
continue
}
// Walk back past whitespace to find the structural predecessor.
j := i - 1
for j >= 0 && (data[j] == ' ' || data[j] == '\t' || data[j] == '\n' || data[j] == '\r') {
j--
}
if j < 0 || (data[j] != '{' && data[j] != ',') {
continue
}
// This '"' is a key opening. Find the closing '"'.
end := -1
for k := i + 1; k < len(data); k++ {
if data[k] == '"' && data[k-1] != '\\' {
end = k
break
}
}
lo := i + 1
hi := end
if hi < 0 || hi > len(data) {
hi = len(data)
}
if hi > lo {
cuts = append(cuts, lo+r.Intn(hi-lo))
}
}
if len(cuts) == 0 {
return data
}
cut := cuts[r.Intn(len(cuts))]
out := make([]byte, cut)
copy(out, data[:cut])
return out
}
// truncateMidStructure cuts after an unclosed '{' or '['. This is the
// truncated_mid_structure class: the parser must detect the missing closing
// token and return a clean MalformedObjectError / MalformedArrayError.
func truncateMidStructure(r *rand.Rand, data []byte) []byte {
pos := findStructuralBytes(data, '{', '[')
if len(pos) == 0 {
return data
}
open := pos[r.Intn(len(pos))]
if open+1 >= len(data) {
return data
}
cut := open + 1 + r.Intn(len(data)-open-1)
out := make([]byte, cut)
copy(out, data[:cut])
return out
}
// truncateMidEscape cuts inside a \uXXXX escape sequence. This is the
// truncated_escape_sequence class: the parser's Unescape routine must
// detect the truncated escape and return MalformedStringEscapeError.
func truncateMidEscape(r *rand.Rand, data []byte) []byte {
var cuts []int
for i := 0; i+1 < len(data); i++ {
if data[i] != '\\' || data[i+1] != 'u' {
continue
}
// \uXXXX is 6 bytes. Cut somewhere in [i+2, i+6).
lo := i + 2
hi := i + 6
if hi > len(data) {
hi = len(data)
}
if hi > lo {
cuts = append(cuts, lo+r.Intn(hi-lo))
}
}
if len(cuts) == 0 {
// No \u escape present; inject a truncated one and exercise the path.
out := make([]byte, 0, len(data)+5)
out = append(out, data...)
out = append(out, '"', '\\', 'u', '3', '0')
return out
}
cut := cuts[r.Intn(len(cuts))]
out := make([]byte, cut)
copy(out, data[:cut])
return out
}
// truncateMidElement cuts inside an array element, after a '[' or ','. The
// truncated_mid_element class: the parser must not read past the cut when
// scanning for the element's value type.
func truncateMidElement(r *rand.Rand, data []byte) []byte {
var pos []int
for i, b := range data {
if (b == '[' || b == ',') && i+2 < len(data) {
pos = append(pos, i)
}
}
if len(pos) == 0 {
return data
}
anchor := pos[r.Intn(len(pos))]
cut := anchor + 1 + r.Intn(len(data)-anchor-1)
out := make([]byte, cut)
copy(out, data[:cut])
return out
}
// duplicateKey injects a duplicate object key, turning {"k":1} into
// {"k":1,"k":1}. This exercises duplicate-key handling: the parser should
// return the first value for Get without structural corruption.
func duplicateKey(r *rand.Rand, data []byte) []byte {
for i := 0; i+2 < len(data); i++ {
if data[i] != '"' {
continue
}
// Find the closing quote of this key.
keyEnd := -1
for k := i + 1; k < len(data); k++ {
if data[k] == '"' && data[k-1] != '\\' {
keyEnd = k
break
}
}
if keyEnd == -1 || keyEnd+1 >= len(data) || data[keyEnd+1] != ':' {
continue
}
// Find the end of the value (next ',' or '}' or ']' at depth 0).
valEnd := keyEnd + 2
depth := 0
inStr := false
done:
for valEnd < len(data) {
b := data[valEnd]
if inStr {
if b == '"' && data[valEnd-1] != '\\' {
inStr = false
}
} else {
switch b {
case '"':
inStr = true
case '{', '[':
depth++
case '}', ']':
if depth == 0 {
break done
}
depth--
case ',':
if depth == 0 {
break done
}
}
}
valEnd++
}
if valEnd <= keyEnd+2 || valEnd > len(data) {
continue
}
pair := data[i:valEnd]
out := make([]byte, 0, len(data)+len(pair)+1)
out = append(out, data[:valEnd]...)
out = append(out, ',')
out = append(out, pair...)
out = append(out, data[valEnd:]...)
return out
}
return data
}
// byteflipAtStructuralByte flips a byte at a structural position ({, }, [,
// ], :, ,, "). This corrupts the document skeleton, exercising the parser's
// malformed-structure detection paths.
func byteflipAtStructuralByte(r *rand.Rand, data []byte) []byte {
pos := findStructuralBytes(data, '{', '}', '[', ']', ':', ',', '"')
if len(pos) == 0 {
return data
}
idx := pos[r.Intn(len(pos))]
out := make([]byte, len(data))
copy(out, data)
// XOR with a nonzero mask to guarantee the byte changes.
out[idx] ^= byte(1 + r.Intn(255))
return out
}
// stringInsertionPoints returns the byte positions of all unescaped closing
// '"' chars that terminate a string body in data. Used by mutation operators
// that need to inject bytes inside a JSON string. The simple scanner does
// not track `\\` sequences perfectly (e.g. `\\"`), but it is good enough
// for fuzz-targeted injection.
func stringInsertionPoints(data []byte) []int {
var pos []int
inStr := false
for i := 1; i < len(data); i++ {
if data[i] != '"' || data[i-1] == '\\' {
continue
}
if !inStr {
inStr = true
} else {
pos = append(pos, i) // just before the closing quote
inStr = false
}
}
return pos
}
// injectInvalidUTF8 inserts a raw invalid-UTF-8 byte sequence inside a JSON
// string value. Targets the parser's UTF-8 validation path: the parser must
// reject cleanly, never panic. Covers overlong encodings (0xC0 0xAF), truncated
// sequences (lone leading byte), never-valid bytes (0xFF / 0xFE), and a UTF-8-
// encoded surrogate (which encoding/json rejects but some parsers accept).
func injectInvalidUTF8(r *rand.Rand, data []byte) []byte {
positions := stringInsertionPoints(data)
if len(positions) == 0 {
return data
}
pos := positions[r.Intn(len(positions))]
invalid := [][]byte{
{0xC0, 0xAF}, // overlong '/'
{0xC1, 0xBF}, // overlong 2-byte
{0xE0, 0x80, 0xAF}, // overlong 3-byte
{0xF0, 0x80, 0x80, 0x80}, // overlong 4-byte
{0xE0}, // truncated 3-byte (lone leading byte)
{0xF0, 0x80}, // truncated 4-byte
{0xFF}, // never-valid byte
{0xFE}, // never-valid byte
{0xED, 0xA0, 0x80}, // UTF-8 encoding of U+D800 (lone surrogate)
}
seq := invalid[r.Intn(len(invalid))]
out := make([]byte, 0, len(data)+len(seq))
out = append(out, data[:pos]...)
out = append(out, seq...)
out = append(out, data[pos:]...)
return out
}
// injectLoneSurrogate corrupts a string by replacing a `\uXXXX` escape with a
// lone surrogate escape (\uD800 / \uDC00 alone, or a high-high pair). Targets
// the escape decoder's surrogate-combination path: it must refuse to combine
// these into a valid code point and must reject the string cleanly. If no
// `\u` escape exists in data, the operator inserts a lone surrogate escape at
// a random string-body position instead.
func injectLoneSurrogate(r *rand.Rand, data []byte) []byte {
// Find existing \u escapes.
var escPos []int
for i := 0; i+1 < len(data); i++ {
if data[i] == '\\' && data[i+1] == 'u' {
escPos = append(escPos, i)
}
}
if len(escPos) > 0 {
pos := escPos[r.Intn(len(escPos))]
end := pos + 6
if end > len(data) {
end = len(data)
}
var seq []byte
switch r.Intn(3) {
case 0:
seq = []byte(`\uD800`) // high alone
case 1:
seq = []byte(`\uDC00`) // low alone
default:
seq = []byte(`\uD800\uD800`) // two highs
}
out := make([]byte, 0, len(data)-6+len(seq))
out = append(out, data[:pos]...)
out = append(out, seq...)
out = append(out, data[end:]...)
return out
}
// Fallback: insert a lone-surrogate escape inside a string body.
positions := stringInsertionPoints(data)
if len(positions) == 0 {
return data
}
pos := positions[r.Intn(len(positions))]
seq := []byte(`\uD800`)
out := make([]byte, 0, len(data)+len(seq))
out = append(out, data[:pos]...)
out = append(out, seq...)
out = append(out, data[pos:]...)
return out
}
// injectUnbalancedOpen inserts unmatched '{' or '[' opens at a random
// position. This produces structures the grammar generator CANNOT emit:
// every generator-produced container is balanced by construction. The
// parser's blockEnd / depth-tracking code must detect the missing closer
// and return a clean error rather than reading past EOF.
//
// Targets the deep-recursion / malformed-structure detection path that
// balanced-only generation leaves uncovered.
func injectUnbalancedOpen(r *rand.Rand, data []byte) []byte {
const maxInserts = 8
n := 1 + r.Intn(maxInserts)
open := byte('{')
if r.Intn(2) == 0 {
open = '['
}
// Bias insertion point: 50% at start (forces full descent), 50% random.
pos := 0
if r.Intn(2) == 0 {
pos = r.Intn(len(data) + 1)
}
out := make([]byte, 0, len(data)+n)
out = append(out, data[:pos]...)
for i := 0; i < n; i++ {
out = append(out, open)
}
out = append(out, data[pos:]...)
return out
}
// injectMismatchedCloser swaps a closing '}' for ']' (or vice versa).
// The grammar generator always pairs '{' with '}' and '[' with ']'; this
// operator produces the cross-type mismatch class ([{...}] → [{...]}) that
// stresses blockEnd's open/close pairing logic.
func injectMismatchedCloser(r *rand.Rand, data []byte) []byte {
closers := findStructuralBytes(data, '}', ']')
if len(closers) == 0 {
return data
}
idx := closers[r.Intn(len(closers))]
out := make([]byte, len(data))
copy(out, data)
if out[idx] == '}' {
out[idx] = ']'
} else {
out[idx] = '}'
}
return out
}
// =============================================================================
// Adversarial key-path generator
// =============================================================================
// genKeyPath returns a variadic key path that targets known-dangerous
// dereference sites: empty strings (the SYS-REQ-111 hazard), [N] array-index
// syntax (the SYS-REQ-110 Set array-index-beyond-length hazard), out-of-range
// indices, and deeply-nested paths.
func genKeyPath(r *rand.Rand) []string {
n := 1 + r.Intn(4) // 1..4 components
path := make([]string, n)
for i := range path {
path[i] = genPathComponent(r)
}
return path
}
// genPathComponent returns a single adversarial path component.
func genPathComponent(r *rand.Rand) string {
switch r.Intn(12) {
case 0: // empty string (SYS-REQ-111 hazard — the 8th-panic class)
return ""
case 1: // valid array index in range
return "[" + strconv.Itoa(r.Intn(5)) + "]"
case 2: // out-of-range array index (SYS-REQ-110 hazard)
return "[99]"
case 3: // very large array index
return "[999999]"
case 4: // malformed array index syntax (empty brackets)
return "[]"
case 5: // negative index
return "[-1]"
case 6: // unicode key
return "すびほ"
case 7: // key with a byte requiring JSON escaping in output
return "a\"b"
case 8: // "key" (matches seed corpus)
return "key"
case 9: // "a" (common test key)
return "a"
case 10: // long ASCII key
return "abcdefghij"
default: // single ASCII char
return string(rune('a' + r.Intn(26)))
}
}
// injectPathHazard randomly injects an adversarial path component into an
// existing path. This implements the injectEmptyKeyComponent and
// injectOobArrayIndex operators from the spec.
func injectPathHazard(r *rand.Rand, path []string) []string {
switch r.Intn(3) {
case 0: // injectEmptyKeyComponent — append "" to the path
out := make([]string, len(path)+1)
copy(out, path)
out[len(path)] = ""
return out
case 1: // injectOobArrayIndex — append "[99]" to the path
out := make([]string, len(path)+1)
copy(out, path)
out[len(path)] = "[99]"
return out
default: // replace with a grammar-generated adversarial path
return genKeyPath(r)
}
}
// =============================================================================
// Enhanced path-shape checker (catches nested D6 divergences)
// =============================================================================
// containerIs reports whether data's first non-whitespace byte equals open.
// Used to check whether a JSON value is an object ('{') or array ('[').
func containerIs(data []byte, open byte) bool {