def test_created_date_comparison(ldap_connection):
    """ Tests that imported users/roles have the same created_date
    value in RethinkDB as the created_date in their source.
    """
    create_fake_group(ldap_connection, "pokemons", "pokemons")
    fake_group = get_fake_group(ldap_connection, "pokemons")
    put_in_inbound_queue(fake_group, "group")
    time.sleep(2)
    ldap_role = get_role("pokemons")
    assert fake_group[0].whenCreated.value == ldap_role[0]["created_date"]
def test_delete_role(ldap_connection):
    """Delete a AD role in NEXT and all related tables

    Args:
        ldap_connection:
            obj: A bound mock mock_ldap_connection
    """
    create_fake_user(ldap_connection, "jchan", "Jackie C", "Jackiec")
    user_remote_id = "CN=jchan,OU=Users,OU=Accounts,DC=AD2012,DC=LAB"
    fake_user = get_fake_user(ldap_connection, "jchan")
    put_in_inbound_queue(fake_user, "user")

    create_fake_group(ldap_connection, "sysadmins", "sysadmins",
                      user_remote_id)
    fake_group = get_fake_group(ldap_connection, "sysadmins")
    put_in_inbound_queue(fake_group, "group")
    time.sleep(3)
    group_distinct_name = "CN=sysadmins,OU=Roles,OU=Security,OU=Groups,DC=AD2012,DC=LAB"
    addMembersToGroups.ad_add_members_to_groups(ldap_connection,
                                                user_remote_id,
                                                group_distinct_name,
                                                fix=True)

    assert is_user_the_role_owner("sysadmins", "jchan") is True
    assert is_group_in_db("sysadmins") is True

    role = get_role("sysadmins")
    role_id = role[0]["role_id"]
    insert_deleted_entries(
        ["CN=sysadmins,OU=Roles,OU=Security,OU=Groups,DC=AD2012,DC=LAB"],
        "group_deleted",
    )
    time.sleep(3)

    is_role_removed = wait_for_resource_removal_in_db("roles", "name",
                                                      "sysadmins")
    assert is_role_removed is True
    is_owner_removed = wait_for_resource_removal_in_db("role_owners",
                                                       "role_id", role_id)
    assert is_owner_removed is True
    is_member_removed = wait_for_resource_removal_in_db(
        "role_members", "role_id", role_id)
    assert is_member_removed is True
