Skip to content
Open
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 src/validators/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@ def base32(value: str, /):
(Literal[True]): If `value` is a valid base32 encoding.
(ValidationError): If `value` is an invalid base32 encoding.
"""
return re.fullmatch(r"^[A-Z2-7]+=*$", value) if value else False
return (
re.fullmatch(
r"(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}(?:={6})?|[A-Z2-7]{4}(?:={4})?|"
r"[A-Z2-7]{5}(?:={3})?|[A-Z2-7]{7}=?)?",
value,
)
if value
else False
)


@validator
Expand Down
13 changes: 13 additions & 0 deletions tests/test_encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,16 @@ def test_encoding_rejects_trailing_characters(
):
"""Reject characters outside the encoded value."""
assert isinstance(validate(value + suffix), ValidationError)


@pytest.mark.parametrize("value", ["A", "AAA", "AAAAAA", "AB=", "AB===", "AB=======", "ABCDEFGH="])
def test_base32_rejects_invalid_length_and_padding(value: str):
"""Reject symbol counts and padding that cannot encode whole bytes."""
assert isinstance(base32(value), ValidationError)


@pytest.mark.parametrize("value", ["MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB"])
def test_base32_accepts_valid_final_quanta(value: str):
"""Accept each legal final quantum with or without padding."""
assert base32(value) is True
assert base32(value.rstrip("=")) is True