gunk-dev/the-valley

exactjson.go

source6a6791929c36main's published tip history
12.0 KiB
1// Package exactjson decodes one JSON document into a Go value, and first
2// refuses any key that the value's type does not name exactly.
3//
4// encoding/json matches an object key to a struct field without regard to
5// case, and DisallowUnknownFields does not change that. cue keeps keys that
6// differ only in case apart, and so does Nix. A CUE document may reopen a
7// definition of the schema it is checked against, and add a field to it.
8// So a document can carry Grants beside an empty grants, and encoding/json
9// reads the first into the second: a reviewer reading the canonical field
10// sees nothing, and the program reads a grant.
11//
12// A key that appears twice in one object is the same problem in another
13// form. encoding/json keeps the last of two values, and merges two objects
14// read into one map or struct, so a reader of the first sees less than the
15// program reads.
16//
17// The check also refuses an array or object that the value's type cannot
18// hold, before it reads inside it, and arrays and objects nested past
19// MaxDepth. So a malformed document costs the check no more than the part
20// of it read before the refusal, however deeply it nests.
21//
22// The package depends on the standard library alone.
23package exactjson
24
25import (
26 "bytes"
27 "encoding/json"
28 "errors"
29 "fmt"
30 "io"
31 "reflect"
32 "strings"
33)
34
35// MaxDepth is how deeply arrays and objects may nest in a value Decode or
36// Check reads. The value's own array or object is one deep, and an array
37// or object inside it two. It is far deeper than any document the valley
38// reads nests. encoding/json stops at 10000.
39const MaxDepth = 1000
40
41// Decode decodes data into v, which must be a non-nil pointer. Before it
42// decodes anything, it reads every object in data, at every depth, and
43// refuses:
44//
45// - a key of an object read into a struct that is not the name a json
46// tag of that struct gives, spelled exactly;
47// - a key that appears twice in one object;
48// - an array read into a type that is not a slice or an array, or an
49// object read into a type that is not a struct or a map;
50// - arrays and objects nested more than MaxDepth deep;
51// - anything after the first JSON value.
52//
53// It refuses an array or object of the wrong kind before it reads inside
54// it, so a document that is refused reads no further than the value that
55// is refused.
56//
57// A struct field takes a key only through the name its json tag gives, so
58// a field with no tag name takes none. The keys of an object read into a
59// map, an interface or a type that decodes itself, such as a
60// json.RawMessage, are data, and any key passes: a map's values are held
61// to its element type, and an interface's or a json.RawMessage's are
62// checked for repeated keys and depth alone.
63//
64// Decode does not read embedded structs. encoding/json reads the fields of
65// a struct embedded with no json tag name as fields of the struct that
66// embeds it, chosen by Go's rules for selecting a field, and the check
67// does not follow those rules. So Decode refuses any object read into a
68// struct that embeds a struct, or a pointer to one, with no json tag name.
69// A struct embedded under a json tag name is an ordinary field.
70func Decode(data []byte, v any) error {
71 t := reflect.TypeOf(v)
72 if t == nil || t.Kind() != reflect.Pointer {
73 return &json.InvalidUnmarshalError{Type: t}
74 }
75 dec := json.NewDecoder(bytes.NewReader(data))
76 // The check reads numbers as written, so a number the decode reads
77 // into an int64 or a json.Number is not refused for overflowing a
78 // float64.
79 dec.UseNumber()
80 if err := Check(dec, t); err != nil {
81 return err
82 }
83 if _, err := dec.Token(); err != io.EOF {
84 return errors.New("the document holds more than one JSON value")
85 }
86 dec = json.NewDecoder(bytes.NewReader(data))
87 dec.DisallowUnknownFields()
88 err := dec.Decode(v)
89 var mismatch *json.UnmarshalTypeError
90 if errors.As(err, &mismatch) {
91 return &kindError{
92 said: fmt.Sprintf("%s is %s, where %s belongs", locate(data, t, mismatch.Offset), written(mismatch.Value), want(mismatch.Type)),
93 err: mismatch,
94 }
95 }
96 return err
97}
98
99// kindError is a value of the wrong kind, said in words. encoding/json's
100// error stays beneath it, for errors.As.
101type kindError struct {
102 said string
103 err *json.UnmarshalTypeError
104}
105
106func (e *kindError) Error() string { return e.said }
107func (e *kindError) Unwrap() error { return e.err }
108
109// locate is where the value that ends offset bytes into data is, written
110// as the check writes a path. encoding/json names the value of a type
111// mismatch by a path of its own, which differs between Go releases, so
112// the check walks the document again and names the value it finds there.
113func locate(data []byte, t reflect.Type, offset int64) string {
114 dec := json.NewDecoder(bytes.NewReader(data))
115 dec.UseNumber()
116 found := "a value"
117 c := &checker{tokens: dec}
118 c.scalar = func() {
119 if dec.InputOffset() == offset {
120 found = c.where()
121 }
122 }
123 _ = c.check(t)
124 return found
125}
126
127// want is the kind of JSON value a value of type t is read from, in
128// words. A refusal says it rather than naming t, so what a reader of a
129// document is told does not change when a Go type is renamed or moved.
130func want(t reflect.Type) string {
131 if t == reflect.TypeFor[json.Number]() {
132 return "a number"
133 }
134 switch t.Kind() {
135 case reflect.Pointer:
136 return want(t.Elem())
137 case reflect.Struct, reflect.Map:
138 return "an object"
139 case reflect.Slice, reflect.Array:
140 return "an array"
141 case reflect.String:
142 return "a string"
143 case reflect.Bool:
144 return "a boolean"
145 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
146 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
147 return "a whole number"
148 case reflect.Float32, reflect.Float64:
149 return "a number"
150 }
151 return "another kind of value"
152}
153
154// written is the JSON value encoding/json names in a type mismatch, in
155// words: "string", "bool", "array", "object", or "number" with the number
156// itself when it is one the type cannot hold.
157func written(value string) string {
158 switch {
159 case value == "bool":
160 return "a boolean"
161 case value == "array" || value == "object":
162 return "an " + value
163 case strings.HasPrefix(value, "number "):
164 return "the number " + strings.TrimPrefix(value, "number ")
165 }
166 return "a " + value
167}
168
169// Tokens is a stream of JSON tokens, as a *json.Decoder reads them.
170type Tokens interface {
171 Token() (json.Token, error)
172 More() bool
173}
174
175// Check reads one JSON value from tokens, and holds it to t, the type the
176// value is decoded into, by the rules Decode holds a document to: a key of
177// an object read into a struct is the name a json tag of that struct
178// gives, spelled exactly, no key appears twice in one object, every array
179// and object is read into a type that holds one, and no array or object
180// is nested more than MaxDepth deep. It reads nothing after the value.
181//
182// Check is for a caller that decodes with a token reader of its own, such
183// as one that stops when a context is cancelled. Such a caller checks the
184// value with Check first, and decodes it only when Check passes it. A
185// token reader that reads numbers as json.Number keeps a number that
186// overflows a float64 from failing the check.
187func Check(tokens Tokens, t reflect.Type) error {
188 return (&checker{tokens: tokens}).check(t)
189}
190
191var (
192 anything = reflect.TypeFor[any]()
193 unmarshaler = reflect.TypeFor[json.Unmarshaler]()
194)
195
196// checker reads one value from tokens. path holds a step for each array
197// and object the value being read is in, so its length is the value's
198// depth, and the value's place is written out only for an error.
199type checker struct {
200 tokens Tokens
201 path []step
202
203 // scalar, when set, is called after each value that is not an array
204 // or an object is read.
205 scalar func()
206}
207
208// step is where a value is in the array or object that holds it: at index
209// in an array, or under key in an object, with an index of -1. field is
210// true when the object is read into a struct, so key names a field.
211type step struct {
212 index int
213 key string
214 field bool
215}
216
217// check reads one value, and holds every array and object in it to t,
218// the type the value is decoded into.
219func (c *checker) check(t reflect.Type) error {
220 for t.Kind() == reflect.Pointer {
221 t = t.Elem()
222 }
223 // The check cannot tell how a type that decodes itself reads its
224 // value, so it reads the value as encoding/json reads one into an
225 // interface.
226 if reflect.PointerTo(t).Implements(unmarshaler) {
227 t = anything
228 }
229 tok, err := c.tokens.Token()
230 if err != nil {
231 return err
232 }
233 switch tok {
234 case json.Delim('['):
235 if len(c.path) == MaxDepth {
236 return tooDeep()
237 }
238 var elem reflect.Type
239 switch t.Kind() {
240 case reflect.Slice, reflect.Array:
241 elem = t.Elem()
242 case reflect.Interface:
243 elem = t
244 default:
245 return fmt.Errorf("%s is an array, where %s belongs", c.where(), want(t))
246 }
247 for i := 0; c.tokens.More(); i++ {
248 c.path = append(c.path, step{index: i})
249 if err := c.check(elem); err != nil {
250 return err
251 }
252 c.path = c.path[:len(c.path)-1]
253 }
254 case json.Delim('{'):
255 if len(c.path) == MaxDepth {
256 return tooDeep()
257 }
258 var fields map[string]reflect.Type
259 switch t.Kind() {
260 case reflect.Struct:
261 if fields, err = tagged(t); err != nil {
262 return fmt.Errorf("%s is read into %w", c.where(), err)
263 }
264 case reflect.Map, reflect.Interface:
265 default:
266 return fmt.Errorf("%s is an object, where %s belongs", c.where(), want(t))
267 }
268 seen := map[string]bool{}
269 for c.tokens.More() {
270 tok, err := c.tokens.Token()
271 if err != nil {
272 return err
273 }
274 key := tok.(string)
275 if seen[key] {
276 return fmt.Errorf("%s holds the key %q twice", c.where(), key)
277 }
278 seen[key] = true
279 elem := t
280 switch t.Kind() {
281 case reflect.Struct:
282 var ok bool
283 if elem, ok = fields[key]; !ok {
284 return unknown(c.where(), key, fields)
285 }
286 case reflect.Map:
287 elem = t.Elem()
288 }
289 c.path = append(c.path, step{index: -1, key: key, field: t.Kind() == reflect.Struct})
290 if err := c.check(elem); err != nil {
291 return err
292 }
293 c.path = c.path[:len(c.path)-1]
294 }
295 default:
296 if c.scalar != nil {
297 c.scalar()
298 }
299 return nil
300 }
301 // The closing delimiter.
302 _, err = c.tokens.Token()
303 return err
304}
305
306// where names the place of the value being read, for a message: a field
307// of a struct by its key after a dot, a map's or an interface's value by
308// its key in brackets, and an array's element by its index.
309func (c *checker) where() string {
310 if len(c.path) == 0 {
311 return "the document"
312 }
313 var b strings.Builder
314 for _, s := range c.path {
315 switch {
316 case s.index >= 0:
317 fmt.Fprintf(&b, "[%d]", s.index)
318 case s.field && b.Len() > 0:
319 fmt.Fprintf(&b, ".%s", s.key)
320 case s.field:
321 b.WriteString(s.key)
322 default:
323 fmt.Fprintf(&b, "[%q]", s.key)
324 }
325 }
326 return b.String()
327}
328
329// tooDeep is the error for an array or object nested past MaxDepth.
330func tooDeep() error {
331 return fmt.Errorf("the document nests arrays and objects more than %d deep", MaxDepth)
332}
333
334// tagged maps the name each json tag of struct type t gives to the type
335// of its field. Its error is for a t that embeds a struct with no json tag
336// name, which Decode does not read.
337func tagged(t reflect.Type) (map[string]reflect.Type, error) {
338 fields := map[string]reflect.Type{}
339 for i := range t.NumField() {
340 f := t.Field(i)
341 name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
342 embedded := f.Type
343 if embedded.Kind() == reflect.Pointer {
344 embedded = embedded.Elem()
345 }
346 if f.Anonymous && name == "" && embedded.Kind() == reflect.Struct {
347 return nil, fmt.Errorf("%s, which embeds %s, and exactjson reads no embedded struct", t, f.Type)
348 }
349 if name != "" && name != "-" {
350 fields[name] = f.Type
351 }
352 }
353 return fields, nil
354}
355
356// unknown is the error for a key no field of the struct at where names.
357// When the key is a field's name spelled another way, as encoding/json
358// would have matched it, the error names that field too.
359func unknown(where, key string, fields map[string]reflect.Type) error {
360 for name := range fields {
361 if strings.EqualFold(name, key) {
362 return fmt.Errorf("%s holds the key %q, which is its field %q spelled another way", where, key, name)
363 }
364 }
365 return fmt.Errorf("%s holds the key %q, which is none of its fields", where, key)
366}