From f63b950ba43fbbad83aa894fbb76950230663432 Mon Sep 17 00:00:00 2001 From: charliesantos Date: Mon, 26 Oct 2020 13:51:33 -0700 Subject: [PATCH] feat: Regional twr header in the access token --- tests/unit/jwt/test_access_token.py | 12 ++++++++++++ twilio/jwt/access_token/__init__.py | 8 ++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/unit/jwt/test_access_token.py b/tests/unit/jwt/test_access_token.py index d863304b3d..cf54c1383a 100644 --- a/tests/unit/jwt/test_access_token.py +++ b/tests/unit/jwt/test_access_token.py @@ -54,6 +54,18 @@ def test_empty_grants(self): self._validate_claims(decoded_token.payload) assert_equal({}, decoded_token.payload['grants']) + def test_region(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', region='foo') + token = scat.to_jwt() + decoded_token = AccessToken.from_jwt(token, 'secret') + assert_equal(decoded_token.headers['twr'], 'foo') + + def test_empty_region(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret') + token = scat.to_jwt() + decoded_token = AccessToken.from_jwt(token, 'secret') + self.assertRaises(KeyError, lambda: decoded_token.headers['twr']) + def test_nbf(self): now = int(time.mktime(datetime.now().timetuple())) scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, 'secret', nbf=now) diff --git a/twilio/jwt/access_token/__init__.py b/twilio/jwt/access_token/__init__.py index 4e542a5f8b..f59f5cac0f 100644 --- a/twilio/jwt/access_token/__init__.py +++ b/twilio/jwt/access_token/__init__.py @@ -21,7 +21,7 @@ def __str__(self): class AccessToken(Jwt): """Access Token containing one or more AccessTokenGrants used to access Twilio Resources""" def __init__(self, account_sid, signing_key_sid, secret, grants=None, - identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None): + identity=None, nbf=Jwt.GENERATE, ttl=3600, valid_until=None, region=None): grants = grants or [] if any(not isinstance(g, AccessTokenGrant) for g in grants): raise ValueError('Grants must be instances of AccessTokenGrant.') @@ -29,6 +29,7 @@ def __init__(self, account_sid, signing_key_sid, secret, grants=None, self.account_sid = account_sid self.signing_key_sid = signing_key_sid self.identity = identity + self.region = region self.grants = grants super(AccessToken, self).__init__( secret_key=secret, @@ -47,9 +48,12 @@ def add_grant(self, grant): self.grants.append(grant) def _generate_headers(self): - return { + headers = { 'cty': 'twilio-fpa;v=1' } + if self.region and isinstance(self.region, str): + headers['twr'] = self.region + return headers def _generate_payload(self): now = int(time.time())