| 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. |
| 23 | package exactjson |
| 24 | |
| 25 | import ( |
| 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. |
| 39 | const 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. |
| 70 | func 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 | return dec.Decode(v) |
| 89 | } |
| 90 | |
| 91 | // Tokens is a stream of JSON tokens, as a *json.Decoder reads them. |
| 92 | type Tokens interface { |
| 93 | Token() (json.Token, error) |
| 94 | More() bool |
| 95 | } |
| 96 | |
| 97 | // Check reads one JSON value from tokens, and holds it to t, the type the |
| 98 | // value is decoded into, by the rules Decode holds a document to: a key of |
| 99 | // an object read into a struct is the name a json tag of that struct |
| 100 | // gives, spelled exactly, no key appears twice in one object, every array |
| 101 | // and object is read into a type that holds one, and no array or object |
| 102 | // is nested more than MaxDepth deep. It reads nothing after the value. |
| 103 | // |
| 104 | // Check is for a caller that decodes with a token reader of its own, such |
| 105 | // as one that stops when a context is cancelled. Such a caller checks the |
| 106 | // value with Check first, and decodes it only when Check passes it. A |
| 107 | // token reader that reads numbers as json.Number keeps a number that |
| 108 | // overflows a float64 from failing the check. |
| 109 | func Check(tokens Tokens, t reflect.Type) error { |
| 110 | return (&checker{tokens: tokens}).check(t) |
| 111 | } |
| 112 | |
| 113 | var ( |
| 114 | anything = reflect.TypeFor[any]() |
| 115 | unmarshaler = reflect.TypeFor[json.Unmarshaler]() |
| 116 | ) |
| 117 | |
| 118 | // checker reads one value from tokens. path holds a step for each array |
| 119 | // and object the value being read is in, so its length is the value's |
| 120 | // depth, and the value's place is written out only for an error. |
| 121 | type checker struct { |
| 122 | tokens Tokens |
| 123 | path []step |
| 124 | } |
| 125 | |
| 126 | // step is where a value is in the array or object that holds it: at index |
| 127 | // in an array, or under key in an object, with an index of -1. field is |
| 128 | // true when the object is read into a struct, so key names a field. |
| 129 | type step struct { |
| 130 | index int |
| 131 | key string |
| 132 | field bool |
| 133 | } |
| 134 | |
| 135 | // check reads one value, and holds every array and object in it to t, |
| 136 | // the type the value is decoded into. |
| 137 | func (c *checker) check(t reflect.Type) error { |
| 138 | for t.Kind() == reflect.Pointer { |
| 139 | t = t.Elem() |
| 140 | } |
| 141 | // The check cannot tell how a type that decodes itself reads its |
| 142 | // value, so it reads the value as encoding/json reads one into an |
| 143 | // interface. |
| 144 | if reflect.PointerTo(t).Implements(unmarshaler) { |
| 145 | t = anything |
| 146 | } |
| 147 | tok, err := c.tokens.Token() |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | switch tok { |
| 152 | case json.Delim('['): |
| 153 | if len(c.path) == MaxDepth { |
| 154 | return tooDeep() |
| 155 | } |
| 156 | var elem reflect.Type |
| 157 | switch t.Kind() { |
| 158 | case reflect.Slice, reflect.Array: |
| 159 | elem = t.Elem() |
| 160 | case reflect.Interface: |
| 161 | elem = t |
| 162 | default: |
| 163 | return fmt.Errorf("%s is an array, and %s holds no array", c.where(), t) |
| 164 | } |
| 165 | for i := 0; c.tokens.More(); i++ { |
| 166 | c.path = append(c.path, step{index: i}) |
| 167 | if err := c.check(elem); err != nil { |
| 168 | return err |
| 169 | } |
| 170 | c.path = c.path[:len(c.path)-1] |
| 171 | } |
| 172 | case json.Delim('{'): |
| 173 | if len(c.path) == MaxDepth { |
| 174 | return tooDeep() |
| 175 | } |
| 176 | var fields map[string]reflect.Type |
| 177 | switch t.Kind() { |
| 178 | case reflect.Struct: |
| 179 | if fields, err = tagged(t); err != nil { |
| 180 | return fmt.Errorf("%s is read into %w", c.where(), err) |
| 181 | } |
| 182 | case reflect.Map, reflect.Interface: |
| 183 | default: |
| 184 | return fmt.Errorf("%s is an object, and %s holds no object", c.where(), t) |
| 185 | } |
| 186 | seen := map[string]bool{} |
| 187 | for c.tokens.More() { |
| 188 | tok, err := c.tokens.Token() |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | key := tok.(string) |
| 193 | if seen[key] { |
| 194 | return fmt.Errorf("%s holds the key %q twice", c.where(), key) |
| 195 | } |
| 196 | seen[key] = true |
| 197 | elem := t |
| 198 | switch t.Kind() { |
| 199 | case reflect.Struct: |
| 200 | var ok bool |
| 201 | if elem, ok = fields[key]; !ok { |
| 202 | return unknown(c.where(), key, fields) |
| 203 | } |
| 204 | case reflect.Map: |
| 205 | elem = t.Elem() |
| 206 | } |
| 207 | c.path = append(c.path, step{index: -1, key: key, field: t.Kind() == reflect.Struct}) |
| 208 | if err := c.check(elem); err != nil { |
| 209 | return err |
| 210 | } |
| 211 | c.path = c.path[:len(c.path)-1] |
| 212 | } |
| 213 | default: |
| 214 | return nil |
| 215 | } |
| 216 | // The closing delimiter. |
| 217 | _, err = c.tokens.Token() |
| 218 | return err |
| 219 | } |
| 220 | |
| 221 | // where names the place of the value being read, for a message: a field |
| 222 | // of a struct by its key after a dot, a map's or an interface's value by |
| 223 | // its key in brackets, and an array's element by its index. |
| 224 | func (c *checker) where() string { |
| 225 | if len(c.path) == 0 { |
| 226 | return "the document" |
| 227 | } |
| 228 | var b strings.Builder |
| 229 | for _, s := range c.path { |
| 230 | switch { |
| 231 | case s.index >= 0: |
| 232 | fmt.Fprintf(&b, "[%d]", s.index) |
| 233 | case s.field && b.Len() > 0: |
| 234 | fmt.Fprintf(&b, ".%s", s.key) |
| 235 | case s.field: |
| 236 | b.WriteString(s.key) |
| 237 | default: |
| 238 | fmt.Fprintf(&b, "[%q]", s.key) |
| 239 | } |
| 240 | } |
| 241 | return b.String() |
| 242 | } |
| 243 | |
| 244 | // tooDeep is the error for an array or object nested past MaxDepth. |
| 245 | func tooDeep() error { |
| 246 | return fmt.Errorf("the document nests arrays and objects more than %d deep", MaxDepth) |
| 247 | } |
| 248 | |
| 249 | // tagged maps the name each json tag of struct type t gives to the type |
| 250 | // of its field. Its error is for a t that embeds a struct with no json tag |
| 251 | // name, which Decode does not read. |
| 252 | func tagged(t reflect.Type) (map[string]reflect.Type, error) { |
| 253 | fields := map[string]reflect.Type{} |
| 254 | for i := range t.NumField() { |
| 255 | f := t.Field(i) |
| 256 | name, _, _ := strings.Cut(f.Tag.Get("json"), ",") |
| 257 | embedded := f.Type |
| 258 | if embedded.Kind() == reflect.Pointer { |
| 259 | embedded = embedded.Elem() |
| 260 | } |
| 261 | if f.Anonymous && name == "" && embedded.Kind() == reflect.Struct { |
| 262 | return nil, fmt.Errorf("%s, which embeds %s, and exactjson reads no embedded struct", t, f.Type) |
| 263 | } |
| 264 | if name != "" && name != "-" { |
| 265 | fields[name] = f.Type |
| 266 | } |
| 267 | } |
| 268 | return fields, nil |
| 269 | } |
| 270 | |
| 271 | // unknown is the error for a key no field of the struct at where names. |
| 272 | // When the key is a field's name spelled another way, as encoding/json |
| 273 | // would have matched it, the error names that field too. |
| 274 | func unknown(where, key string, fields map[string]reflect.Type) error { |
| 275 | for name := range fields { |
| 276 | if strings.EqualFold(name, key) { |
| 277 | return fmt.Errorf("%s holds the key %q, which is its field %q spelled another way", where, key, name) |
| 278 | } |
| 279 | } |
| 280 | return fmt.Errorf("%s holds the key %q, which is none of its fields", where, key) |
| 281 | } |