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

Fix non-string map keys check in decode_dag_cbor #17

Merged
merged 1 commit into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion pytests/test_dag_cbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,22 @@ def _dag_cbor_roundtrip(benchmark, data) -> None:
assert obj == decoded, f'{obj} != {decoded}'


def test_dag_cbor_decode_duplicate_keys() -> None:
def test_dag_cbor_decode_duplicate_keys_error() -> None:
with pytest.raises(ValueError) as exc_info:
# {"abc": 1, "abc": 2}
libipld.decode_dag_cbor(bytes.fromhex('a263616263016361626302'))

assert 'Duplicate keys are not allowed' in str(exc_info.value)


def test_dag_cbor_decode_non_string_key_error() -> None:
with pytest.raises(ValueError) as exc_info:
# {1:2}
libipld.decode_dag_cbor(bytes.fromhex('A10102'))

assert 'Map keys must be strings' in str(exc_info.value)


@pytest.mark.parametrize('data', load_data_fixtures(_ROUNDTRIP_DATA_DIR), ids=lambda data: data[0])
def test_dag_cbor_encode(benchmark, data) -> None:
_dag_cbor_encode(benchmark, data)
Expand Down
10 changes: 9 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,15 @@ fn decode_dag_cbor_to_pyobject<R: Read + Seek>(py: Python, r: &mut R, deep: usiz
let len = decode_len(decode::read_uint(r, major)?)?;
let dict = PyDict::new(py);
for _ in 0..len {
let key = decode_dag_cbor_to_pyobject(py, r, deep + 1)?;
// DAG-CBOR keys are always strings
let key_major = decode::read_major(r)?;
if key_major.kind() != MajorKind::TextString {
return Err(anyhow::anyhow!("Map keys must be strings"));
}

let key_len = decode::read_uint(r, key_major)?;
let key = decode::read_str(r, key_len)?.to_object(py);

let value = decode_dag_cbor_to_pyobject(py, r, deep + 1)?;

if dict.get_item(&key)?.is_some() {
Expand Down
Loading