Example #1
0
 def test_scopes_default_to_profile(self, oauth_client, core_client):
     get_bearer_token("email",
                      "password",
                      client_id="543210789456",
                      account_server_url="account_server_url",
                      oauth_server_url="oauth_server_url")
     oauth_client().authorize_token.assert_called_with(
         'abcd', 'profile', '543210789456')
Example #2
0
 def test_scopes_default_to_profile(self, oauth_client, core_client):
     get_bearer_token("email", "password",
                      client_id="543210789456",
                      account_server_url="account_server_url",
                      oauth_server_url="oauth_server_url")
     oauth_client().authorize_token.assert_called_with(
         core_client.return_value.login.return_value,
         'profile'
     )
Example #3
0
 def test_client_id_is_mandatory(self):
     try:
         get_bearer_token("email", "password",
                          account_server_url="account_server_url",
                          oauth_server_url="oauth_server_url")
     except ValueError as e:
         self.assertEqual("%s" % e, 'Please define a client_id.')
     else:
         self.fail("ValueError not raised")
Example #4
0
 def test_client_id_is_mandatory(self):
     try:
         get_bearer_token("email",
                          "password",
                          account_server_url="account_server_url",
                          oauth_server_url="oauth_server_url")
     except ValueError as e:
         self.assertEqual("%s" % e, 'Please define a client_id.')
     else:
         self.fail("ValueError not raised")
Example #5
0
def test_fxa_validate():
    """Test the FxA validation routines.

    This requires the PyFxA 0.5.0 module.

    """
    from fxa.tools.create_user import create_new_fxa_account
    from fxa.tools.bearer import get_bearer_token
    from fxa.constants import ENVIRONMENT_URLS

    token = os.environ.get("FXA_TOKEN")
    if not token:
        email, password = create_new_fxa_account(
            fxa_user_salt=None,
            account_server_url=ENVIRONMENT_URLS['stage']['authentication'],
            prefix='fxa',
            content_server_url=ENVIRONMENT_URLS['stage']['content'],
        )
        token = get_bearer_token(
            email=email,
            password=password,
            scopes=["https://identity.mozilla.com/apps/pushbox/"],
            account_server_url=ENVIRONMENT_URLS['stage']['authentication'],
            oauth_server_url=ENVIRONMENT_URLS['stage']['oauth'],
            client_id="5882386c6d801776",
        )
    print("Token: Bearer {}".format(token))
    result = fxa_validate_read(
        {
            "type":
            'TOKEN',
            "methodArn": ("arn:aws:execute-api:us-east-1:927034868273:3ksq"
                          "xftunj/dev/POST/v1/store/fxa/e6bddbeae45048"
                          "838e5a97eeba6633a7/11579fc58d0c5120329b5f7e0f7e"
                          "7c3a"),
            "authorizationToken":
            "Bearer {}".format(token)
        }, None)
    assert (result == {
        'principalId': 'user',
        'policyDocument': {
            'Version':
            '2012-10-17',
            'Statement': [{
                'Action':
                'execute-api:Invoke',
                'Effect':
                'Allow',
                'Resource': ('arn:aws:execute-api:us-east-1:927034868273:'
                             '3ksqxftunj/dev/POST/*')
            }]
        }
    })
    print("Ok")
    return token
Example #6
0
    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)
Example #7
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
    def __call__(self, request):
        cache_key = get_cache_key(
            self.account_server_url, self.oauth_server_url,
            self.email, self.password, self.scopes, self.client_id)
        token = None
        if self.cache:
            token = self.cache.get(cache_key)

        if not token:
            token = get_bearer_token(
                self.email, self.password, self.scopes,
                client_id=self.client_id,
                account_server_url=self.account_server_url,
                oauth_server_url=self.oauth_server_url)

            if self.cache:
                self.cache.set(cache_key, token)

        request.headers["Authorization"] = "Bearer %s" % token
        return request
