Skip to content

Commit dfd33df

Browse files
muneikhnandgator
authored andcommitted
Validate Base32 quantum lengths and padding
1 parent dce580d commit dfd33df

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎src/validators/encoding.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,15 @@ def base32(value: str, /):
4646
(Literal[True]): If `value` is a valid base32 encoding.
4747
(ValidationError): If `value` is an invalid base32 encoding.
4848
"""
49-
return re.fullmatch(r"^[A-Z2-7]+=*$", value) if value else False
49+
return (
50+
re.fullmatch(
51+
r"(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}(?:={6})?|[A-Z2-7]{4}(?:={4})?|"
52+
r"[A-Z2-7]{5}(?:={3})?|[A-Z2-7]{7}=?)?",
53+
value,
54+
)
55+
if value
56+
else False
57+
)
5058

5159

5260
@validator

‎tests/test_encoding.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,16 @@ def test_encoding_rejects_trailing_characters(
130130
):
131131
"""Reject characters outside the encoded value."""
132132
assert isinstance(validate(value + suffix), ValidationError)
133+
134+
135+
@pytest.mark.parametrize("value", ["A", "AAA", "AAAAAA", "AB=", "AB===", "AB=======", "ABCDEFGH="])
136+
def test_base32_rejects_invalid_length_and_padding(value: str):
137+
"""Reject symbol counts and padding that cannot encode whole bytes."""
138+
assert isinstance(base32(value), ValidationError)
139+
140+
141+
@pytest.mark.parametrize("value", ["MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB"])
142+
def test_base32_accepts_valid_final_quanta(value: str):
143+
"""Accept each legal final quantum with or without padding."""
144+
assert base32(value) is True
145+
assert base32(value.rstrip("=")) is True

0 commit comments

Comments
 (0)