Esempio n. 1
0
 def test_create_for_rbac_failed_with_regular_error(self, graph_client_mock, auth_client_mock):
     cmd = mock.MagicMock()
     cmd.cli_ctx = DummyCli()
     TestRoleMocked._common_rbac_err_polish_test_mock_setup(graph_client_mock, auth_client_mock,
                                                            'something bad for you',
                                                            self.subscription_id)
     # action
     with self.assertRaises(GraphErrorException):
         create_service_principal_for_rbac(cmd, 'will-fail')
 def test_create_for_rbac_failed_with_regular_error(self, graph_client_mock, auth_client_mock):
     cmd = mock.MagicMock()
     cmd.cli_ctx = TestCli()
     TestRoleMocked._common_rbac_err_polish_test_mock_setup(graph_client_mock, auth_client_mock,
                                                            'something bad for you',
                                                            self.subscription_id)
     # action
     with self.assertRaises(GraphErrorException):
         create_service_principal_for_rbac(cmd, 'will-fail')
    def test_create_for_rbac_failed_with_polished_error_if_due_to_permission(self, graph_client_mock, auth_client_mock):
        cmd = mock.MagicMock()
        cmd.cli_ctx = TestCli()
        TestRoleMocked._common_rbac_err_polish_test_mock_setup(graph_client_mock, auth_client_mock,
                                                               'Insufficient privileges to complete the operation',
                                                               self.subscription_id)

        # action
        with self.assertRaises(CLIError) as context:
            create_service_principal_for_rbac(cmd, 'will-fail', skip_assignment=True)

        # assert we handled such error
        self.assertTrue('https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal' in str(context.exception))
Esempio n. 4
0
    def test_create_for_rbac_failed_with_polished_error_if_due_to_permission(self, graph_client_mock, auth_client_mock):
        cmd = mock.MagicMock()
        cmd.cli_ctx = DummyCli()
        TestRoleMocked._common_rbac_err_polish_test_mock_setup(graph_client_mock, auth_client_mock,
                                                               'Insufficient privileges to complete the operation',
                                                               self.subscription_id)

        # action
        with self.assertRaises(CLIError) as context:
            create_service_principal_for_rbac(cmd, 'will-fail', skip_assignment=True)

        # assert we handled such error
        self.assertTrue('https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' in str(context.exception))
    def test_create_for_rbac_password_plumbed_through(self, graph_client_mock, auth_client_mock):
        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id

        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        test_pwd = 'verySecret'
        name = 'mysp'
        test_app_id = 'app_id_123'
        app = Application(app_id=test_app_id)
        faked_graph_client.applications.create.return_value = app
        sp = ServicePrincipal()
        faked_graph_client.service_principals.create.return_value = sp

        # action
        cmd = mock.MagicMock()
        cmd.cli_ctx = TestCli()
        result = create_service_principal_for_rbac(cmd, name, test_pwd, 12, skip_assignment=True)

        # assert
        self.assertEqual(result['password'], test_pwd)
        self.assertEqual(result['name'], 'http://' + name)
        self.assertEqual(result['appId'], test_app_id)
