def decrypt_token(self, username, token):
version, user_type, _from = self._parse_username(username)<EOL>if (version > self.maximum_token_version or<EOL>version < self.minimum_token_version):<EOL><INDENT>raise TokenValidationError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>token_key = '<STR_LIT>'.format(<EOL>hashlib.sha256(ensure_bytes(token)).hexdigest(),<EOL>_from,<EOL>self.to_auth_context,<EOL>user_type<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>raise TokenValidationError('<STR_LIT>')<EOL><DEDENT>if token_key not in self.TOKENS:<EOL><INDENT>try:<EOL><INDENT>token = base64.b64decode(token)<EOL>context = copy.deepcopy(self.extra_context)<EOL>context['<STR_LIT:to>'] = self.to_auth_context<EOL>context['<STR_LIT>'] = _from<EOL>if version > <NUM_LIT:1>:<EOL><INDENT>context['<STR_LIT>'] = user_type<EOL><DEDENT>data = self.kms_client.decrypt(<EOL>CiphertextBlob=token,<EOL>EncryptionContext=context<EOL>)<EOL>key_arn = data['<STR_LIT>']<EOL>if user_type == '<STR_LIT>':<EOL><INDENT>if not self._valid_service_auth_key(key_arn):<EOL><INDENT>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>elif user_type == '<STR_LIT:user>':<EOL><INDENT>if not self._valid_user_auth_key(key_arn):<EOL><INDENT>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>plaintext = data['<STR_LIT>']<EOL>payload = json.loads(plaintext)<EOL>key_alias = self._get_key_alias_from_cache(key_arn)<EOL>ret = {'<STR_LIT>': payload, '<STR_LIT>': key_alias}<EOL><DEDENT>except TokenValidationError:<EOL><INDENT>raise<EOL><DEDENT>except (ConnectionError, EndpointConnectionError):<EOL><INDENT>logging.exception('<STR_LIT>')<EOL>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>logging.exception('<STR_LIT>')<EOL>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ret = self.TOKENS[token_key]<EOL><DEDENT>now = datetime.datetime.utcnow()<EOL>try:<EOL><INDENT>not_before = datetime.datetime.strptime(<EOL>ret['<STR_LIT>']['<STR_LIT>'],<EOL>TIME_FORMAT<EOL>)<EOL>not_after = datetime.datetime.strptime(<EOL>ret['<STR_LIT>']['<STR_LIT>'],<EOL>TIME_FORMAT<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>logging.exception(<EOL>'<STR_LIT>'<EOL>)<EOL>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>delta = (not_after - not_before).seconds / <NUM_LIT><EOL>if delta > self.auth_token_max_lifetime:<EOL><INDENT>logging.warning('<STR_LIT>')<EOL>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if (now < not_before) or (now > not_after):<EOL><INDENT>logging.warning('<STR_LIT>')<EOL>raise TokenValidationError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>self.TOKENS[token_key] = ret<EOL>return self.TOKENS[token_key]<EOL>
Decrypt a token.