Пример #1
0
 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)
Пример #2
0
def login(user):
    client = Client("https://api.accounts.firefox.com")
    session = client.login(user['email'], user['password'], keys=True)

    keyA,keyB = session.fetch_keys()

    info = b"identity.mozilla.com/picl/v1/oldsync"
    namespace = b"oldsync"
    keys = derive_key(secret=keyB, namespace=namespace, size=64)
    encryption_key = keys[0:32]
    hmac_key = keys[32:64]

    # TODO: Store this or a derived longer-lived token
    #       Causes a login event which causes an email
    # TODO: Should move to use OAuth which solves the long-term cred storage
    #       issue
    fxab = FxABrowserIDAuth(user['email'], user['password'], with_client_state=True)
    raw_resp = requests.get('https://token.services.mozilla.com/1.0/sync/1.5', auth=fxab)
    raw_resp.raise_for_status()
    hawk_resp = raw_resp.json()

    return {
        "hawk_resp": hawk_resp,
        "hawk_uid": hawk_resp['uid'],
        "hawk_hashalg": hawk_resp['hashalg'],
        "hawk_api_endpoint": hawk_resp['api_endpoint'],
        "hawk_duration": hawk_resp['duration'],
        "hawk_key": hawk_resp['key'],
        "hawk_hashed_fxa_uid": hawk_resp['hashed_fxa_uid'],
        "hawk_id": hawk_resp['id'],

        'encryption_key': encryption_key.hex(),
        'hmac_key': hmac_key.hex(),
    }
Пример #3
0
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()
Пример #4
0
def destroy(ctx, _all, email, password):
    """Destroy a Firefox Account."""
    accounts = []
    stored = load()

    try:
        if email and password:
            account = {
                "url": ctx.obj["URL"],
                "email": email,
                "password": password
            }
            accounts.append(account)
            stored.remove(account)
        elif email:
            click.echo("You must specify a {}! 🔑".format(
                crayons.magenta("--password")))
            exit(1)
        else:
            if _all and stored:
                accounts.extend(stored)
                stored = []
            else:
                accounts.append(stored.pop())
    except ValueError:
        pass  # account unknown to .accounts
    except IndexError:
        click.echo("No account to destroy! 🎻")
        exit(1)

    for account in accounts:
        client = Client(account["url"])
        try:
            client.destroy_account(account["email"], account["password"])
            click.echo("Account {}! 💥\n{}".format(
                crayons.red("destroyed"),
                render(account["url"], account["email"], account["password"]),
            ))
        except ClientError as e:
            if e.errno == 102:
                click.echo("Account {}! 🔍\n{}".format(
                    crayons.cyan("unknown"),
                    render(account["url"], account["email"],
                           account["password"]),
                ))
            else:
                raise

    save(stored)
Пример #5
0
 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
Пример #6
0
def get_oauth_token(client_id=CLIENT_ID,
                    oauth_server=OAUTH_SERVER,
                    auth_server=AUTH_SERVER,
                    email=EMAIL,
                    password=PASSWORD):

    if password is None:
        raise Exception('You must set FXA_PASSWORD')

    print('Getting an oauth token from FxA')
    oauth_client = OAuthClient(client_id, server_url=oauth_server)
    session = Client(server_url=auth_server).login(email, password=password)
    assertion = session.get_identity_assertion(oauth_server)

    return oauth_client.authorize_token(assertion, scope="profile")
Пример #7
0
    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"])
Пример #8
0
def login(user):
    """
    Logs a user into their Firefox account and returns tempoary credentials
    for use by AuthRequest.
    """
    # TODO: pull out the urls to be part of the config.
    client = Client("https://api.accounts.firefox.com")
    session = client.login(user['email'], user['password'], keys=True)

    keyA, keyB = session.fetch_keys()

    # Magic strings from the docs
    # https://moz-services-docs.readthedocs.io/en/latest/sync/storageformat5.html
    info = b"identity.mozilla.com/picl/v1/oldsync"
    namespace = b"oldsync"
    keys = derive_key(secret=keyB, namespace=namespace, size=64)
    encryption_key = keys[0:32]
    hmac_key = keys[32:64]

    # TODO: Store this or a derived longer-lived token
    #       Causes a login event which causes an email
    # TODO: Should move to use OAuth which solves the long-term cred storage
    #       issue
    fxab = FxABrowserIDAuth(user['email'],
                            user['password'],
                            with_client_state=True)
    raw_resp = requests.get('https://token.services.mozilla.com/1.0/sync/1.5',
                            auth=fxab)
    raw_resp.raise_for_status()
    hawk_resp = raw_resp.json()

    return {
        "hawk_resp": hawk_resp,
        "hawk_uid": hawk_resp['uid'],
        "hawk_hashalg": hawk_resp['hashalg'],
        "hawk_api_endpoint": hawk_resp['api_endpoint'],
        "hawk_duration": hawk_resp['duration'],
        "hawk_key": hawk_resp['key'],
        "hawk_hashed_fxa_uid": hawk_resp['hashed_fxa_uid'],
        "hawk_id": hawk_resp['id'],
        'encryption_key': encryption_key.hex(),
        'hmac_key': hmac_key.hex(),
    }
Пример #9
0
    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, {})
Пример #10
0
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
Пример #11
0
 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)
Пример #12
0
 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)
Пример #13
0
def get_fxa_client():
    fxa_env = os.getenv('FXA_ENV', 'stable')
    return Client(ENVIRONMENT_URLS[fxa_env]['authentication'])
Пример #14
0
def fxa_client(fxa_urls):
    return Client(fxa_urls["authentication"])
Пример #15
0
 def setUp(self):
     super(LoadTest, self).setUp()
     self.client = Client(APIClient(self.server_url, session=self.session))
Пример #16
0
import hashlib
import hmac

config_file_name = 'config.test.ini'

config = ConfigParser()
config.read(config_file_name)

hawk_resp = None
encryption_key = None
hmac_key = None

if 'hawk' not in config or 'fxa' not in config:
    user = config['user']

    client = Client("https://api.accounts.firefox.com")
    session = client.login(user['email'], user['password'], keys=True)

    keyA, keyB = session.fetch_keys()

    info = b"identity.mozilla.com/picl/v1/oldsync"
    namespace = b"oldsync"
    keys = derive_key(secret=keyB, namespace=namespace, size=64)
    encryption_key = keys[0:32]
    hmac_key = keys[32:64]

    # TODO: Store this or a derived longer-lived token
    #       Causes a login event which causes an email
    fxab = FxABrowserIDAuth(user['email'],
                            user['password'],
                            with_client_state=True)
Пример #17
0
 def setUp(self):
     self.client = Client(self.server_url)
     self._accounts_to_delete = []
Пример #18
0
def fxa_client(fxa_urls):
    return Client(fxa_urls['authentication'])