Skip to content

Commit e263d8d

Browse files
committed
fix(jsonrpc): report JSON contents even on incomplete/malformed responses
- Sets Content-Type: application/json before switching/parsing the request body. - Removes redundant branch-specific assignments. - Adds a regression test for malformed single-object input.
1 parent 2cbf0a5 commit e263d8d

2 files changed

Lines changed: 10 additions & 3 deletions

File tree

internal/jsonrpc/batchcalls_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,15 @@ func TestJSONRPCMalformedBatchReturnsParseErrorObject(t *testing.T) {
157157
requireRPCError(t, decodeRPCResponse(t, rr.Body.Bytes()), nil, JSONRPC_PARSE_ERROR)
158158
}
159159

160+
func TestJSONRPCMalformedObjectReturnsJSONContentType(t *testing.T) {
161+
s := newBatchTestService()
162+
rr := serveRPC(t, s, []byte(`{"jsonrpc":"2.0"`))
163+
164+
require.Equal(t, http.StatusOK, rr.Code)
165+
require.Equal(t, "application/json", rr.Header().Get("Content-Type"))
166+
requireRPCError(t, decodeRPCResponse(t, rr.Body.Bytes()), nil, JSONRPC_PARSE_ERROR)
167+
}
168+
160169
func TestJSONRPCBatchMalformedElementDoesNotPoisonValidSiblings(t *testing.T) {
161170
s := newBatchTestService()
162171
body := []byte(`[

internal/jsonrpc/jsonrpc.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ func (s *Service) handleRPC(w http.ResponseWriter, r *http.Request) {
331331
}
332332

333333
budgetResp := newBudgetWriter(w, MAX_RESPONSE_SIZE)
334+
w.Header().Set("Content-Type", "application/json")
334335

335336
switch body[0] {
336337
case '{':
@@ -339,12 +340,10 @@ func (s *Service) handleRPC(w http.ResponseWriter, r *http.Request) {
339340
s.writeRPCError(w, nil, JSONRPC_PARSE_ERROR, "invalid request")
340341
return
341342
}
342-
w.Header().Set("Content-Type", "application/json")
343343
s.Logger.Info("Dispatching RPC request", "method", truncatedMethod(req.Method))
344344
s.dispatchOneRequest(w, r, req, budgetResp)
345345

346346
case '[':
347-
w.Header().Set("Content-Type", "application/json")
348347
var reqSeq []json.RawMessage
349348
if err := json.Unmarshal(body, &reqSeq); err != nil {
350349
s.writeRPCError(w, nil, JSONRPC_PARSE_ERROR, "invalid request batch")
@@ -401,7 +400,6 @@ func (s *Service) handleRPC(w http.ResponseWriter, r *http.Request) {
401400
s.writeByte(w, ']')
402401

403402
default:
404-
w.Header().Set("Content-Type", "application/json")
405403
if json.Valid(body) {
406404
s.writeRPCError(w, nil, JSONRPC_INVALID_REQUEST, "invalid request")
407405
} else {

0 commit comments

Comments
 (0)