Skip to content

Crashes on getting non-text non-UTF8 values #30

@ulidtko

Description

@ulidtko

Consul KV does not guarantee that values are text at all. (Even less so, in any particular encoding, e.g. UTF-8)

Steps to reproduce

~> export CONSUL_HTTP_ADDR=...
~>
~> printf '\x00\x01\x02\x03\x04\x05\xde' > nontext.data
~> curl -X PUT $CONSUL_HTTP_ADDR/v1/kv/nontext-test --data-binary @nontext.data
true⏎
~> curl -X GET $CONSUL_HTTP_ADDR/v1/kv/nontext-test
[{"LockIndex":0,"Key":"nontext-test","Flags":0,"Value":"AAECAwQF3g==","CreateIndex":13723496,"ModifyIndex":13724362}]⏎
~>
~> echo 'AAECAwQF3g==' | base64 -d | hexdump -C
00000000  00 01 02 03 04 05 de                              |.......|
00000007

⬆️ using curl with Consul's HTTP API directly, we've written the binary data byte array [0, 1, 2, 3, 4, 5, 222] to a key /nontext-test, and read it back. This is as expected 🟢 👌

Notice it's not text data! And that's completely fine, Consul KV supports that.

Yet, the python library crashes 💥 if we try to read it:

>>> import consul_kv, os
>>> 
>>> c = consul_kv.Connection(endpoint=os.getenv('CONSUL_HTTP_ADDR') + '/v1')
>>> 
>>> c.get('nontext-test')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/tmp/venv/lib/python3.10/site-packages/consul_kv/__init__.py", line 94, in get
    return get_kv(
  File "/tmp/venv/lib/python3.10/site-packages/consul_kv/api.py", line 135, in get_kv_raw
    return postprocessor(result)
  File "/tmp/venv/lib/python3.10/site-packages/consul_kv/api.py", line 148, in <lambda>
    lambda x: {
  File "/tmp/venv/lib/python3.10/site-packages/consul_kv/api.py", line 151, in <dictcomp>
    r['Key']: b64decode(r['Value']).decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xde in position 6: unexpected end of data

This code is wrong:

r['Key']: b64decode(r['Value']).decode('utf-8')

because it explicitly assumes that the b64-encoded data is always utf-8 text — while Consul provides no such guarantee.

Docs: https://developer.hashicorp.com/consul/api-docs/kv

[Response]
Value is a base64-encoded blob of data.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions