Skip to content

Commit

Permalink
Added verification for response ids in jsonrpc protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
azebell committed Aug 15, 2021
1 parent caaef86 commit 4481aa6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions tests/test_jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,24 @@ def test_parsing_invalid_arguments(prot):
),
])
def test_good_reply_samples(prot, data, id, result):
# assume the protocol is awaiting a response for
# a request with `id`
prot._incomplete_requests = [id]

reply = prot.parse_reply(data)

assert reply.unique_id == id
assert reply.result == result


@pytest.mark.parametrize(('data'), [
"""{"jsonrpc": "2.0", "result": 19, "id": 9001}"""
])
def test_unsolicited_reply_raises_error(prot, data):
prot._incomplete_requests = [4]
with pytest.raises(InvalidReplyError):
reply = prot.parse_reply(data)

@pytest.mark.parametrize(('exc', 'code', 'message'), [
(JSONRPCParseError, -32700, 'Parse error'),
(JSONRPCInvalidRequestError, -32600, 'Invalid Request'),
Expand Down
8 changes: 8 additions & 0 deletions tinyrpc/protocols/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,7 @@ def __init__(
) -> None:
super(JSONRPCProtocol, self).__init__(*args, **kwargs)
self._id_generator = id_generator
self._incomplete_requests = []

def _get_unique_id(self) -> object:
return next(self._id_generator)
Expand Down Expand Up @@ -573,6 +574,7 @@ def create_request(

if not one_way:
request.unique_id = self._get_unique_id()
self._incomplete_requests.append(request.unique_id)

request.method = method
if args is not None:
Expand Down Expand Up @@ -634,6 +636,12 @@ def parse_reply(
response.result = rep.get('result', None)

response.unique_id = rep['id']
if response.unique_id not in self._incomplete_requests:
raise InvalidReplyError(
'Reply id does not correspond to any sent requests.'
)
else:
self._incomplete_requests.remove(response.unique_id)

return response

Expand Down

0 comments on commit 4481aa6

Please sign in to comment.