Ejemplo n.º 1
0
class AWSFederationClientCmdTest(TestCase):
    def setUp(self):
        self.api_client = AWSFederationClientCmd()

    @patch("afp_cli.client.requests.get")
    def test_get_correct_account_and_role_list(self, mock_get):
        expected_result = Mock(text='{"testaccount": ["testrole"]}',
                               status_code=200,
                               reason="Ok")
        mock_get.return_value = expected_result
        result = self.api_client.get_account_and_role_list()
        self.assertEqual(
            result, {"testaccount": ["testrole"]}, msg='Should be the same')

    @patch("afp_cli.client.requests.get")
    def test_get_correct_aws_credentials(self, mock_get):
        expected_result = Mock(
            text='{"Code": "Success", '
            '"AccessKeyId": "testAccessKey", '
            '"SecretAccessKey": "testSecretAccessKey", '
            '"Token": "testToken", '
            '"Expiration": "2015-01-01T12:34:56Z"}',
            status_code=200,
            reason="Ok")
        mock_get.return_value = expected_result
        result = self.api_client.get_aws_credentials("testaccount", "testrole")
        self.assertEqual(result, {
            "AWS_ACCESS_KEY_ID": "testAccessKey",
            "AWS_SECRET_ACCESS_KEY": "testSecretAccessKey",
            "AWS_SESSION_TOKEN": "testToken",
            "AWS_SECURITY_TOKEN": "testToken",
            "AWS_EXPIRATION_DATE": "2015-01-01T12:34:56Z"},
            msg='Should be the same')
Ejemplo n.º 2
0
def main():
    """Main function for script execution"""
    arguments = docopt(__doc__)
    if arguments['--debug']:
        global DEBUG
        DEBUG = True
    debug(arguments)

    try:
        config = load_config()
    except Exception as exc:
        error("Failed to load configuration: %s" % exc)

    api_url = arguments['--api-url'] or config.get('api_url') or \
              'https://{fqdn}/afp-api/latest'.format(fqdn=get_default_afp_server())
    username = arguments['--user'] or config.get("user") or getpass.getuser()
    password = '******' if arguments['--no-ask-pw'] else get_password(username)
    federation_client = AWSFederationClientCmd(api_url=api_url,
                                               username=username,
                                               password=password)
    if arguments['<accountname>']:
        account = arguments['<accountname>']
        role = arguments['<rolename>'] or get_first_role(federation_client, account)
        aws_credentials = get_aws_credentials(federation_client, account, role)

        if arguments['--show']:
            print(cli.format_aws_credentials(aws_credentials))

        elif arguments['--export']:
            if os.name == "nt":
                print(cli.format_aws_credentials(aws_credentials, prefix='set '))
            else:
                print(cli.format_aws_credentials(aws_credentials, prefix='export '))
        elif arguments['--write']:
            aws_credentials_file.write(aws_credentials)
        else:
            print("Entering AFP subshell for account {0}, role {1}.".format(
                account, role))
            try:
                if os.name == "nt":
                    start_subcmd(aws_credentials=aws_credentials, role=role, account=account)
                else:
                    start_subshell(aws_credentials=aws_credentials, role=role, account=account)
            except Exception as exc:
                error("Failed to start subshell: %s" % exc)
    else:
        try:
            print(cli.format_account_and_role_list(federation_client.get_account_and_role_list()))
        except Exception as exc:
            error("Failed to get account list from AWS: %s" % exc)
