def testTokenClient(self): """ Test the AWSSRP client is invoked and throws an error """ sa = StaxAuth("ApiAuth") with self.assertRaises(InvalidCredentialsException): sa.id_token_from_cognito(username="******", password="******")
def testSigV4Headers(self): """ Test sigv4 signed auth headers """ # Get signed auth headers sa = StaxAuth("ApiAuth") id_creds = { "Credentials": { "AccessKeyId": "ASIAX000000000000000", "SecretKey": "0000000000000000000000000000000000000000", "SessionToken": "a-totally-valid-JWT", "Expiration": datetime(2020, 1, 14, 11, 52, 26), } } auth = sa.sigv4_signed_auth_headers(id_creds) # Mock request response_dict = {"Status": "OK"} responses.add( responses.GET, f"{Config.api_base_url()}/auth", json=response_dict, status=200, ) response = requests.get(f"{Config.api_base_url()}/auth", auth=auth) self.assertEqual(response.json(), response_dict) self.assertIn("Authorization", response.request.headers)
def testToken(self): """ Test valid JWT is returned """ sa = StaxAuth("ApiAuth") self.stub_aws_srp(sa, "valid_username") token = sa.id_token_from_cognito( username="******", password="******", srp_client=self.aws_srp_client, ) self.assertEqual(token, "valid_token")
def testCreds(self): """ Test valid credentials are returned """ sa = StaxAuth("ApiAuth") token = jwt.encode({"sub": "unittest"}, "secret", algorithm="HS256") jwt_token = jwt.decode(token, verify=False) self.stub_cognito_creds(sa, jwt_token.get("sub")) creds = sa.sts_from_cognito_identity_pool(jwt_token.get("sub"), self.cognito_client) self.assertIn("Credentials", creds) self.assertTrue(creds.get("IdentityId").startswith("ap-southeast-2"))
def testAuthErrors(self): """ Test that errors are thrown when keys are invalid """ sa = StaxAuth("ApiAuth") # Test with no username with self.assertRaises(InvalidCredentialsException): sa.requests_auth(username=None, password="******") # Test with no username with self.assertRaises(InvalidCredentialsException): sa.requests_auth(username="******", password=None)
def testApiTokenAuthExpiring(self, requests_auth_mock): """ Test credentials close to expiration get refreshed """ sa = StaxAuth("ApiAuth") StaxConfig = Config ## expiration 20 minutes in the future, no need to refresh StaxConfig.expiration = datetime.now( timezone.utc) + timedelta(minutes=20) ApiTokenAuth.requests_auth( "username", "password", srp_client=self.aws_srp_client, cognito_client=self.cognito_client, ) requests_auth_mock.assert_not_called() requests_auth_mock.reset_mock() ## expiration in 5 seconds from now, refresh to avoid token becoming stale used StaxConfig.expiration = datetime.now( timezone.utc) + timedelta(seconds=5) ApiTokenAuth.requests_auth( "username", "password", srp_client=self.aws_srp_client, cognito_client=self.cognito_client, ) requests_auth_mock.assert_called_once() requests_auth_mock.reset_mock() ## expiration in 5 minutes from now, refresh to avoid token becoming stale used ## override default triggering library to not refresh environ["TOKEN_EXPIRY_THRESHOLD_IN_MINS"] = "10" StaxConfig.expiration = datetime.now( timezone.utc) + timedelta(minutes=2) ApiTokenAuth.requests_auth( "username", "password", srp_client=self.aws_srp_client, cognito_client=self.cognito_client, ) requests_auth_mock.assert_called_once()
def testRootAuth(self): """ Test generating new credentials """ sa = StaxAuth("JumaAuth") StaxConfig = Config StaxConfig.expiration = None token = jwt.encode({"sub": "valid_token"}, "secret", algorithm="HS256") jwt_token = jwt.decode(token, verify=False) self.stub_cognito_creds(sa, jwt_token.get("sub")) self.stub_aws_srp(sa, "username") RootAuth.requests_auth( "username", "password", srp_client=self.aws_srp_client, cognito_client=self.cognito_client, ) self.assertIsNotNone(StaxConfig.auth)
def testCredentialErrors(self): """ Test that boto errors are caught and converted to InvalidCredentialExceptions """ sa = StaxAuth("ApiAuth") # Test with invalid username password self.stub_aws_srp(sa, "bad_password", "NotAuthorizedException") user_not_found_success = False try: sa.id_token_from_cognito( username="******", password="******", srp_client=self.aws_srp_client, ) except InvalidCredentialsException as e: self.assertIn("Please check your Secret Key is correct", str(e)) user_not_found_success = True self.assertTrue(user_not_found_success) # Test with no access self.stub_aws_srp(sa, "no_access", "UserNotFoundException") no_access_success = False try: sa.id_token_from_cognito(username="******", password="******", srp_client=self.aws_srp_client) except InvalidCredentialsException as e: self.assertIn( "Please check your Access Key, that you have created your Api Token and that you are using the right STAX REGION", str(e), ) no_access_success = True self.assertTrue(no_access_success) # Test Unknown Error self.stub_aws_srp(sa, "Unknown", "UnitTesting") with self.assertRaises(InvalidCredentialsException): sa.id_token_from_cognito(username="******", password="******", srp_client=self.aws_srp_client)
def testApiAuth(self): """ Test auth through the Api class """ sa = StaxAuth("ApiAuth") StaxConfig = Config StaxConfig.expiration = None StaxConfig.access_key = "username" StaxConfig.secret_key = "password" token = jwt.encode({"sub": "valid_token"}, "secret", algorithm="HS256") jwt_token = jwt.decode(token, verify=False) self.stub_cognito_creds(sa, jwt_token.get("sub")) self.stub_aws_srp(sa, "username") Api._requests_auth = None Api._auth( srp_client=self.aws_srp_client, cognito_client=self.cognito_client, ) self.assertIsNotNone(Api._requests_auth)
def testCredsClient(self): """ Test the cognito client is invoked and throws an error """ sa = StaxAuth("ApiAuth") # Test Invalid Credentials token = jwt.encode({"sub": "unittest"}, "secret", algorithm="HS256") jwt_token = jwt.decode(token, verify=False) with self.assertRaises(InvalidCredentialsException): sa.sts_from_cognito_identity_pool(jwt_token.get("sub")) # Test "Couldn't verify signed token" retry expected_parameters = { "IdentityPoolId": sa.identity_pool, "Logins": { f"cognito-idp.{sa.aws_region}.amazonaws.com/{sa.user_pool}": "unittest" } } for i in range(sa.max_retries): self.cognito_stub.add_client_error( "get_id", service_error_code="NotAuthorizedException", service_message= "Invalid login token. Couldn't verify signed token.", expected_params=expected_parameters, ) self.cognito_stub.activate() with self.assertRaises(InvalidCredentialsException) as e: sa.sts_from_cognito_identity_pool( jwt_token.get("sub"), cognito_client=self.cognito_client) self.assertEqual( str(e.exception), "InvalidCredentialsException: Retries Exceeded: Unexpected Client Error" ) self.assertEqual(len(self.cognito_stub._queue), 0)
def testStaxAuthInit(self): """ Test to initialise StaxAuth """ sa = StaxAuth("ApiAuth") self.assertEqual(sa.aws_region, "ap-southeast-2")