gunk-dev/the-valley

exactjson_test.go

source1c37c8d22741main's published tip history
12.2 KiB
1package exactjson
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "reflect"
9 "runtime"
10 "strings"
11 "testing"
12)
13
14// A registry-shaped document: a struct at the top, maps of structs, a
15// slice of structs, a pointer, and a field read by nobody.
16type doc struct {
17 Principals map[string]principal `json:"principals"`
18 Genesis string `json:"genesis"`
19 Derived json.RawMessage `json:"derived"`
20 Count int64 `json:"count"`
21}
22
23type principal struct {
24 Keys []key `json:"keys"`
25 Grants map[string]grant `json:"grants"`
26 Notes any `json:"notes"`
27 hidden string
28 Bare string
29}
30
31type key struct {
32 Public string `json:"public"`
33 Proof *proof `json:"proof,omitempty"`
34}
35
36type proof struct {
37 Slot string `json:"slot"`
38}
39
40type grant struct {
41 Boundary string `json:"boundary"`
42}
43
44// A document spelled exactly decodes as encoding/json decodes it. Map keys
45// are data, whatever their case, and so are the keys inside an interface
46// and a json.RawMessage. A number past a float64's range is read only by
47// the decode.
48func TestAnExactDocumentDecodesAsEncodingJSONDoes(t *testing.T) {
49 const data = `{
50 "principals": {
51 "alice": {
52 "keys": [{"public": "k1", "proof": {"slot": "s"}}, {"public": "k2"}],
53 "grants": {"push": {"boundary": "b"}, "Push": {"boundary": "B"}},
54 "notes": {"Anything": [{"goes": 1}]}
55 },
56 "Alice": {"keys": [], "grants": {}}
57 },
58 "genesis": "alice",
59 "derived": {"Grants": [1, {"x": 2}]},
60 "count": 9007199254740993
61 }`
62 var got, want doc
63 if err := Decode([]byte(data), &got); err != nil {
64 t.Fatal(err)
65 }
66 if err := json.Unmarshal([]byte(data), &want); err != nil {
67 t.Fatal(err)
68 }
69 if !reflect.DeepEqual(got, want) {
70 t.Errorf("Decode read %+v, encoding/json %+v", got, want)
71 }
72}
73
74// Every key a struct does not name exactly is refused, at every depth,
75// before anything is decoded. encoding/json would have read each of the
76// spellings below into the field it folds to, under Unicode's simple case
77// folding: ſ folds to s, and the Kelvin sign to k.
78func TestAKeyNotSpelledExactlyIsRefused(t *testing.T) {
79 for _, c := range []struct{ name, data, says string }{
80 {"a field in another case, beside the field",
81 `{"principals": {"alice": {"grants": {}, "Grants": {"push": {"boundary": "b"}}}}}`,
82 `principals["alice"] holds the key "Grants", which is its field "grants" spelled another way`},
83 {"at the top",
84 `{"genesis": "alice", "GENESIS": "mallory"}`,
85 `the document holds the key "GENESIS", which is its field "genesis" spelled another way`},
86 {"in a map's struct value",
87 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "Boundary": "b"}}}}}`,
88 `principals["alice"].grants["push"] holds the key "Boundary", which is its field "boundary" spelled another way`},
89 {"in a slice's element",
90 `{"principals": {"alice": {"keys": [{"public": "k1"}, {"public": "k2", "Public": "k3"}]}}}`,
91 `principals["alice"].keys[1] holds the key "Public", which is its field "public" spelled another way`},
92 {"behind a pointer",
93 `{"principals": {"alice": {"keys": [{"public": "k1", "proof": {"sLot": "s"}}]}}}`,
94 `principals["alice"].keys[0].proof holds the key "sLot", which is its field "slot" spelled another way`},
95 {"folded beyond ASCII",
96 `{"principals": {"alice": {"grantſ": {"push": {"boundary": "b"}}}}}`,
97 `principals["alice"] holds the key "grantſ", which is its field "grants" spelled another way`},
98 {"with the Kelvin sign",
99 "{\"principals\": {\"alice\": {\"Keys\": []}}}",
100 `principals["alice"] holds the key "` + "K" + `eys", which is its field "keys" spelled another way`},
101 {"a field no tag names",
102 `{"principals": {"alice": {"Bare": "x"}}}`,
103 `principals["alice"] holds the key "Bare", which is none of its fields`},
104 {"an unexported field",
105 `{"principals": {"alice": {"hidden": "x"}}}`,
106 `principals["alice"] holds the key "hidden", which is none of its fields`},
107 {"a field nobody declared",
108 `{"genesis": "alice", "extra": true}`,
109 `the document holds the key "extra", which is none of its fields`},
110 } {
111 var d doc
112 err := Decode([]byte(c.data), &d)
113 if err == nil || err.Error() != c.says {
114 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
115 }
116 if !reflect.DeepEqual(d, doc{}) {
117 t.Errorf("%s: a refused document decoded %+v", c.name, d)
118 }
119 }
120}
121
122// A key that appears twice in one object is refused wherever the object
123// is, a map's and a raw value's included, and however the key is escaped.
124// So is anything after the document.
125func TestAKeyTwiceOrASecondDocumentIsRefused(t *testing.T) {
126 for _, c := range []struct{ name, data, says string }{
127 {"at the top",
128 `{"principals": {}, "principals": {"mallory": {}}}`,
129 `the document holds the key "principals" twice`},
130 {"in a map",
131 `{"principals": {"alice": {}, "alice": {"grants": {"push": {"boundary": "b"}}}}}`,
132 `principals holds the key "alice" twice`},
133 {"in a struct in a map",
134 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "boundary": "b"}}}}}`,
135 `principals["alice"].grants["push"] holds the key "boundary" twice`},
136 {"escaped",
137 `{"genesis": "alice", "\u0067enesis": "mallory"}`,
138 `the document holds the key "genesis" twice`},
139 {"in a raw value",
140 `{"derived": [{"a": 1, "a": 2}]}`,
141 `derived[0] holds the key "a" twice`},
142 {"in an interface",
143 `{"principals": {"alice": {"notes": {"n": {"x": 1, "x": 2}}}}}`,
144 `principals["alice"].notes["n"] holds the key "x" twice`},
145 {"a second document",
146 `{"genesis": "alice"} {"genesis": "mallory"}`,
147 `the document holds more than one JSON value`},
148 } {
149 var d doc
150 if err := Decode([]byte(c.data), &d); err == nil || err.Error() != c.says {
151 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
152 }
153 }
154 if err := Decode([]byte(`{}`), doc{}); err == nil || !strings.Contains(err.Error(), "non-pointer") {
155 t.Errorf("Decode into a value: %v", err)
156 }
157}
158
159// Structs that embed a struct, as a value, as a pointer, and under a json
160// tag name.
161type embeds struct {
162 grant
163 Name string `json:"name"`
164}
165
166type embedsPointer struct {
167 *grant
168}
169
170type embedsTagged struct {
171 Extra `json:"extra"`
172}
173
174type Extra struct {
175 Slot string `json:"slot"`
176}
177
178// encoding/json reads the fields of an embedded struct as the embedding
179// struct's own, and Decode does not follow it there: it refuses any
180// object read into a struct that embeds one, at any depth, whatever the
181// object holds. A struct embedded under a json tag name is an ordinary
182// field.
183func TestAnEmbeddedStructIsRefused(t *testing.T) {
184 var e embeds
185 if err := json.Unmarshal([]byte(`{"boundary": "b"}`), &e); err != nil || e.Boundary != "b" {
186 t.Fatalf("encoding/json read %+v, %v", e, err)
187 }
188 for _, c := range []struct {
189 name, data, says string
190 v any
191 }{
192 {"a struct", `{"boundary": "b"}`,
193 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
194 &embeds{}},
195 {"an empty object", `{}`,
196 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
197 &embeds{}},
198 {"a pointer, in a map", `{"push": {"boundary": "b"}}`,
199 `["push"] is read into exactjson.embedsPointer, which embeds *exactjson.grant, and exactjson reads no embedded struct`,
200 &map[string]embedsPointer{}},
201 } {
202 if err := Decode([]byte(c.data), c.v); err == nil || err.Error() != c.says {
203 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, c.v, err, c.says)
204 }
205 }
206 var tagged embedsTagged
207 if err := Decode([]byte(`{"extra": {"slot": "s"}}`), &tagged); err != nil || tagged.Slot != "s" {
208 t.Errorf("a struct embedded under a tag name: Decode read %+v, %v", tagged, err)
209 }
210 if err := Decode([]byte(`{"slot": "s"}`), &embedsTagged{}); err == nil {
211 t.Errorf("a struct embedded under a tag name: Decode read its field's key as the embedding struct's")
212 }
213}
214
215// An array or object read into a type that holds none is refused where it
216// is, before anything inside it is read. encoding/json would refuse each
217// of these too, but only after reading the whole document.
218func TestAContainerOfTheWrongKindIsRefused(t *testing.T) {
219 for _, c := range []struct{ name, data, says string }{
220 {"an array for the document",
221 `[{"genesis": "alice"}]`,
222 `the document is an array, and exactjson.doc holds no array`},
223 {"an array for a map",
224 `{"principals": [{"keys": []}]}`,
225 `principals is an array, and map[string]exactjson.principal holds no array`},
226 {"an object for a string",
227 `{"genesis": {"Genesis": "alice"}}`,
228 `genesis is an object, and string holds no object`},
229 {"an object for a slice",
230 `{"principals": {"alice": {"keys": {"public": "k1"}}}}`,
231 `principals["alice"].keys is an object, and []exactjson.key holds no object`},
232 {"an array for a number",
233 `{"count": [1]}`,
234 `count is an array, and int64 holds no array`},
235 {"an array behind a pointer",
236 `{"principals": {"alice": {"keys": [{"public": "k1", "proof": []}]}}}`,
237 `principals["alice"].keys[0].proof is an array, and exactjson.proof holds no array`},
238 } {
239 var d doc
240 if err := Decode([]byte(c.data), &d); err == nil || err.Error() != c.says {
241 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
242 }
243 if err := json.Unmarshal([]byte(c.data), &doc{}); err == nil {
244 t.Errorf("%s: encoding/json reads the document", c.name)
245 }
246 }
247}
248
249// Arrays and objects may nest MaxDepth deep, counting the document's own,
250// and no deeper. Only a raw value or an interface nests freely enough to
251// reach the bound.
252func TestNestingPastMaxDepthIsRefused(t *testing.T) {
253 nested := func(depth int) string {
254 return `{"derived": ` + strings.Repeat("[", depth-1) + strings.Repeat("]", depth-1) + `}`
255 }
256 var d doc
257 if err := Decode([]byte(nested(MaxDepth)), &d); err != nil {
258 t.Errorf("a document %d deep: %v", MaxDepth, err)
259 }
260 says := fmt.Sprintf("the document nests arrays and objects more than %d deep", MaxDepth)
261 if err := Decode([]byte(nested(MaxDepth+1)), &d); err == nil || err.Error() != says {
262 t.Errorf("a document %d deep: Decode read %v, not %q", MaxDepth+1, err, says)
263 }
264 var v any
265 if err := Decode([]byte(strings.Repeat(`{"a":`, MaxDepth)+"1"+strings.Repeat("}", MaxDepth)), &v); err != nil {
266 t.Errorf("objects %d deep in an interface: %v", MaxDepth, err)
267 }
268 if err := Decode([]byte(strings.Repeat(`{"a":`, MaxDepth+1)+"1"+strings.Repeat("}", MaxDepth+1)), &v); err == nil || err.Error() != says {
269 t.Errorf("objects %d deep in an interface: Decode read %v, not %q", MaxDepth+1, err, says)
270 }
271}
272
273// counted counts the bytes read from r.
274type counted struct {
275 r io.Reader
276 n int
277}
278
279func (c *counted) Read(p []byte) (int, error) {
280 n, err := c.r.Read(p)
281 c.n += n
282 return n, err
283}
284
285// A million brackets around null is refused at the first bracket the type
286// cannot hold, or at the bracket past MaxDepth, whichever comes first.
287// The check reads no further than that, and what it holds while it reads
288// grows with the depth it reaches, not with the document.
289func TestDeepBracketsAreRefusedEarly(t *testing.T) {
290 const n = 1 << 20
291 brackets := strings.Repeat("[", n) + "null" + strings.Repeat("]", n)
292 deep := fmt.Sprintf("the document nests arrays and objects more than %d deep", MaxDepth)
293 for _, c := range []struct {
294 name, data, says string
295 v any
296 }{
297 {"a struct", brackets,
298 `the document is an array, and exactjson.doc holds no array`, &doc{}},
299 {"a slice of structs", brackets,
300 `[0] is an array, and exactjson.doc holds no array`, &[]doc{}},
301 {"an interface", brackets, deep, new(any)},
302 {"a raw value", brackets, deep, &json.RawMessage{}},
303 {"a raw value in a struct", `{"derived": ` + brackets + `}`, deep, &doc{}},
304 } {
305 in := []byte(c.data)
306 r := &counted{r: bytes.NewReader(in)}
307 if err := Check(json.NewDecoder(r), reflect.TypeOf(c.v)); err == nil || err.Error() != c.says {
308 t.Errorf("%s: Check read %v, not %q", c.name, err, c.says)
309 }
310 if r.n > 64<<10 {
311 t.Errorf("%s: Check read %d bytes of %d", c.name, r.n, len(in))
312 }
313 var before, after runtime.MemStats
314 runtime.ReadMemStats(&before)
315 if err := Decode(in, c.v); err == nil || err.Error() != c.says {
316 t.Errorf("%s: Decode read %v, not %q", c.name, err, c.says)
317 }
318 runtime.ReadMemStats(&after)
319 if grew := after.TotalAlloc - before.TotalAlloc; grew > 1<<20 {
320 t.Errorf("%s: Decode allocated %d bytes", c.name, grew)
321 }
322 }
323}