Skip to content

Commit

Permalink
Follow rfc 7515 and strip padding from JWS segments (#324)
Browse files Browse the repository at this point in the history
* strip off illegal padding

* oops: remove unused import base64
  • Loading branch information
adityanatraj authored and theacodes committed Feb 15, 2019
1 parent b4eee9c commit ae7e4f3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
17 changes: 17 additions & 0 deletions google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,20 @@ def padded_urlsafe_b64decode(value):
b64string = to_bytes(value)
padded = b64string + b'=' * (-len(b64string) % 4)
return base64.urlsafe_b64decode(padded)


def unpadded_urlsafe_b64encode(value):
"""Encodes base64 strings removing any padding characters.
`rfc 7515`_ defines Base64url to NOT include any padding
characters, but the stdlib doesn't do that by default.
_rfc7515: https://tools.ietf.org/html/rfc7515#page-6
Args:
value (Union[str|bytes]): The bytes-like value to encode
Returns:
Union[str|bytes]: The encoded value
"""
return base64.urlsafe_b64encode(value).rstrip(b'=')
13 changes: 9 additions & 4 deletions google/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"""

import base64
import collections
import copy
import datetime
Expand Down Expand Up @@ -86,13 +85,19 @@ def encode(signer, payload, header=None, key_id=None):
header['kid'] = key_id

segments = [
base64.urlsafe_b64encode(json.dumps(header).encode('utf-8')),
base64.urlsafe_b64encode(json.dumps(payload).encode('utf-8')),
_helpers.unpadded_urlsafe_b64encode(
json.dumps(header).encode('utf-8')
),
_helpers.unpadded_urlsafe_b64encode(
json.dumps(payload).encode('utf-8')
),
]

signing_input = b'.'.join(segments)
signature = signer.sign(signing_input)
segments.append(base64.urlsafe_b64encode(signature))
segments.append(
_helpers.unpadded_urlsafe_b64encode(signature)
)

return b'.'.join(segments)

Expand Down
12 changes: 12 additions & 0 deletions tests/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,15 @@ def test_padded_urlsafe_b64decode():

for case, expected in cases:
assert _helpers.padded_urlsafe_b64decode(case) == expected


def test_unpadded_urlsafe_b64encode():
cases = [
(b'', b''),
(b'a', b'YQ'),
(b'aa', b'YWE'),
(b'aaa', b'YWFh'),
]

for case, expected in cases:
assert _helpers.unpadded_urlsafe_b64encode(case) == expected

0 comments on commit ae7e4f3

Please sign in to comment.