Skip to content

Commit 408f487

Browse files
committed
Catch KeyError for TYPE_TYPE missing in message
Added additional resiliency to the network protocol, such that if an entirely garbled message is sent to the server (such as making a test connection with nc and sending random characters), the protocol parser reports that the message is invalid rather than producing KeyError due to not being able to locate a message type. Fixes: #4 Change-Id: I4839af0dc30fa1d6682129e60c13f9685fd845cf
1 parent b7c8bdc commit 408f487

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

sqlalchemy_collectd/protocol.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,12 @@ def __init__(self, *types):
261261

262262
def receive(self, buf):
263263
result = self._unpack_packet(buf)
264-
type_name = result[TYPE_TYPE]
264+
try:
265+
type_name = result[TYPE_TYPE]
266+
except KeyError:
267+
log.warn("Message did not have TYPE_TYPE block, skipping")
268+
return None
269+
265270
type_ = None
266271
try:
267272
type_ = self._types[type_name]

sqlalchemy_collectd/tests/test_protocol.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,24 @@ def test_decode_packet(self):
8181
},
8282
result,
8383
)
84+
85+
def test_decode_unknown_type(self):
86+
type_ = protocol.Type(
87+
"my_type",
88+
("some_val", protocol.VALUE_GAUGE),
89+
("some_other_val", protocol.VALUE_DERIVE),
90+
)
91+
92+
message_receiver = protocol.MessageReceiver(type_)
93+
with mock.patch.object(protocol, "log") as log:
94+
result = message_receiver.receive(b"asdfjq34kt2n34kjnas")
95+
self.assertEqual(result, None)
96+
self.assertEqual(
97+
log.mock_calls,
98+
[
99+
mock.call.warn("Message %s not known, skipping", mock.ANY),
100+
mock.call.warn(
101+
"Message did not have TYPE_TYPE block, skipping"
102+
),
103+
],
104+
)

unreleased_changes/4.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
.. change::
2+
:tags: bug, protocl
3+
:tickets: 4
4+
5+
Added additional resiliency to the network protocol, such that if an
6+
entirely garbled message is sent to the server (such as making a test
7+
connection with nc and sending random characters), the protocol parser
8+
reports that the message is invalid rather than producing KeyError due to
9+
not being able to locate a message type.

0 commit comments

Comments
 (0)