Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raising MemcacheIllegalInputError when key contains null byte, newline, or carriage return #138

Merged
merged 10 commits into from
Feb 18, 2017
23 changes: 19 additions & 4 deletions pymemcache/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,27 @@ def _check_key(key, allow_unicode_keys, key_prefix=b''):
except (UnicodeEncodeError, UnicodeDecodeError):
raise MemcacheIllegalInputError("Non-ASCII key: '%r'" % (key,))
key = key_prefix + key
if b' ' in key or b'\n' in key:
raise MemcacheIllegalInputError(
"Key contains space and/or newline: '%r'" % (key,)
)

if len(key) > 250:
raise MemcacheIllegalInputError("Key is too long: '%r'" % (key,))

for c in bytearray(key):
if c == ord(b' '):
raise MemcacheIllegalInputError(
"Key contains space: '%r'" % (key,)
)
elif c == ord(b'\n'):
raise MemcacheIllegalInputError(
"Key contains newline: '%r'" % (key,)
)
elif c == ord(b'\00'):
raise MemcacheIllegalInputError(
"Key contains null character: '%r'" % (key,)
)
elif c == ord(b'\r'):
raise MemcacheIllegalInputError(
"Key contains carriage return: '%r'" % (key,)
)
return key


Expand Down
38 changes: 37 additions & 1 deletion pymemcache/test/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,42 @@ def _set():
with pytest.raises(MemcacheUnknownError):
_set()

def test_set_key_with_space(self):
client = self.make_client([b''])

def _set():
client.set(b'key has space', b'value', noreply=False)

with pytest.raises(MemcacheIllegalInputError):
_set()

def test_set_key_with_newline(self):
client = self.make_client([b''])

def _set():
client.set(b'key\n', b'value', noreply=False)

with pytest.raises(MemcacheIllegalInputError):
_set()

def test_set_key_with_carriage_return(self):
client = self.make_client([b''])

def _set():
client.set(b'key\r', b'value', noreply=False)

with pytest.raises(MemcacheIllegalInputError):
_set()

def test_set_key_with_null_character(self):
client = self.make_client([b''])

def _set():
client.set(b'key\00', b'value', noreply=False)

with pytest.raises(MemcacheIllegalInputError):
_set()

def test_set_many_socket_handling(self):
client = self.make_client([b'STORED\r\n'])
result = client.set_many({b'key': b'value'}, noreply=False)
Expand Down Expand Up @@ -664,7 +700,7 @@ def test_too_long_unicode_key(self):
with pytest.raises(MemcacheClientError):
client.get(u'\u0FFF'*150)

def test_key_contains_spae(self):
def test_key_contains_space(self):
client = self.make_client([b'END\r\n'])
with pytest.raises(MemcacheClientError):
client.get(b'abc xyz')
Expand Down