oficina / suite Public

Clone
git clone https://amadan.net/oficina/suite

Plain git — no account needed to clone.

Download

Download this file

1package suite
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "strings"
9)
10
11// rejectAmbiguousJSON refuses a body whose meaning depends on which duplicate
12// wins.
13//
14// encoding/json resolves a duplicate object key by keeping the last one, and
15// matches field names case-insensitively, so a sibling can send
16// `{"result":"NOT_VISIBLE","result":"VISIBLE"}` — or spell the second one
17// `RESULT` — and the value that survives is not the one a reader of the bytes
18// would expect. That defeats every check made *after* decoding, including S2's
19// duplicate-row rule: the duplicate is gone before the rule can see it.
20//
21// Keys are folded to lower case before comparison because that is how
22// encoding/json matches them. Two keys differing only in case are therefore
23// treated as the same key, which is the safe reading and costs nothing: no
24// call in this contract has two fields whose names differ only by case.
25func rejectAmbiguousJSON(data []byte) error {
26 dec := json.NewDecoder(bytes.NewReader(data))
27 if err := scanUnique(dec); err != nil {
28 return err
29 }
30 // Anything after the first complete value means the body is two documents
31 // wearing one Content-Length, and which one is "the" answer is a guess.
32 // The end is io.EOF from one more Token, never Decoder.More: More answers
33 // false in front of a stray ']' or '}', so `{...}]` passed as one
34 // document (Fable, review of c38e3ad, L6; the server package had already
35 // learned this from Astra, 2026-11-01).
36 if _, err := dec.Token(); err != io.EOF {
37 return fmt.Errorf("suite: trailing content after the JSON document")
38 }
39 return nil
40}
41
42func scanUnique(dec *json.Decoder) error {
43 tok, err := dec.Token()
44 if err != nil {
45 return err
46 }
47
48 delim, isDelim := tok.(json.Delim)
49 if !isDelim {
50 return nil // a scalar; nothing nested to check
51 }
52
53 switch delim {
54 case '{':
55 seen := make(map[string]bool)
56 for dec.More() {
57 keyTok, err := dec.Token()
58 if err != nil {
59 return err
60 }
61 key, ok := keyTok.(string)
62 if !ok {
63 return fmt.Errorf("suite: object key is not a string")
64 }
65 folded := strings.ToLower(key)
66 if seen[folded] {
67 return fmt.Errorf("suite: duplicate object key %q", key)
68 }
69 seen[folded] = true
70
71 if err := scanUnique(dec); err != nil {
72 return err
73 }
74 }
75 case '[':
76 for dec.More() {
77 if err := scanUnique(dec); err != nil {
78 return err
79 }
80 }
81 }
82
83 _, err = dec.Token() // the matching close
84 return err
85}
86