Skip to content

Commit 2b95926

Browse files
authored
fix: throw an error on non-valid base64 strings
1 parent 6329b74 commit 2b95926

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

src/joserfc/util.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from typing import Any
33
import base64
44
import struct
5+
import binascii
56
import json
67

78

@@ -26,8 +27,10 @@ def json_dumps(data: Any, ensure_ascii: bool = False) -> str:
2627

2728

2829
def urlsafe_b64decode(s: bytes) -> bytes:
30+
if b"+" in s or b"/" in s:
31+
raise binascii.Error
2932
s += b"=" * (-len(s) % 4)
30-
return base64.urlsafe_b64decode(s)
33+
return base64.b64decode(s, b"-_", validate=True)
3134

3235

3336
def urlsafe_b64encode(s: bytes) -> bytes:

tests/test_util.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from unittest import TestCase
22
from joserfc import util
3-
3+
import binascii
44

55
class TestUtil(TestCase):
66
def test_to_bytes(self):
@@ -22,3 +22,11 @@ def test_int_to_base64(self):
2222

2323
def test_json_b64encode(self):
2424
self.assertEqual(util.json_b64encode("{}"), b"e30")
25+
26+
def test_urlsafe_b64decode(self):
27+
self.assertEqual(util.urlsafe_b64decode(b'_foo123-'), b'\xfd\xfa(\xd7m\xfe')
28+
self.assertRaises(
29+
binascii.Error,
30+
util.urlsafe_b64decode,
31+
b'+foo123/'
32+
)

0 commit comments

Comments
 (0)