Esempio n. 6
0
def register_credential_secrets(cmd, database_engine, server, repository):
    logger.warning('Adding secret "AZURE_CREDENTIALS" to github repository')
    resource_group = parse_resource_id(server.id)["resource_group"]
    provider = "DBforMySQL"
    if database_engine == "postgresql":
        provider = "DBforPostgreSQL"
    scope = "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.{}/flexibleServers/{}".format(get_subscription_id(cmd.cli_ctx), resource_group, provider, server.name)

    app = create_service_principal_for_rbac(cmd, name=server.name, role='contributor', scopes=[scope])
    app['clientId'], app['clientSecret'], app['tenantId'] = app.pop('appId'), app.pop('password'), app.pop('tenant')
    app['subscriptionId'] = get_subscription_id(cmd.cli_ctx)
    app.pop('displayName')
    app.pop('name')

    app_key_val = []
    for key, val in app.items():
        app_key_val.append('"{}": "{}"'.format(key, val))

    app_json = ',\n  '.join(app_key_val)
    app_json = '{\n  ' + app_json + '\n}'
    credential_file = "./temp_app_credential.txt"
    with open(credential_file, "w") as f:
        f.write(app_json)
    run_subprocess('gh secret set {} --repo {} < {}'.format(AZURE_CREDENTIALS, repository, credential_file))
    os.remove(credential_file)
    def test_create_for_rbac_password_plumbed_through(self, graph_client_mock,
                                                      auth_client_mock):
        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id

        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        test_pwd = 'verySecret'
        name = 'mysp'
        test_app_id = 'app_id_123'
        app = Application(app_id=test_app_id)
        faked_graph_client.applications.create.return_value = app
        sp = ServicePrincipal()
        faked_graph_client.service_principals.create.return_value = sp

        # action
        cmd = mock.MagicMock()
        cmd.cli_ctx = TestCli()
        result = create_service_principal_for_rbac(cmd,
                                                   name,
                                                   test_pwd,
                                                   12,
                                                   skip_assignment=True)

        # assert
        self.assertEqual(result['password'], test_pwd)
        self.assertEqual(result['name'], 'http://' + name)
        self.assertEqual(result['appId'], test_app_id)
Esempio n. 8
0
def create_resource_manager_sp(cmd):
    from azure.cli.command_modules.role.custom import create_service_principal_for_rbac, add_permission, admin_consent

    sp = create_service_principal_for_rbac(
        cmd, name='http://TeamCloud.ResourceManager', years=10, role='Owner')
    # Azure Active Directory Graph permissions
    add_permission(
        cmd,
        identifier=sp['appId'],
        api='00000002-0000-0000-c000-000000000000',
        api_permissions=[
            '5778995a-e1bf-45b8-affa-663a9f3f4d04=Role',  # Directory.Read.All
            '824c81eb-e3f8-4ee6-8f6d-de7f50d565b7=Role'
        ])  # Application.ReadWrite.OwnedBy
    # Microsoft Graph permissions
    add_permission(
        cmd,
        identifier=sp['appId'],
        api='00000003-0000-0000-c000-000000000000',
        api_permissions=[
            '7ab1d382-f21e-4acd-a863-ba3e13f7da61=Role',  # Directory.Read.All
            '18a4783c-866b-4cc7-a460-3d5e5662c884=Role'
        ])  # Application.ReadWrite.OwnedBy

    # 'e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope', # User.Read
    # 'df021288-bdef-4463-88db-98f22de89214=Role', # User.Read

    admin_consent(cmd, identifier=sp['appId'])

    return sp
    def test_create_for_rbac_use_cert_date(self, logger_mock, graph_client_mock, auth_client_mock):
        test_app_id = 'app_id_123'
        app = Application(app_id=test_app_id)

        def mock_app_create(parameters):
            end_date = parameters.key_credentials[0].end_date
            # sample check the cert's expiration time
            self.assertEqual(end_date.day, 21)
            self.assertEqual(end_date.month, 4)
            return app

        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id
        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        curr_dir = os.path.dirname(os.path.realpath(__file__))
        cert_file = os.path.join(curr_dir, 'cert.pem').replace('\\', '\\\\')
        with open(cert_file) as f:
            cert = f.read()

        name = 'mysp'
        faked_graph_client.applications.create.side_effect = mock_app_create
        sp = ServicePrincipal(object_id='does not matter')
        faked_graph_client.service_principals.create.return_value = sp

        # action
        result = create_service_principal_for_rbac(name, cert=cert, years=2, skip_assignment=True)

        # assert
        self.assertEqual(result['name'], 'http://' + name)
        self.assertEqual(result['appId'], test_app_id)
        self.assertTrue(logger_mock.warning.called)  # we should warn 'years' will be dropped
        self.assertTrue(faked_graph_client.applications.create.called)
    def test_create_for_rbac_use_cert_date(self, logger_mock, graph_client_mock, auth_client_mock):
        import OpenSSL.crypto

        def mock_app_create(parameters):
            end_date = parameters['keyCredentials'][0]['endDateTime']
            # Check the cert's expiration time
            self.assertEqual(end_date, '2018-04-21T18:27:50Z')
            return MOCKED_APP

        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id
        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        curr_dir = os.path.dirname(os.path.realpath(__file__))
        cert_file = os.path.join(curr_dir, 'cert.pem').replace('\\', '\\\\')
        with open(cert_file) as f:
            cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())

        faked_graph_client.application_create.side_effect = mock_app_create
        faked_graph_client.service_principal_create.return_value = MOCKED_SP

        # action
        cmd = mock.MagicMock()
        cmd.cli_ctx = DummyCli()
        result = create_service_principal_for_rbac(cmd, MOCKED_APP_DISPLAY_NAME, cert=cert, years=2)

        # assert
        self.assertEqual(result['appId'], MOCKED_APP_APP_ID)
        self.assertTrue(logger_mock.warning.called)  # we should warn 'years' will be dropped
        self.assertTrue(faked_graph_client.application_create.called)
