From f1f3e9c4aecc73ee2a21ea9f25a93840cd02611d Mon Sep 17 00:00:00 2001 From: Vincent Gao Date: Fri, 19 Jun 2026 05:16:37 +0200 Subject: [PATCH] Validate oversized base62 values --- ksuid/ksuid.py | 8 +++++++- tests/test_ksuid.py | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ksuid/ksuid.py b/ksuid/ksuid.py index c1b96b9..b08606a 100644 --- a/ksuid/ksuid.py +++ b/ksuid/ksuid.py @@ -48,7 +48,13 @@ class Ksuid: @classmethod def from_base62(cls: type[SelfT], data: str) -> SelfT: """initializes Ksuid from base62 encoding""" - return cls.from_bytes(int.to_bytes(int(base62.decode(data)), cls.BYTES_LENGTH, "big")) + decoded = int(base62.decode(data)) + try: + value = int.to_bytes(decoded, cls.BYTES_LENGTH, "big") + except OverflowError as exc: + byte_length = (decoded.bit_length() + 7) // 8 + raise ByteArrayLengthException(f"Incorrect value length {byte_length}") from exc + return cls.from_bytes(value) @classmethod def from_bytes(cls: type[SelfT], value: bytes) -> SelfT: diff --git a/tests/test_ksuid.py b/tests/test_ksuid.py index b1488e3..a25d1f8 100644 --- a/tests/test_ksuid.py +++ b/tests/test_ksuid.py @@ -72,6 +72,12 @@ def test_to_from_base62(): assert ksuid == ksuid_from_base62 +@pytest.mark.parametrize("ksuid_cls", [Ksuid, KsuidMs]) +def test_from_base62_rejects_oversized_value(ksuid_cls): + with pytest.raises(ByteArrayLengthException): + ksuid_cls.from_base62("z" * ksuid_cls.BASE62_LENGTH) + + def test_eq_with_non_ksuid_does_not_raise(): ksuid = Ksuid.from_bytes(bytes(Ksuid.BYTES_LENGTH))