Debian Codegraph @

server/parser_fuzz_test.go

raw
1 // Copyright 2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "sync"
18 "testing"
19 )
20
21 func dummyFuzzClient(kind int) *client {
22 var r *route
23 var gw *gateway
24 var lf *leaf
25
26 switch kind {
27 case ROUTER:
28 r = &route{}
29 case GATEWAY:
30 gw = &gateway{outbound: false, connected: true, insim: make(map[string]*insie), outsim: &sync.Map{}}
31 case LEAF:
32 lf = &leaf{}
33 }
34
35 return &client{
36 srv: func() *Server {
37 opts := defaultServerOptions
38 return New(&opts)
39 }(),
40 kind: kind,
41 msubs: -1,
42 in: readCache{
43 results: make(map[string]*SublistResult),
44 pacache: make(map[string]*perAccountCache),
45 },
46 mpay: MAX_PAYLOAD_SIZE,
47 mcl: MAX_CONTROL_LINE_SIZE,
48 route: r,
49 gw: gw,
50 leaf: lf,
51 }
52 }
53
54 // FuzzParser performs fuzz testing on the NATS protocol parser implementation.
55 // It tests the parser's ability to handle various NATS protocol messages, including
56 // partial (chunked) message delivery scenarios that may occur in real-world usage.
57 func FuzzParser(f *testing.F) {
58 msgs := []string{
59 "PING\r\n",
60 "PONG\r\n",
61 "PUB foo 33333\r\n",
62 "HPUB foo INBOX.22 0 5\r\nHELLO\r",
63 "HMSG $foo foo 10 8\r\nXXXhello\r",
64 "MSG $foo foo 5\r\nhello\r",
65 "SUB foo 1\r\nSUB foo 2\r\n",
66 "UNSUB 1 5\r\n",
67 "RMSG $G foo.bar | baz 11\r\nhello world\r",
68 "CONNECT {\"verbose\":false,\"pedantic\":true,\"tls_required\":false}\r\n",
69 }
70
71 clientKinds := []int{
72 CLIENT,
73 ROUTER,
74 GATEWAY,
75 LEAF,
76 }
77
78 for _, ck := range clientKinds {
79 for _, crp := range msgs {
80 f.Add(ck, crp)
81 }
82 }
83
84 f.Fuzz(func(t *testing.T, kind int, orig string) {
85 c := dummyFuzzClient(kind)
86
87 data := []byte(orig)
88 half := len(data) / 2
89
90 if err := c.parse(data[:half]); err != nil {
91 return
92 }
93
94 if err := c.parse(data[half:]); err != nil {
95 return
96 }
97 })
98 }