def test_role_outq_insertion():
    """ Test the insertion of a new fake role resource which is unique
        into the outbound_queue table."""
    user1_payload = {
        "name": "Test Unique User",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    with requests.Session() as session:
        expected_result = True
        user_response1 = create_test_user(session, user1_payload)
        user1_result = assert_api_success(user_response1)
        user1_id = user1_result["data"]["user"]["id"]
        role_payload = {
            "name": "TestUniqueRole0501201903",
            "owners": user1_id,
            "administrators": user1_id,
            "description": "Test Unique Role 1",
        }
        role_response = create_test_role(session, role_payload)
        assert_api_success(role_response)

        inserted_queue_item = peek_at_q_unfiltered("outbound_queue")
        LOGGER.info("Received queue entry %s from outbound queue...",
                    inserted_queue_item["id"])
        successful_insert = bool(inserted_queue_item)
        assert expected_result == successful_insert

        # Check status of new outbound_entry
        role_entry = get_role("TestUniqueRole0501201903")
        outbound_queue_data = prepare_outbound_queue_data(
            role_entry[0], "role")
        outbound_entry = get_outbound_queue_entry(outbound_queue_data)
        assert outbound_entry[0]["status"] == "UNCONFIRMED"

        delete_role_by_name("TestUniqueRole0501201903")
        delete_user_by_username("testuniqueuser0501201901")
def test_delete_user(ldap_connection):
    """Deletes a AD user in NEXT

    Args:
        ldap_connection:
            obj: A bound mock mock_ldap_connection
    """
    # Create fake user and attach as owner to a role
    create_fake_user(ldap_connection, "jchan20", "Jackie Chan", "Jackie")
    user_remote_id = "CN=jchan20,OU=Users,OU=Accounts,DC=AD2012,DC=LAB"
    create_fake_group(ldap_connection, "jchan_role", "jchan_role",
                      user_remote_id)
    group_distinct_name = (
        "CN=jchan_role,OU=Roles,OU=Security,OU=Groups,DC=AD2012,DC=LAB")
    addMembersToGroups.ad_add_members_to_groups(ldap_connection,
                                                user_remote_id,
                                                group_distinct_name,
                                                fix=True)
    fake_user = get_fake_user(ldap_connection, "jchan20")
    put_in_inbound_queue(fake_user, "user")
    fake_group = get_fake_group(ldap_connection, "jchan_role")
    put_in_inbound_queue(fake_group, "group")
    time.sleep(3)

    # See if owner and role are in the system
    email = "*****@*****.**"
    assert is_user_in_db(email) is True
    assert is_group_in_db("jchan_role") is True

    # See if all LDAP user has entries in the following
    # off chain tables: user_mapping and metadata
    user = get_user_in_db_by_email(email)
    next_id = user[0]["next_id"]
    assert get_user_mapping_entry(next_id)
    assert get_user_metadata_entry(next_id)

    # See that the owner is assigned to correct role
    role = get_role("jchan_role")
    owners = get_role_owners(role[0]["role_id"])
    members = get_role_members(role[0]["role_id"])
    assert owners[0]["related_id"] == next_id
    assert members[0]["related_id"] == next_id

    # Create a NEXT role with LDAP user as an admin and
    # check for LDAP user's entry in auth table
    next_role_id = create_next_role_ldap(user=user[0], role_name="managers")
    admins = get_role_admins(next_role_id)
    assert admins[0]["related_id"] == next_id
    assert get_auth_entry(next_id)

    # Create a NEXT pack with LDAP user as an owner
    next_pack_id = create_pack_ldap(user=user[0],
                                    pack_name="technology department")
    assert check_user_is_pack_owner(next_pack_id, next_id)

    # Delete user and verify LDAP user and related off chain
    # table entries have been deleted, role still exists
    # and role relationships have been deleted
    insert_deleted_entries([user_remote_id], "user_deleted")
    time.sleep(3)

    assert get_deleted_user_entries(next_id) == []
    assert get_pack_owners_by_user(next_id) == []
    assert is_group_in_db("jchan_role") is True
    assert get_role_owners(role[0]["role_id"]) == []
    assert get_role_admins(next_role_id) == []
    assert get_role_members(role[0]["role_id"]) == []

    delete_role_by_name("managers")
    delete_pack_by_name("technology department")
def test_add_role_member_outqueue():
    """Test adding a new member to a role.

    Creates two test users and a role using the first user,
    then adds the second user as member to role."""
    user1_payload = {
        "name": "Test Owner 0521201905",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    user2_payload = {
        "name": "Test Member 0521201906",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    with requests.Session() as session:
        user1_response = create_test_user(session, user1_payload)
        user1_result = assert_api_success(user1_response)
        user1_id = user1_result["data"]["user"]["id"]
        user2_response = create_test_user(session, user2_payload)
        user2_result = assert_api_success(user2_response)
        user2_id = user2_result["data"]["user"]["id"]
        role_payload = {
            "name": "TestRole0521201902",
            "owners": user1_id,
            "administrators": user1_id,
            "description": "Test Role 3",
        }
        role_response = create_test_role(session, role_payload)
        role_result = assert_api_success(role_response)
        role_id = role_result["data"]["id"]
        start_depth = get_outbound_queue_depth()
        role_update_payload = {
            "id": user2_id,
            "reason": "Integration test of adding a member.",
            "metadata": "",
        }
        response = session.post(
            "http://rbac-server:8000/api/roles/{}/members".format(role_id),
            json=role_update_payload,
        )
        result = assert_api_success(response)
        proposal_response = get_proposal_with_retry(session,
                                                    result["proposal_id"])
        proposal = assert_api_success(proposal_response)
        # Logging in as role owner
        credentials_payload = {
            "id": user1_payload["username"],
            "password": user1_payload["password"],
        }
        log_in(session, credentials_payload)
        # Approve proposal as role owner
        approval_response = approve_proposal(session, result["proposal_id"])
        end_depth = get_outbound_queue_depth()
        assert end_depth > start_depth

        # Check status of new outbound_entry
        role_entry = get_role("TestRole0521201902")
        outbound_queue_data = prepare_outbound_queue_data(
            role_entry[0], "role")
        outbound_entry = get_outbound_queue_entry(outbound_queue_data)
        assert outbound_entry[0]["status"] == "UNCONFIRMED"

        delete_role_by_name("TestRole0521201902")
        delete_user_by_username("test0521201905")
        delete_user_by_username("test0521201906")