8000 Fix python3.2 failing jwt tests · chunkingz/twilio-python@05133ff · GitHub
[go: up one dir, main page]

Skip to content

Commit 05133ff

Browse files
committed
Fix python3.2 failing jwt tests
1 parent 087dd2e commit 05133ff

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

twilio/jwt/__init__.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
import hmac
2+
import sys
3+
4+
from twilio.jwt import compat
5+
6+
if sys.version_info[0] == 3 and sys.version_info[1] == 2:
7+
# PyJWT expects hmac.compare_digest to exist even under python 3.2
8+
hmac.compare_digest = compat.compare_digest
9+
110
import jwt as jwt_lib
211

312
try:
@@ -140,7 +149,7 @@ def from_jwt(cls, jwt, key=''):
140149
verify = True if key else False
141150

142151
try:
143-
payload = jwt_lib.decode(jwt, key, verify=verify, options={
152+
payload = jwt_lib.decode(bytes(jwt), key, verify=verify, options={
144153
'verify_signature': True,
145154
'verify_exp': True,
146155
'verify_nbf': True,

twilio/jwt/compat.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
##
2+
## PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3
3+
## Copied from: https://github.com/python/cpython/commit/6cea65555caf2716b4633827715004ab0291a282#diff-c49659257ec1b129707ce47a98adc96eL16
4+
##
5+
def compare_digest(a, b):
6+
"""Returns the equivalent of 'a == b', but avoids content based short
7+
circuiting to reduce the vulnerability to timing attacks."""
8+
# Consistent timing matters more here than data type flexibility
9+
if not (isinstance(a, bytes) and isinstance(b, bytes)):
10+
raise TypeError("inputs must be bytes instances")
11+
12+
# We assume the length of the expected digest is public knowledge,
13+
# thus this early return isn't leaking anything an attacker wouldn't
14+
# already know
15+
if len(a) != len(b):
16+
return False
17+
18+
# We assume that integers in the bytes range are all cached,
19+
# thus timing shouldn't vary much due to integer object creation
20+
result = 0
21+
for x, y in zip(a, b):
22+
result |= x ^ y
23+
return result == 0

0 commit comments

Comments
 (0)
0