Skip to content

Commit e6650bf

Browse files
committed
pgproto3: hex-decode CopyData.Data in UnmarshalJSON
MarshalJSON encodes Data with hex.EncodeToString but UnmarshalJSON did []byte(msg.Data), so round-tripping any CopyData with non-text bytes through JSON would silently corrupt the payload (e.g. [0x01 0x02 0xff] came back as the literal bytes for the string "0102ff"). Now mirrors the marshal side with hex.DecodeString, with the empty-Data shortcut preserved so the existing TestJSONUnmarshalCopyData fixture still unmarshals to []byte{}. Added a round-trip test. Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
1 parent 5e5c1a2 commit e6650bf

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

pgproto3/copy_data.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ func (dst *CopyData) UnmarshalJSON(data []byte) error {
5454
return err
5555
}
5656

57-
dst.Data = []byte(msg.Data)
57+
if msg.Data == "" {
58+
dst.Data = []byte{}
59+
return nil
60+
}
61+
b, err := hex.DecodeString(msg.Data)
62+
if err != nil {
63+
return err
64+
}
65+
dst.Data = b
5866
return nil
5967
}

pgproto3/json_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,25 @@ func TestJSONUnmarshalCopyData(t *testing.T) {
172172
}
173173
}
174174

175+
func TestJSONRoundTripCopyData(t *testing.T) {
176+
want := CopyData{
177+
Data: []byte{0x00, 0x01, 0x02, 0xff, 'h', 'i'},
178+
}
179+
180+
b, err := json.Marshal(want)
181+
if err != nil {
182+
t.Fatalf("marshal: %v", err)
183+
}
184+
185+
var got CopyData
186+
if err := json.Unmarshal(b, &got); err != nil {
187+
t.Fatalf("unmarshal: %v", err)
188+
}
189+
if !reflect.DeepEqual(got, want) {
190+
t.Errorf("round-trip mismatch:\n want: %v\n got: %v", want.Data, got.Data)
191+
}
192+
}
193+
175194
func TestJSONUnmarshalCopyInResponse(t *testing.T) {
176195
data := []byte(`{"Type":"CopyBothResponse", "OverallFormat": "W"}`)
177196
want := CopyBothResponse{

0 commit comments

Comments
 (0)