Skip to content

Commit

Permalink
rfc8785: raise CanonicalizationError on nonstr keys (#11)
Browse files Browse the repository at this point in the history
Signed-off-by: William Woodruff <william@trailofbits.com>
  • Loading branch information
woodruffw authored Mar 20, 2024
1 parent d8b4a64 commit 1796ae7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/rfc8785/_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,11 @@ def dump(obj: _Value, sink: typing.IO[bytes]) -> None:
# RFC 8785 3.2.3: Objects are sorted by key; keys are ordered
# by their UTF-16 encoding. The spec isn't clear about which endianness,
# but the examples imply that the big endian encoding is used.
obj_sorted = sorted(obj.items(), key=lambda kv: kv[0].encode("utf-16be"))
try:
obj_sorted = sorted(obj.items(), key=lambda kv: kv[0].encode("utf-16be"))
except AttributeError:
# Failing to call `encode()` indicates that a key isn't a string.
raise CanonicalizationError("object keys must be strings")

sink.write(b"{")
for idx, (key, value) in enumerate(obj_sorted):
Expand Down
5 changes: 5 additions & 0 deletions test/test_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,8 @@ class X(StrEnum):

raw = impl.dumps([X.A, X.B, X.C])
assert json.loads(raw) == ["foo", "bar", "baz"]


def test_dumps_nonstring_key():
with pytest.raises(impl.CanonicalizationError, match="object keys must be strings"):
impl.dumps({1: 2, None: 3})

0 comments on commit 1796ae7

Please sign in to comment.