Example #9
0
def main(args=None):
    """The main routine."""
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(description="PyFxA commands")
    parser.add_argument('--bearer',
                        help='Generate a Bearer token',
                        dest='bearer',
                        action='store_true')

    parser.add_argument('--browserid',
                        '--bid',
                        help='Generate a BrowserID assertion',
                        dest='browserid',
                        action='store_true')

    parser.add_argument('--create-user',
                        '-c',
                        help='Create a new user',
                        dest='create',
                        action='store_true')
    parser.add_argument('--auth',
                        '-u',
                        help='User credentials',
                        dest='auth',
                        required=False)
    parser.add_argument('--out',
                        '-o',
                        '-O',
                        help='Output file',
                        dest='output_file',
                        required=False,
                        default=None)

    parser.add_argument('--verbose',
                        '-v',
                        help='Display status',
                        dest='verbose',
                        action='store_true')

    # Creation args
    parser.add_argument('--user-salt',
                        help=('Salt used to calculate the user credentials. '
                              '(Random by default)'),
                        dest='fxa_user_salt',
                        required=False)

    # FxA server configuration
    parser.add_argument('--env',
                        help='The Firefox Account env to use',
                        dest='env',
                        choices=ENVIRONMENT_URLS.keys(),
                        default=DEFAULT_ENV,
                        required=False)
    parser.add_argument('--account-server',
                        help='Firefox Account server URL',
                        dest='account_server_url',
                        required=False)

    parser.add_argument('--oauth-server',
                        help='Firefox Account OAuth server URL',
                        dest='oauth_server_url',
                        required=False)

    parser.add_argument('--client-id',
                        help='Firefox Account OAuth client id.',
                        dest='client_id',
                        required=False,
                        default=DEFAULT_CLIENT_ID)

    parser.add_argument('--scopes',
                        help='Firefox Account OAuth scopes.',
                        dest='scopes',
                        required=False,
                        default='profile')

    parser.add_argument('--audience',
                        help='Firefox BrowserID assertion audience.',
                        dest='audience',
                        required=False)

    parser.add_argument('--duration',
                        help='Firefox BrowserID assertion duration.',
                        dest='duration',
                        required=False,
                        default='3600')

    parser.add_argument('--user-email-prefix',
                        '--prefix',
                        help='Firefox Account user creation email prefix.',
                        dest='prefix',
                        required=False,
                        default='fxa')

    args = vars(parser.parse_args())
    create = args['create']
    auth = args.get('auth')
    verbose = args['verbose']

    if verbose:
        logger.setLevel(logging.INFO)

    fxa_env = args['env']
    account_server_url = ENVIRONMENT_URLS[fxa_env]['authentication']
    oauth_server_url = ENVIRONMENT_URLS[fxa_env]['oauth']
    content_server_url = ENVIRONMENT_URLS[fxa_env]['content']
    token_server_url = ENVIRONMENT_URLS[fxa_env]['token']

    if args['account_server_url']:
        account_server_url = args['account_server_url']

    if args['oauth_server_url']:
        oauth_server_url = args['oauth_server_url']

    fd = sys.stdout  # By default write to the standard output
    fd_is_to_close = False
    out = args.get('output_file')
    if out:
        out = os.path.abspath(out)
        file_path = os.path.dirname(out)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        fd = open(out, 'w')
        fd_is_to_close = True

    if auth:
        # Ask for the user password if needed
        auth = auth.split(':', 1)
        if len(auth) < 2:
            email = auth[0]
            password = getpass.getpass('Please enter a password for %s: ' %
                                       auth[0])
    elif create:
        # Create a new user
        logger.info('Creating the account.')

        try:
            email, password = create_new_fxa_account(
                os.getenv('FXA_USER_SALT', args.get('fxa_user_salt')),
                account_server_url, args['prefix'], content_server_url)
        except (ClientError, ValueError) as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Account created: %s' % email)

    if args['bearer']:
        # Generate a Bearer Token for the user and write it into a file.
        scopes = [
            s.strip() for s in re.split(';|,|\t|\n', args['scopes'])
            if s.strip()
        ]
        client_id = args['client_id']

        logger.info('Generating the Bearer Token.')

        try:
            token = get_bearer_token(email, password, scopes,
                                     account_server_url, oauth_server_url,
                                     client_id)
        except ClientError as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Bearer Token generated.')

        print('# ---- BEARER TOKEN INFO ----', file=fd)
        print('# User: %s' % email, file=fd)
        print('# Scopes: %s' % ' '.join(scopes), file=fd)
        print('# Account: %s' % account_server_url, file=fd)
        print('# Oauth: %s' % oauth_server_url, file=fd)
        print('# Client ID: %s' % client_id, file=fd)
        print('# ---------------------------', file=fd)
        print('export OAUTH_BEARER_TOKEN="%s"\n' % token, file=fd)

    if args['browserid']:
        # Generate a BrowserID assertion for the user and write it into a file.
        audience = args['audience'] or token_server_url
        duration = int(args['duration'])

        logger.info('Creating the token.')

        try:
            bid_assertion, client_state = get_browserid_assertion(
                email, password, audience, account_server_url, duration)
        except ClientError as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Token created.')

        print('# ---- BROWSER ID ASSERTION INFO ----', file=fd)
        print('# User: %s' % email, file=fd)
        print('# Audience: %s' % audience, file=fd)
        print('# Account: %s' % account_server_url, file=fd)
        print('# ------------------------------------', file=fd)
        print('export FXA_BROWSERID_ASSERTION="%s"' % bid_assertion, file=fd)
        print('export FXA_CLIENT_STATE="%s"\n' % client_state, file=fd)

    if fd_is_to_close:
        fd.close()