Ejemplo n.º 3
0
def main():
    """Main function for script execution"""
    arguments = docopt(__doc__)
    try:
        config = load_config()
    except Exception as exc:
        error("Failed to load configuration: %s" % exc)

    api_url = arguments['--api-url'] or config.get('api_url')
    if api_url is None:
        api_url = 'https://{fqdn}/afp-api/latest'.format(fqdn=get_default_afp_server())
    username = get_user(arguments['--user'] or config.get("user"))
    password = get_password(username)
    federation_client = AWSFederationClientCmd(api_url=api_url,
                                               username=username,
                                               password=password)
    if arguments['<accountname>']:
        account = arguments['<accountname>']
        role = get_role(arguments, federation_client, account)
        aws_credentials = get_aws_credentials(federation_client, account, role)

        if arguments['--show']:
            for key, value in aws_credentials.items():
                print("{key}='{value}'".format(key=key, value=value))

        elif arguments['--export']:
            for key, value in aws_credentials.items():
                if os.name == "nt":
                    print("set {key}='{value}'".format(key=key, value=value))
                else:
                    print("export {key}='{value}'".format(key=key, value=value))

        else:
            print("Entering AFP subshell for account {0}, role {1}.".format(
                account, role))
            try:
                if os.name == "nt":
                    start_subcmd(aws_credentials=aws_credentials, role=role, account=account)
                else:
                    start_subshell(aws_credentials=aws_credentials, role=role, account=account)
            except Exception as exc:
                error("Failed to start subshell: %s" % exc)
    else:
        try:
            federation_client.print_account_and_role_list()
        except Exception as exc:
            error("Failed to get account list from AWS: %s" % exc)
class AWSFederationClientCmdTest(TestCase):
    def setUp(self):
        self.api_client = AWSFederationClientCmd()

    @patch("afp_cli.client.requests.get")
    def test_get_correct_account_and_role_list(self, mock_get):
        expected_result = Mock(text='{"testaccount": ["testrole"]}',
                               status_code=200,
                               reason="Ok")
        mock_get.return_value = expected_result
        result = self.api_client.get_account_and_role_list()
        self.assertEqual(result, {"testaccount": ["testrole"]}, msg='Should be the same')

    @patch("afp_cli.client.requests.get")
    def test_get_correct_aws_credentials(self, mock_get):
        expected_result = Mock(text='{"Code": "Success", '
                                    '"AccessKeyId": "testAccessKey", '
                                    '"SecretAccessKey": "testSecretAccessKey", '
                                    '"Token": "testToken", '
                                    '"Expiration": "2015-01-01T12:34:56Z"}',
                               status_code=200,
                               reason="Ok")
        mock_get.return_value = expected_result
        result = self.api_client.get_aws_credentials("testaccount", "testrole")
        self.assertEqual(result, {"AWS_ACCESS_KEY_ID": "testAccessKey",
                                  "AWS_SECRET_ACCESS_KEY": "testSecretAccessKey",
                                  "AWS_SESSION_TOKEN": "testToken",
                                  "AWS_SECURITY_TOKEN": "testToken",
                                  "AWS_EXPIRATION_DATE": "2015-01-01T12:34:56Z"},
                         msg='Should be the same')

    @patch("six.moves.builtins.print")
    @patch("afp_cli.client.AWSFederationClientCmd.get_account_and_role_list")
    def test_print_account_and_one_role_with_correct_format(self, mock_get_account_and_role_list, mock_print):
        expected_result = {"testaccount1": ["testrole1"]}
        mock_get_account_and_role_list.return_value = expected_result
        self.api_client.print_account_and_role_list()
        mock_print.assert_called_with("testaccount1         testrole1")

    @patch("six.moves.builtins.print")
    @patch("afp_cli.client.AWSFederationClientCmd.get_account_and_role_list")
    def test_print_account_and_two_roles_with_correct_format(self, mock_get_account_and_role_list, mock_print):
        expected_result = {"testaccount2": ["testrole1", "testrole2"]}
        mock_get_account_and_role_list.return_value = expected_result
        self.api_client.print_account_and_role_list()
        mock_print.assert_called_with("testaccount2         testrole1,testrole2")

    @patch("six.moves.builtins.print")
    @patch("afp_cli.client.AWSFederationClientCmd.get_aws_credentials")
    def test_print_aws_credentials_with_export_style_with_correct_format(self, mock_get_aws_credentials, mock_print):
        expected_result = {"AWS_ACCESS_KEY_ID": "testAccessKey"}
        mock_get_aws_credentials.return_value = expected_result
        self.api_client.print_aws_credentials_with_export_style("testaccount", "testrole")
        mock_print.assert_called_with("export AWS_ACCESS_KEY_ID=testAccessKey")
 def setUp(self):
     self.api_client = AWSFederationClientCmd()
Ejemplo n.º 6
0
 def setUp(self):
     self.api_client = AWSFederationClientCmd()