示例#1
0
def test_update_managed_account(pas_setup, core_session, pas_config):
    """
    :param pas_config:
    :param pas_setup:    Fixture for adding a system and an account associated with it.
    :param core_admin_ui: Authenticated Centrify Session.
    :param core_session: Authenticated Centrify Session.
     TC: C2547 - Update managed account
     trying to Update managed account password
            Steps:
                Pre: Create system with 1 manage account hand
                1. Try to update invalid password
                    -Assert Failure
                2. Try to update valid password
                    -Assert Failure
                3. Try to check password history
    """
    user_name = core_session.get_user().get_login_name()
    System_configurations_from_yaml = pas_config
    system_data = System_configurations_from_yaml[
        'Windows_infrastructure_data']
    added_system_id, account_id, sys_info = pas_setup
    Result, success = ResourceManager.update_password(core_session, account_id,
                                                      guid())
    assert success, "Did not update password"
    Result, success = ResourceManager.update_password(core_session, account_id,
                                                      system_data['password'])
    assert success, "Did not update password"
    result, success = ResourceManager.check_out_password(
        core_session, 1, account_id)
    assert success, "Did not retrieve password"
    query = f"select EntityId, State, StateUpdatedBy, StateUpdatedTime from PasswordHistory where EntityId=" \
            f"'{account_id}' and StateUpdatedBy='{user_name}' and State='Retired'"
    password_history = RedrockController.get_result_rows(
        RedrockController.redrock_query(core_session, query))[0]
    assert len(password_history) > 0, "Password history table did not update"
def test_system_default_management_port(core_session, network_device_setup,
                                        core_admin_ui):
    """
    TC: C2607 - System default management port
    :param core_session: Authenticated Centrify session.
    :param network_device_setup: Adds a network with account and returns UUID of both.
    :param core_admin_ui: Authenticated Centrify browser session.
    """

    system_id, account_id, device_data, system_list, account_list = network_device_setup(
        'paloalto')
    system_info = RedrockController.get_computer_with_ID(
        core_session, system_id)
    ui = core_admin_ui
    ui.navigate('Resources', 'Systems')
    ui.search(system_info['Name'])
    ui.click_row(GridRowByGuid(system_id))
    ui.tab('Settings')
    ui.input("ManagementPort", "1")
    ui.save()
    ui.expect(TextField('ManagementPort'),
              "Unable to locate management port input").clear()
    ui.save()
    management_port = RedrockController.get_computer_with_ID(
        core_session, system_id)['ManagementPort']
    assert management_port is None, "Management port value isn't 443 i.e. default."
    logger.info(
        f'Management port value retrieved via API is {management_port} i.e. placeholder 443 in UI.'
    )
def test_bulk_account_delete_by_sql_query_only_deletes_correct_accounts_fast_track(
        clean_bulk_delete_systems_and_accounts, core_session,
        list_of_created_systems):
    batch = ResourceManager.add_multiple_systems_with_accounts(
        core_session, 2, 12, list_of_created_systems)

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

    sql_query = 'SELECT * FROM VaultAccount WHERE ' + ' OR '.join(
        ('VaultAccount.ID = "' + str(n) + '"' for n in list(delete_ids)))

    result, success = ResourceManager.del_multiple_accounts_by_query(
        core_session, sql_query, run_sync=True)
    assert success, "del_multiple_accounts_by_query failed " + result

    assert set(ResourceManager.get_multi_added_system_ids(core_session, all_systems).values()) == set(all_systems), \
        "Wrong set of added systems found"
    assert set(ResourceManager.get_multi_added_account_ids(core_session, all_systems)) == set(keep_ids), \
        "Wrong set of added accounts found"

    user_info = core_session.get_current_session_user_info().json()['Result']
    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkAccountDelete.StartQuery.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkAccountDelete.Success.Multi'
    start_message = f'{username} initiated delete of multiple accounts'
    end_message = f'{username} successfully deleted {len(delete_ids)} accounts'

    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_by_ids_only_deletes_correct_systems_and_accounts_fast_track(
        clean_bulk_delete_systems_and_accounts, core_session, list_of_created_systems):
    user_info = core_session.get_current_session_user_info().json()['Result']

    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])

    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])

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

    ResourceManager.del_multiple_systems(core_session, delete_system_ids, savepasswords=True, wait_time=0,
                                         skip_if_has_apps_or_services=True, run_sync=True)

    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.Start.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkSystemDelete.Success.Multi'
    start_message = f'{username} initiated delete of {len(delete_system_ids)} 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)
示例#5
0
def test_import_all_nix_system(core_session, cleanup_accounts, cleanup_resources):
    """
    Test case: C279397
    :param core_session: Centrify session
    """
    # datframe to store systems with unique name in csv import template
    # dataframe to store systems in csv import template
    # datframe to store systems with unique name in csv import template
    system_list = cleanup_resources[0]
    accounts_list = cleanup_accounts[0]
    dataframe = pd.read_csv('Assets\\serverimport.csv')
    server_list = dataframe['Name']
    for server in server_list:
        dataframe = dataframe.replace(server, f'{server}{guid()}')
    temp_server_csv = f"Assets\\serverimport{guid()}.csv"
    dataframe.to_csv(temp_server_csv, encoding='utf-8', index=False)

    # API call with server import template
    result, success = ResourceManager.bulk_import_system(core_session, temp_server_csv)
    assert success, f"failed to add systems, return result is: {result}"
    logger.info('bulk import successful')

    server = RedrockController.get_accounts(core_session)
    for row in server:
        if row['User'].__contains__("Administrator"):
            accounts_list.append(row["ID"])

    server = RedrockController.get_computers(core_session)
    for row in server:
        if row['Name'].__contains__("host"):
            system_list.append(row["ID"])
    if os.path.exists(temp_server_csv):
        os.remove(temp_server_csv)
    else:
        pass