Example #10
0
def main(args=None):
    """The main routine."""
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(description="PyFxA commands")
    parser.add_argument('--bearer',
                        help='Generate a Bearer token',
                        dest='bearer',
                        action='store_true')

    parser.add_argument('--browserid', '--bid',
                        help='Generate a BrowserID assertion',
                        dest='browserid',
                        action='store_true')

    parser.add_argument('--create-user', '-c',
                        help='Create a new user',
                        dest='create',
                        action='store_true')
    parser.add_argument('--auth', '-u',
                        help='User credentials',
                        dest='auth',
                        required=False)
    parser.add_argument('--out', '-o', '-O',
                        help='Output file',
                        dest='output_file',
                        required=False,
                        default=None)

    parser.add_argument('--verbose', '-v',
                        help='Display status',
                        dest='verbose',
                        action='store_true')

    # Creation args
    parser.add_argument('--user-salt',
                        help=('Salt used to calculate the user credentials. '
                              '(Random by default)'),
                        dest='fxa_user_salt',
                        required=False)

    # FxA server configuration
    parser.add_argument('--env',
                        help='The Firefox Account env to use',
                        dest='env',
                        choices=ENVIRONMENT_URLS.keys(),
                        default=DEFAULT_ENV,
                        required=False)
    parser.add_argument('--account-server',
                        help='Firefox Account server URL',
                        dest='account_server_url',
                        required=False)

    parser.add_argument('--oauth-server',
                        help='Firefox Account OAuth server URL',
                        dest='oauth_server_url',
                        required=False)

    parser.add_argument('--client-id',
                        help='Firefox Account OAuth client id.',
                        dest='client_id',
                        required=False,
                        default=DEFAULT_CLIENT_ID)

    parser.add_argument('--scopes',
                        help='Firefox Account OAuth scopes.',
                        dest='scopes',
                        required=False,
                        default='profile')

    parser.add_argument('--audience',
                        help='Firefox BrowserID assertion audience.',
                        dest='audience',
                        required=False)

    parser.add_argument('--duration',
                        help='Firefox BrowserID assertion duration.',
                        dest='duration',
                        required=False,
                        default='3600')

    parser.add_argument('--user-email-prefix', '--prefix',
                        help='Firefox Account user creation email prefix.',
                        dest='prefix',
                        required=False,
                        default='fxa')

    args = vars(parser.parse_args())
    create = args['create']
    auth = args.get('auth')
    verbose = args['verbose']

    if verbose:
        logger.setLevel(logging.INFO)

    fxa_env = args['env']
    account_server_url = ENVIRONMENT_URLS[fxa_env]['authentication']
    oauth_server_url = ENVIRONMENT_URLS[fxa_env]['oauth']
    content_server_url = ENVIRONMENT_URLS[fxa_env]['content']
    token_server_url = ENVIRONMENT_URLS[fxa_env]['token']

    if args['account_server_url']:
        account_server_url = args['account_server_url']

    if args['oauth_server_url']:
        oauth_server_url = args['oauth_server_url']

    fd = sys.stdout  # By default write to the standard output
    fd_is_to_close = False
    out = args.get('output_file')
    if out:
        out = os.path.abspath(out)
        file_path = os.path.dirname(out)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        fd = open(out, 'w')
        fd_is_to_close = True

    if auth:
        # Ask for the user password if needed
        auth = auth.split(':', 1)
        if len(auth) < 2:
            email = auth[0]
            password = getpass.getpass('Please enter a password for %s: '
                                       % auth[0])
    elif create:
        # Create a new user
        logger.info('Creating the account.')

        try:
            email, password = create_new_fxa_account(
                os.getenv('FXA_USER_SALT', args.get('fxa_user_salt')),
                account_server_url, args['prefix'], content_server_url)
        except (ClientError, ValueError) as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Account created: %s' % email)

    if args['bearer']:
        # Generate a Bearer Token for the user and write it into a file.
        scopes = [s.strip() for s in re.split(';|,|\t|\n', args['scopes'])
                  if s.strip()]
        client_id = args['client_id']

        logger.info('Generating the Bearer Token.')

        try:
            token = get_bearer_token(email, password, scopes,
                                     account_server_url,
                                     oauth_server_url, client_id)
        except ClientError as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Bearer Token generated.')

        print('# ---- BEARER TOKEN INFO ----', file=fd)
        print('# User: %s' % email, file=fd)
        print('# Scopes: %s' % ' '.join(scopes), file=fd)
        print('# Account: %s' % account_server_url, file=fd)
        print('# Oauth: %s' % oauth_server_url, file=fd)
        print('# Client ID: %s' % client_id, file=fd)
        print('# ---------------------------', file=fd)
        print('export OAUTH_BEARER_TOKEN="%s"\n' % token, file=fd)

    if args['browserid']:
        # Generate a BrowserID assertion for the user and write it into a file.
        audience = args['audience'] or token_server_url
        duration = int(args['duration'])

        logger.info('Creating the token.')

        try:
            bid_assertion, client_state = get_browserid_assertion(
                email, password, audience, account_server_url, duration)
        except ClientError as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Token created.')

        print('# ---- BROWSER ID ASSERTION INFO ----', file=fd)
        print('# User: %s' % email, file=fd)
        print('# Audience: %s' % audience, file=fd)
        print('# Account: %s' % account_server_url, file=fd)
        print('# ------------------------------------', file=fd)
        print('export FXA_BROWSERID_ASSERTION="%s"' % bid_assertion, file=fd)
        print('export FXA_CLIENT_STATE="%s"\n' % client_state, file=fd)

    if fd_is_to_close:
        fd.close()