goccy / go-json

Fast JSON encoder/decoder compatible with encoding/json for Go
MIT License
3.11k stars 148 forks source link

[BUG] runtime error: slice bounds out of range [23:21] while escaping #507

Open alexey-slivkin opened 6 months ago

alexey-slivkin commented 6 months ago

Problem: panic while escaping.

Example:

package main

import (
    "encoding/json"
    "fmt"
    goccy "github.com/goccy/go-json"
    "log"
)

func main() {

    rawData := []byte(`{"steps": [{"config":{"message": "Fail 
<"}}]}`)

    type config struct {
        Steps []struct {
            Config json.RawMessage `json:"config"`
        }
    }

    v1 := config{}

    if err := json.Unmarshal(rawData, &v1); err != nil {
        log.Fatal(err)
    }

    dataFromSTD, err := json.Marshal(v1) // {"Steps":[{"config":{"message":"Fail \u2028\u003c"}}]}
    if err != nil {
        log.Fatal(err)
    }

    v2 := config{}
    if err := goccy.Unmarshal(rawData, &v2); err != nil {
        log.Fatal(err)
    }

    // https://github.com/goccy/go-json/blob/master/internal/encoder/compact.go#L208
    dataFromGOCCY, err := goccy.Marshal(v1) // panic: runtime error: slice bounds out of range [23:21]
    if err != nil {
        log.Fatal(err)
    }

    if string(dataFromSTD) == string(dataFromGOCCY) {
        fmt.Println("OK")
        return
    }

    log.Fatal("diff")
}

Original: main.txt

Result:

panic: runtime error: slice bounds out of range [23:21]

goroutine 1 [running]:
github.com/goccy/go-json/internal/encoder.compactString({0x140000e6000?, 0x0?, 0x220000000000?}, {0x140000da060, 0x19, 0x30}, 0x400?, 0x1)
        /Users/test/projects/goccy-test/vendor/github.com/goccy/go-json/internal/encoder/compact.go:208 +0x6a8

Expected result:

OK

It seems this problem is being solved in https://github.com/goccy/go-json/pull/479/files