Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
span_observer = mock.Mock(spec=SpanObserver)
with serve_thrift(handler) as server:
with baseplate_thrift_client(server.endpoint, span_observer) as context:
context.example_service.example()
try:
self.assertEqual(handler.request_context.user.id, "t2_example")
self.assertEqual(handler.request_context.user.roles, set())
self.assertEqual(handler.request_context.user.is_logged_in, True)
self.assertEqual(handler.request_context.user.loid, "t2_deadbeef")
self.assertEqual(handler.request_context.user.cookie_created_ms, 100000)
self.assertEqual(handler.request_context.oauth_client.id, None)
self.assertFalse(handler.request_context.oauth_client.is_type("third_party"))
self.assertEqual(handler.request_context.session.id, "beefdead")
except jwt.exceptions.InvalidAlgorithmError:
raise unittest.SkipTest("cryptography is not installed")
import os
import time
from paradrop.base import nexus
def generate_jwt_secret():
# 32 bytes = 256 bits, recommended key length for HS256.
material = os.urandom(32)
return binascii.b2a_hex(material)
class TokenManager(object):
# Inherit this exception class so that callers can use it without depending
# on the jwt library.
InvalidTokenError = jwt.exceptions.InvalidTokenError
def __init__(self):
self.secret = nexus.core.getKey('jwt-secret')
if self.secret is None:
self.secret = generate_jwt_secret()
nexus.core.saveKey(self.secret, 'jwt-secret')
def decode(self, token):
"""
Decode a JWT that was issued by us.
Throws an InvalidTokenError on decoding failure or token expiration.
"""
return jwt.decode(token, self.secret, algorithms=['HS256'])
def issue(self, subject, expires=2592000, **claims):
def decode_signed_jwt_token(self, signed_token, leeway):
try:
if signed_token:
logger.debug("decoding signed jwt", jwt_token=strings.to_str(signed_token))
self._check_token(signed_token)
token = jwt.decode(signed_token, self.rrm_public_key, algorithms=['RS256'],
leeway=leeway)
if not token:
raise InvalidTokenException("Missing Payload")
return token
else:
raise NoTokenException("JWT Missing")
except (jwt.DecodeError,
jwt.exceptions.InvalidAlgorithmError,
jwt.exceptions.ExpiredSignatureError,
jwt.exceptions.InvalidIssuedAtError) as e:
raise InvalidTokenException(repr(e))
If correct, it return the username, if not, it
returns None
'''
if not header:
logger.info('No header')
return None
# Retrieve the Bearer token
parse_result = parse('Bearer {}', header)
if not parse_result:
logger.info(f'Wrong format for header "{header}"')
return None
token = parse_result[0]
try:
decoded_token = decode_token(token.encode('utf8'), public_key)
except jwt.exceptions.DecodeError:
logger.warning(f'Error decoding header "{header}". '
'This may be key missmatch or wrong key')
return None
except jwt.exceptions.ExpiredSignatureError:
logger.error(f'Authentication header has expired')
return None
# Check expiry is in the token
if 'exp' not in decoded_token:
logger.warning('Token does not have expiry (exp)')
return None
# Check username is in the token
if 'username' not in decoded_token:
logger.warning('Token does not have username')
return None
def get(self, request, format=None, *args, **kwargs):
if settings.JWT_AUTH_SETTINGS["GET_PARAMETER"] in request.GET:
# Retrieve the token.
token = request.GET[settings.JWT_AUTH_SETTINGS["GET_PARAMETER"]]
try:
claims = decode_token(
token, verify=settings.JWT_AUTH_SETTINGS["VERIFY_SIGNATURE"]
)
except jwt.exceptions.InvalidTokenError as e:
raise AuthenticationFailed(e) from e
# Verify if the token can authenticate an user.
JWTCookieAuthentication().get_user(claims)
# Set it as a cookie.
response = Response({"token": token}, status=status.HTTP_200_OK)
response.set_cookie(
key=settings.JWT_AUTH_SETTINGS["ACCESS_TOKEN_COOKIE_NAME"],
value=token,
expires=datetime.now()
+ settings.JWT_AUTH_SETTINGS["ACCESS_TOKEN_LIFETIME"],
httponly=True,
secure=not settings.DEBUG,
)
asap_claims = parse_jwt_func(verifier, auth[1])
if verify_issuers_func is not None:
verify_issuers_func(asap_claims, issuers)
asap_claim_holder.asap_claims = asap_claims
except PublicKeyRetrieverException as e:
if e.status_code not in (403, 404):
# Any error other than "not found" is a problem and should be dealt
# with elsewhere.
# Note that we treat 403 like 404 to account for the fact that
# a server configured to secure directory listings will return 403
# for a missing file to avoid leaking information.
raise
# Couldn't find key in key server
message = 'Unauthorized: Invalid key'
exception = e
except jwt.exceptions.InvalidIssuerError as e:
message = 'Forbidden: Invalid token issuer'
exception = e
except jwt.exceptions.InvalidTokenError as e:
# Something went wrong with decoding the JWT
message = 'Unauthorized: Invalid token'
exception = e
if message is not None:
logger = logging.getLogger(__name__)
logger.debug(message,
extra={'original_message': str(exception)})
if message.startswith('Unauthorized:'):
kwargs = {
'status': 401,
'headers': {'WWW-Authenticate': 'Bearer'},
}
elif message.startswith('Forbidden:'):