Esempio n. 11
0
 def test_create_for_rbac_retry(self, create_application_mock, create_service_principal_mock,
                                graph_client_factory_mock, auth_client_factory_mock):
     graph_client_factory_mock.return_value.config.tenant_id = '00000001-0000-0000-0000-000000000000'
     create_application_mock.return_value.app_id = '00000000-0000-0000-0000-000000000000'
     create_service_principal_mock.side_effect = [
         # Mock replication exceptions
         Exception("The appId '00000000-0000-0000-0000-000000000000' of the service principal "
                   "does not reference a valid application object."),
         Exception("When using this permission, the backing application of the service principal being "
                   "created must in the local tenant"),
         # Success
         mock.MagicMock()
     ]
     # action
     cmd = mock.MagicMock()
     cmd.cli_ctx = DummyCli()
     with mock.patch("time.sleep", lambda _: None):
         create_service_principal_for_rbac(cmd, skip_assignment=True)
    def test_create_for_rbac_password_plumbed_through(self, graph_client_mock, auth_client_mock):
        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id

        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        faked_graph_client.application_create.return_value = MOCKED_APP
        faked_graph_client.application_add_password.return_value = {'secretText': MOCKED_PASSWORD}
        faked_graph_client.service_principal_create.return_value = MOCKED_SP

        # action
        cmd = mock.MagicMock()
        cmd.cli_ctx = DummyCli()
        result = create_service_principal_for_rbac(cmd, MOCKED_APP_DISPLAY_NAME, 12)

        # assert
        self.assertEqual(result['displayName'], MOCKED_APP_DISPLAY_NAME)
        self.assertEqual(result['appId'], MOCKED_APP_APP_ID)
        self.assertEqual(result['password'], MOCKED_PASSWORD)
    def test_create_for_rbac_use_cert_date(self, logger_mock, graph_client_mock, auth_client_mock):
        import OpenSSL.crypto
        test_app_id = 'app_id_123'
        app = Application(app_id=test_app_id)

        def mock_app_create(parameters):
            end_date = parameters.key_credentials[0].end_date
            # sample check the cert's expiration time
            self.assertEqual(end_date.day, 21)
            self.assertEqual(end_date.month, 4)
            return app

        faked_role_client = mock.MagicMock()
        auth_client_mock.return_value = faked_role_client
        faked_role_client.config.subscription_id = self.subscription_id
        faked_graph_client = mock.MagicMock()
        graph_client_mock.return_value = faked_graph_client

        curr_dir = os.path.dirname(os.path.realpath(__file__))
        cert_file = os.path.join(curr_dir, 'cert.pem').replace('\\', '\\\\')
        with open(cert_file) as f:
            cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())

        name = 'mysp'
        faked_graph_client.applications.create.side_effect = mock_app_create
        sp = ServicePrincipal()
        faked_graph_client.service_principals.create.return_value = sp

        # action
        cmd = mock.MagicMock()
        cmd.cli_ctx = TestCli()
        result = create_service_principal_for_rbac(cmd, name, cert=cert, years=2, skip_assignment=True)

        # assert
        self.assertEqual(result['name'], 'http://' + name)
        self.assertEqual(result['appId'], test_app_id)
        self.assertTrue(logger_mock.warning.called)  # we should warn 'years' will be dropped
        self.assertTrue(faked_graph_client.applications.create.called)