Skip to content

Commit 7e3c1a8

Browse files
committed
jsonrpc2: decode requests with empty method fields
1 parent 5045d86 commit 7e3c1a8

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

internal/jsonrpc2/messages.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,10 @@ func EncodeIndent(msg Message, prefix, indent string) ([]byte, error) {
172172
}
173173

174174
func DecodeMessage(data []byte) (Message, error) {
175+
fields := map[string]json.RawMessage{}
176+
if err := internaljson.Unmarshal(data, &fields); err != nil {
177+
return nil, fmt.Errorf("unmarshaling jsonrpc message: %w", err)
178+
}
175179
msg := wireCombined{}
176180
if err := internaljson.Unmarshal(data, &msg); err != nil {
177181
return nil, fmt.Errorf("unmarshaling jsonrpc message: %w", err)
@@ -183,8 +187,8 @@ func DecodeMessage(data []byte) (Message, error) {
183187
if err != nil {
184188
return nil, err
185189
}
186-
if msg.Method != "" {
187-
// has a method, must be a call
190+
if _, ok := fields["method"]; ok {
191+
// has a method field, must be a call, even if the method is empty
188192
return &Request{
189193
Method: msg.Method,
190194
ID: id,

internal/jsonrpc2/wire_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,23 @@ func TestWireMessage(t *testing.T) {
6363
}
6464
}
6565

66+
func TestDecodeRequestWithEmptyMethod(t *testing.T) {
67+
msg, err := jsonrpc2.DecodeMessage([]byte(`{"jsonrpc":"2.0","id":5,"method":"","params":{}}`))
68+
if err != nil {
69+
t.Fatal(err)
70+
}
71+
req, ok := msg.(*jsonrpc2.Request)
72+
if !ok {
73+
t.Fatalf("DecodeMessage returned %T, want *jsonrpc2.Request", msg)
74+
}
75+
if req.Method != "" {
76+
t.Fatalf("Request method = %q, want empty string", req.Method)
77+
}
78+
if !req.ID.IsValid() || req.ID.Raw() != int64(5) {
79+
t.Fatalf("Request ID = %#v, want 5", req.ID.Raw())
80+
}
81+
}
82+
6683
func newNotification(method string, params any) jsonrpc2.Message {
6784
msg, err := jsonrpc2.NewNotification(method, params)
6885
if err != nil {

0 commit comments

Comments
 (0)