Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

follow rfc 7515 : strip padding from JWS segments #324

Merged
merged 2 commits into from
Feb 15, 2019
Merged
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
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