def test_bulk_system_by_api_set_correct_systems_and_accounts_fast_track(clean_bulk_delete_systems_and_accounts,
                                                                        core_session, list_of_created_systems):
    batch1 = ResourceManager.add_multiple_systems_with_accounts(core_session, 3, 4, list_of_created_systems)
    batch2 = ResourceManager.add_multiple_systems_with_accounts(core_session, 1, 2, list_of_created_systems,
                                                                sys_type="Unix")
    batch3 = ResourceManager.add_multiple_systems_with_accounts(core_session, 5, 1, list_of_created_systems,
                                                                sys_type="Unix")

    delete_system_ids, delete_account_ids = DataManipulation.aggregate_lists_in_dict_values([batch2])
    keep_system_ids, keep_account_ids = DataManipulation.aggregate_lists_in_dict_values([batch1, batch3])

    all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values([batch1, batch2, batch3])

    some_set_name = "ApiSet" + guid()
    SetsManager.create_manual_collection(core_session, some_set_name, "Server", None)
    set_id = SetsManager.get_collection_id(core_session, some_set_name, "Server")
    SetsManager.update_members_collection(core_session, 'add', list(delete_system_ids), 'Server', set_id)

    collection_and_filters = SetsManager.get_object_collection_and_filter_by_name(core_session, some_set_name, "Server")
    filters = collection_and_filters['Filters']

    logger.info(f'Manual set {collection_and_filters} - members - {delete_system_ids}')
    result, success = ResourceManager.del_multiple_systems_by_query(core_session, filters, savepasswords=False,
                                                                    secretname="", run_sync=True)
    assert success is True, f'Delete systems job failed when expected success'

    SetsManager.delete_collection(core_session, set_id)

    assert set(ResourceManager.get_multi_added_system_ids(core_session,
                                                          all_systems).values()) == keep_system_ids, "Set of expected remaining systems did not match search"
    assert set(ResourceManager.get_multi_added_account_ids(core_session,
                                                           all_systems)) == keep_account_ids, "Set of expected remaining accounts did not match search"
def test_bulk_system_delete_by_sql_query_only_deletes_correct_systems_and_accounts(
        clean_bulk_delete_systems_and_accounts, core_session, list_of_created_systems):
    user_info = core_session.get_current_session_user_info().json()['Result']

    assert len(ResourceManager.get_multi_added_system_ids(core_session, [
        "x"])) == 0  # Use fake GUID string to ensure that filter is working properly, since empty list means no filter
    assert len(ResourceManager.get_multi_added_account_ids(core_session, ["x"])) == 0

    batch1 = ResourceManager.add_multiple_systems_with_accounts(core_session, 3, 4, list_of_created_systems)
    batch2 = ResourceManager.add_multiple_systems_with_accounts(core_session, 1, 2, list_of_created_systems)
    batch3 = ResourceManager.add_multiple_systems_with_accounts(core_session, 4, 6, list_of_created_systems)
    batch4 = ResourceManager.add_multiple_systems_with_accounts(core_session, 2, 8, list_of_created_systems)
    batch5 = ResourceManager.add_multiple_systems_with_accounts(core_session, 5, 1, list_of_created_systems)

    all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values(
        [batch1, batch2, batch3, batch4, batch5])

    assert len(ResourceManager.get_multi_added_system_ids(core_session,
                                                          all_systems)) == 15, "Found wrong number of added systems"
    assert len(ResourceManager.get_multi_added_account_ids(core_session,
                                                           all_systems)) == 59, "Found wrong number of add accounts"

    delete_system_ids, delete_account_ids = DataManipulation.aggregate_lists_in_dict_values([batch2, batch4])
    keep_system_ids, keep_account_ids = DataManipulation.aggregate_lists_in_dict_values([batch1, batch3, batch5])

    sql_query = RedrockController.get_query_for_ids('Server', delete_system_ids)
    ResourceManager.del_multiple_systems_by_query(core_session, sql_query, False, "")

    assert set(ResourceManager.get_multi_added_system_ids(core_session,
                                                          all_systems).values()) == keep_system_ids, "Set of expected remaining systems did not match search"
    assert set(ResourceManager.get_multi_added_account_ids(core_session,
                                                           all_systems)) == keep_account_ids, "Set of expected remaining accounts did not match search"

    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkSystemDelete.StartQuery.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkSystemDelete.Success.Multi'
    start_message = f'{username} initiated delete of multiple systems'
    end_message = f'{username} successfully deleted {len(delete_system_ids)} systems'

    RedrockController.expect_event_message_by_type(core_session, start_type, start_message)
    RedrockController.expect_event_message_by_type(core_session, end_type, end_message)
