class FxATestAccount: """A base test class that can be extended by other tests to include utility methods.""" password = ''.join([random.choice(string.ascii_letters) for i in range(8)]) def __init__(self, url=DEV_URL): """ Creates an FxATestAccount object, which includes a verified account. :param url: The url for the api host. Defaults to DEV_URL. """ self.url = url random_string = ''.join( random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) self.client = Client(self.url) # Create and verify the Firefox account self.session = self.client.create_account(self.account.email, self.password) print('fxapom created an account for email: %s at %s on %s' % (self.account.email, self.url, datetime.now())) m = self.account.wait_for_email( lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) def __del__(self): """ Deletes the Firefox Account that was created during __init__. """ try: self.account.clear() self.client.destroy_account(self.email, self.password) print('fxapom deleted the account for email: %s at %s on %s' % (self.account.email, self.url, datetime.now())) except ClientError as err: # 'Unknown Account' error is ok - account already deleted # https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-format if err.errno == 102: return raise def login(self): try: session = self.client.login(self.email, self.password) return session except ClientError as err: # 'Unknown Account' error is the only one we care about and will # cause us to throw a custom exception # https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-format if err.errno == 102: raise AccountNotFoundException('FxA Account Not Found') raise @property def email(self): return self.account.email @property def is_verified(self): return self.session.get_email_status()['verified']
def __init__(self, server=_FXA_SERVER, oauth=_FXA_OAUTH, password=_PWD): self.server = server self.oauth = oauth self.session = self.token = None self.password = password self.acct = TestEmailAccount() self.client = Client(_FXA_SERVER)
class FxATestAccount: """A base test class that can be extended by other tests to include utility methods.""" password = ''.join([random.choice(string.letters) for i in range(8)]) def __init__(self, url=DEV_URL): """ Creates an FxATestAccount object, which includes a verified account. :param url: The url for the api host. Defaults to DEV_URL. """ self.url = url random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) self.client = Client(self.url) # Create and verify the Firefox account self.session = self.client.create_account(self.account.email, self.password) print 'fxapom created an account for email: %s at %s on %s' % ( self.account.email, self.url, datetime.now()) m = self.account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) def __del__(self): """ Deletes the Firefox Account that was created during __init__. """ try: self.account.clear() self.client.destroy_account(self.email, self.password) print 'fxapom deleted the account for email: %s at %s on %s' % ( self.account.email, self.url, datetime.now()) except ClientError as err: # 'Unknown Account' error is ok - account already deleted # https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-format if err.errno == 102: return raise def login(self): try: session = self.client.login(self.email, self.password) return session except ClientError as err: # 'Unknown Account' error is the only one we care about and will # cause us to throw a custom exception # https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-format if err.errno == 102: raise AccountNotFoundException('FxA Account Not Found') raise @property def email(self): return self.account.email @property def is_verified(self): return self.session.get_email_status()['verified']
def test_account_creation(self): acct = TestEmailAccount() acct.password = DUMMY_PASSWORD session = self.client.create_account(acct.email, DUMMY_PASSWORD) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertEqual(session._key_fetch_token, None) with self.assertRaises(Exception): session.fetch_keys()
def test_resend_verify_code(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) is_verify_email = lambda m: "x-verify-code" in m["headers"] m1 = acct.wait_for_email(is_verify_email) code1 = m1["headers"]["x-verify-code"] # NOQA acct.clear() session.resend_email_code()
def get_fxa_account(): fxa_client = get_fxa_client() account = TestEmailAccount() password = ''.join([random.choice(string.ascii_letters) for i in range(8)]) FxAccount = collections.namedtuple('FxAccount', 'email password') fxa_account = FxAccount(email=account.email, password=password) session = fxa_client.create_account(fxa_account.email, fxa_account.password) account.fetch() message = account.wait_for_email(lambda m: 'x-verify-code' in m['headers']) session.verify_email_code(message['headers']['x-verify-code']) return fxa_account, account
def create(ctx): """Create a Firefox Account.""" account = TestEmailAccount() client = Client(ctx.obj["URL"]) password = "".join([random.choice(string.ascii_letters) for i in range(8)]) session = client.create_account(account.email, password) add(ctx.obj["URL"], account.email, password) click.echo("Account {}!\n{}".format( crayons.yellow("created"), render(ctx.obj["URL"], account.email, password))) message = account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) session.verify_email_code(message["headers"]["x-verify-code"]) click.echo("Account {}! 🎉".format(crayons.green("verified"))) account.clear()
def test_add_content(env, conf): # Grab a bearer token that we can use to talk to the webextensions endpoint acct = TestEmailAccount() email = acct.email passwd = str(uuid.uuid4()) fxaclient = FxaClient("https://api.accounts.firefox.com") session = fxaclient.create_account(email, passwd) m = acct.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if m is None: raise RuntimeErrors("Verification email did not arrive") session.verify_email_code(m["headers"]["x-verify-code"]) auth = FxABearerTokenAuth( email, passwd, scopes=['sync:addon_storage'], client_id=DEFAULT_CLIENT_ID, account_server_url=conf.get(env, 'account_server_url'), oauth_server_url=conf.get(env, 'oauth_server_url'), ) client = Client(server_url=conf.get(env, 'we_server_url'), auth=auth) # Add a record to our QA collection and make sure we have N+1 records existing_records = client.get_records(collection=conf.get( env, 'qa_collection'), bucket='default') assert len(existing_records) == 0 data = {"payload": {"encrypted": "SmluZ28gdGVzdA=="}} resp = client.create_record(data=data, collection=conf.get(env, 'qa_collection'), bucket='default') new_record_id = resp['data']['id'] updated_records = client.get_records(collection=conf.get( env, 'qa_collection'), bucket='default') assert len(updated_records) == len(existing_records) + 1 client.delete_record(id=new_record_id, collection=conf.get(env, 'qa_collection')) updated_records = client.get_records(collection=conf.get( env, 'qa_collection'), bucket='default') assert len(updated_records) == len(existing_records) # Clean up the account that we created for the test acct.clear() fxaclient.destroy_account(email, passwd)
def _create_fxa_user(self): """Create fxa user for logging in.""" fxa_client = Client(ENVIRONMENT_URLS['stable']['authentication']) account = TestEmailAccount(email=self.fxa_email) password = self.fxa_password FxAccount = collections.namedtuple('FxAccount', 'email password') fxa_account = FxAccount(email=account.email, password=password) session = fxa_client.create_account(fxa_account.email, fxa_account.password) account.fetch() message = account.wait_for_email(lambda m: 'x-verify-code' in m[ 'headers'] and session.uid == m['headers']['x-uid']) session.verify_email_code(message['headers']['x-verify-code']) log.info('fxa account created: {}'.format(fxa_account)) return session.uid
class FxATestAccount: """A base test class that can be extended by other tests to include utility methods.""" password = ''.join([random.choice(string.letters) for i in xrange(8)]) def __init__(self, base_url=None): if base_url and '-dev.allizom' in base_url: self.fxa_url = 'https://stable.dev.lcip.org/auth/' else: self.fxa_url = 'https://api.accounts.firefox.com/' def create_account(self): random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) client = Client(self.fxa_url) print 'fxapom created an account for email: %s at %s on %s' % ( self.account.email, self.fxa_url, datetime.now()) # Create and verify the Firefox account self.session = client.create_account(self.account.email, self.password) m = self.account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) return self @property def email(self): return self.account.email @property def is_verified(self): return self.session.get_email_status()['verified']
def _create_fxa_user(self): """Create fxa user for logging in.""" fxa_client = Client(ENVIRONMENT_URLS['stable']['authentication']) account = TestEmailAccount(email=self.fxa_email) password = self.fxa_password FxAccount = collections.namedtuple('FxAccount', 'email password') fxa_account = FxAccount(email=account.email, password=password) session = fxa_client.create_account(fxa_account.email, fxa_account.password) account.fetch() message = account.wait_for_email( lambda m: 'x-verify-code' in m['headers'] and session.uid == m['headers']['x-uid'] ) session.verify_email_code(message['headers']['x-verify-code']) log.debug('fxa account created: {}'.format(fxa_account)) return session.uid
def __init__(self, url=DEV_URL): """ Creates an FxATestAccount object, which includes a verified account. :param url: The url for the api host. Defaults to DEV_URL. """ self.url = url random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) self.client = Client(self.url) # Create and verify the Firefox account self.session = self.client.create_account(self.account.email, self.password) print('fxapom created an account for email: %s at %s on %s' % ( self.account.email, self.url, datetime.now())) m = self.account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"])
def fxa_account(fxa_client, fxa_email): logger = logging.getLogger() account = TestEmailAccount(email=fxa_email) password = "".join([random.choice(string.ascii_letters) for i in range(8)]) FxAccount = collections.namedtuple("FxAccount", "email password") fxa_account = FxAccount(email=account.email, password=password) try: session = fxa_client.create_account(fxa_account.email, fxa_account.password) logger.info("Created: {}".format(fxa_account)) message = account.wait_for_email(lambda m: "x-verify-code" in m[ "headers"] and session.uid == m["headers"]["x-uid"]) assert message is not None, "Verification email not found." session.verify_email_code(message["headers"]["x-verify-code"]) logger.info("Verified: {}".format(fxa_account)) yield fxa_account finally: fxa_cleanup(account, fxa_client, fxa_account)
def create_account_and_token(args): acct = TestEmailAccount() client = Client("https://api.accounts.firefox.com") session = client.create_account(acct.email, 'MySecretPassword') m = acct.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if m is None: raise RuntimeError("verification email did not arrive") session.verify_email_code(m["headers"]["x-verify-code"]) _FXA['token'] = get_bearer_token( acct.email, 'MySecretPassword', account_server_url="https://api.accounts.firefox.com/v1", oauth_server_url="https://oauth.accounts.firefox.com/v1", scopes=['sync:addon_storage'], client_id=DEFAULT_CLIENT_ID) _FXA['acct'] = acct _FXA['client'] = client
def test_email_code_verification(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.client.create_account( email=self.acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) def wait_for_email(m): return "x-uid" in m["headers"] and "x-verify-code" in m["headers"] m = self.acct.wait_for_email(wait_for_email) if not m: raise RuntimeError("Verification email was not received") # If everything went well, verify_email_code should return an empty json object response = self.client.verify_email_code(m["headers"]["x-uid"], m["headers"]["x-verify-code"]) self.assertEquals(response, {})
def get_auth(self): acct = TestEmailAccount(self.email) client = Client(self.server) session = client.create_account(self.email, password=self.password) def is_verify_email(m): return "x-verify-code" in m["headers"] message = acct.wait_for_email(is_verify_email) session.verify_email_code(message["headers"]["x-verify-code"]) url = urlparse(SERVER_URL) audience = "%s://%s" % (url.scheme, url.hostname) return FxABrowserIDAuth( self.email, password=self.password, audience=audience, server_url=self.server)
def test_account_creation_with_key_fetch(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, keys=True, ) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertNotEqual(session._key_fetch_token, None)
def test_send_unblock_code(self): acct = TestEmailAccount(email="block-{uniq}@{hostname}") self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate sending unblock code response = self.client.send_unblock_code(acct.email) self.assertEquals(response, {}) m = acct.wait_for_email(lambda m: "x-unblock-code" in m["headers"]) if not m: raise RuntimeError("Unblock code email was not received") code = m["headers"]["x-unblock-code"] self.assertTrue(len(code) > 0) self.client.login(email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, unblock_code=code)
def test_account_login(self): acct = TestEmailAccount() session1 = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) session2 = self.client.login( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self.assertEqual(session1.email, session2.email) self.assertNotEqual(session1.token, session2.token)
def test_forgot_password_flow(self): acct = TestEmailAccount() self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate the password reset flow, and grab the verification code. pftok = self.client.send_reset_code(acct.email, service="foobar") m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") acct.clear() code = m["headers"]["x-recovery-code"] # Try with an invalid code to test error handling. tries = pftok.tries_remaining self.assertTrue(tries > 1) with self.assertRaises(Exception): pftok.verify_code(mutate_one_byte(code)) pftok.get_status() self.assertEqual(pftok.tries_remaining, tries - 1) # Re-send the code, as if we've lost the email. pftok.resend_code() m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") self.assertEqual(m["headers"]["x-recovery-code"], code) # Now verify with the actual code, and reset the account. artok = pftok.verify_code(code) self.client.reset_account( email=acct.email, token=artok, stretchpwd=DUMMY_STRETCHED_PASSWORD )
def create_account(self): random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) client = Client(self.fxa_url) print 'fxapom created an account for email: %s at %s on %s' % ( self.account.email, self.fxa_url, datetime.now()) # Create and verify the Firefox account self.session = client.create_account(self.account.email, self.password) m = self.account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) return self
def get_auth(self): self.account_server_url = os.getenv("FXA_URL", DEFAULT_FXA_URL) random_user = uuid.uuid4().hex self.user_email = "*****@*****.**" % random_user acct = TestEmailAccount(self.user_email) client = Client(self.account_server_url) fxa_session = client.create_account(self.user_email, password=random_user) def is_verify_email(m): return "x-verify-code" in m["headers"] message = acct.wait_for_email(is_verify_email) fxa_session.verify_email_code(message["headers"]["x-verify-code"]) url = urlparse(self.base_url) audience = "%s://%s" % (url.scheme, url.hostname) return FxABrowserIDAuth( self.user_email, password=random_user, audience=audience, server_url=self.account_server_url)
def setUp(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.stretchpwd = quick_stretch_password( self.acct.email, DUMMY_PASSWORD, ) self.session = self.client.create_account( email=self.acct.email, stretchpwd=self.stretchpwd, keys=True, ) # Verify the account so that we can actually use the session. m = self.acct.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) # Fetch the keys. self.session.fetch_keys() self.assertEqual(len(self.session.keys), 2) self.assertEqual(len(self.session.keys[0]), 32) self.assertEqual(len(self.session.keys[1]), 32)
class FXATestAccount(object): def __init__(self, server=_FXA_SERVER, oauth=_FXA_OAUTH, password=_PWD): self.server = server self.oauth = oauth self.session = self.token = None self.password = password self.acct = TestEmailAccount() self.client = Client(_FXA_SERVER) def _verify(self, session, response): code = response["headers"].get('x-verify-code') if code is None: return False session.verify_email_code(code) return True def create(self): session = self.client.create_account(self.acct.email, self.password) m = self.acct.wait_for_email(functools.partial(self._verify, session)) if m is None: raise RuntimeError("verification email did not arrive") self.token = get_bearer_token(self.acct.email, self.password, account_server_url=self.server + "/v1", oauth_server_url=self.oauth, scopes=['sync:addon_storage'], client_id=DEFAULT_CLIENT_ID) def cleanup(self): self.acct.clear() self.client.destroy_account(self.acct.email, self.password) def authorization(self): if self.token is None: raise RuntimeError("You need to call create() first") return "Bearer %s" % self.token
def test_send_unblock_code(self): acct = TestEmailAccount(email="block-{uniq}@{hostname}") self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate sending unblock code response = self.client.send_unblock_code(acct.email) self.assertEquals(response, {}) m = acct.wait_for_email(lambda m: "x-unblock-code" in m["headers"]) if not m: raise RuntimeError("Unblock code email was not received") code = m["headers"]["x-unblock-code"] self.assertTrue(len(code) > 0) self.client.login( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, unblock_code=code )
def __init__(self, url=DEV_URL): """ Creates an FxATestAccount object, which includes a verified account. :param url: The url for the api host. Defaults to DEV_URL. """ self.url = url random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(12)) email_pattern = random_string + '@{hostname}' self.account = TestEmailAccount(email=email_pattern) self.client = Client(self.url) # Create and verify the Firefox account self.session = self.client.create_account(self.account.email, self.password) print 'fxapom created an account for email: %s at %s on %s' % ( self.account.email, self.url, datetime.now()) m = self.account.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"])
def fxa_account(fxa_client): logger = logging.getLogger() account = TestEmailAccount() password = ''.join([random.choice(string.ascii_letters) for i in range(8)]) FxAccount = collections.namedtuple('FxAccount', 'email password') fxa_account = FxAccount(email=account.email, password=password) session = fxa_client.create_account(fxa_account.email, fxa_account.password) logger.info('Created: {}'.format(fxa_account)) account.fetch() message = account.wait_for_email(lambda m: 'x-verify-code' in m['headers']) session.verify_email_code(message['headers']['x-verify-code']) logger.info('Verified: {}'.format(fxa_account)) yield fxa_account account.clear() fxa_client.destroy_account(fxa_account.email, fxa_account.password) logger.info('Removed: {}'.format(fxa_account))
def setUpClass(cls): # Create an ephemeral email account to use to create an FxA account cls.acct = TestEmailAccount() cls.client = Client(FXA_ACCOUNT_STAGE_HOST) cls.oauth_client = OAuthClient(CLIENT_ID, None, server_url=FXA_OAUTH_STAGE_HOST) cls.fxa_password = cls._generate_password() # Create an FxA account for these end-to-end tests cls.session = cls.client.create_account(cls.acct.email, password=cls.fxa_password) # Loop until we receive the verification email from FxA while not cls.acct.messages: time.sleep(0.5) cls.acct.fetch() # Find the message containing the verification code and verify the # code for m in cls.acct.messages: if 'x-verify-code' in m['headers']: cls.session.verify_email_code(m['headers']['x-verify-code']) # Create an OAuth token to be used for the end-to-end tests cls.oauth_token = cls.oauth_client.authorize_token(cls.session, SCOPE) cls.browserid_assertion = \ cls.session.get_identity_assertion(BROWSERID_AUDIENCE)
def test_forgot_password_flow(self): acct = TestEmailAccount() self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate the password reset flow, and grab the verification code. pftok = self.client.send_reset_code(acct.email, service="foobar") m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") acct.clear() code = m["headers"]["x-recovery-code"] # Try with an invalid code to test error handling. tries = pftok.tries_remaining self.assertTrue(tries > 1) with self.assertRaises(Exception): pftok.verify_code(mutate_one_byte(code)) pftok.get_status() self.assertEqual(pftok.tries_remaining, tries - 1) # Re-send the code, as if we've lost the email. pftok.resend_code() m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") self.assertEqual(m["headers"]["x-recovery-code"], code) # Now verify with the actual code, and reset the account. artok = pftok.verify_code(code) self.client.reset_account(email=acct.email, token=artok, stretchpwd=DUMMY_STRETCHED_PASSWORD)
class TestCoreClient(unittest.TestCase): server_url = TEST_SERVER_URL def setUp(self): self.client = Client(self.server_url) self._accounts_to_delete = [] def tearDown(self): for acct in self._accounts_to_delete: acct.clear() try: stretchpwd = acct.stretchpwd except AttributeError: try: password = acct.password stretchpwd = quick_stretch_password(acct.email, password) except AttributeError: stretchpwd = DUMMY_STRETCHED_PASSWORD self.client.destroy_account(acct.email, stretchpwd=stretchpwd) def test_account_creation(self): acct = TestEmailAccount() acct.password = DUMMY_PASSWORD session = self.client.create_account(acct.email, DUMMY_PASSWORD) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertEqual(session._key_fetch_token, None) with self.assertRaises(Exception): session.fetch_keys() def test_account_creation_with_key_fetch(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, keys=True, ) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertNotEqual(session._key_fetch_token, None) def test_account_login(self): acct = TestEmailAccount() session1 = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) session2 = self.client.login( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self.assertEqual(session1.email, session2.email) self.assertNotEqual(session1.token, session2.token) def test_get_random_bytes(self): b1 = self.client.get_random_bytes() b2 = self.client.get_random_bytes() self.assertTrue(isinstance(b1, binary_type)) self.assertNotEqual(b1, b2) def test_resend_verify_code(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) def is_verify_email(m): return "x-verify-code" in m["headers"] m1 = acct.wait_for_email(is_verify_email) code1 = m1["headers"]["x-verify-code"] # NOQA acct.clear() session.resend_email_code() # XXX TODO: this won't work against a live server because we # refuse to send duplicate emails within a short timespan. # m2 = acct.wait_for_email(is_verify_email) # code2 = m2["headers"]["x-verify-code"] # self.assertNotEqual(m1, m2) # self.assertEqual(code1, code2) def test_forgot_password_flow(self): acct = TestEmailAccount() self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate the password reset flow, and grab the verification code. pftok = self.client.send_reset_code(acct.email, service="foobar") m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") acct.clear() code = m["headers"]["x-recovery-code"] # Try with an invalid code to test error handling. tries = pftok.tries_remaining self.assertTrue(tries > 1) with self.assertRaises(Exception): pftok.verify_code(mutate_one_byte(code)) pftok.get_status() self.assertEqual(pftok.tries_remaining, tries - 1) # Re-send the code, as if we've lost the email. pftok.resend_code() m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") self.assertEqual(m["headers"]["x-recovery-code"], code) # Now verify with the actual code, and reset the account. artok = pftok.verify_code(code) self.client.reset_account( email=acct.email, token=artok, stretchpwd=DUMMY_STRETCHED_PASSWORD ) def test_email_code_verification(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.client.create_account( email=self.acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) def wait_for_email(m): return "x-uid" in m["headers"] and "x-verify-code" in m["headers"] m = self.acct.wait_for_email(wait_for_email) if not m: raise RuntimeError("Verification email was not received") # If everything went well, verify_email_code should return an empty json object response = self.client.verify_email_code(m["headers"]["x-uid"], m["headers"]["x-verify-code"]) self.assertEquals(response, {}) def test_send_unblock_code(self): acct = TestEmailAccount(email="block-{uniq}@{hostname}") self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate sending unblock code response = self.client.send_unblock_code(acct.email) self.assertEquals(response, {}) m = acct.wait_for_email(lambda m: "x-unblock-code" in m["headers"]) if not m: raise RuntimeError("Unblock code email was not received") code = m["headers"]["x-unblock-code"] self.assertTrue(len(code) > 0) self.client.login( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, unblock_code=code )
class TestCoreClientSession(unittest.TestCase): server_url = TEST_SERVER_URL def setUp(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.stretchpwd = quick_stretch_password( self.acct.email, DUMMY_PASSWORD, ) self.session = self.client.create_account( email=self.acct.email, stretchpwd=self.stretchpwd, keys=True, ) # Verify the account so that we can actually use the session. m = self.acct.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.session.verify_email_code(m["headers"]["x-verify-code"]) # Fetch the keys. self.session.fetch_keys() self.assertEqual(len(self.session.keys), 2) self.assertEqual(len(self.session.keys[0]), 32) self.assertEqual(len(self.session.keys[1]), 32) def tearDown(self): # Clean up the session and account. # This might fail if the test already cleaned it up. try: self.session.destroy_session() except fxa.errors.ClientError: pass try: self.client.destroy_account( email=self.acct.email, stretchpwd=self.stretchpwd, ) except fxa.errors.ClientError: pass self.acct.clear() def test_session_status(self): self.session.check_session_status() self.session.destroy_session() with self.assertRaises(fxa.errors.ClientError): self.session.check_session_status() def test_email_status(self): status = self.session.get_email_status() self.assertTrue(status["verified"]) def test_get_random_bytes(self): b1 = self.session.get_random_bytes() b2 = self.session.get_random_bytes() self.assertTrue(isinstance(b1, six.binary_type)) self.assertNotEqual(b1, b2) def test_sign_certificate(self): email = self.acct.email pubkey = browserid.tests.support.get_keypair(email)[0] cert = self.session.sign_certificate(pubkey) issuer = browserid.utils.decode_json_bytes(cert.split(".")[1])["iss"] expected_issuer = urlparse.urlparse(self.client.server_url).hostname self.assertEqual(issuer, expected_issuer) def test_change_password(self): # Change the password. newpwd = mutate_one_byte(DUMMY_PASSWORD) self.stretchpwd = quick_stretch_password(self.acct.email, newpwd) self.session.change_password(DUMMY_PASSWORD, newpwd) # Check that we can use the new password. session2 = self.client.login(self.acct.email, newpwd, keys=True) # Check that encryption keys have been preserved. session2.fetch_keys() self.assertEquals(self.session.keys, session2.keys)
def _get_new_user_email_acct(self): uid = uniq() email = "loads-fxa-{}[email protected]".format(uid) return TestEmailAccount(email)
def _get_existing_user_email_acct(self): uid = random.randint(1, 999) email = "loads-fxa-{}[email protected]".format(uid) return TestEmailAccount(email)
class TestCoreClient(unittest.TestCase): server_url = TEST_SERVER_URL def setUp(self): self.client = Client(self.server_url) self._accounts_to_delete = [] def tearDown(self): for acct in self._accounts_to_delete: acct.clear() try: stretchpwd = acct.stretchpwd except AttributeError: try: password = acct.password stretchpwd = quick_stretch_password(acct.email, password) except AttributeError: stretchpwd = DUMMY_STRETCHED_PASSWORD self.client.destroy_account(acct.email, stretchpwd=stretchpwd) def test_account_creation(self): acct = TestEmailAccount() acct.password = DUMMY_PASSWORD session = self.client.create_account(acct.email, DUMMY_PASSWORD) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertEqual(session._key_fetch_token, None) with self.assertRaises(Exception): session.fetch_keys() def test_account_creation_with_key_fetch(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, keys=True, ) self._accounts_to_delete.append(acct) self.assertEqual(session.email, acct.email) self.assertFalse(session.verified) self.assertEqual(session.keys, None) self.assertNotEqual(session._key_fetch_token, None) def test_account_login(self): acct = TestEmailAccount() session1 = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) session2 = self.client.login( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self.assertEqual(session1.email, session2.email) self.assertNotEqual(session1.token, session2.token) def test_get_random_bytes(self): b1 = self.client.get_random_bytes() b2 = self.client.get_random_bytes() self.assertTrue(isinstance(b1, binary_type)) self.assertNotEqual(b1, b2) def test_resend_verify_code(self): acct = TestEmailAccount() session = self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) def is_verify_email(m): return "x-verify-code" in m["headers"] m1 = acct.wait_for_email(is_verify_email) code1 = m1["headers"]["x-verify-code"] # NOQA acct.clear() session.resend_email_code() # XXX TODO: this won't work against a live server because we # refuse to send duplicate emails within a short timespan. # m2 = acct.wait_for_email(is_verify_email) # code2 = m2["headers"]["x-verify-code"] # self.assertNotEqual(m1, m2) # self.assertEqual(code1, code2) def test_forgot_password_flow(self): acct = TestEmailAccount() self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate the password reset flow, and grab the verification code. pftok = self.client.send_reset_code(acct.email, service="foobar") m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") acct.clear() code = m["headers"]["x-recovery-code"] # Try with an invalid code to test error handling. tries = pftok.tries_remaining self.assertTrue(tries > 1) with self.assertRaises(Exception): pftok.verify_code(mutate_one_byte(code)) pftok.get_status() self.assertEqual(pftok.tries_remaining, tries - 1) # Re-send the code, as if we've lost the email. pftok.resend_code() m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") self.assertEqual(m["headers"]["x-recovery-code"], code) # Now verify with the actual code, and reset the account. artok = pftok.verify_code(code) self.client.reset_account(email=acct.email, token=artok, stretchpwd=DUMMY_STRETCHED_PASSWORD) def test_email_code_verification(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.client.create_account( email=self.acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) def wait_for_email(m): return "x-uid" in m["headers"] and "x-verify-code" in m["headers"] m = self.acct.wait_for_email(wait_for_email) if not m: raise RuntimeError("Verification email was not received") # If everything went well, verify_email_code should return an empty json object response = self.client.verify_email_code(m["headers"]["x-uid"], m["headers"]["x-verify-code"]) self.assertEquals(response, {}) def test_send_unblock_code(self): acct = TestEmailAccount(email="block-{uniq}@{hostname}") self.client.create_account( email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, ) self._accounts_to_delete.append(acct) # Initiate sending unblock code response = self.client.send_unblock_code(acct.email) self.assertEquals(response, {}) m = acct.wait_for_email(lambda m: "x-unblock-code" in m["headers"]) if not m: raise RuntimeError("Unblock code email was not received") code = m["headers"]["x-unblock-code"] self.assertTrue(len(code) > 0) self.client.login(email=acct.email, stretchpwd=DUMMY_STRETCHED_PASSWORD, unblock_code=code)
class TestCoreClientSession(unittest.TestCase): server_url = TEST_SERVER_URL def setUp(self): self.client = Client(self.server_url) # Create a fresh testing account. self.acct = TestEmailAccount() self.stretchpwd = quick_stretch_password( self.acct.email, DUMMY_PASSWORD, ) self.session = self.client.create_account( email=self.acct.email, stretchpwd=self.stretchpwd, keys=True, ) # Verify the account so that we can actually use the session. m = self.acct.wait_for_email(lambda m: "x-verify-code" in m["headers"]) if not m: raise RuntimeError("Verification email was not received") self.acct.clear() self.session.verify_email_code(m["headers"]["x-verify-code"]) # Fetch the keys. self.session.fetch_keys() self.assertEqual(len(self.session.keys), 2) self.assertEqual(len(self.session.keys[0]), 32) self.assertEqual(len(self.session.keys[1]), 32) def tearDown(self): # Clean up the session and account. # This might fail if the test already cleaned it up. try: self.session.destroy_session() except fxa.errors.ClientError: pass try: self.client.destroy_account( email=self.acct.email, stretchpwd=self.stretchpwd, ) except fxa.errors.ClientError: pass self.acct.clear() def test_session_status(self): self.session.check_session_status() self.session.destroy_session() with self.assertRaises(fxa.errors.ClientError): self.session.check_session_status() def test_email_status(self): status = self.session.get_email_status() self.assertTrue(status["verified"]) def test_get_random_bytes(self): b1 = self.session.get_random_bytes() b2 = self.session.get_random_bytes() self.assertTrue(isinstance(b1, binary_type)) self.assertNotEqual(b1, b2) def test_sign_certificate(self): email = self.acct.email pubkey = browserid.tests.support.get_keypair(email)[0] cert = self.session.sign_certificate(pubkey) issuer = browserid.utils.decode_json_bytes(cert.split(".")[1])["iss"] expected_issuer = urlparse(self.client.server_url).hostname self.assertEqual(issuer, expected_issuer) def test_sign_certificate_handles_duration(self): email = self.acct.email pubkey = browserid.tests.support.get_keypair(email)[0] millis = int(round(time.time() * 1000)) cert = self.session.sign_certificate(pubkey, duration=4000) cert_exp = browserid.utils.decode_json_bytes(cert.split(".")[1])["exp"] ttl = round(float(cert_exp - millis) / 1000) self.assertGreaterEqual(ttl, 2) self.assertLessEqual(ttl, 30) def test_change_password(self): # Change the password. newpwd = mutate_one_byte(DUMMY_PASSWORD) self.stretchpwd = quick_stretch_password(self.acct.email, newpwd) self.session.change_password(DUMMY_PASSWORD, newpwd) # Check that we can use the new password. session2 = self.client.login(self.acct.email, newpwd, keys=True) if not session2.get_email_status().get("verified"): def has_verify_code(m): return "x-verify-code" in m["headers"] m = self.acct.wait_for_email(has_verify_code) if not m: raise RuntimeError("Verification email was not received") self.acct.clear() session2.verify_email_code(m["headers"]["x-verify-code"]) # Check that encryption keys have been preserved. session2.fetch_keys() self.assertEquals(self.session.keys, session2.keys) def test_get_identity_assertion(self): assertion = self.session.get_identity_assertion("http://example.com") data = browserid.verify(assertion, audience="http://example.com") self.assertEquals(data["status"], "okay") expected_issuer = urlparse(self.session.server_url).hostname self.assertEquals(data["issuer"], expected_issuer) expected_email = "{0}@{1}".format(self.session.uid, expected_issuer) self.assertEquals(data["email"], expected_email) def test_get_identity_assertion_handles_duration(self): millis = int(round(time.time() * 1000)) bid_assertion = self.session.get_identity_assertion( "http://example.com", 1234) cert, assertion = browserid.utils.unbundle_certs_and_assertion( bid_assertion) cert = jwt.parse(cert[0]).payload assertion = jwt.parse(assertion).payload # Validate cert expiry ttl = round(float(cert['exp'] - millis) / 1000) self.assertGreaterEqual(ttl, 1230) self.assertLessEqual(ttl, 1260) # Validate assertion expiry ttl = round(float(assertion['exp'] - millis) / 1000) self.assertGreaterEqual(ttl, 1230) self.assertLessEqual(ttl, 1260) def test_get_identity_assertion_accepts_service(self): # We can't observe any side-effects of sending the service query param, # but we can test that it doesn't error out. assertion = self.session.get_identity_assertion("http://example.com", service="test-me") data = browserid.verify(assertion, audience="http://example.com") self.assertEquals(data["status"], "okay") def test_totp(self): resp = self.session.totp_create() # Double create causes a client error with self.assertRaises(fxa.errors.ClientError): self.session.totp_create() # Created but not verified returns false (and deletes the token) self.assertFalse(self.session.totp_exists()) # Creating again should work this time resp = self.session.totp_create() # Verify the code code = pyotp.TOTP(resp["secret"]).now() self.assertTrue(self.session.totp_verify(code)) self.assertTrue(self.session.verified) # Should exist now self.assertTrue(self.session.totp_exists()) # Remove the code resp = self.session.totp_delete() # And now should not exist self.assertFalse(self.session.totp_exists())