def test_check_ui_on_subnet_mapping_page(core_session, cleanup_system_subnet_mapping):
    """
    TC:C2197 Check UI on Subnet Mappings page.
        1) Login Admin Portal as cloud admin
        2) Add System subnet mapping by calling API add_system_subnet_mapping
        3) Checking through UI for assertion

    :param core_session: Authenticated Centrify session.
    :param core_admin_ui: Authenticated Centrify browser session.
    :param: cleanup_system_subnet_mapping: cleanup for created system subnet.
    """
    subnet = Configs.get_environment_node('update_discovery_profile',
                                          'automation_main')['port_scan_scope']['subnet_mask']
    subnet_list = cleanup_system_subnet_mapping

    # Adding System Subnet Mapping.
    result, success, message = ResourceManager.add_system_subnet_mapping(core_session, subnet, chooseConnector="on")
    system_subnet_id = result['ID']
    assert success, f'Failed to add System subnet mapping with API response: {message}'
    subnet_list.append(system_subnet_id)
    logger.info(f"System subnet mapping added successfully, {system_subnet_id}")

    # Checking on ui for assertion
    query = "select * from ProxyGroup"
    results = RedrockController.get_result_rows(RedrockController.redrock_query(core_session, query))
    assert results[0]['Subnet'] == subnet, \
        f'Failed to see the detail of System Subnet Mapping with API response: {message}'
def test_app_management_user_can_create_job_but_not_delete_servers(clean_bulk_delete_systems_and_accounts, core_session,
                                                                   core_tenant, clean_users, users_and_roles,
                                                                   list_of_created_systems):
    batch = ResourceManager.add_multiple_systems_with_accounts(core_session, 3, 2, list_of_created_systems)
    all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values([batch])

    requestor_session = users_and_roles.get_session_for_user('Application Management')

    user_info = requestor_session.get_current_session_user_info().json()['Result']

    all_systems = batch.keys()

    job_id, result = ResourceManager.del_multiple_systems(requestor_session, all_systems)

    result = ResourceManager.get_job_state(core_session, job_id)

    assert result == "Succeeded", "Job did not execute"

    assert len(
        ResourceManager.get_multi_added_system_ids(core_session, all_systems)) == 3, "Wrong number of remaining systems"
    assert len(ResourceManager.get_multi_added_account_ids(core_session,
                                                           all_systems)) == 6, "Wrong number of remaining accounts"

    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkSystemDelete.Start.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkSystemDelete.Failure.Multi'
    start_message = f'{username} initiated delete of {len(all_systems)} systems'
    end_message = f'{username} failed to delete {len(all_systems)} of {len(all_systems)} 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_unenroll_by_ids_only_unenrolls_correct_systems_fast_track(core_session,
                                                                               test_four_virtual_aapm_agents):
    user_info = core_session.get_current_session_user_info().json()['Result']

    agents, _ = test_four_virtual_aapm_agents
    all_agent_ids, all_server_ids = _setup_agents(core_session, agents)
    unenroll_agent_ids = all_agent_ids[:2]
    unenroll_server_ids = all_server_ids[:2]
    keep_agent_ids = all_agent_ids[2:]

    _validate_aapm_agent_details(core_session, all_agent_ids, True)

    _, success = ResourceManager.unenroll_multiple_systems(core_session, unenroll_server_ids, wait_time=0,
                                              SkipIfAgentReconciliationEnabled=True, run_sync=True)
    assert success, f"Unenroll multiple systems failed: {unenroll_server_ids}"

    _validate_aapm_agent_details(core_session, unenroll_agent_ids, False)
    _validate_aapm_agent_details(core_session, keep_agent_ids, True)

    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkSystemUnenrollClient.StartQuery.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkSystemUnenrollClient.Success.Multi'
    start_message = f'{username} initiated unenroll of multiple systems'
    end_message = f'{username} successfully unenrolled {len(unenroll_server_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)
示例#9
0
def test_delete_ssh_keys_and_account(core_session, add_system_with_ssh_account, get_ssh_key_function, remove_related):
    system_id, account_id, ssh_id, system_list, account_list, ssh_list = add_system_with_ssh_account

    # Deleting SSH Account
    all_key_ids = [ssh_id, get_ssh_key_function]
    delete_result, delete_success = ResourceManager.del_multiple_ssh_keys(core_session, all_key_ids,
                                                                          run_sync=True, remove_related_account=remove_related)
    if remove_related:
        assert delete_success, f"SSH key {ssh_id} deletion failed with API response result: {delete_result}"
        logger.info(f"Account{account_id} associated with system {system_id} and SSH key {ssh_id} was deleted successfully")
    else:
        assert not delete_success, "Delete should have failed with attached account {delete_result}"
    account_list.remove(account_id)
    activity = RedrockController.get_ssh_activity(core_session, ssh_id)
    sql_query = RedrockController.get_query_for_ids('VaultAccount', [account_id])
    result = RedrockController.redrock_query(core_session, sql_query)

    if remove_related:
        assert len(result) == 0, f"Account not deleted as expected {result}"
    else:
        assert len(result) == 1, f"Account was delete and should not have been {result} when removed_related_account == False"

    sql_query = RedrockController.get_query_for_ids('SshKeys', all_key_ids)
    result = RedrockController.redrock_query(core_session, sql_query)

    if remove_related:
        assert len(result) == 0, f"SSH keys not deleted as expected {result}"
    else:
        assert len(result) == 1 and ssh_id in str(result), f"Should remain exactly 1 SSH key associated with account {result}"
def test_bulk_system_unenroll_by_sql_query_only_unenrolls_correct_systems(core_session, test_four_virtual_aapm_agents):
    user_info = core_session.get_current_session_user_info().json()['Result']

    agents, _ = test_four_virtual_aapm_agents
    all_agent_ids, all_server_ids = _setup_agents(core_session, agents)
    unenroll_agent_ids = all_agent_ids[:2]
    unenroll_server_ids = all_server_ids[:2]
    keep_agent_ids = all_agent_ids[2:]

    _validate_aapm_agent_details(core_session, all_agent_ids, True)

    sql_query = RedrockController.get_query_for_ids('Server', unenroll_server_ids)
    _, success = ResourceManager.unenroll_multiple_systems_by_query(core_session, sql_query)
    assert success, f"Unenroll Multiple systems by query failed: {sql_query}"

    _validate_aapm_agent_details(core_session, unenroll_agent_ids, False)
    _validate_aapm_agent_details(core_session, keep_agent_ids, True)

    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkSystemUnenrollClient.StartQuery.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkSystemUnenrollClient.Success.Multi'
    start_message = f'{username} initiated unenroll of multiple systems'
    end_message = f'{username} successfully unenrolled {len(unenroll_server_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 _validate_aapm_agent_details(session, agent_ids, expected):
    query = RedrockController.get_query_for_ids('centrifyclients', agent_ids, columns='ResourceID, FeatureAAPM')
    results = RedrockController.get_result_rows(
        RedrockController.redrock_query(session, query))

    # make sure num of systems match
    assert len(results) == len(agent_ids)

    for row in results:
        assert row["FeatureAAPM"] is expected
示例#12
0
def test_cannot_manage_accounts_without_permission(
        core_session,
        remote_unmanaged_users_with_mirrored_managed_local_users_qty3,
        windows_test_machine_config, users_and_roles):
    right_data = [
        "Privileged Access Service Power User",
        "role_Privileged Access Service Power User"
    ]
    requestor_session = users_and_roles.get_session_for_user(right_data[0])
    results_role = users_and_roles.get_role(right_data[0])

    account_ids = remote_unmanaged_users_with_mirrored_managed_local_users_qty3

    job_id, success = ResourceManager.manage_multiple_accounts(
        requestor_session, account_ids)
    assert success, "Did not kick off bulk manage accounts job"
    result = ResourceManager.get_job_state(core_session, job_id)
    assert result == "Succeeded", "Job did not execute"

    # Validates accounts are still not managed.
    _validate_accounts_are_not_managed(requestor_session, account_ids, job_id)

    permission_string = "Owner,View,Manage,Delete,Login,Naked,UpdatePassword,RotatePassword,FileTransfer,UserPortalLogin"

    account_id = account_ids[
        2]  # Grant permission to only one of the accounts, the middle one
    result, success = ResourceManager.assign_account_permissions(
        core_session, permission_string, results_role['Name'],
        results_role['ID'], "Role", account_id)
    assert success, "Did not set account permissions " + str(result)

    job_id, success = ResourceManager.manage_multiple_accounts(
        requestor_session, account_ids)
    assert success, "Did not kick off bulk rotate passwords job"
    result = ResourceManager.get_job_state(core_session, job_id)
    assert result == "Succeeded", "Job did not execute"

    # Validate the one account is managed.
    _validate_accounts_are_not_managed(requestor_session,
                                       [account_ids[0], account_ids[1]],
                                       job_id)
    _validate_accounts_are_managed(requestor_session, [account_ids[2]], job_id)

    user_info = requestor_session.get_current_session_user_info().json(
    )['Result']
    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.AccountBulkManagement.Start.Multi'
    end_type = 'Cloud.Core.AsyncOperation.AccountBulkManagement.Failure.Multi'
    start_message = f'{username} initiated management of {len(account_ids)} accounts'
    end_message = f'{username} failed to manage 2 of 3 accounts'

    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_delete_administrative_account(core_session, network_device_setup):
    """
    TC: C2623 - Delete administrative account
    :param core_session: Authenticated Centrify session.
    :param network_device_setup: Adds a network with account and returns UUID of both.
    """
    system_id, account_id, device_data, system_list, account_list = network_device_setup(
        'checkpoint')
    system_info = RedrockController.get_computer_with_ID(
        core_session, system_id)

    # setting up Admin account for system
    result, success, message = ResourceManager.set_system_administrative_account(
        core_session, system_id, account_id)
    assert success, f"Failed to update Administrative account for system {system_info['Name']}"
    logger.info(
        f"Successfully added an administrative account for system {system_info['Name']}"
    )

    # deleting administrative account
    del_result, del_success = ResourceManager.del_account(
        core_session, account_id)
    assert del_success is False, f"Admin account deleted successfully, unexpected behaviour as Admin account " \
                                 f"should not be deleted. API response result: {del_success}"
    logger.info(
        f'Admin account could not be deleted as expected, API response result: {del_success}'
    )

    # finding all systems for cleanup:
    acc_script = "@/lib/server/get_accounts.js(mode:'AllAccounts', newcode:true, localOnly:true, colmemberfilter:" \
                 "'Select ID from VaultAccount WHERE Host IS NOT NULL')"
    acc = RedrockController.redrock_query(core_session, acc_script)
    for account in acc:
        if account['Row']['FQDN'] == "Check.Point":
            # Removing Admin Account for successful cleanup of system and account
            result, success, message = ResourceManager.set_administrative_account(
                core_session, systems=[account['Row']['Host']])
            assert success, f"Failed to update Administrative account for system {account['Row']['Name']}"

            # Removing Admin Account for successful cleanup of system and account
            ResourceManager.update_system(
                core_session,
                account['Row']['Host'],
                account['Row']['Name'],
                account['Row']['FQDN'],
                'CheckPointGaia',
                sessiontype=account['Row']['SessionType'])

            # deleting administrative account from this system
            ResourceManager.del_account(core_session, account['Row']['ID'])

            # Removing Admin Account for successful cleanup of system and account
            result, success, message = ResourceManager.set_administrative_account(
                core_session, systems=[account['Row']['Host']])
            assert success, f"Failed to update Administrative account for system {account['Row']['Name']}"
def test_other_user_cant_see_secret_created_by_first_user(core_session, users_and_roles, created_system_id_list,
                                                          swap_roles):
    roles = ["Privileged Access Service Administrator", "Privileged Access Service Power User"]

    if swap_roles:
        roles_new = [roles[1], roles[0]]
        roles = roles_new

    batch = ResourceManager.add_multiple_systems_with_accounts(core_session, 2, 2, created_system_id_list)
    all_systems, all_accounts = DataManipulation.aggregate_lists_in_dict_values([batch])

    deleter_user_0_session = users_and_roles.get_session_for_user(roles[0])
    deleter_user_0_role = users_and_roles.get_role(roles[0])
    deleter_user_0_role_name = deleter_user_0_role['Name']
    deleter_user_0_role_id = deleter_user_0_role['ID']
    other_user_1_session = users_and_roles.get_session_for_user(roles[1])

    for account_id in all_accounts:
        permission_string = 'Owner,View,Manage,Delete,Login,Naked,UpdatePassword,FileTransfer,UserPortalLogin'
        result, success = ResourceManager.assign_account_permissions(core_session, permission_string,
                                                                     deleter_user_0_role_name, deleter_user_0_role_id,
                                                                     "Role", account_id)
        assert success, "Did not set account permissions " + str(result)

    for system_id in all_systems:
        permission_string = 'Grant,View,Edit,Delete,ManageSession,AgentAuth,RequestZoneRole,AddAccount,UnlockAccount'
        result, success = ResourceManager.assign_system_permissions(core_session, permission_string,
                                                                    deleter_user_0_role_name, deleter_user_0_role_id,
                                                                    "Role", system_id)
        assert success, "Did not set system permissions " + result

    secret_name = f"secret{guid()}"
    job_id, result = ResourceManager.del_multiple_systems(deleter_user_0_session, batch.keys(), secretname=secret_name)

    result = ResourceManager.get_job_state(core_session, job_id)
    assert result == "Succeeded", "Job did not execute"

    remaining_accounts = set(ResourceManager.get_multi_added_account_ids(core_session, created_system_id_list))
    remaining_systems = set(ResourceManager.get_multi_added_system_ids(core_session, created_system_id_list).values())

    assert remaining_accounts == set(), "Remaining accounts did not match expectation"
    assert remaining_systems == set(), "Remaining systems did not match expectation"

    secret_id = RedrockController.get_secret_id_by_name(deleter_user_0_session, secret_name)
    assert secret_id is not None, f"Secret was not visible to creator '{roles[0]}' user, either because it wasn't created or because of a permissions issue"

    secret_id = RedrockController.get_secret_id_by_name(other_user_1_session, secret_name)
    assert secret_id is None, f"Secret should not be '{roles[1]}' user when created by '{roles[0]}' user"

    secret_id = RedrockController.get_secret_id_by_name(core_session, secret_name)
    assert secret_id is not None, f"Sys admin should be able to see secret created by {roles[0]}"
示例#15
0
def test_bulk_manage_works_with_different_methods_of_specifying_systems(
        core_session,
        remote_unmanaged_users_with_mirrored_managed_local_users_qty3,
        windows_test_machine_config, change_method):
    account_ids = remote_unmanaged_users_with_mirrored_managed_local_users_qty3

    job_result = None
    if change_method == "ids":
        job_result, success = ResourceManager.manage_multiple_accounts(
            core_session, account_ids)
        assert success, "Did not bulk manage account"
    elif change_method == "ids_with_invalid":
        job_result, success = ResourceManager.manage_multiple_accounts(
            core_session, ["foo"] + list(account_ids))
        assert success, "Did not bulk manage account"
    elif change_method == "sql":
        sql_query = 'SELECT * FROM VaultAccount WHERE ' + ' OR '.join(
            ('VaultAccount.ID = "' + str(n) + '"' for n in account_ids))
        job_result, success = ResourceManager.manage_multiple_accounts(
            core_session, [], set_query=sql_query)
        assert success, "Did not bulk manage accounts"
    elif change_method == "group":
        some_set_name = "ApiSet" + guid()
        SetsManager.create_manual_collection(core_session, some_set_name,
                                             "VaultAccount", None)
        set_id = SetsManager.get_collection_id(core_session, some_set_name,
                                               "VaultAccount")
        SetsManager.update_members_collection(core_session, 'add', account_ids,
                                              'VaultAccount', set_id)
        filters = SetsManager.get_object_collection_and_filter_by_name(
            core_session, some_set_name, "VaultAccount")['Filters']
        job_result, success = ResourceManager.manage_multiple_accounts(
            core_session, [], set_query=filters)
        assert success, "Did not bulk manage accounts"
    else:
        raise Exception(f"Bad input variable change_method {change_method}")

    _validate_accounts_are_managed(core_session, account_ids, job_result)

    user_info = core_session.get_current_session_user_info().json()['Result']
    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.AccountBulkManagement.Start.Multi'
    end_type = 'Cloud.Core.AsyncOperation.AccountBulkManagement.Success.Multi'
    start_message = f'{username} initiated management of {len(account_ids)} accounts'
    end_message = f'{username} successfully managed {len(account_ids)} accounts'

    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_checkout_password_for_sql_unmanaged_account(
        core_session, add_database_with_account):
    """
    Test case: C1101 - Checkout password for a SQL unmanaged account
    :param core_session: Authenticated centrify session
    :param add_database_with_account: fixture to create database with account as optional.
    """
    db_name, db_id, db_account_id, db_data, database_cleaner_list, sql_account_cleaner_list = \
        add_database_with_account(db_class='sql', add_account=True)

    result, status = ResourceManager.check_out_password(
        core_session, lifetime=15, accountid=db_account_id)
    assert status, f'failed to checkout account {db_data["db_account"]} password.'
    assert result['Password'] == db_data[
        'password'], "Checked out password dose'nt match the actual password"
    logger.info(f'{db_data["db_account"]} password check out successfully.')

    acc_activity = RedrockController.get_account_activity(
        core_session, db_account_id)
    assert f'{core_session.auth_details["User"]} checked out database account "{db_data["db_account"]}" password for ' \
           f'database "{db_name}"' in \
           acc_activity[0]['Detail'], f"no activity of checkout found for account {db_data['db_account']}"
    logger.info(
        f"There is a checkout record for the account {db_data['db_account']} in activity"
    )
def test_import_system_and_health_check(core_session, pas_windows_setup):
    """
    C1554 : Import system and check health
    :param core_session: Authenticated Centrify Session.
    :param pas_windows_setup:
    """
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup()
    system_details = RedrockController.get_computer_with_ID(core_session, system_id)

    system_counter = 1
    while system_counter < 60:
        if system_details['HealthStatus'] == 'OK' and system_details['LastHealthCheck']:
            break
        system_counter += 1
    ResourceManager.get_date(system_details['LastHealthCheck'])
    assert system_details['HealthStatus'] == 'OK', "System not reachable because connector is not up."
    logger.info(f"System is reachable successfully: {system_details}")

    account_counter = 1
    account_details = None
    while account_counter < 60:
        account_details = ResourceManager.get_account_information(core_session, account_id)
        if account_details[0]['VaultAccount']['Row']['Healthy'] == 'OK' and \
                account_details[0]['VaultAccount']['Row']['LastHealthCheck']:
            break
        account_counter += 1
    ResourceManager.get_date(account_details[0]['VaultAccount']['Row']['LastHealthCheck'])
    assert account_details[0]['VaultAccount']['Row']['Healthy'] == 'OK', \
        "System not reachable because connector is not up."
    logger.info(f"Account is reachable successfully: {account_details}")
示例#18
0
def test_system_password_rotation_switch_page(core_session, pas_setup, core_admin_ui):
    """
    Test Case ID: C1672
    :param core_session: Returns API session
    :param pas_setup: Creates System and Account
    :param core_admin_ui: Authenticates Centrify UI session
    """
    # Creating windows system.
    system_id, account_id, sys_info = pas_setup
    system_name = sys_info[0]

    # Navigating to System and enabling the "password rotation duration" option with valid values.
    ui = core_admin_ui
    ui.navigate('Resources', 'Systems')
    ui.search(system_name)
    ui.click_row(GridRowByGuid(system_id))
    ui.tab('Advanced')
    ui.switch_context(RenderedTab("Advanced"))
    ui.select_option("AllowPasswordRotation", "Yes")
    expected_password_rotation_duration = 5
    ui.input("PasswordRotateDuration", expected_password_rotation_duration)
    ui.save()
    ui.navigate('Resources', 'Domains')

    # Leaving the page and coming back to the System's page as per the test case.
    ui.navigate('Resources', 'Systems')
    system_list = RedrockController.get_computers(core_session)
    discovered_system = []
    for system in system_list:
        if system['Name'] == sys_info[0]:
            discovered_system.append(system['ID'])
            discovered_system.append(system['PasswordRotateDuration'])
    assert expected_password_rotation_duration == discovered_system[1], f"password rotation duration count {expected_password_rotation_duration} not matched with actual count {discovered_system[1]}"
    logger.info(
        f"Password rotation duration of the system {system_name} with id {system_id} saved with count {discovered_system[1]}")
示例#19
0
def test_add_system_account_with_win_rm(core_session, pas_windows_setup):
    """C2536 Add system with managed account with WinRM http setting
           validate the added Account with win rm and check out password after 5 minutes"""

    # Getting system details.
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup(
        True)

    # Verifying Default management mode should be 'RpcOverTcp'
    system_rows = RedrockController.get_computer_with_ID(
        core_session, system_id)
    assert system_rows[
        'ManagementMode'] == 'RpcOverTcp', "Default Management mode is not RpcOverTcp"
    logger.info("Default Management mode is RPC Over TCP")

    # Checkout Password
    checkout_password_result, checkout_password_success = ResourceManager. \
        check_out_password(core_session,
                           lifetime=1,
                           accountid=account_id)
    assert checkout_password_success, f"Failed to checkout password due to {checkout_password_result}"
    logger.info("Password checkout successfully")

    assert checkout_password_result[
        'Password'] != user_password, "Password is same after adding managed account"
    logger.info("Password updated after adding managed account")

    success, response = ResourceManager.update_system(
        core_session,
        system_id,
        sys_info[0],
        sys_info[1],
        'Windows',
        proxycollectionlist=connector_id,
        chooseConnector="on",
        managementmode="WinRMOverHttp")
    assert success, "Failed to update system"
    logger.info(f"Successfully updated system '{sys_info[0]}'")

    # Adding account in portal.
    acc_result, acc_success = ResourceManager.add_account(
        core_session,
        sys_info[6],
        password=user_password,
        host=system_id,
        ismanaged=True)
    assert acc_success, f"Failed to add account in the portal: {acc_result}"
    logger.info(f"Successfully added account {sys_info[6]} in the portal")

    # Checkout Password after changing management mode to WinRMOverHttp
    checkout_password_winrm, checkout_password_success = ResourceManager. \
        check_out_password(core_session,
                           lifetime=1,
                           accountid=acc_result)
    assert checkout_password_success, f"Failed to checkout password due to {checkout_password_winrm}"
    logger.info("Password checkout successfully")

    assert checkout_password_winrm[
        'Password'] != user_password, "Password is same after adding managed account"
    logger.info("Password updated after adding managed account")
def test_bulk_rotate_works(core_session,
                           remote_users_with_mirrored_managed_local_users_qty3,
                           windows_test_machine_config, users_and_roles):
    remote_ip = windows_test_machine_config['ip_address']

    account_ids, accounts = BulkOperations.grab_relevant_users(
        core_session, remote_users_with_mirrored_managed_local_users_qty3)
    account_names = []
    for i in range(len(accounts)):
        account_names.append(accounts[i][1])

    passwords_fetched = BulkOperations.checkout_users(core_session, accounts)

    result, success = ResourceManager.rotate_multiple_passwords(
        core_session, account_ids)
    assert success, "Did not bulk rotate passwords"
    job_ids = RedrockController.get_all_running_bulk_rotate_password_jobs(
        core_session)

    for id in job_ids:
        ResourceManager.wait_for_job_state_succeeded(core_session, id)

    # Verify passwords are no longer right
    BulkOperations.validate_users_with_login(remote_ip, passwords_fetched,
                                             [False] * len(passwords_fetched),
                                             "E2E")
def test_bulk_account_delete_generates_secret(
        clean_bulk_delete_systems_and_accounts, core_session,
        list_of_created_systems, secret_cleaner):
    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)

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

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

    sql_query = 'SELECT * FROM VaultAccount WHERE ' + ' OR '.join(
        ('VaultAccount.ID = "' + str(n) + '"' for n in list(all_accounts)))
    ResourceManager.del_multiple_accounts_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, "Secret not found"
    secret_cleaner.append(secret_id)
    assert len(
        ResourceManager.get_multi_added_account_ids(
            core_session,
            all_systems)) == 0, "Expected zero added accounts remain"
def test_bulk_account_delete_does_not_generate_secret_when_told_not_to(
        clean_bulk_delete_systems_and_accounts, core_session,
        list_of_created_systems):
    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)

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

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

    sql_query = 'SELECT * FROM VaultAccount WHERE ' + ' OR '.join(
        ('VaultAccount.ID = "' + str(n) + '"' for n in list(all_accounts)))
    ResourceManager.del_multiple_accounts_by_query(core_session, sql_query,
                                                   False, secret_name)

    ResourceManager.wait_for_secret_to_exist_or_timeout(core_session,
                                                        secret_name,
                                                        intervals_to_wait=60)
    # set low intervals to wait, since secret should not be generated

    secret_id = RedrockController.get_secret_id_by_name(
        core_session, secret_name)
    assert secret_id is None, "Secret not found!"

    assert len(ResourceManager.get_multi_added_account_ids(core_session, all_systems)) == 0, \
        "Expected zero remaining added accounts remain"
示例#23
0
def test_system_with_managed_account(core_session, setup_pas_system_for_unix):
    """
    Test case : C279339
    :param core_session: Centrify session manager
    :param setup_pas_system_for_unix: fixture that provide created unix system data
    """
    system_id, account_id, system_info = setup_pas_system_for_unix
    system_rows = RedrockController.get_computer_with_ID(
        core_session, system_id)
    assert system_rows['Name'] == system_info[
        0], f"failed to find system {system_info[0]} in portal as returned system result is {system_rows}"
    logger.info(f"system found {system_rows}")

    account, status = ResourceManager.get_accounts_from_resource(
        core_session, system_id)
    assert status, f"failed to find accounts in system {system_info[0]} as returned account result is {account}"
    logger.info(f"Account found {account}")

    # Fetching account information to validate desired account is unmanaged
    result, status = ResourceManager.get_account_information(
        core_session, account_id)
    assert status, f"failed to retrieve account information, returned result is {result}"

    is_managed = result['VaultAccount']['Row']['IsManaged']
    assert is_managed is False, f"Added account is not managed account"
def test_bulk_system_deletes_manually_single_system_and_secret(clean_bulk_delete_systems_and_accounts, core_session, core_ui, list_of_created_systems, secret_cleaner):
    server_prefix, names_of_servers, server_ids = _make_one_server_get_name(core_session, list_of_created_systems)

    ui = core_ui
    ui.navigate('Resources', 'Systems')
    ui.search(server_prefix)

    for name in names_of_servers:
        assert ui.check_exists(GridCell(name)), "Missing server from view " + name

    ui.action('Delete', names_of_servers)
    core_ui.switch_context(Modal('System Delete'))

    secret_name = "secret_e2e_name_" + guid()
    core_ui.input("SecretName", secret_name)

    core_ui.button('Delete')

    ResourceManager.wait_for_systems_to_delete_or_timeout(core_session, server_ids)
    assert len(ResourceManager.get_multi_added_account_ids(core_session, server_ids)) == 0, "All added accounts not removed"
    assert len(ResourceManager.get_multi_added_system_ids(core_session, server_ids)) == 0, "All added systems not removed"

    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, "Secret not found"
    secret_cleaner.append(secret_id)
def test_bulk_account_delete_job_fails_with_request_query_returning_zero_rows_fast_track(
        clean_bulk_delete_systems_and_accounts, core_session, simulate_failure,
        list_of_created_systems):
    batch = ResourceManager.add_multiple_systems_with_accounts(
        core_session, 1, 1, list_of_created_systems)
    _, delete_account_ids = DataManipulation.aggregate_lists_in_dict_values(
        [batch])
    # Invalid query for the failure case.
    if simulate_failure:
        sql_query = f"select * from VaultAccount where ID = '{guid()}'"
    else:
        sql_query = RedrockController.get_query_for_ids(
            'VaultAccount', delete_account_ids)

    params = Util.scrub_dict({
        'Ids': [],
        'SaveToSecrets': False,
        'SecretName': "",
        'SetQuery': sql_query,
        'RunSync': True
    })

    request = core_session.apirequest(EndPoints.ACCOUNT_MULTI_DELETE, params)
    request_json = request.json()
    result, success = request_json['Result'], request_json['success']
    assert not simulate_failure == success, \
        f'Invalid query bulk account delete request succeeded even though it should fail {result}'
def test_add_account_unlock_account_permission(core_session,
                                               domain_config_data,
                                               get_admin_user_function):
    """
                      Steps for this scenario using API:
                        1)Get the domain that needs to be added managed account with add account permission
                        2)Set add account and unlock permission in the domain
              """
    conf = domain_config_data
    limited_sesh, limited_user = get_admin_user_function
    name = conf['pas_bat_scenario1_infrastructure_data'][0]
    script = "Select * FROM VaultDomain"
    request = RedrockController.redrock_query(core_session, script)
    for directory_service in request:
        if directory_service['Row']['Name'] == name["Domain_name2"]:
            directory_service = directory_service['Row']['ID']
            break
    permissions = "Grant,View,Edit,Delete,AddAccount,UnlockAccount"

    result, add_domain_account_success = ResourceManager.set_domain_account_permissions(
        core_session,
        permissions,
        limited_user.get_login_name(),
        limited_user.get_id(),
        id=directory_service,
        pvid=directory_service,
        rowkey=directory_service)
    assert add_domain_account_success, f'Failed to set add account permission in the domain {result}'
    logger.info(f"add account permission set successfully in the Domain.")
示例#27
0
def test_add_managed_proxy_account(core_session, pas_windows_setup):
    """
    :param core_session: Authenticated Centrify Session.
    :param pas_windows_setup: Fixture for adding a system and an account associated with it.
    TC: C2537 - Add system with managed account and Proxy account with WinRM https settings
     trying to Add system with managed account and Proxy account with WinRM https settings
            Steps:
                Pre: Create system with 1 manage and proxy account
                1. Try to fetch the management mode in setting page
                    -Assert Failure
                2. Try to check out password from account
                    -Assert Failure
    """
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup(True, True)
    logger.info(f"System: {sys_info[0]} successfully added with UUID: {system_id} and account: {sys_info[4]} "
                f"with UUID: {account_id} associated with it.")
    managementmode = RedrockController.get_computer_with_ID(core_session, system_id)
    assert managementmode['ManagementMode'] == "WinRMOverHttps", \
        f"management mode is failed because of system doesnt have proxy account. API response result: {managementmode}"
    logger.info(f"Fetch management mode successfully: {managementmode['ManagementMode']}")
    password_checkout_result, password_checkout_success = ResourceManager.check_out_password(core_session, 1,
                                                                                             accountid=account_id)
    assert password_checkout_result['Password'] is not user_password, \
        f"password checkout Failed. API response result: {password_checkout_result}"
    logger.info(f"password successfully checkout Account password: {password_checkout_result['COID']}")
