Skip to content

DAG-CBOR doesn't reject non-string map keys — violates DAG-CBOR spec #24

Description

@sumanjeet0012

The DAG-CBOR specification requires all map keys to be strings. _prepare_for_cbor() passes through non-string keys without validation, producing invalid DAG-CBOR output.

Problem

In dag/codecs/dag_cbor.py:

def _prepare_for_cbor(node: Any) -> Any:
    if is_cid(node):
        cid_bytes = node.buffer
        return cbor2.CBORTag(_CID_CBOR_TAG, _MULTIBASE_IDENTITY + cid_bytes)

    if isinstance(node, dict):
        return {k: _prepare_for_cbor(v) for k, v in node.items()}
        # ← Non-string keys are passed through without validation
    # ...

The DAG-CBOR spec states:

"Map keys MUST be strings. No other types are allowed as map keys."

This means:

# This should raise an error, but doesn't:
encode({1: "value"})        # Integer key — invalid
encode({(1, 2): "value"})   # Tuple key — invalid
encode({b"bytes": "value"}) # Bytes key — invalid

Proposed Solution

Add validation in _prepare_for_cbor():

def _prepare_for_cbor(node: Any) -> Any:
    if is_cid(node):
        cid_bytes = node.buffer
        return cbor2.CBORTag(_CID_CBOR_TAG, _MULTIBASE_IDENTITY + cid_bytes)

    if isinstance(node, dict):
        for k in node.keys():
            if not isinstance(k, str):
                raise ValueError(
                    f"DAG-CBOR map keys must be strings, got {type(k).__name__}: {k!r}"
                )
        return {k: _prepare_for_cbor(v) for k, v in node.items()}

    # ...

Add tests verifying that non-string keys raise ValueError.

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions