Exemplo n.º 1
0
class WarrantLiteTestCase(unittest.TestCase):
    def setUp(self):
        if env('USE_CLIENT_SECRET') == 'True':
            self.client_secret = env('COGNITO_CLIENT_SECRET')
            self.app_id = env('COGNITO_APP_WITH_SECRET_ID')
        else:
            self.app_id = env('COGNITO_APP_ID')
            self.client_secret = None
        self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
        self.username = env('COGNITO_TEST_USERNAME')
        self.password = env('COGNITO_TEST_PASSWORD')
        self.wl = WarrantLite(username=self.username,
                              password=self.password,
                              pool_id=self.cognito_user_pool_id,
                              client_id=self.app_id,
                              client_secret=self.client_secret)

    def tearDown(self):
        del self.wl

    def test_verify_token(self):
        tokens = self.wl.authenticate_user()

        bad_access_token = '{}wrong'.format(
            tokens['AuthenticationResult']['AccessToken'])

        with self.assertRaises(TokenVerificationException) as vm:
            self.wl.verify_token(bad_access_token, 'access_token', 'access')

    def test_authenticate_user(self):
        tokens = self.wl.authenticate_user()
        self.assertTrue('IdToken' in tokens['AuthenticationResult'])
        self.assertTrue('AccessToken' in tokens['AuthenticationResult'])
        self.assertTrue('RefreshToken' in tokens['AuthenticationResult'])
Exemplo n.º 2
0
 def authenticate(self):
     """This method authenticates against a Cognito User Pool. The JWT is stored as attribute of the class
     """
     logging.info("authenticate with {}".format(self.__user_pool_client_id))
     if not self.__intra_vpc:
         try:
             aws = WarrantLite(username=self.__username,
                               password=self.__password,
                               pool_id=self.__user_pool_id,
                               client_id=self.__user_pool_client_id,
                               client=self.__cognito_client)
             tokens = aws.authenticate_user()
             self.__user_token_id = tokens["AuthenticationResult"][
                 "IdToken"]
             self.__user_refresh_token = tokens["AuthenticationResult"][
                 "RefreshToken"]
             logging.info("authentication successful for user {}".format(
                 self.__user_token_id))
             self.__scheduler.add_job(AWSConnector.refresh,
                                      'interval',
                                      seconds=TOKEK_REFRESH_INTERVAL_SEC,
                                      args=[self])
             self.__scheduler.start()
         except Exception as e:
             logging.error("Cannot authenticate user {}".format(
                 self.__username))
             raise e
         self.__authorization_headers = {
             "authorization": self.__user_token_id
         }
Exemplo n.º 3
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        wl = WarrantLite(username=username,
                         password=password,
                         pool_id=app.config.get('USER_POOL_ID'),
                         pool_region=app.config.get('USER_POOL_REGION'),
                         client_id=app.config.get('COGNITO_CLIENT_ID'),
                         client_secret=app.config.get('COGNITO_CLIENT_SECRET'))
        try:
            tokens = wl.authenticate_user()
            session.clear()
            session['user_token'] = tokens.get(
                'AuthenticationResult')['AccessToken']
            flash('You were successfully logged in')
            return redirect(url_for('home'))

        except:
            flash('oops, an error happened (probably password related)')
            return render_template('login.html', route_name='login')

    else:
        session.clear()
        flash('good work logging out')

    return render_template('login.html')
Exemplo n.º 4
0
    async def run(self):
        """
        Executes a single request
        :return: Response class
        """
        path = '{}{}'.format(self.get_url(), self.req_config.get('path'))

        method_type = self.req_config.get('method_type')
        data = self.req_config.get('data')
        params = self.req_config.get('params')

        try:
            self.session._loadlamb_tokens
        except AttributeError:
            user = random.choice(self.proj_config.get('users'))
            wl = WarrantLite(username=user.get('username'),
                             password=user.get('password'),
                             pool_id=self.proj_config.get('pool_id'),
                             client_id=self.proj_config.get('client_id'))
            self.session._loadlamb_tokens = wl.authenticate_user()

        headers = {
            'Authorization':
            self.session._loadlamb_tokens['AuthenticationResult']['IdToken'],
            'Accept':
            'application/json; version=1.0'
        }
        start_time = time.perf_counter()
        try:
            if data:
                data = self.get_choice(data)
                resp = await self.session.request(method_type,
                                                  path,
                                                  headers=headers,
                                                  json=data,
                                                  timeout=self.timeout)
            elif params:
                params = self.get_choice(params)
                resp = await self.session.request(method_type,
                                                  path,
                                                  headers=headers,
                                                  payload=params,
                                                  timeout=self.timeout)
            else:
                resp = await self.session.request(method_type,
                                                  path,
                                                  headers=headers)
        except asyncio.TimeoutError:
            return await self.get_null_response(self.timeout)
        end_time = time.perf_counter()

        resp = Response(resp, self.req_config,
                        self.proj_config.get('project_slug'),
                        self.proj_config.get('run_slug'),
                        end_time - start_time, self.user_no, self.group_no)
        await resp.assert_contains()
        ltr = await resp.get_ltr()
        return ltr
Exemplo n.º 5
0
 def setUp(self):
     if env('USE_CLIENT_SECRET') == 'True':
         self.client_secret = env('COGNITO_CLIENT_SECRET')
         self.app_id = env('COGNITO_APP_WITH_SECRET_ID')
     else:
         self.app_id = env('COGNITO_APP_ID')
         self.client_secret = None
     self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
     self.username = env('COGNITO_TEST_USERNAME')
     self.password = env('COGNITO_TEST_PASSWORD')
     self.wl = WarrantLite(username=self.username, password=self.password,
                       pool_id=self.cognito_user_pool_id,
                       client_id=self.app_id, client_secret=self.client_secret)
Exemplo n.º 6
0
def refresh(user_id: str, refresh_token: str, **kwargs) -> WinixAuthResponse:
    """Refresh """
    from warrant_lite import WarrantLite

    client_id = kwargs.get("client_id", COGNITO_APP_CLIENT_ID)

    auth_params = {
        "REFRESH_TOKEN": refresh_token,
        "SECRET_HASH": WarrantLite.get_secret_hash(
            username=user_id,
            client_id=client_id,
            client_secret=kwargs.get("client_secret", COGNITO_CLIENT_SECRET_KEY),
        ),
    }

    resp = _boto_client(kwargs.get("pool_region")).initiate_auth(
        ClientId=client_id, AuthFlow="REFRESH_TOKEN", AuthParameters=auth_params,
    )

    return WinixAuthResponse(
        user_id=user_id,
        access_token=resp["AuthenticationResult"]["AccessToken"],
        refresh_token=refresh_token,
        id_token=resp["AuthenticationResult"]["IdToken"],
    )
Exemplo n.º 7
0
 def new_password_challenge(self, password, new_password):
     """
     Respond to the new password challenge using the SRP protocol
     :param password: The user's current passsword
     :param new_password: The user's new passsword
     """
     aws = WarrantLite(username=self.username,
                       password=password,
                       pool_id=self.user_pool_id,
                       client_id=self.client_id,
                       client=self.client,
                       client_secret=self.client_secret)
     tokens = aws.set_new_password_challenge(new_password)
     self.id_token = tokens['AuthenticationResult']['IdToken']
     self.refresh_token = tokens['AuthenticationResult']['RefreshToken']
     self.access_token = tokens['AuthenticationResult']['AccessToken']
     self.token_type = tokens['AuthenticationResult']['TokenType']
Exemplo n.º 8
0
 def _add_secret_hash(self, parameters, key):
     """
     Helper function that computes SecretHash and adds it
     to a parameters dictionary at a specified key
     """
     if self.client_secret is not None:
         secret_hash = WarrantLite.get_secret_hash(self.username,
                                                   self.client_id,
                                                   self.client_secret)
         parameters[key] = secret_hash
Exemplo n.º 9
0
    def authenticate(self, password):
        """
        Authenticate the user using the SRP protocol
        :param password: The user's passsword
        :return:
        """

        aws = WarrantLite(username=self.username,
                          password=password,
                          pool_id=self.user_pool_id,
                          client_id=self.client_id,
                          client=self.client,
                          client_secret=self.client_secret)
        tokens = aws.authenticate_user()
        self.verify_token(tokens['AuthenticationResult']['IdToken'],
                          'id_token', 'id')
        self.refresh_token = tokens['AuthenticationResult']['RefreshToken']
        self.verify_token(tokens['AuthenticationResult']['AccessToken'],
                          'access_token', 'access')
        self.token_type = tokens['AuthenticationResult']['TokenType']
Exemplo n.º 10
0
def do_authentication(username, password, cognito_pool_id, cognito_client_id):
    """ authenticates to AWS Cognito via eyn's credentials and returns
        authentication tokens

        params:
            username (str): username to authenticate (supplied by EYN)
            password (str): password to authenticate (supplied by EYN)
            cognito_pool_id (str): AWS cognito user pool id
            cognito_client_id (str): AWS cognito app client id

        returns:
            (dict): authentication tokens
    """
    wl = WarrantLite(username=username,
                     password=password,
                     pool_id=cognito_pool_id,
                     client_id=cognito_client_id,
                     client_secret=None,
                     pool_region="eu-west-2")
    tokens = wl.authenticate_user()
    return tokens
Exemplo n.º 11
0
def login(username: str, password: str, **kwargs):
    """Generate fresh credentials"""
    from warrant_lite import WarrantLite
    from jose import jwt

    wl = WarrantLite(
        username=username,
        password=password,
        pool_id=kwargs.get("pool_id", COGNITO_USER_POOL_ID),
        client_id=kwargs.get("client_id", COGNITO_APP_CLIENT_ID),
        client_secret=kwargs.get("client_secret", COGNITO_CLIENT_SECRET_KEY),
        client=_boto_client(kwargs.get("pool_region")),
    )

    resp = wl.authenticate_user()
    return WinixAuthResponse(
        user_id=jwt.get_unverified_claims(
            resp["AuthenticationResult"]["AccessToken"])["sub"],
        access_token=resp["AuthenticationResult"]["AccessToken"],
        refresh_token=resp["AuthenticationResult"]["RefreshToken"],
        id_token=resp["AuthenticationResult"]["IdToken"],
    )