omnet
aien-dev/omnet
Brought by drakestapleton
omnet / om / json / test / oracle / main.go
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Test-only oracle: encoding/json and actual tailscale.com v1.102.0 tailcfg types. |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "math/rand/v2" |
| 12 | "os" |
| 13 | "regexp" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "tailscale.com/tailcfg" |
| 17 | ) |
| 18 | |
| 19 | type token struct { fields [7]uint64; data []byte } |
| 20 | type parser struct { dec *json.Decoder; tok []token; used int } |
| 21 | func (p *parser) value(parent, key uint64, depth int) error { |
| 22 | if len(p.tok) == 4095 { return fmt.Errorf("tokens") } |
| 23 | v, err := p.dec.Token(); if err != nil { return err } |
| 24 | id := len(p.tok)+1 |
| 25 | t := token{fields:[7]uint64{0,uint64(p.used),0,uint64(id+1),parent,0,key}} |
| 26 | switch x:=v.(type) { |
| 27 | case json.Delim: |
| 28 | if x!='{' && x!='[' { return fmt.Errorf("delimiter") } |
| 29 | if depth == 32 { return fmt.Errorf("depth") } |
| 30 | t.fields[0]=1; if x=='[' {t.fields[0]=2} |
| 31 | p.tok=append(p.tok,t) |
| 32 | seen:=map[string]bool{} |
| 33 | for p.dec.More() { |
| 34 | if x=='{' { |
| 35 | if len(seen)==256{return fmt.Errorf("members")} |
| 36 | k,err:=p.dec.Token(); if err!=nil{return err}; s,ok:=k.(string); if !ok{return fmt.Errorf("key")} |
| 37 | if seen[s] {return fmt.Errorf("duplicate")}; seen[s]=true |
| 38 | if len(p.tok)==4095{return fmt.Errorf("tokens")} |
| 39 | kid:=len(p.tok)+1 |
| 40 | p.tok=append(p.tok,token{[7]uint64{3,uint64(p.used),uint64(len(s)),uint64(kid+1),uint64(id),0,1},[]byte(s)}) |
| 41 | p.used+=len(s); if p.used>65536{return fmt.Errorf("bytes")} |
| 42 | p.tok[id-1].fields[5]++ |
| 43 | } |
| 44 | if err:=p.value(uint64(id),0,depth+1);err!=nil{return err} |
| 45 | p.tok[id-1].fields[5]++ |
| 46 | } |
| 47 | close,err:=p.dec.Token(); if err!=nil{return err} |
| 48 | want:=json.Delim('}'); if x=='['{want=']'}; if close!=want{return fmt.Errorf("close")} |
| 49 | p.tok[id-1].fields[3]=uint64(len(p.tok)+1) |
| 50 | return nil |
| 51 | case string: t.fields[0]=3; t.data=[]byte(x) |
| 52 | case json.Number: t.fields[0]=4; t.data=[]byte(x.String()) |
| 53 | case bool: t.fields[0]=6; if x {t.fields[0]=5} |
| 54 | case nil: t.fields[0]=7 |
| 55 | default: return fmt.Errorf("unexpected token") |
| 56 | } |
| 57 | t.fields[2]=uint64(len(t.data)); p.used+=len(t.data) |
| 58 | if p.used>65536{return fmt.Errorf("bytes")} |
| 59 | p.tok=append(p.tok,t) |
| 60 | return nil |
| 61 | } |
| 62 | func (p *parser) encoded(id int) []byte { |
| 63 | t:=p.tok[id-1] |
| 64 | switch t.fields[0] { |
| 65 | case 1,2: |
| 66 | obj:=t.fields[0]==1; var b bytes.Buffer |
| 67 | if obj {b.WriteByte('{')} else {b.WriteByte('[')} |
| 68 | i:=id+1 |
| 69 | for i<int(t.fields[3]) { |
| 70 | if i>id+1 {b.WriteByte(',')} |
| 71 | if obj {s,_:=json.Marshal(string(p.tok[i-1].data));b.Write(s);b.WriteByte(':');i++} |
| 72 | b.Write(p.encoded(i));i=int(p.tok[i-1].fields[3]) |
| 73 | } |
| 74 | if obj {b.WriteByte('}')} else {b.WriteByte(']')};return b.Bytes() |
| 75 | case 3: b,_:=json.Marshal(string(t.data));return b |
| 76 | case 4:return t.data |
| 77 | case 5:return []byte("true") |
| 78 | case 6:return []byte("false") |
| 79 | default:return []byte("null") |
| 80 | } |
| 81 | } |
| 82 | var uintRE=regexp.MustCompile(`^(0|[1-9][0-9]*)$`) |
| 83 | var intRE=regexp.MustCompile(`^-?(0|[1-9][0-9]*)$`) |
| 84 | func expected(mode string, raw []byte) string { |
| 85 | switch mode { |
| 86 | case "P": |
| 87 | if len(raw)==0 || len(raw)>65536{return "E"} |
| 88 | p:=parser{dec:json.NewDecoder(bytes.NewReader(raw))};p.dec.UseNumber() |
| 89 | if p.value(0,0,0)!=nil{return "E"} |
| 90 | if _,e:=p.dec.Token();e!=io.EOF{return "E"} |
| 91 | h:=uint64(14695981039346656037) |
| 92 | for _,t:=range p.tok {for _,v:=range t.fields{h=(h^v)*1099511628211};for _,v:=range t.data{h=(h^uint64(v))*1099511628211}} |
| 93 | b:=p.encoded(1);encoded:=hex.EncodeToString(b);if len(b)>65536{encoded="!"} |
| 94 | return fmt.Sprintf("O %d %s",h,encoded) |
| 95 | case "Q": |
| 96 | b,_:=json.Marshal(string(raw));if len(b)>65536{return "E"};return "O "+hex.EncodeToString(b) |
| 97 | case "U": |
| 98 | if !uintRE.Match(raw){return "E"};var v uint64;if json.Unmarshal(raw,&v)!=nil{return "E"};return "O "+strconv.FormatUint(v,10) |
| 99 | case "I": |
| 100 | if !intRE.Match(raw){return "E"};var v int64;if json.Unmarshal(raw,&v)!=nil{return "E"};return "O "+strconv.FormatInt(v,10) |
| 101 | } |
| 102 | panic(mode) |
| 103 | } |
| 104 | type row struct { Class string `json:"class"`; Mode string `json:"mode"`; Hex string `json:"hex"`; Want string `json:"want"` } |
| 105 | var enc=json.NewEncoder(os.Stdout) |
| 106 | func emit(class,mode string,raw []byte){if len(raw)>65536{panic("oversized driver record")};if err:=enc.Encode(row{class,mode,hex.EncodeToString(raw),expected(mode,raw)});err!=nil{panic(err)}} |
| 107 | func typed(name,raw string,v any){if err:=json.Unmarshal([]byte(raw),v);err!=nil{panic(fmt.Sprintf("%s: %v",name,err))};emit("tailcfg-"+name,"P",[]byte(raw));b,e:=json.Marshal(v);if e!=nil{panic(e)};emit("tailcfg-"+name+"-marshal","P",b)} |
| 108 | func tailcfgCases(){ |
| 109 | nk:="nodekey:"+strings.Repeat("01",32) |
| 110 | base:=`"Version":106,"NodeKey":"`+nk+`"` |
| 111 | typed("init-begin",`{`+base+`,"GenesisAUM":"AAECA/8="}`,&tailcfg.TKAInitBeginRequest{}) |
| 112 | typed("init-finish",`{`+base+`,"Signatures":{"9007199254740993":"AAE=","9223372036854775807":null},"SupportDisablement":""}`,&tailcfg.TKAInitFinishRequest{}) |
| 113 | typed("bootstrap",`{`+base+`,"Head":""}`,&tailcfg.TKABootstrapRequest{}) |
| 114 | typed("sync-offer",`{`+base+`,"Head":"A","Ancestors":["B","C"]}`,&tailcfg.TKASyncOfferRequest{}) |
| 115 | typed("sync-send",`{`+base+`,"Head":"A","MissingAUMs":["AAE=",null,""],"Interactive":true}`,&tailcfg.TKASyncSendRequest{}) |
| 116 | typed("disable",`{`+base+`,"Head":"A","DisablementSecret":"AAE="}`,&tailcfg.TKADisableRequest{}) |
| 117 | typed("sign",`{`+base+`,"Signature":"AAE="}`,&tailcfg.TKASubmitSignatureRequest{}) |
| 118 | typed("affected",`{`+base+`,"KeyID":"AAE="}`,&tailcfg.TKASignaturesUsingKeyRequest{}) |
| 119 | typed("begin-response",`{"NeedSignatures":[{"NodeID":9007199254740993,"NodePublic":"`+nk+`","RotationPubkey":"AAE="}]}`,&tailcfg.TKAInitBeginResponse{}) |
| 120 | typed("bootstrap-response",`{"GenesisAUM":"AAE=","DisablementSecret":"AAE="}`,&tailcfg.TKABootstrapResponse{}) |
| 121 | typed("offer-response",`{"Head":"A","Ancestors":["B"],"MissingAUMs":["AAE=",null,""]}`,&tailcfg.TKASyncOfferResponse{}) |
| 122 | typed("send-response",`{"Head":"A"}`,&tailcfg.TKASyncSendResponse{}) |
| 123 | typed("affected-response",`{"Signatures":["AAE=",null,""]}`,&tailcfg.TKASignaturesUsingKeyResponse{}) |
| 124 | typed("finish-response",`{}`,&tailcfg.TKAInitFinishResponse{}) |
| 125 | typed("disable-response",`{}`,&tailcfg.TKADisableResponse{}) |
| 126 | typed("sign-response",`{}`,&tailcfg.TKASubmitSignatureResponse{}) |
| 127 | typed("map-info",`{"Head":"A","Disabled":true}`,&tailcfg.TKAInfo{}) |
| 128 | typed("case-insensitive",`{"vErSiOn":106,"nodekey":"`+nk+`","GenesisAUM":null}`,&tailcfg.TKAInitBeginRequest{}) |
| 129 | typed("byte-array",`{`+base+`,"GenesisAUM":[0,1,2,255]}`,&tailcfg.TKAInitBeginRequest{}) |
| 130 | typed("null-optionals",`{"Version":null,"NodeKey":null,"Head":null,"Ancestors":null}`,&tailcfg.TKASyncOfferRequest{}) |
| 131 | typed("escaped-key",`{"\u0056ersion":106,"NodeKey":"`+nk+`","GenesisAUM":"AA\nE="}`,&tailcfg.TKAInitBeginRequest{}) |
| 132 | typed("unknown-field",`{`+base+`,"GenesisAUM":"","Future":{"x":[1,true,null]}}`,&tailcfg.TKAInitBeginRequest{}) |
| 133 | for _,field:=range []string{`"Version":1.0`,`"Version":9223372036854775808`,`"GenesisAUM":true`,`"GenesisAUM":"?"`,`"GenesisAUM":[256]`,`"NodeKey":"bad"`} { |
| 134 | raw:=[]byte(`{`+field+`}`);var v tailcfg.TKAInitBeginRequest |
| 135 | if json.Unmarshal(raw,&v)==nil{panic("expected typed rejection")} |
| 136 | emit("tailcfg-syntax-not-schema","P",raw) |
| 137 | } |
| 138 | } |
| 139 | func randomBytes(r *rand.Rand, n int) []byte { b:=make([]byte,n);for i:=range b{b[i]=byte(r.Uint64())};return b } |
| 140 | func randomValue(r *rand.Rand, depth int) any { |
| 141 | k:=r.IntN(7);if depth==4{k=r.IntN(5)} |
| 142 | switch k { |
| 143 | case 0:return nil |
| 144 | case 1:return r.IntN(2)==1 |
| 145 | case 2:return json.Number(fmt.Sprintf("%d",r.Uint64())) |
| 146 | case 3:return json.Number(fmt.Sprintf("-%de-%d",r.IntN(100000),r.IntN(1000))) |
| 147 | case 4:return string(randomBytes(r,r.IntN(40))) |
| 148 | case 5:a:=make([]any,r.IntN(6));for i:=range a{a[i]=randomValue(r,depth+1)};return a |
| 149 | default:a:=map[string]any{};for i:=range r.IntN(6){a[fmt.Sprintf("key%d",i)]=randomValue(r,depth+1)};return a |
| 150 | } |
| 151 | } |
| 152 | func main(){ |
| 153 | tailcfgCases() |
| 154 | valid:=[]string{`null`,`true`,`false`,`0`,`-0`,`18446744073709551615`,`-9223372036854775808`,`9007199254740993`,`1.234567890123456789e+999999`,`[]`,`{}`,`{"a":[],"b":{},"c":[1,{"d":2}],"e":false}`,`"\"\\\/\b\f\n\r\t"`,`"\u0000\u001f\u007f"`,`"\ud800\udc00\udbff\udfff"`,`"\ud800x\udc00\ud800\ud800"`,`"\u2028\u2029<>&"`,`"\uD834\uDd1E"`,`{"A":1,"a":2}`," \r\n\t[1, 2]\n"} |
| 155 | for _,s:=range valid{emit("grammar","P",[]byte(s))} |
| 156 | invalid:=[]string{""," ","+1","01","-01","--1","1.",".1","1e","1e+","1e-","NaN","Infinity","truefalse","null null","[1,]","[,1]","[1 2]","{,}","{\"a\":}","{\"a\":1,}","{1:2}","{\"a\" 2}","{\"a\":1 \"b\":2}","\"\\x00\"","\"\\u12\"","\"\\uZZZZ\"","\"a\nb\"","\"","\"abc\\","[","{","\ufeff{}","\x00","[true,false,null}",`"\ud800\u12xx"`} |
| 157 | for _,s:=range invalid{emit("malformed","P",[]byte(s))} |
| 158 | for _,s:=range []string{`{"a":1,"a":2}`,`{"a":1,"\u0061":2}`,`{"x":{"a":1,"a":2}}`,`{"\ud800":0,"\udc00":1}`,`{"a":{},"a":[]}`} {emit("duplicate-policy","P",[]byte(s))} |
| 159 | for i:=range 256 {emit("byte-quote","Q",[]byte{byte(i)});emit("byte-string","P",[]byte{'"',byte(i),'"'})} |
| 160 | for _,b:=range [][]byte{{0xc0,0x80},{0xe0,0x80,0x80},{0xed,0xa0,0x80},{0xf4,0x90,0x80,0x80},{0xf0,0x80,0x80,0x80},{0xe2,0x82},{0xef,0xbf,0xbd},{0xf0,0x90,0x80,0x80},{0xf4,0x8f,0xbf,0xbf}} {emit("utf8","Q",b);emit("utf8","P",append(append([]byte{'"'},b...), '"'))} |
| 161 | for _,s:=range []string{"0","-0","1","-1","9007199254740993","18446744073709551615","18446744073709551616","9223372036854775807","9223372036854775808","-9223372036854775808","-9223372036854775809","","00","01","-01","+1","1e0","1.0"," 1","1 ","--1",strings.Repeat("9",65536)} {emit("integer","U",[]byte(s));emit("integer","I",[]byte(s))} |
| 162 | for _,n:=range []int{31,32,33}{emit("depth-bound","P",[]byte(strings.Repeat("[",n)+"0"+strings.Repeat("]",n)))} |
| 163 | for _,n:=range []int{4093,4094,4095}{emit("token-bound","P",[]byte("["+strings.Repeat("0,",n-1)+"0]"))} |
| 164 | for _,n:=range []int{255,256,257}{ |
| 165 | fields:=make([]string,n);for i:=range fields{fields[i]=fmt.Sprintf(`"key%03d":0`,i)} |
| 166 | obj:="{"+strings.Join(fields,",")+"}" |
| 167 | emit("member-bound","P",[]byte(obj)) |
| 168 | emit("nested-member-bound","P",[]byte(`{"nested":`+obj+`}`)) |
| 169 | } |
| 170 | fields:=make([]string,256);for i:=range fields{fields[i]=fmt.Sprintf(`"%s%03x":0`,strings.Repeat("a",247),i)} |
| 171 | worst:="{"+strings.Join(fields,",")+"}" |
| 172 | worst+=strings.Repeat(" ",65536-len(worst)) |
| 173 | emit("member-long-prefix","P",[]byte(worst)) |
| 174 | for _,n:=range []int{65533,65534}{emit("message-bound","P",[]byte(`"`+strings.Repeat("a",n)+`"`))} |
| 175 | emit("message-bound","P",[]byte(strings.Repeat(" ",65535)+"0")) |
| 176 | emit("message-bound","P",[]byte(strings.Repeat(" ",65536))) |
| 177 | for _,n:=range []int{21845,21846}{emit("decoded-bound","P",append(append([]byte{'"'},bytes.Repeat([]byte{255},n)...),'"'))} |
| 178 | emit("writer-bound","Q",bytes.Repeat([]byte{0},65536)) |
| 179 | emit("writer-bound","P",[]byte(`"`+strings.Repeat("<",12000)+`"`)) |
| 180 | r:=rand.New(rand.NewPCG(1020,2119)) |
| 181 | for range 2000 { |
| 182 | b,e:=json.Marshal(randomValue(r,0));if e!=nil{panic(e)};emit("random-valid","P",b) |
| 183 | if len(b)>0{c:=append([]byte(nil),b...);c[r.IntN(len(c))]=byte(r.IntN(256));emit("random-mutation","P",c)} |
| 184 | } |
| 185 | for range 1000{b:=randomBytes(r,r.IntN(100));emit("random-bytes","P",b);emit("random-quote","Q",b)} |
| 186 | for range 500{v:=r.Uint64();emit("random-integer","U",[]byte(strconv.FormatUint(v,10)));emit("random-integer","I",[]byte(strconv.FormatInt(int64(v),10)))} |
| 187 | } |