示例#28
0
def test_bulk_rotate_works_with_different_methods_of_specifying_systems(
        core_session,
        remote_users_with_mirrored_managed_local_users_qty3, windows_test_machine_config, change_method):

    remote_ip = windows_test_machine_config['ip_address']

    account_ids, accounts = BulkOperations.grab_relevant_users(core_session, remote_users_with_mirrored_managed_local_users_qty3)
    passwords_fetched = BulkOperations.checkout_users(core_session, accounts)
    BulkOperations.validate_users_with_login(remote_ip, passwords_fetched)

    if change_method == "checkin":   # disabled, out of scope
        BulkOperations.check_in_users(core_session, passwords_fetched)
    elif change_method == "ids":
        result, success = ResourceManager.rotate_multiple_passwords(core_session, account_ids)
        assert success, "Did not bulk rotate passwords"
    elif change_method == "ids_with_invalid":
        result, success = ResourceManager.rotate_multiple_passwords(core_session, account_ids)
        assert success, "Did not bulk rotate passwords"
    elif change_method == "sql":
        sql_query = 'SELECT * FROM VaultAccount ' \
                    'WHERE ' + ' OR '.join(('VaultAccount.ID = "' + str(n) + '"' for n in account_ids))
        result, success = ResourceManager.rotate_multiple_passwords(core_session, [], set_query=sql_query)
        assert success, "Did not bulk rotate passwords"
    elif change_method == "group":
        some_set_name = "ApiSet" + guid()
        SetsManager.create_manual_collection(core_session, some_set_name, "VaultAccount", None)
        set_id = SetsManager.get_collection_id(core_session, some_set_name, "VaultAccount")
        SetsManager.update_members_collection(core_session, 'add', account_ids, 'VaultAccount', set_id)
        filters = SetsManager.get_object_collection_and_filter_by_name(core_session,
                                                                       some_set_name, "VaultAccount")['Filters']
        result, success = ResourceManager.rotate_multiple_passwords(core_session, [], set_query=filters)
        assert success, "Did not bulk rotate passwords"
    else:
        raise Exception(f"Bad input variable change_method {change_method}")

    BulkOperations.validate_users_with_login(remote_ip, passwords_fetched, [False] * len(passwords_fetched), change_method)
    # Verify passwords are no longer right

    user_info = core_session.get_current_session_user_info().json()['Result']
    username = user_info['Name']
    start_type = 'Cloud.Core.AsyncOperation.BulkPasswordRotationJob.Start.Multi'
    end_type = 'Cloud.Core.AsyncOperation.BulkPasswordRotationJob.Success.Multi'
    start_message = f'{username} initiated password rotation of {len(account_ids)} accounts'
    end_message = f'{username} successfully rotated {len(account_ids)} account passwords'

    RedrockController.expect_event_message_by_type(core_session, start_type, start_message)
    RedrockController.expect_event_message_by_type(core_session, end_type, end_message)
示例#29
0
def test_a_secret_can_belong_to_multiple_sets(core_session, create_set_manual,
                                              added_secrets,
                                              pas_general_secrets,
                                              cleanup_secrets_and_folders,
                                              set_cleaner):
    """test method to check that a secret belongs to multiple set"""
    added_secret_id, added_secret_name = added_secrets
    set_params = pas_general_secrets
    prefix = guid()
    set_success, set_id = create_set_manual
    """Api to create another set manually"""
    success, setid = SetsManager.create_manual_collection(
        core_session, prefix + set_params['set_name'], 'DataVault')
    logger.info(f'creating manual set:{success} with setid as: {setid}')
    assert success is True, f'Failed to create manual set with one initial member {setid}'

    text_secret_id = added_secret_id[0]
    """Api to add set to existing secret"""
    added_to_set_success, added_to_set_result = SetsManager.update_members_collection(
        core_session, 'add', [text_secret_id], "DataVault", set_id)
    assert added_to_set_success, f'Failed to add secret to set{added_to_set_result}'
    logger.info(f'Adding secret to one set: {added_to_set_success}')
    """Api to add another set to same secret"""
    added_to_set_success, added_to_set_result = SetsManager.update_members_collection(
        core_session, 'add', [text_secret_id], "DataVault", setid)
    assert added_to_set_success, f'Failed to add secret to set{added_to_set_result}'
    logger.info(f'Adding secret to another set: {added_to_set_success}')
    """Redrock query to fetch set related details"""
    get_set_1 = RedrockController.verify_set_secret(core_session, set_id,
                                                    text_secret_id)
    logger.info(f'{get_set_1}')
    logger.info(
        f'Verifiying secret name {get_set_1[0]["Row"]["SecretName"]} in '
        f'set 1 with ID {get_set_1[0]["Row"]["CollectionID"]} ')

    get_set_2 = RedrockController.verify_set_secret(core_session, setid,
                                                    text_secret_id)
    logger.info(
        f'Verifiying secret name {get_set_2[0]["Row"]["SecretName"]} in another '
        f'set with ID {get_set_2[0]["Row"]["CollectionID"]}')
    """to verify that same secret is added to multiple sets"""
    text_to_verify = 'secret1'
    assert (text_to_verify in get_set_1[0]["Row"]["SecretName"]) and (
        text_to_verify in get_set_2[0]["Row"]["SecretName"]
    ), f'secret doesnt belong to multiple set'
    set_cleaner.append(setid)
示例#30
0
def _validate_accounts_are_not_managed(session, account_ids, job_id):
    rows = RedrockController.get_rows_matching_ids(session, 'VaultAccount',
                                                   account_ids)
    job_report = JobManager.get_job_report(session, job_id)

    for row in rows:
        assert row[
            'IsManaged'] is False, f'Expected account to not be managed after bulk manage account but it was {row} {job_report}'