Example #1
0
def test_syncdirectionflag_rolename():
    """ Testing the presence and the value of syncdirection flag
        is set to OUTBOUND of a role in roles table.
    """
    new_rolename = "ManagerRandom0501201902"
    new_username = "******"
    expected_metadata = {"metadata": {"sync_direction": "OUTBOUND"}}
    time.sleep(3)
    conn = connect_to_db()
    metadata_object = (r.db("rbac").table("roles").filter({
        "name": new_rolename
    }).pluck("metadata").coerce_to("array").run(conn))
    actual_metadata = metadata_object[0]
    assert actual_metadata == expected_metadata
    conn.close()
    delete_user_by_username(new_username)
    delete_role_by_name(new_rolename)
Example #2
0
def test_proposals():
    """Create a new fake role and try to add yourself to role you created"""
    with requests.Session() as session:
        # create test user
        user_payload = {
            "name": "Susan S",
            "username": "******",
            "password": "******",
            "email": "*****@*****.**",
        }
        user_response = create_test_user(session, user_payload)
        assert user_response.status_code == 200, ("Error creating user: %s" %
                                                  user_response.json())

        # create test role
        user_id = user_response.json()["data"]["user"]["id"]
        role_resource = {
            "name": "Office_Assistant",
            "owners": user_id,
            "administrators": user_id,
        }
        role_response = session.post("http://rbac-server:8000/api/roles",
                                     json=role_resource)
        assert role_response.status_code == 200, ("Error creating role: %s" %
                                                  role_response.json())

        # Wait for role in rethinkdb
        role_id = role_response.json()["data"]["id"]
        is_role_in_db = wait_for_role_in_db(role_id)
        assert (
            is_role_in_db is True
        ), "Couldn't find role in rethinkdb, maximum attempts exceeded."

        # create a membership proposal to test autoapproval
        res = session.post(
            "http://rbac-server:8000/api/roles/" + role_id + "/members",
            json=user_response.json()["data"]["user"],
        )
        assert (res.json()["message"] ==
                "Owner is the requester. Proposal is autoapproved")

        # clean up
        delete_user_by_username("susans2224")
        delete_role_by_name("Office_Assistant")
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_update_manager_outqueue():
    """ Creates a user and then updates their manager

    Manager is the second user created here."""
    # TODO: Rewrite this test after data gets sent to outbound_queue
    # after a user has their manager updated.
    user1_payload = {
        "name": "Test User 0521201901",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    user2_payload = {
        "name": "Test User 0521201902",
        "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"]
        start_depth = get_outbound_queue_depth()
        next_admins = {
            "name": "NextAdmins",
            "owners": [user2_id],
            "administrators": [user2_id],
        }
        role_response = create_test_role(session, next_admins)
        add_role_member(session,
                        role_response.json()["data"]["id"], {"id": user2_id})
        manager_payload = {
            "id": user2_id,
            "reason": "Integration test of adding role owner.",
            "metadata": "",
        }
        response = session.put(
            "http://rbac-server:8000/api/users/{}/manager".format(user1_id),
            json=manager_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": user2_payload["username"],
            "password": user2_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
        # TODO: Add tests to check for UNCONFIRMED outbound_queue entry status
        # when a user's manager gets updated.
        delete_user_by_username("test0521201901")
        delete_user_by_username("test0521201902")
        delete_role_by_name("NextAdmins")
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")
def test_user_delete_api():
    """Test that user has been removed from database when users delete api is hit"""
    user = {
        "name": "nadia one",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    pack = {
        "name": "michael pack one",
        "roles": [],
        "description": "Michael's test pack",
    }
    with requests.Session() as session:
        response = create_test_user(session, user)
        next_id = response.json()["data"]["user"]["id"]
        role_payload = {
            "name": "test_role",
            "owners": [next_id],
            "administrators": [next_id],
            "description": "This is a test Role",
        }
        role_resp = create_test_role(session, role_payload)
        role_id = role_resp.json()["data"]["id"]

        pack = {
            "name": "michael pack one",
            "owners": [next_id],
            "roles": [],
            "description": "Michael's test pack",
        }
        pack_response = create_test_pack(session, pack)

        add_role_member_payload = {
            "id": next_id,
            "reason": "Integration test of adding a member.",
            "metadata": "",
        }

        add_role_member(session, role_id, add_role_member_payload)

        conn = connect_to_db()
        user_exists = (r.db("rbac").table("users").filter({
            "next_id": next_id
        }).coerce_to("array").run(conn))

        role_owner_exists = (r.table("role_owners").filter({
            "identifiers": [next_id],
            "role_id":
            role_id
        }).coerce_to("array").run(conn))

        role_member_exists = (r.table("role_members").filter({
            "identifiers": [next_id],
            "role_id":
            role_id
        }).coerce_to("array").run(conn))

        assert user_exists
        assert role_owner_exists
        assert role_member_exists
        assert get_user_mapping_entry(next_id)
        assert get_auth_entry(next_id)
        assert get_user_metadata_entry(next_id)
        assert check_user_is_pack_owner(
            pack_id=pack_response.json()["data"]["pack_id"], next_id=next_id)

        role_admin_is_user = (r.db("rbac").table("role_admins").filter({
            "related_id":
            next_id
        }).coerce_to("array").run(conn))
        role_admin = role_admin_is_user[0]["identifiers"][0]
        assert role_admin == next_id

        deletion = session.delete("http://rbac-server:8000/api/users/" +
                                  next_id)
        time.sleep(5)
        assert deletion.json() == {
            "message": "User {} successfully deleted".format(next_id),
            "deleted": 1,
        }

        role_admin_user = (r.db("rbac").table("role_admins").filter({
            "related_id":
            next_id
        }).coerce_to("array").run(conn))

        role_owners = (
            r.db("rbac").table("role_owners").filter(lambda doc: doc[
                "identifiers"].contains(next_id)).coerce_to("array").run(conn))

        role_members = (
            r.db("rbac").table("role_members").filter(lambda doc: doc[
                "identifiers"].contains(next_id)).coerce_to("array").run(conn))
        delete_role_by_name("test_role")
        conn.close()

        assert role_admin_user == []
        assert role_members == []
        assert role_owners == []
        assert get_deleted_user_entries(next_id) == []
        assert get_pack_owners_by_user(next_id) == []

        delete_pack_by_name("michael pack one")
def test_add_role_member():
    """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 1",
        "username": "******",
        "password": "******",
        "email": "*****@*****.**",
    }
    user2_payload = {
        "name": "Test Member",
        "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": "TestRole0501201903",
            "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"]
        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)
        assert proposal["data"]["assigned_approver"][0] == user1_id
        # 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
        approve_proposal(session, result["proposal_id"])
        proposal_response = get_proposal_with_retry(session,
                                                    result["proposal_id"])
        proposal = assert_api_success(proposal_response)
        assert proposal["data"]["status"] == "CONFIRMED"
        delete_role_by_name("TestRole0501201903")
        delete_user_by_username("testowner")
        delete_user_by_username("testmemeber")
Example #9
0
def test_delete_role_not_owner():
    """
    Test the delete role api

    Create a test user for auth
    Create a test user for role membership
    Create a test role
    Attempt to delete the test role as a non role owner/admin
    Check that the deletion attempt was autorejected
    """
    with requests.Session() as session:
        # Create test user
        role_owner = {
            "name": "Fred Pirate",
            "username": "******",
            "password": "******",
            "email": "*****@*****.**",
        }
        user_response = create_test_user(session, role_owner)
        assert user_response.status_code == 200, "Error creating user: %s;\n %s" % (
            role_owner["name"],
            user_response.json(),
        )
        role_owner["next_id"] = user_response.json()["data"]["user"]["id"]

        # Create test user
        test_user = {
            "name": "Meunster Monster",
            "username": "******",
            "password": "******",
            "email": "*****@*****.**",
        }
        user_response = create_test_user(session, test_user)
        assert user_response.status_code == 200, "Error creating user: %s;\n %s" % (
            test_user["name"],
            user_response.json(),
        )
        test_user["next_id"] = user_response.json()["data"]["user"]["id"]

        # Auth as new_member
        payload = {
            "id": role_owner["username"],
            "password": role_owner["password"]
        }
        auth_response = session.post(
            "http://rbac-server:8000/api/authorization/", json=payload)
        assert auth_response.status_code == 200, "Failed to authenticate as %s. %s" % (
            test_user["name"],
            auth_response.json(),
        )

        # Create test role
        role_resource = {
            "name": "Men of Low Moral Fiber",
            "owners": role_owner["next_id"],
            "administrators": role_owner["next_id"],
        }
        role_response = session.post("http://rbac-server:8000/api/roles",
                                     json=role_resource)
        assert role_response.status_code == 200, ("Error creating role: %s" %
                                                  role_response.json())

        # Wait for role in db
        role_id = role_response.json()["data"]["id"]
        is_role_in_db = wait_for_role_in_db(role_id)
        assert (
            is_role_in_db is True
        ), "Couldn't find role in rethinkdb, maximum attempts exceeded."

        # Auth as test_user
        payload = {
            "id": test_user["username"],
            "password": test_user["password"]
        }
        auth_response = session.post(
            "http://rbac-server:8000/api/authorization/", json=payload)
        assert auth_response.status_code == 200, "Failed to authenticate as %s. %s" % (
            role_owner["name"],
            auth_response.json(),
        )

        # Delete test role
        delete_role_response = session.delete(
            "http://rbac-server:8000/api/roles/%s" % role_id)
        assert delete_role_response.status_code == 403, (
            "Unexpected response: %s" % delete_role_response.json())

    # clean up
    delete_user_by_username("fred1")
    delete_user_by_username("meunster1")
    delete_role_by_name("Men of Low Moral Fiber")