interplane.Get Omega
Read in your language

omnet

aien-dev/omnet

Brought by drakestapleton

branch main Branches Tags History

omnet / om / json / README.md

143 lines · 9545 bytes Raw Blame History Rendered
1# Bounded JSON
2
3`json.om` is an Omega-only, global-free JSON parser and encoder for the daemon's raw TKA requests.
4It has no dependencies on another unit. Concatenate it before callers. Parsing is iterative, not
5recursive, and retains exact number lexemes rather than converting through floating point.
6
7## Limits and policy
8
9- Input, decoded string/number arena, and output each have a separate 65,536-byte capacity.
10- At most 4,095 tokens, counting object keys and container tokens. At most 32 nested containers.
11 Scalars inside the 32nd container are accepted. A string of 65,534 ASCII bytes fits as one input
12 string; decoded replacement characters can expand invalid input beyond the arena limit.
13- At most 256 members per object, independently at every nesting level. The attempted 257th key
14 is rejected before its decoding or duplicate scan. This intentionally rejects larger objects
15 that Go accepts. It bounds the quadratic duplicate-key scan; the daemon's 64-node signature
16 map fits this profile. Arrays remain governed by the overall token bound.
17- All JSON grammar is checked, including number grammar, matching delimiters, separators, control
18 characters, escapes, and the absence of a second root value or trailing non-whitespace bytes.
19- Strings follow Go `encoding/json`: UTF-16 surrogate pairs combine; lone surrogates become U+FFFD;
20 invalid UTF-8 is replaced one offending byte at a time. Embedded U+0000 is preserved with an
21 explicit length. Valid UTF-8 and literal Unicode are retained.
22- **Duplicate decoded object keys are rejected in every object.** This intentionally differs from
23 Go's last-value/merge behavior. Escape aliases (`"a"` and `"\u0061"`), invalid UTF-8 aliases and
24 lone-surrogate aliases therefore cannot overwrite one another. Equality is case-sensitive; it
25 does not perform Unicode normalization. Callers implementing Go's case-insensitive struct-field
26 lookup must additionally reject aliases of the same known field. `jsonfind` is exact-case only.
27- This unit checks JSON syntax, not the TKA schema. For example `{"GenesisAUM":true}` is valid JSON
28 but is not a valid `tailcfg.TKAInitBeginRequest`. The daemon must enforce field types, required
29 fields, case aliases, integer destination widths and codec-specific limits. Byte arrays/base64,
30 node keys and AUM hashes are decoded by their existing codec/model units.
31
32Bound violations return errors, never attacker-triggered traps. Callers must provide the fixed-size
33arrays named in the signatures, use distinct input/arena/token/output arrays, and discard partial
34output on failure. Token accessors and `jsonencode` require an unmodified table and arena from a
35successful `jsonparse`; a forged token table is a caller contract violation. Only `tok[0]` is valid
36following a failed parse (it is zero). Other data is scratch and may contain partial results.
37
38## Parsing API
39
40`jsonparse(raw view uchar 65536, n ulong, tok edit ulong 32768,
41 dec edit uchar 65536) -> int`
42
43Returns zero on success, otherwise: 1 syntax, 2 input/decoded-byte bound, 3 token bound,
444 depth bound, 5 duplicate key, 6 object-member bound. Empty input is rejected. No I/O or global state is used.
45
46`tok[0]` is the token count. Root id is 1; zero is the absent-id sentinel. Header slots 1..7
47are reserved. Token `id` starts at `id * 8`, with these fields:
48
49| Offset | Meaning |
50|---|---|
51| 0 | Kind: 1 object, 2 array, 3 string, 4 number, 5 true, 6 false, 7 null |
52| 1 | Offset into `dec` for decoded string or raw number lexeme |
53| 2 | Byte length; zero for containers, booleans and null |
54| 3 | Id immediately after the entire subtree |
55| 4 | Parent container id; zero at root |
56| 5 | Direct-child count; includes both keys and values for objects |
57| 6 | 1 for an object key, otherwise 0 |
58| 7 | Internal parser phase; callers must not inspect it |
59
60Children are preorder. An object's children alternate key, value; a key is always a string token
61and its value starts at `key_id + 1`. Use a value's subtree-next field to advance to the next key.
62
63- `jsonfind(tok, dec, obj ulong, key view uchar 65536, n ulong) -> ulong`: exact decoded key lookup;
64 returns the value id or zero. Only direct members of `obj` are searched.
65- `jsoncopy(tok, dec, id ulong, out edit uchar 65536) -> ulong`: copies the token's string/number
66 bytes, returning their length; invalid id returns `jsonbad` (65,537).
67- `jsonuint(dec, off ulong, n ulong, result edit ulong 1) -> int`: exact unsigned 64-bit decimal
68 conversion; zero on success. Rejects negative signs, leading zeros, fractions, exponents,
69 whitespace and overflow. Result is zero on failure.
70- `jsonint(dec, off ulong, n ulong, result edit long 1) -> int`: exact signed 64-bit conversion,
71 including -9,223,372,036,854,775,808 and `-0`; same rejection rules except an optional minus.
72
73No number precision is lost: numbers beyond 64-bit range remain valid JSON tokens but fail the
74integer helpers. There is no implicit float conversion or arbitrary exponent computation.
75
76## Encoding API
77
78Every writer returns the next output offset, or `jsonbad` (65,537). That sentinel is sticky through
79further writer calls. No writer terminates output with a NUL. Capacity is checked before access;
80an error can leave a partial prefix, which must not be sent. Writer helpers do not maintain a JSON
81syntax state: punctuation/field sequencing is the caller's responsibility.
82
83- `jsonbyte(out edit uchar 65536, pos ulong, byte uchar) -> ulong`
84- `jsonraw(out, pos, src view uchar 65536, n ulong) -> ulong`
85- `jsonspan(out, pos, src, off ulong, n ulong) -> ulong`
86- `jsonstr(out, pos, src, n ulong) -> ulong`: encode a JSON string, including quotes.
87- `jsonquote(out, pos, src, off ulong, n ulong) -> ulong`: same, for an arena span without a copy.
88- `jsonu64(out, pos, value ulong) -> ulong`
89- `jsoni64(out, pos, value long) -> ulong`
90- `jsonencode(tok view ulong 32768, dec view uchar 65536, out edit uchar 65536) -> ulong`:
91 compactly encode the parsed tree. Retains member order and number spelling. This is not a
92 canonicalization scheme. Output can exceed the input size and fail explicitly.
93
94String output matches Go `json.Marshal(string)`: standard short control escapes, lowercase `\u`
95 hex, HTML escapes for `<`, `>`, and `&`, and escapes for U+2028/U+2029. Invalid UTF-8 becomes the six-character escape `\ufffd`, matching the Go 1.26 encoder the test corpus is generated with; a valid U+FFFD scalar is written as its raw UTF-8 bytes.
96U+FFFD scalar is written the same way, matching Go. Internal helpers all have the
97`json` prefix; callers should use the APIs above.
98
99## Focused tests
100
101```sh
102GO=/path/to/go1.26.8/bin/go sh om/json/test/run.sh
103# Or pass the compiler already verified by tools/omc.sh:
104GO=/path/to/go1.26.8/bin/go sh om/json/test/run.sh /path/to/pinned/omc
105```
106
107The suite builds with the repository-pinned Omega compiler. Go is a **test oracle only** and is
108required for this suite; the module pins `tailscale.com v1.102.0`. Deterministic generated cases
109compare complete token metadata/decoded data (a 64-bit rolling fingerprint), exact output bytes,
110accept/reject behavior and exact signed/unsigned integer results with Go `encoding/json`. The
111oracle uses `Decoder.UseNumber`, independently walks the token stream, and applies only the
112explicit resource bounds and duplicate-key policy above.
113
114Coverage includes all eight actual `tailcfg` request types, their responses, map `TKAInfo`, NodeID
115values above 2^53 and at the signed limit, nil/empty byte values, arrays, maps, case-insensitive
116field decoding, escaped field names, ignored unknown fields, all 256 byte values, malformed and
117boundary UTF-8, surrogate pairs, exact integer limits, malformed grammar, and message/token/depth/
118member/writer bounds. Tests explicitly distinguish valid generic JSON from a typed tailcfg rejection.
119The driver also checks lookup, token copying, offset/length boundaries and sticky writer errors.
120`test/vectors.json` supplies independently authored committed golden cases. Generated Go records
121and compiled test artifacts live in `build/test/json`, not the production unit.
122The member boundary includes 256 accepted and 257 rejected members, both at root and nested.
123A measured smoke sends ten full 65,536-byte messages, each with 256 distinct 250-byte keys sharing
124a 247-byte prefix. It prints actual wall time for parsing, token hashing and encoding together,
125including process startup and pipe I/O; this is not an isolated parser benchmark or a latency SLA.
126
127Six mutants must finish the entire differential run normally and produce at least one wrong
128answer: duplicate acceptance, wrong surrogate replacement, depth and member off-by-ones, integer
129bound, and HTML escaping. A separate trapping mutant must be classified as abnormal, not counted as a
130successful detection. A short output, compiler failure, process signal, trap or timeout fails.
131These are host-only tests and make no stock-client deployment claim.
132
133## Third-party material and notices
134
135No upstream implementation or vector text is copied or translated into this unit. Tests import
136the upstream Go packages through their pinned modules, which retain their own licenses. The
137vectors are independently authored. Format references:
138
139- [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259), especially sections 6 and 7.
140- [Go encoding/json](https://pkg.go.dev/encoding/json).
141- [Pinned tailcfg TKA types](https://github.com/tailscale/tailscale/blob/v1.102.0/tailcfg/tka.go).
142
143References checked against the local pinned sources on 2026-10-25.