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/josepy/b64.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
"""

import base64
from typing import Union
import string
from typing import Final, Union

VALID_B64_CHARS: Final[frozenset[int]] = frozenset(
string.ascii_letters.encode("ascii") + string.digits.encode("ascii") + b"-_="
)


def b64encode(data: bytes) -> bytes:
Expand Down Expand Up @@ -54,4 +59,7 @@ def b64decode(data: Union[bytes, str]) -> bytes:
elif not isinstance(data, bytes):
raise TypeError("argument should be a str or unicode")

if any(c not in VALID_B64_CHARS for c in data):
raise ValueError("argument should contain only valid Base64 characters")

return base64.urlsafe_b64decode(data + b"=" * (4 - (len(data) % 4)))
13 changes: 11 additions & 2 deletions tests/b64_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for josepy.b64."""

import sys
import unittest
from typing import Union

import pytest
Expand All @@ -21,7 +22,7 @@
}


class B64EncodeTest:
class B64EncodeTest(unittest.TestCase):
"""Tests for josepy.b64.b64encode."""

@classmethod
Expand All @@ -47,7 +48,7 @@ def test_unicode_fails_with_type_error(self) -> None:
self._call("some unicode") # type: ignore


class B64DecodeTest:
class B64DecodeTest(unittest.TestCase):
"""Tests for josepy.b64.b64decode."""

@classmethod
Expand Down Expand Up @@ -80,6 +81,14 @@ def test_type_error_no_unicode_or_bytes(self) -> None:
# We're purposefully testing with the incorrect type here.
self._call(object()) # type: ignore

def test_non_urlsafe(self) -> None:
with pytest.raises(ValueError):
self._call("+/8")

def test_non_base64_chars(self) -> None:
with pytest.raises(ValueError):
self._call("*&$")


if __name__ == "__main__":
sys.exit(pytest.main(sys.argv[1:] + [__file__])) # pragma: no cover
Loading