def test_bulk_system_delete_generates_secret(clean_bulk_delete_systems_and_accounts, core_session,
                                             list_of_created_systems, secret_cleaner, core_tenant):
    batch1 = ResourceManager.add_multiple_systems_with_accounts(core_session, 1, 4, list_of_created_systems)
    batch2 = ResourceManager.add_multiple_systems_with_accounts(core_session, 2, 3, list_of_created_systems)
    batch3 = ResourceManager.add_multiple_ssh_systems_with_accounts(core_session, 1, 1, list_of_created_systems)

    all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values([batch1, batch2, batch3])
    all_non_ssh_systems, all_non_shh_accounts = DataManipulation.aggregate_lists_in_dict_values([batch1, batch2])

    secret_name = "TestSecret-" + str(ResourceManager.time_mark_in_hours()) + "-" + guid()

    sql_query = RedrockController.get_query_for_ids('Server', all_systems)
    ResourceManager.del_multiple_systems_by_query(core_session, sql_query, True, secret_name)

    ResourceManager.wait_for_secret_to_exist_or_timeout(core_session, secret_name)

    secret_id = RedrockController.get_secret_id_by_name(core_session, secret_name)

    assert secret_id is not None, "No secret was created"

    secret_cleaner.append(secret_id)
    user_name = core_tenant['admin_user']
    user_id = UserManager.get_user_id(core_session, user_name)

    result, success = set_users_effective_permissions(core_session, user_name, "View,Edit,Retrieve", user_id, secret_id)
    assert success, f"Did not set secret permission successfully with message {result}"

    secret_file_contents = get_file_secret_contents(core_session, secret_id)

    assert secret_file_contents.strip().count("\n") == len(
        all_accounts), f"Secret file contained the wrong number of lines {secret_file_contents}"
    assert secret_file_contents.count("thisIsaPAsSwO0rd") == len(
        all_non_shh_accounts), f"Secret file contained the wrong number of passwords {secret_file_contents}"
    # Commenting following assert as AutomationTestKey is not available in secret_file_contents, Tested on both AWS,
    # Azure devdog tenants
    # assert 'AutomationTestKey' in secret_file_contents, f"Name of SSH key did not appear in secret file {secret_file_contents}"
    for server_id in all_non_ssh_systems:
        assert server_id in secret_file_contents, f"Server ID absent from secret file {secret_file_contents}"
    for account_id in all_non_shh_accounts:
        assert account_id in secret_file_contents, f"Account ID absent from secret file {secret_file_contents}"
def test_bulk_system_delete_works_with_built_in_set(clean_bulk_delete_systems_and_accounts, core_session, core_tenant,
                                                    clean_users, users_and_roles, list_of_created_systems,
                                                    get_environment):
    Engines = get_environment
    if Engines == "AWS - PLV8":
        batch = ResourceManager.add_multiple_systems_with_accounts(core_session, 3, 3, list_of_created_systems)

        all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values([batch])

        right_data = ("Privileged Access Service Power User", "role_Privileged Access Service Power User")

        requester_session = users_and_roles.get_session_for_user(right_data[0])
        role_info = users_and_roles.get_role(right_data[0])

        account_ids = ResourceManager.get_multi_added_account_ids(core_session, all_systems)

        for account_id in account_ids:
            permission_string = 'Owner,View,Manage,Delete,Login,Naked,UpdatePassword,FileTransfer,UserPortalLogin'
            result, success = ResourceManager.assign_account_permissions(
                core_session,
                permission_string,
                role_info['Name'], role_info['ID'], "Role",
                account_id)
            assert success, "Did not set account permissions " + str(result)

        system_ids = list(ResourceManager.get_multi_added_system_ids(core_session, all_systems).values())

        for system_id in system_ids:
            permission_string = 'Grant,View,Edit,Delete,ManageSession,AgentAuth,RequestZoneRole,AddAccount,' \
                                'UnlockAccount '
            result, success = ResourceManager.assign_system_permissions(core_session,
                                                                        permission_string,
                                                                        role_info['Name'], role_info['ID'], "Role",
                                                                        system_id)
            assert success, "Did not set system permissions " + result

        job_id, result = ResourceManager.del_multiple_systems_by_query(requester_session, '@@Windows Servers')
        report = JobManager.get_job_report(core_session, job_id)

        # not asserting success or failure, the admin may have access to windows systems created by other tests which
        # would not succeed such as windows systems with uncertain accounts

        assert len(ResourceManager.get_multi_added_account_ids(core_session,
                                                               all_systems)) == 0, f"Expected no remaining added accounts {report}"
        assert len(ResourceManager.get_multi_added_system_ids(core_session,
                                                              all_systems)) == 0, f"Expected no remaining added systems  {report}"
    else:
        skip('todo: Fix this test to work on azure')