Unify privilege representation
[platform/core/test/security-tests.git] / src / security-manager-tests / test_cases_privacy_manager.cpp
index 7645f55..ac72b73 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ * Copyright (c) 2016-2020 Samsung Electronics Co., Ltd All Rights Reserved
  *
  *    Licensed under the Apache License, Version 2.0 (the "License");
  *    you may not use this file except in compliance with the License.
@@ -14,9 +14,9 @@
  *    limitations under the License.
  */
 
+#include <algorithm>
 #include <cstdlib>
 #include <map>
-#include <set>
 #include <string>
 #include <sys/types.h>
 #include <unistd.h>
 #include <utility>
 #include <vector>
 
+#include <app_install_helper.h>
 #include <cynara_test_admin.h>
 #include <dpl/test/test_runner.h>
-#include <memory.h>
-#include <passwd_access.h>
-#include <scoped_label.h>
+#include <dpl/test/test_runner_child.h>
+#include <pkg_privacy_privileges.h>
+#include <policy_configuration.h>
+#include <scoped_installer.h>
 #include <sm_api.h>
 #include <sm_commons.h>
 #include <sm_policy_request.h>
 #include <synchronization_pipe.h>
 #include <temp_test_user.h>
 #include <tests_common.h>
+#include <privilege_names.h>
+#include <app_def_privilege.h>
 
 using namespace SecurityManagerTest;
-
-static const std::vector<std::string> PM_MANY_APPS = {
-    "security_manager_pm_app_1",
-    "security_manager_pm_app_2",
-    "security_manager_pm_app_3",
-    "security_manager_pm_app_4",
-    "security_manager_pm_app_5"
+using namespace PrivilegeNames;
+namespace {
+struct UserInfo {
+    std::string userName;
+    GumUserType userType;
 };
 
-const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
-const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
-const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/notexist";
-const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/internal/usermanagement";
-
-static const std::map<std::string, struct app_attributes> PM_MANY_APPS_PKGS = {
-    {"security_manager_pm_app_1", {"security_manager_pm_pkg_1", "2.1"}},
-    {"security_manager_pm_app_2", {"security_manager_pm_pkg_2", "3.0"}},
-    {"security_manager_pm_app_3", {"security_manager_pm_pkg_3", "2.1.1"}},
-    {"security_manager_pm_app_4", {"security_manager_pm_pkg_4", "3.1"}},
-    {"security_manager_pm_app_5", {"security_manager_pm_pkg_5", "2.2"}},
-    {PRIVILEGE_MANAGER_APP, {PRIVILEGE_MANAGER_PKG, "3.0"}}
+// Privileges required for having permission to self/admin get/set policies.
+const std::string& SELF_PRIVILEGE = PRIV_NOTEXIST;
+const std::string& ADMIN_PRIVILEGE = PRIV_INTERNAL_USERMANAGEMENT;
+
+const std::vector<PrivilegeVector> TEST_PRIVILEGES = {
+    {PRIV_INTERNET, PRIV_DISPLAY},
+    {PRIV_TELEPHONY, PRIV_DATASHARING},
+    {PRIV_CONTENT_WRITE, PRIV_LED, PRIV_EMAIL},
+    {PRIV_LED, PRIV_EMAIL, PRIV_TELEPHONY, PRIV_DATASHARING},
+    {PRIV_INTERNET, PRIV_DISPLAY, PRIV_LED, PRIV_EMAIL}
 };
 
-static const std::vector<privileges_t> PM_MANY_APPS_PRIVILEGES = {
-    {
-        "http://tizen.org/privilege/internet",
-        "http://tizen.org/privilege/display"
-    },
-    {
-        "http://tizen.org/privilege/telephony",
-        "http://tizen.org/privilege/datasharing"
-    },
+const PrivilegeVector TEST_PRIVACY_PRIVILEGES[] = {
     {
-        "http://tizen.org/privilege/content.write",
-        "http://tizen.org/privilege/led",
-        "http://tizen.org/privilege/email"
+        Privilege(PRIV_TELEPHONY),
+        Privilege(PRIV_LED),
+        Privilege(PRIV_CALLHISTORY_READ, Privilege::PRIVACY),
+        Privilege(PRIV_ACCOUNT_READ, Privilege::PRIVACY),
+        Privilege(PRIV_HEALTHINFO, Privilege::PRIVACY),
     },
     {
-        "http://tizen.org/privilege/led",
-        "http://tizen.org/privilege/email",
-        "http://tizen.org/privilege/telephony",
-        "http://tizen.org/privilege/datasharing"
-    },
-    {
-        "http://tizen.org/privilege/internet",
-        "http://tizen.org/privilege/display",
-        "http://tizen.org/privilege/led",
-        "http://tizen.org/privilege/email"
+        Privilege(PRIV_TELEPHONY),
+        Privilege(PRIV_LED),
+        Privilege(PRIV_CALLHISTORY_READ, Privilege::PRIVACY),
     }
 };
 
-RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_PRIVACY_MANAGER)
+}
 
-static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
-{
-    InstallRequest request;
-    request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
-    request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
-    request.setUid(uid);
-    request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
-    if (forAdmin)
-        request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
-    Api::install(request);
-    Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-};
+RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_PRIVACY_MANAGER)
 
 RUNNER_CHILD_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
 {
-    //TEST DATA
-    const std::string username("sm_test_10_user_name");
-    unsigned int privileges_count = 0;
-
-    std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
-    std::map<std::string, std::set<std::string>> apps2PrivsMap;
-
-    for (unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-        apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-            PM_MANY_APPS.at(i), std::set<std::string>(
-                PM_MANY_APPS_PRIVILEGES.at(i).begin(),
-                PM_MANY_APPS_PRIVILEGES.at(i).end())));
-        privileges_count += PM_MANY_APPS_PRIVILEGES.at(i).size();
-    };
+    TemporaryTestUser tmpUser("sm_test_10_user_name", GUM_USERTYPE_NORMAL, false);
+    tmpUser.create();
+
+    unsigned expectedPolicyCount = 0;
+    std::map<std::string, AppInstallHelper> appIdToAIH;
+    for (unsigned i = 0; i < TEST_PRIVILEGES.size(); i++) {
+        AppInstallHelper app("sm_test_10_" + std::to_string(i), tmpUser.getUid());
+        app.addPrivileges(TEST_PRIVILEGES[i]);
+        expectedPolicyCount += app.getPrivileges().size();
+        appIdToAIH.emplace(app.getAppId(), std::move(app));
+    }
 
-    apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-        PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
-    ++privileges_count;
-    users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
-    //TEST DATA END
+    AppInstallHelper privManager("sm_test_10_privilege_manager", tmpUser.getUid());
+    std::string privManagerAppId = privManager.getAppId();
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    expectedPolicyCount += privManager.getPrivileges().size();
+    appIdToAIH.emplace(privManager.getAppId(), std::move(privManager));
 
-    SynchronizationPipe pipe;
-    pid_t pid = fork();
+    std::vector<ScopedInstaller> scopedInstallations;
+    for (const auto &appIdAIH : appIdToAIH) {
+        scopedInstallations.emplace_back(ScopedInstaller(appIdAIH.second));
+    }
 
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
     if (pid != 0) { //parent process
-        pipe.claimParentEp();
-        TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
-        tmpUser.create();
-
-        for(const auto &user : users2AppsMap) {
-            for(const auto &app : user.second) {
-                InstallRequest requestInst;
-                requestInst.setAppId(app.first.c_str());
-                try {
-                    requestInst.setPkgId(PM_MANY_APPS_PKGS.at(app.first).package.c_str());
-                } catch (const std::out_of_range &e) {
-                    RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
-                };
-                requestInst.setUid(tmpUser.getUid());
-
-                for (const auto &privilege : app.second) {
-                    requestInst.addPrivilege(privilege.c_str());
-                };
-
-                Api::install(requestInst);
-            };
-
-            //check_app_after_install(PM_MANY_APPS[i].c_str(), PM_MANY_APPS_PKGS[i].c_str());
-        };
-
-        //Start child process
-        pipe.post();
         waitPid(pid);
-
-        tmpUser.remove();
     } else { //child process
-        pipe.claimChildEp();
-        pipe.wait();
-
-        uid_t uid; gid_t gid;
-        PasswdAccess::allUser(username, uid, gid);
-        std::string uidStr = std::to_string(uid);
-        register_current_process_as_privilege_manager(uid);
-        int result = drop_root_privileges(uid, gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+        Api::setProcessLabel(privManagerAppId);
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(tmpUser.getUid(), tmpUser.getGid()) == 0,
+                                "drop_root_privileges failed");
 
         std::vector<PolicyEntry> policyEntries;
-        PolicyEntry filter;
-        Api::getPolicy(filter, policyEntries);
+        Api::getPolicy(PolicyEntry(), policyEntries);
 
         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
+        RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
+                          "Number of policies doesn't match - should be: " << expectedPolicyCount
+                          << " and is " << policyEntries.size());
 
         for (const auto &policyEntry : policyEntries) {
             std::string user = policyEntry.getUser();
             std::string app = policyEntry.getAppId();
             std::string privilege = policyEntry.getPrivilege();
 
-            RUNNER_ASSERT_MSG(user == uidStr, "Unexpected user: " << user);
+            RUNNER_ASSERT_MSG(user == tmpUser.getUidString(), "Unexpected user: " << user);
 
-            try {
-                std::set<std::string>::iterator tmp = users2AppsMap.at(username).at(app).find(privilege);
-                if (tmp == users2AppsMap.at(username).at(app).end())
-                    RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
-            } catch (const std::out_of_range &e) {
-                RUNNER_FAIL_MSG("Unexpected policy entry: unexpected app: " << policyEntry << ". Exception: " << e.what());
-            };
-        };
+            auto appIt = appIdToAIH.find(app);
+            RUNNER_ASSERT_MSG(appIt != appIdToAIH.end(), "Policy returned unexpected app: " << app);
+
+            AppInstallHelper &aih = appIt->second;
+            auto& appPrivileges = aih.getPrivileges();
+            auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
+            RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
+                              "Unexpected privilege " << privilege << " for app " << app);
+        }
         exit(0);
-    };
+    }
 }
 
 RUNNER_CHILD_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
 {
-    //TEST DATA
-    const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
-    unsigned int privileges_count = 0;
+    const std::string normalNameToSwitch = "sm_test_11_user_name_normal";
+    const std::vector<UserInfo> userInfos = {{normalNameToSwitch, GUM_USERTYPE_NORMAL},
+                                             {"sm_test_11_user_name_admin", GUM_USERTYPE_ADMIN}};
 
-    std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
-    std::map<std::string, std::set<std::string>> apps2PrivsMap;
+    std::map<std::string, TemporaryTestUser> usernameToTTU;
+    // uid + app_id -> AppInstallHelper (different users can have same app_id installed)
+    std::map<std::pair<uid_t,std::string>, AppInstallHelper> userAppIdToAIH;
+    unsigned expectedPolicyCount = 0;
 
-    for (const auto &username : usernames) {
-        //Only entries for one of the users will be listed
-        privileges_count = 0;
-
-        for(unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-            apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-                PM_MANY_APPS.at(i), std::set<std::string>(
-                    PM_MANY_APPS_PRIVILEGES.at(i).begin(),
-                    PM_MANY_APPS_PRIVILEGES.at(i).end())));
-            privileges_count+=PM_MANY_APPS_PRIVILEGES.at(i).size();
+    for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
+        TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
+        user.create();
+
+        for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
+            AppInstallHelper app("sm_test_11_" + std::to_string(p_i), user.getUid());
+            app.addPrivileges(TEST_PRIVILEGES[p_i]);
+            if (user.getUserName() == normalNameToSwitch) // Only entries for this user should be fetched
+                expectedPolicyCount += app.getPrivileges().size();
+            userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
         };
 
-        users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
+        usernameToTTU.emplace(userInfos[u_i].userName, std::move(user));
     };
 
-    users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
-        PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
+    TemporaryTestUser &normalUserToSwitch = usernameToTTU.at(normalNameToSwitch);
 
-    ++privileges_count;
-    //TEST DATA END
+    AppInstallHelper privManager("sm_test_11_priv_manager", normalUserToSwitch.getUid());
+    std::string privManagerAppId = privManager.getAppId();
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    expectedPolicyCount += privManager.getPrivileges().size();
+    userAppIdToAIH.emplace(std::make_pair(normalUserToSwitch.getUid(), privManager.getAppId()),
+                           std::move(privManager));
 
-    SynchronizationPipe pipe;
-    pid_t pid = fork();
+    std::vector<ScopedInstaller> scopedInstallations;
+    for (const auto &userAppIdAIH : userAppIdToAIH) {
+        scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
+    }
 
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
     if (pid != 0) { //parent process
-        pipe.claimParentEp();
-        std::vector<TemporaryTestUser> users = {
-            TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
-            TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
-            };
-
-        users.at(0).create();
-        users.at(1).create();
-
-        //Install apps for both users
-        for(const auto &user : users) {
-            for(const auto &app : users2AppsMap.at(user.getUserName())) {
-                InstallRequest requestInst;
-                requestInst.setAppId(app.first.c_str());
-                try {
-                    requestInst.setPkgId(PM_MANY_APPS_PKGS.at(app.first).package.c_str());
-                } catch (const std::out_of_range &e) {
-                    RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
-                };
-                requestInst.setUid(user.getUid());
-
-                for (const auto &privilege : app.second) {
-                    requestInst.addPrivilege(privilege.c_str());
-                };
-
-                Api::install(requestInst);
-            };
-
-            //check_app_after_install(PM_MANY_APPS[i].c_str(), PM_MANY_APPS_PKGS[i].c_str());
-        };
-
-        //Start child
-        pipe.post();
         waitPid(pid);
-
-        for (auto &user : users)
-            user.remove();
-
     } else { //child process
-        pipe.claimChildEp();
-        pipe.wait();
-
-        uid_t uid; gid_t gid;
-        PasswdAccess::allUser(usernames.at(0), uid, gid);
-        std::string uidStr = std::to_string(uid);
-        register_current_process_as_privilege_manager(uid);
-
-        //change uid to normal user
-        errno = 0;
-        int result = drop_root_privileges(uid, gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+        Api::setProcessLabel(privManagerAppId);
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUserToSwitch.getUid(),
+                                                     normalUserToSwitch.getGid()) == 0,
+                                "drop_root_privileges failed");
 
         std::vector<PolicyEntry> policyEntries;
-        PolicyEntry filter;
-
-        //this call should only return privileges belonging to the current uid
-        Api::getPolicy(filter, policyEntries);
+        Api::getPolicy(PolicyEntry(), policyEntries);
 
         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
+        RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
+                          "Number of policies doesn't match - should be: " << expectedPolicyCount
+                          << " and is " << policyEntries.size());
 
         for (const auto &policyEntry : policyEntries) {
+            // Expect policy only for current process user
             std::string user = policyEntry.getUser();
             std::string app = policyEntry.getAppId();
             std::string privilege = policyEntry.getPrivilege();
 
-            RUNNER_ASSERT_MSG(uidStr == user, "Unexpected user: " << user);
+            RUNNER_ASSERT_MSG(normalUserToSwitch.getUidString() == user, "Unexpected user: " << user);
+            auto userAppIdToAIHIt = userAppIdToAIH.find(std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
+            RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
+                              "Unknown app " << app << " for user " << user);
 
-            try {
-                std::set<std::string>::iterator tmp = users2AppsMap.at(usernames.at(0)).at(app).find(privilege);
-                if (tmp == users2AppsMap.at(usernames.at(0)).at(app).end())
-                    RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
-            } catch (const std::out_of_range &e) {
-                RUNNER_FAIL_MSG("Unexpected policy entry: app: " << policyEntry << ". Exception: " << e.what());
-            };
-        };
+            AppInstallHelper &aih = userAppIdToAIHIt->second;
+            auto privs = aih.getPrivileges();
+
+            auto& appPrivileges = aih.getPrivileges();
+            auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
+            RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
+                              "Unexpected privilege " << privilege << " for app " << app);
+        }
         exit(0);
-    };
+    }
 }
 
 RUNNER_CHILD_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
@@ -318,216 +229,181 @@ RUNNER_CHILD_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_adm
     Api::getPolicy(PolicyEntry(), oldPolicyVec);
     std::unordered_set<PolicyEntry> oldPolicySet(oldPolicyVec.begin(), oldPolicyVec.end());
 
-    //TEST DATA
-    const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
-    unsigned int privileges_count = oldPolicyVec.size();
+    std::string adminNameToSwitch = "sm_test_12_user_name_admin";
+    const std::vector<UserInfo> userInfos = {{"sm_test_12_user_name_normal",GUM_USERTYPE_NORMAL},
+                                             {adminNameToSwitch, GUM_USERTYPE_ADMIN}};
 
-    std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
-    std::map<std::string, std::set<std::string>> apps2PrivsMap;
+    std::map<std::string, TemporaryTestUser> usernameToTTU;
+    std::vector<std::string> uidStrings;
+    // uidstring + app_id -> AppInstallHelper
+    std::map<std::pair<uid_t, std::string>, AppInstallHelper> userAppIdToAIH;
+    unsigned expectedPolicyCount = oldPolicyVec.size();
 
-    for (const auto &username : usernames) {
-        for(unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-            apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-                PM_MANY_APPS.at(i), std::set<std::string>(
-                    PM_MANY_APPS_PRIVILEGES.at(i).begin(),
-                    PM_MANY_APPS_PRIVILEGES.at(i).end())));
-            privileges_count+=PM_MANY_APPS_PRIVILEGES.at(i).size();
+    for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
+        TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
+        user.create();
+        uidStrings.push_back(user.getUidString());
+
+        for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
+            AppInstallHelper app("sm_test_12_" + std::to_string(p_i), user.getUid());
+            // Shift privileges, so same app_id for different users doesn't have same privileges
+            app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
+            expectedPolicyCount += app.getPrivileges().size();
+            userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
         };
-
-        users2AppsMap.insert(std::make_pair(username, apps2PrivsMap));
+        usernameToTTU.emplace(user.getUserName(), std::move(user));
     };
 
-    users2AppsMap.at(usernames.at(1)).insert(std::make_pair(PRIVILEGE_MANAGER_APP,
-        std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
+    TemporaryTestUser &adminUserToSwitch = usernameToTTU.at(adminNameToSwitch);
 
-    privileges_count += 2;
-    //TEST DATA END
+    AppInstallHelper privManager("sm_test_12_priv_manager", adminUserToSwitch.getUid());
+    std::string privManagerAppId = privManager.getAppId();
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    privManager.addPrivilege(ADMIN_PRIVILEGE);
+    expectedPolicyCount += privManager.getPrivileges().size();
 
-    SynchronizationPipe pipe;
-    pid_t pid = fork();
+    userAppIdToAIH.emplace(std::make_pair(adminUserToSwitch.getUid(), privManager.getAppId()),
+                           std::move(privManager));
 
-    if (pid != 0) { //parent process
-        pipe.claimParentEp();
-        std::vector<TemporaryTestUser> users = {
-            TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
-            TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
-            };
-
-        users.at(0).create();
-        users.at(1).create();
-        //Install apps for both users
-        for(const auto &user : users) {
-            for(const auto &app : users2AppsMap.at(user.getUserName())) {
-                InstallRequest requestInst;
-                requestInst.setAppId(app.first.c_str());
-                try {
-                    requestInst.setPkgId(PM_MANY_APPS_PKGS.at(app.first).package.c_str());
-                } catch (const std::out_of_range &e) {
-                    RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
-                };
-                requestInst.setUid(user.getUid());
-
-                for (const auto &privilege : app.second) {
-                    requestInst.addPrivilege(privilege.c_str());
-                };
-
-                Api::install(requestInst);
-            };
-
-            //check_app_after_install(PM_MANY_APPS[i].c_str(), PM_MANY_APPS_PKGS[i].c_str());
-        };
+    std::vector<ScopedInstaller> scopedInstallations;
+    for (const auto &userAppIdAIH : userAppIdToAIH) {
+        scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
+    }
 
-        //Start child process
-        pipe.post();
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
         waitPid(pid);
-
-        for (auto &user : users)
-            user.remove();
-
     } else { //child process
-        pipe.claimChildEp();
-        pipe.wait();
-
-        uid_t adminUid;
-        gid_t adminGid;
-        PasswdAccess::allUser(usernames.at(1), adminUid, adminGid);
-        std::string adminUidStr = std::to_string(adminUid);
-        uid_t normalUid = PasswdAccess::uid(usernames.at(0));
-        std::string normalUidStr = std::to_string(normalUid);
-        register_current_process_as_privilege_manager(adminUid, true);
-
-        //change uid to normal user
-        int result = drop_root_privileges(adminUid, adminGid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
-
+        Api::setProcessLabel(privManagerAppId);
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
+                                                     adminUserToSwitch.getGid()) == 0,
+                                "drop_root_privileges failed");
 
         std::vector<PolicyEntry> policyEntries;
-        //this call should succeed as the calling user is privileged
         Api::getPolicy(PolicyEntry(), policyEntries);
-
         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
+        RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
+                          "Number of policies doesn't match - should be: " << expectedPolicyCount
+                          << " and is " << policyEntries.size());
 
         for (const auto &policyEntry : policyEntries) {
+            // Expect policy for all users to be returned
             if (oldPolicySet.count(policyEntry))
                 continue;
-
             std::string user = policyEntry.getUser();
             std::string app = policyEntry.getAppId();
             std::string privilege = policyEntry.getPrivilege();
 
-            RUNNER_ASSERT_MSG(user == normalUidStr || user == adminUidStr, "Unexpected user: " << user);
+            auto uidStringIt = std::find(uidStrings.begin(), uidStrings.end(), user);
+            RUNNER_ASSERT_MSG(uidStringIt != uidStrings.end(), "Unexpected user: " << user);
 
-            std::string uidStrToLook = user == normalUidStr ? usernames.at(0) : usernames.at(1);
+            auto userAppIdToAIHIt = userAppIdToAIH.find(
+                    std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
+            RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
+                              "Unknown app " << app << " for user " << user);
 
-            try {
-                std::set<std::string>::iterator tmp = users2AppsMap.at(uidStrToLook).at(app).find(privilege);
-                if (tmp == users2AppsMap.at(uidStrToLook).at(app).end())
-                    RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
-            } catch (const std::out_of_range &e) {
-                RUNNER_FAIL_MSG("Unexpected policy entry: unexpected app: " << policyEntry << ". Exception: " << e.what());
-            } catch (const std::invalid_argument& e) {
-                RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
-            };
-        };
+            AppInstallHelper &aih = userAppIdToAIHIt->second;
+            auto privs = aih.getPrivileges();
 
+            auto& appPrivileges = aih.getPrivileges();
+            auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
+            RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
+                              "Unexpected privilege " << privilege << " for app " << app);
+        };
         exit(0);
     };
 }
 
 RUNNER_CHILD_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
 {
-    //TEST DATA
-    const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
+    std::string normalName = "sm_test_13_user_name_normal";
+    std::string adminName = "sm_test_13_user_name_admin";
+    const std::vector<UserInfo> userInfos = {{normalName,GUM_USERTYPE_NORMAL},
+                                             {adminName, GUM_USERTYPE_ADMIN}};
 
-    std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
-    std::map<std::string, std::set<std::string>> apps2PrivsMap;
+    std::map<std::string, TemporaryTestUser> usernameToTTU;
+    std::map<uid_t, std::vector<AppInstallHelper>> uidToAIHs;
+    unsigned expectedPolicyCount = 0;
+    std::string privManagerAppId;
 
-    for (const auto &username : usernames) {
+    for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
+        //Only entries for one of the users will be listed
+        TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
+        user.create();
 
-        for(unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-            apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-                PM_MANY_APPS.at(i), std::set<std::string>(
-                    PM_MANY_APPS_PRIVILEGES.at(i).begin(),
-                    PM_MANY_APPS_PRIVILEGES.at(i).end())));
+        for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
+            AppInstallHelper app("sm_test_13_" + std::to_string(p_i), user.getUid());
+            // Shift privileges, so same app_id for different user doesn't have same privileges
+            app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
+            expectedPolicyCount += app.getPrivileges().size();
+            uidToAIHs[user.getUid()].emplace_back(std::move(app));
         };
+        AppInstallHelper privManager("sm_test_13_priv_manager", user.getUid());
+        privManagerAppId = privManager.getAppId();
+        privManager.addPrivilege(SELF_PRIVILEGE);
+        expectedPolicyCount += privManager.getPrivileges().size();
+        uidToAIHs[user.getUid()].emplace_back(std::move(privManager));
 
-        users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
+        usernameToTTU.emplace(user.getUserName(), std::move(user));
     };
 
-    users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
-        PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
-
-    //TEST DATA END
-
-    pid_t pid[2];
-    SynchronizationPipe sync[2];
-    std::vector<PolicyEntry> policyEntries;
-
-    pid[0] = fork();
-
-    if (pid[0] == 0) { //child #1 process
-        sync[0].claimChildEp();
-        sync[0].wait();
-
-        uid_t uid; gid_t gid;
-        PasswdAccess::allUser(usernames.at(0), uid, gid);
-        register_current_process_as_privilege_manager(uid);
+    std::vector<ScopedInstaller> scopedInstallations;
+    for (const auto &userAIHs : uidToAIHs) {
+        for (const auto &aih : userAIHs.second)
+        scopedInstallations.emplace_back(ScopedInstaller(aih));
+    }
 
-        //change uid to normal user
-        int result = drop_root_privileges(uid, gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+    TemporaryTestUser &adminUser = usernameToTTU.at(adminName);
+    TemporaryTestUser &normalUser = usernameToTTU.at(normalName);
 
-        PolicyEntry filter;
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
+    if (pid == 0) { //child #1 process
+        Api::setProcessLabel(privManagerAppId);
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUser.getUid(), normalUser.getGid()) == 0,
+                                "drop_root_privileges failed");
+        auto &app1 = uidToAIHs[normalUser.getUid()][0];
+        auto &app2 = uidToAIHs[normalUser.getUid()][0];
         PolicyRequest policyRequest;
-
         PolicyEntry policyEntry(
-                PM_MANY_APPS[0],
-                std::to_string(uid),
-                "http://tizen.org/privilege/internet"
+                app1.getAppId(),
+                normalUser.getUidString(),
+                app1.getPrivileges()[0]
                 );
-        policyEntry.setLevel("Deny");
+        policyEntry.setLevel(PolicyEntry::LEVEL_DENY);
 
         policyRequest.addEntry(policyEntry);
         policyEntry = PolicyEntry(
-                PM_MANY_APPS[1],
-                std::to_string(uid),
-                "http://tizen.org/privilege/display"
+                app2.getAppId(),
+                normalUser.getUidString(),
+                app1.getPrivileges()[1]
                 );
-        policyEntry.setLevel("Deny");
-
+        policyEntry.setLevel(PolicyEntry::LEVEL_DENY);
         policyRequest.addEntry(policyEntry);
         Api::sendPolicy(policyRequest);
 
         exit(0);
-    } else { //parent process
-        sync[0].claimParentEp();
-        pid[1] = fork();
-
-        if (pid[1] == 0) { //child #2 process
-            sync[1].claimChildEp();
-            sync[1].wait();
-
-            uid_t target_uid = PasswdAccess::uid(usernames.at(0));
-            uid_t my_uid;
-            gid_t my_gid;
-            PasswdAccess::allUser(usernames.at(1), my_uid, my_gid);
-
-            register_current_process_as_privilege_manager(my_uid);
-
-            //change uid to normal user
-            int result = drop_root_privileges(my_uid, my_gid);
-            RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+    } else {
+        waitPid(pid);
+        pid = fork();
+        RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
+        if (pid == 0) { //child #2 process
+            Api::setProcessLabel(privManagerAppId);
+            // Admin user, but in context of app, which doesn't have usermanagement privilege
+            RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
+                              "drop_root_privileges failed");
 
             PolicyEntry filter = PolicyEntry(
                         SECURITY_MANAGER_ANY,
-                        std::to_string(target_uid),
+                        normalUser.getUidString(),
                         SECURITY_MANAGER_ANY
                         );
-
+            std::vector<PolicyEntry> policyEntries;
             //U2 requests contents of U1 privacy manager - should fail
             Api::getPolicyForSelf(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
-            RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but is " << policyEntries.size());
+            RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
+                              << policyEntries.size() << " entries");
 
             filter = PolicyEntry(
                         SECURITY_MANAGER_ANY,
@@ -539,673 +415,837 @@ RUNNER_CHILD_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_
 
             //U2 requests contents of ADMIN bucket - should fail
             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
-            RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but is " << policyEntries.size());
+            RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
+                              << policyEntries.size() << " entries");
             exit(0);
-        } else { //parent
-            sync[1].claimParentEp();
-            std::vector<TemporaryTestUser> users = {
-                TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
-                TemporaryTestUser(usernames.at(1), GUM_USERTYPE_NORMAL, false)
-                };
-
-            users.at(0).create();
-            users.at(1).create();
-
-            //Install apps for both users
-            for(const auto &user : users2AppsMap) {
-
-                for(const auto &app : user.second) {
-                    InstallRequest requestInst;
-                    requestInst.setAppId(app.first.c_str());
-                    try {
-                        requestInst.setPkgId(PM_MANY_APPS_PKGS.at(app.first).package.c_str());
-                    } catch (const std::out_of_range &e) {
-                        RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
-                    };
-                    requestInst.setUid(users.at(0).getUid());
-
-                    for (const auto &privilege : app.second) {
-                        requestInst.addPrivilege(privilege.c_str());
-                    };
-
-                    Api::install(requestInst);
-                };
-
-                //check_app_after_install(PM_MANY_APPS[i].c_str(), PM_MANY_APPS_PKGS[i].c_str());
-            };
-
-            //Start child #1
-            sync[0].post();
-            waitPid(pid[0]);
-
-            //Start child #2
-            sync[1].post();
-            waitPid(pid[1]);
-
-            for (auto &user : users)
-                user.remove();
-        };
-    };
+        } else {
+            waitPid(pid);
+        }
+    }
 }
 
 RUNNER_CHILD_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
 {
-    //TEST DATA
-    const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
-    unsigned int privileges_count = 0;
-
-    std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
-    std::map<std::string, std::set<std::string>> apps2PrivsMap;
-
-    for (const auto &username : usernames) {
-
-        for(unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-            apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
-                PM_MANY_APPS.at(i), std::set<std::string>(
-                    PM_MANY_APPS_PRIVILEGES.at(i).begin(),
-                    PM_MANY_APPS_PRIVILEGES.at(i).end())));
-            privileges_count+=PM_MANY_APPS_PRIVILEGES.at(i).size();
-        };
-
-        users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
-    };
+    TemporaryTestUser adminUserToSwitch("sm_test_14_user_name_admin", GUM_USERTYPE_ADMIN);
+    adminUserToSwitch.create();
 
-    users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
-        PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
+    AppInstallHelper privManager("sm_test_14_priv_manager", adminUserToSwitch.getUid());
+    privManager.addPrivilege(ADMIN_PRIVILEGE);
 
-    privileges_count += 2;
-    //TEST DATA END
-    SynchronizationPipe pipe;
+    ScopedInstaller privManagerInstall(privManager);
 
     pid_t pid = fork();
     if (pid != 0) {
-        pipe.claimParentEp();
-        std::vector<TemporaryTestUser> users = {
-            TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
-            TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
-            };
-
-        users.at(0).create();
-        users.at(1).create();
-
-        //Install apps for both users
-        for(const auto &user : users) {
-
-            for(const auto &app : users2AppsMap.at(user.getUserName())) {
-                InstallRequest requestInst;
-                requestInst.setAppId(app.first.c_str());
-                try {
-                    requestInst.setPkgId(PM_MANY_APPS_PKGS.at(app.first).package.c_str());
-                } catch (const std::out_of_range &e) {
-                    RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
-                };
-                requestInst.setUid(user.getUid());
-
-                for (const auto &privilege : app.second) {
-                    requestInst.addPrivilege(privilege.c_str());
-                };
-
-                Api::install(requestInst);
-            };
-        };
-
-        //Start child process
-        pipe.post();
         waitPid(pid);
-
-        //switch back to root
-        for (auto &user : users)
-            user.remove();
-
     } else { //child process
-        pipe.claimChildEp();
-        pipe.wait();
-
-        uid_t uid; gid_t gid;
-        PasswdAccess::allUser(usernames.at(1), uid, gid);
-        register_current_process_as_privilege_manager(uid, true);
+        Api::setProcessLabel(privManager.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
+                                                     adminUserToSwitch.getGid()) == 0,
+                                "drop_root_privileges failed");
 
-        //change uid to normal user
-        int result = drop_root_privileges(uid, gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
-
-        PolicyRequest *policyRequest = new PolicyRequest();
-        PolicyEntry filter;
+        PolicyRequest setPolicyRequest;
         std::vector<PolicyEntry> policyEntries;
-        //this call should succeed as the calling user is privileged
-        Api::getPolicyForSelf(filter, policyEntries);
 
-        unsigned int policyNum = policyEntries.size();
+        PolicyEntry internetPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, PRIV_INTERNET);
+        internetPolicyEntry.setMaxLevel(PolicyEntry::LEVEL_DENY);
+        setPolicyRequest.addEntry(internetPolicyEntry);
 
-        PolicyEntry policyEntry(
-                SECURITY_MANAGER_ANY,
-                SECURITY_MANAGER_ANY,
-                "http://tizen.org/privilege/internet"
-                );
-        policyEntry.setMaxLevel("Deny");
+        PolicyEntry displayPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, PRIV_DISPLAY);
+        displayPolicyEntry.setMaxLevel(PolicyEntry::LEVEL_DENY);
+        setPolicyRequest.addEntry(displayPolicyEntry);
 
-        policyRequest->addEntry(policyEntry);
-        policyEntry = PolicyEntry(
-                SECURITY_MANAGER_ANY,
-                SECURITY_MANAGER_ANY,
-                "http://tizen.org/privilege/display"
-                );
-        policyEntry.setMaxLevel("Deny");
+        Api::sendPolicy(setPolicyRequest);
 
-        policyRequest->addEntry(policyEntry);
-        Api::sendPolicy(*policyRequest);
-        Api::getPolicyForAdmin(filter, policyEntries);
+        Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
+        RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2"
+                                                     " and is " << policyEntries.size());
 
-        RUNNER_ASSERT_MSG(policyEntries.size() == policyNum + 2, "Number of policies doesn't match - should be: "
-                                    << policyNum + 2 << "  and is " << policyEntries.size());
+        PolicyRequest delPolicyRequest;
 
-        delete policyRequest;
-        policyRequest = new PolicyRequest();
-        policyEntry = PolicyEntry(
-                SECURITY_MANAGER_ANY,
-                SECURITY_MANAGER_ANY,
-                "http://tizen.org/privilege/internet"
-                );
-        policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
-        policyRequest->addEntry(policyEntry);
+        internetPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
+        delPolicyRequest.addEntry(internetPolicyEntry);
 
-        policyEntry = PolicyEntry(
-                SECURITY_MANAGER_ANY,
-                SECURITY_MANAGER_ANY,
-                "http://tizen.org/privilege/display"
-                );
-        policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
+        displayPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
+        delPolicyRequest.addEntry(displayPolicyEntry);
 
-        policyRequest->addEntry(policyEntry);
-        Api::sendPolicy(*policyRequest);
+        Api::sendPolicy(delPolicyRequest);
 
         policyEntries.clear();
-        Api::getPolicyForAdmin(filter, policyEntries);
-        RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
-
-        delete policyRequest;
-
+        Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
+        RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0"
+                                                     " and is " << policyEntries.size());
         exit(0);
     };
-
 }
 
 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
 {
-    const char *const update_app_id = "security_manager_15_update_app_id";
-    const char *const update_privilege = "http://tizen.org/privilege/led";
-    const char *const check_start_bucket = "ADMIN";
-    const std::string username("sm_test_15_username");
-    PolicyRequest addPolicyRequest;
-    CynaraTestAdmin::Admin admin;
-    ScopedProcessLabel keepLabel;
+    const std::string& updatePriv = PRIV_LED;
 
-    struct message {
-        uid_t uid;
-        gid_t gid;
-    } msg;
+    TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
+    adminUser.create();
 
-    int pipefd[2];
-    pid_t pid;
-    int result = 0;
+    AppInstallHelper updatedApp("security_manager_15_update");
+    ScopedInstaller updatedAppInstall(updatedApp);
 
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
-
-    TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
-    user.create();
-
-    pid = fork();
-    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
-    if (pid != 0)//parent process
-    {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
-
-        register_current_process_as_privilege_manager(user.getUid(), true);
-
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
-
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+    AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
+    privManager.addPrivilege(ADMIN_PRIVILEGE);
+    ScopedInstaller privManagerInstall(privManager);
 
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
+    if (pid != 0) { //parent process
         waitPid(pid);
-
-        admin.adminCheck(check_start_bucket, false, generateProcessLabel(update_app_id).c_str(),
-                std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
+        CynaraTestAdmin::Admin admin;
+        admin.adminCheck("ADMIN", false, updatedApp.generateAppLabel().c_str(),
+                         adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
+                         nullptr);
+    } else {
+        Api::setProcessLabel(privManager.getAppId());
+
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
+                                "drop_root_privileges failed");
+
+        PolicyEntry entry(updatedApp.getAppId(), adminUser.getUidString(), updatePriv);
+        entry.setMaxLevel(PolicyEntry::LEVEL_ALLOW);
+        PolicyRequest addPolicyRequest;
+        addPolicyRequest.addEntry(entry);
+        Api::sendPolicy(addPolicyRequest);
+        exit(0);
     }
-    if(pid == 0)
-    {
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
+}
 
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
+{
+    const std::string& updatePriv = PRIV_LED;
 
-        //become admin privacy manager manager
-        Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+    TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
+    adminUser.create();
 
-        PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
-        entry.setMaxLevel("Allow");
+    AppInstallHelper app("security_manager_15");
+    ScopedInstaller appInstall(app);
 
+    AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
+    privManager.addPrivilege(ADMIN_PRIVILEGE);
+    ScopedInstaller privManagerInstall(privManager);
+
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
+    if (pid != 0) {
+        waitPid(pid);
+        CynaraTestAdmin::Admin admin;
+        admin.adminCheck("ADMIN", false, app.generateAppLabel().c_str(),
+                         adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
+                         nullptr);
+    } else {
+        Api::setProcessLabel(privManager.getAppId());
+        RUNNER_ASSERT_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
+                          "drop_root_privileges failed");
+
+        PolicyEntry entry(SECURITY_MANAGER_ANY, adminUser.getUidString(), updatePriv);
+        entry.setMaxLevel(PolicyEntry::LEVEL_ALLOW);
+
+        PolicyRequest addPolicyRequest;
         addPolicyRequest.addEntry(entry);
         Api::sendPolicy(addPolicyRequest);
         exit(0);
     }
 }
 
-RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
+RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
 {
-    const char *const update_other_app_id = "security_manager_15_update_other_app_id";
-    const char *const update_privilege = "http://tizen.org/privilege/led";
-    const char *const check_start_bucket = "ADMIN";
-    const std::string username("sm_test_15_username");
-    PolicyRequest addPolicyRequest;
-    CynaraTestAdmin::Admin admin;
-    ScopedProcessLabel keepLabel;
-
-    struct message {
-        uid_t uid;
-        gid_t gid;
-    } msg;
-
-    int pipefd[2];
-    pid_t pid;
-    int result = 0;
-
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
+    const std::string& updatePriv = PRIV_LED;
 
-    TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
+    TemporaryTestUser user("sm_test_15_username", GUM_USERTYPE_NORMAL);
     user.create();
 
-    pid = fork();
-    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
-    if (pid != 0)//parent process
-    {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
+    AppInstallHelper app("security_manager_15");
+    ScopedInstaller appInstall(app);
 
-        register_current_process_as_privilege_manager(user.getUid(), true);
+    AppInstallHelper privManager("security_manager_15_priv_manager", user.getUid());
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    ScopedInstaller privManagerInstall(privManager);
 
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
+    pid_t pid = fork();
+    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
+    if (pid != 0) {
+        waitPid(pid);
+        CynaraTestAdmin::Admin admin;
+        admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
+                         updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
+    } else {
+        Api::setProcessLabel(privManager.getAppId());
+        RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                          "drop_root_privileges failed");
+
+        PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
+        entry.setLevel(PolicyEntry::LEVEL_ALLOW);
+
+        PolicyRequest addPolicyRequest;
+        addPolicyRequest.addEntry(entry);
+        Api::sendPolicy(addPolicyRequest);
+        exit(0);
+    }
+}
 
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+RUNNER_CHILD_TEST(security_manager_16_policy_levels_get)
+{
+    TemporaryTestUser user("sm_test_16_user_name", GUM_USERTYPE_NORMAL);
+    user.create();
 
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
+    if (pid != 0) {
         waitPid(pid);
+    } else {
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                          "drop_root_privileges failed");
 
-        admin.adminCheck(check_start_bucket, false, generateProcessLabel(update_other_app_id).c_str(),
-                std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
-    }
-    if(pid == 0)
-    {
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
+        char** levels;
+        size_t count;
+        int ret = security_manager_policy_levels_get(&levels, &count);
+        RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
+                "Invlid return code: " << ret);
+        std::unique_ptr<char *, std::function<void(char**)>> descriptionsPtr(levels,
+                [count](char **levels) { security_manager_policy_levels_free(levels, count);});
 
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+        RUNNER_ASSERT_MSG(count >= 2, "Invalid number of policy levels. Should be 3,"
+                                      " instead there is: " << count);
 
-        //become admin privacy manager manager
-        Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+        std::string denyPolicy = std::string(levels[0]);
+        std::string allowPolicy = std::string(levels[count-1]);
 
-        // use wildcard as appId
-        PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
-        entry.setMaxLevel("Allow");
+        // first should always be Deny
+        RUNNER_ASSERT_MSG(denyPolicy.compare(PolicyEntry::LEVEL_DENY) == 0,
+                "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
 
-        addPolicyRequest.addEntry(entry);
-        Api::sendPolicy(addPolicyRequest);
+        // last should always be Allow
+        RUNNER_ASSERT_MSG(allowPolicy.compare(PolicyEntry::LEVEL_ALLOW) == 0,
+                "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
         exit(0);
     }
 }
 
-RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
+RUNNER_CHILD_TEST(security_manager_17a_privacy_manager_delete_policy_for_self)
 {
-    const char *const update_app_id = "security_manager_15_update_app_id";
-    const char *const update_privilege = "http://tizen.org/privilege/led";
-    const char *const check_start_bucket = "";
-    const std::string username("sm_test_15_username");
-    PolicyRequest addPolicyRequest;
-    CynaraTestAdmin::Admin admin;
-    ScopedProcessLabel keepLabel;
+    const std::string& updatePriv = PRIV_LED;
 
-    struct message {
-        uid_t uid;
-        gid_t gid;
-    } msg;
+    TemporaryTestUser user("sm_test_17a_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-    int pipefd[2];
-    pid_t pid;
-    int result = 0;
+    AppInstallHelper app("security_manager_17a");
+    ScopedInstaller appInstall(app);
 
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
+    SynchronizationPipe synchPipe;
+    pid_t pid = fork();
+    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
+    if (pid != 0) {
+        synchPipe.claimParentEp();
 
-    TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
-    user.create();
+        synchPipe.wait();
+        CynaraTestAdmin::Admin admin;
+        admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
+                         updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
+        synchPipe.post();
 
-    pid = fork();
-    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
-    if (pid != 0)//parent process
-    {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
+        synchPipe.wait();
+        admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
+                         updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
+        waitPid(pid);
+    } else {
+        synchPipe.claimChildEp();
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                                            "drop_root_privileges failed");
+
+        PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
+        entry.setLevel(PolicyEntry::LEVEL_ALLOW);
+        PolicyRequest addPolicyRequest;
+        addPolicyRequest.addEntry(entry);
+        Api::sendPolicy(addPolicyRequest);
+        synchPipe.post();
 
-        register_current_process_as_privilege_manager(user.getUid(), false);
+        synchPipe.wait();
+        PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
+        deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
+        PolicyRequest deletePolicyRequest;
+        deletePolicyRequest.addEntry(deleteEntry);
+        Api::sendPolicy(deletePolicyRequest);
+        synchPipe.post();
 
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
+        exit(0);
+    }
+}
 
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+RUNNER_CHILD_TEST(security_manager_17b_privacy_manager_delete_policy_for_self)
+{
+    const std::string& updatePriv = PRIV_LED;
 
-        waitPid(pid);
+    TemporaryTestUser user("sm_test_17b_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        admin.adminCheck(check_start_bucket, false, generateProcessLabel(update_app_id).c_str(),
-                std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
-    }
-    if(pid == 0)
-    {
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
+    AppInstallHelper app("security_manager_17b");
+    ScopedInstaller appInstall(app);
 
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+    AppInstallHelper privManager("security_manager_17b_priv_manager", user.getUid());
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    ScopedInstaller privManagerInstall(privManager);
 
-        //become admin privacy manager manager
-        Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+    SynchronizationPipe synchPipe;
+    pid_t pid = fork();
+    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
+    if (pid != 0) {
+        synchPipe.claimParentEp();
+        synchPipe.wait();
+        CynaraTestAdmin::Admin admin;
+        admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
+                         updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
+        synchPipe.post();
+
+        synchPipe.wait();
+        admin.adminCheck("", false, app.generateAppLabel().c_str(),
+                         user.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
+        waitPid(pid);
 
-        PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
-        entry.setLevel("Allow");
+    } else {
+        synchPipe.claimChildEp();
+        Api::setProcessLabel(privManager.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                                "drop_root_privileges failed");
 
+        PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
+        entry.setLevel(PolicyEntry::LEVEL_ALLOW);
+        PolicyRequest addPolicyRequest;
         addPolicyRequest.addEntry(entry);
         Api::sendPolicy(addPolicyRequest);
+        synchPipe.post();
+
+        synchPipe.wait();
+        PolicyRequest deletePolicyRequest;
+        PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
+        deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
+        deletePolicyRequest.addEntry(deleteEntry);
+        Api::sendPolicy(deletePolicyRequest);
+        synchPipe.post();
         exit(0);
     }
 }
 
-RUNNER_CHILD_TEST(security_manager_16_policy_levels_get)
+RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
 {
-    const std::string username("sm_test_16_user_cynara_policy");
-    CynaraTestAdmin::Admin admin;
-    int pipefd[2];
-    pid_t pid;
-    int result = 0;
+    const std::string username("sm_test_17_user_name");
+    std::vector<AppInstallHelper> appHelpers;
+    std::vector<ScopedInstaller> scopedInstallations;
+    std::map<std::string, unsigned> privToCount;
+    unsigned policyCount = 0;
 
-    struct message {
-        uid_t uid;
-        gid_t gid;
-    } msg;
+    TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
+    user.create();
 
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
+    for (unsigned int i = 0; i < TEST_PRIVILEGES.size(); i++) {
+        AppInstallHelper app("sm_test_17_" + std::to_string(i), user.getUid());
+        app.addPrivileges(TEST_PRIVILEGES[i]);
+        policyCount += app.getPrivileges().size();
 
-    TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
-    user.create();
+        appHelpers.emplace_back(std::move(app));
+        for (auto &priv: TEST_PRIVILEGES[i]) {
+            privToCount[priv]++;
+        }
+    }
 
-    pid = fork();
+    AppInstallHelper privManager("sm_test_17_priv_manager", user.getUid());
+    std::string privManagerAppId = privManager.getAppId();
+    privManager.addPrivilege(SELF_PRIVILEGE);
+    privToCount[SELF_PRIVILEGE]++;
+    policyCount += privManager.getPrivileges().size();
+
+    appHelpers.emplace_back(std::move(privManager));
+    for (const auto &app : appHelpers)
+        scopedInstallations.emplace_back(std::move(ScopedInstaller(app)));
+
+    pid_t pid = fork();
     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
     if (pid != 0)//parent process
     {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
+        waitPid(pid);
+    } else {
+        Api::setProcessLabel(privManagerAppId);
+        RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                          "drop_root_privileges failed");
+
+        for (const auto &privCount : privToCount) {
+            std::vector<PolicyEntry> policyEntries;
+            PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, privCount.first);
+            Api::getPolicy(filter, policyEntries);
+            RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
+            RUNNER_ASSERT_MSG(policyEntries.size() == privCount.second,
+                              "Number of policies doesn't match - should be: " << privCount.second
+                               << " and is " << policyEntries.size());
+        }
 
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
+        for (const auto &app : appHelpers) {
+            std::vector<PolicyEntry> policyEntries;
+            PolicyEntry filter(app.getAppId(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
+            Api::getPolicy(filter, policyEntries);
+            RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
+            RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
+                              "Number of policies doesn't match - should be: " << app.getPrivileges().size()
+                              << " and is " << policyEntries.size());
+        }
 
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+        std::vector<PolicyEntry> policyEntries;
+        PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
+        Api::getPolicy(filter, policyEntries);
+        RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
+        RUNNER_ASSERT_MSG(policyEntries.size() == policyCount,
+                          "Number of policies doesn't match - should be: " << policyCount
+                          << " and is " << policyEntries.size());
 
-        waitPid(pid);
+        exit(0);
     }
-    if(pid == 0)
-    {
-        int ret;
-        char** levels;
-        std::string allow_policy, deny_policy;
-        size_t count;
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
+}
 
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+RUNNER_CHILD_TEST(security_manager_18_privacy_manager_privacy_related_privileges_policy_install_remove)
+{
+    TemporaryTestUser user("sm_test_18_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        //become admin privacy manager manager
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+    AppInstallHelper app("sm_test_18", user.getUid());
+    app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
 
-        // 3 should be there when ask-user is installed
-        ret = security_manager_policy_levels_get(&levels, &count);
+    PolicyEntry filter (app.getAppId(), user.getUidString(), SECURITY_MANAGER_ANY);
+    std::vector<PolicyEntry> policyEntries;
+    {
+        PkgPrivacyPrivileges setupPrivacyPrivs(app);
+        ScopedInstaller installer(app);
+        unsigned int privacyNum = countPrivacyPrivileges(app.getPrivileges());
 
-        RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
-                "Invlid return code: " << ret);
+        Api::getPolicy(filter, policyEntries);
 
-        RUNNER_ASSERT_MSG(count == 3, "Invalid number of policy levels. Should be 3, instead there is: " << static_cast<int>(count));
+        RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
+            "Number of policy entries doesn't match; should be " << app.getPrivileges().size()
+            << " but is " << policyEntries.size());
+
+        if (PolicyConfiguration::getIsAskuserEnabled() ) {
+            unsigned int privacyActNum = 0;
+            for (auto &entry : policyEntries)
+                if (isPrivilegePrivacy(entry.getPrivilege())) {
+                    RUNNER_ASSERT_MSG(entry.getCurrentLevel() == PolicyEntry::LEVEL_ASK_USER,
+                                      "Invalid policy setup; policy should be \"Ask user\" but is "
+                                      << entry.getCurrentLevel());
+                    ++privacyActNum;
+                }
+            RUNNER_ASSERT_MSG(privacyActNum == privacyNum,
+                              "Should be " << privacyNum << " privacy privileges,"
+                              "but is " << privacyActNum);
+        }
+    }
 
-        deny_policy = std::string(levels[0]);
-        allow_policy = std::string(levels[count-1]);
+    policyEntries.clear();
+    Api::getPolicy(filter, policyEntries);
+    RUNNER_ASSERT_MSG(policyEntries.size() == 0,
+                      "After deinstallation, policy entries size should be 0,"
+                      "but is: "  << policyEntries.size());
+}
 
-        // first should always be Deny
-        RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
-                "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
+void test_privacy_related_privileges(bool isHybrid) {
+    TemporaryTestUser user("sm_test_19_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        // last should always be Allow
-        RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
-                "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
+    const std::string pkgId = "sm_test_19_pkg_id";
+
+    AppInstallHelper app1("sm_test_19_app_id_1", pkgId, user.getUid());
+    if (isHybrid)
+        app1.setHybrid();
+    app1.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
+    PkgPrivacyPrivileges setupPrivacyPrivs1(app1);
+    ScopedInstaller installer1(app1);
+
+    AppInstallHelper app2("sm_test_19_app_id_2", pkgId, user.getUid());
+    if (isHybrid)
+        app2.setHybrid();
+    app2.addPrivileges(TEST_PRIVACY_PRIVILEGES[1]);
+    PkgPrivacyPrivileges setupPrivacyPrivs2(app2);
+    ScopedInstaller installer2(app2);
+
+    int privacyCount1, privacyCount2;
+    if (!PolicyConfiguration::getIsAskuserEnabled()) {
+        privacyCount1 = 0;
+        privacyCount2 = 0;
+    } else if (isHybrid) {
+        privacyCount1 = countPrivacyPrivileges(app1.getPrivileges());
+        privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
+    } else {
+        privacyCount1 = privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
+    }
 
-        security_manager_policy_levels_free(levels, count);
-        exit(0);
+    std::vector<PolicyEntry> policyEntries;
+    PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
+    Api::getPolicy(filter, policyEntries);
+
+    int privacyAct1 = 0, privacyAct2 = 0;
+    for (auto &entry : policyEntries) {
+        RUNNER_ASSERT_MSG(entry.getAppId() == app1.getAppId() || entry.getAppId() == app2.getAppId(),
+                          "Invalid appId: should be either " << app1.getAppId() << " or "
+                          << app2.getAppId() << " but is " << entry.getAppId());
+        if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(entry.getPrivilege())) {
+            RUNNER_ASSERT_MSG(entry.getCurrentLevel() == PolicyEntry::LEVEL_ASK_USER,
+                              "Invalid policy setup; policy should be \"Ask user\" but is "
+                              << entry.getCurrentLevel());
+            if (entry.getAppId() == app1.getAppId())
+                ++privacyAct1;
+            else
+                ++privacyAct2;
+        }
     }
+    RUNNER_ASSERT_MSG(privacyCount1 == privacyAct1, "Should be " << privacyCount1
+                      << " privacy privileges, but is " << privacyAct1);
+    RUNNER_ASSERT_MSG(privacyCount2 == privacyAct2, "Should be " << privacyCount2
+                      << " privacy privileges, but is " << privacyAct2);
+}
+
+RUNNER_CHILD_TEST(security_manager_19a_privacy_manager_privacy_related_privileges_policy_hybrid)
+{
+    test_privacy_related_privileges(true);
 }
 
-RUNNER_CHILD_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
+RUNNER_CHILD_TEST(security_manager_19b_privacy_manager_privacy_related_privileges_policy_no_hybrid)
 {
-    const char *const update_app_id = "security_manager_17_update_app_id";
-    const char *const update_privilege = "http://tizen.org/privilege/led";
-    const char *const check_start_bucket = "";
-    const std::string username("sm_test_17_username");
-    PolicyRequest addPolicyRequest;
+    test_privacy_related_privileges(false);
+}
+
+RUNNER_CHILD_TEST(security_manager_20_privacy_manager_privacy_related_privileges_policy_admin_check)
+{
+    TemporaryTestUser user("sm_test_20_username", GUM_USERTYPE_NORMAL);
+    user.create();
+
+    AppInstallHelper app("sm_test_20", user.getUid());
+    app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
+
+    PkgPrivacyPrivileges setupPrivacyPrivs(app);
+    ScopedInstaller installer(app);
+
     CynaraTestAdmin::Admin admin;
+    int policyType = CYNARA_ADMIN_ALLOW;
+    int privacyPolicyType = -1;
+    if (PolicyConfiguration::getIsAskuserEnabled())
+        admin.getPolicyTypeForDescription(PolicyEntry::LEVEL_ASK_USER, privacyPolicyType);
+
+    for (auto &priv : app.getPrivileges()) {
+        if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(priv)) {
+            admin.adminCheck("", true, app.generateAppLabel().c_str(),
+                             user.getUidString().c_str(), priv, privacyPolicyType,
+                             nullptr);
+        } else {
+            admin.adminCheck("", true, app.generateAppLabel().c_str(),
+                             user.getUidString().c_str(), priv, policyType, nullptr);
+        }
+    }
+}
 
-    struct message {
-        uid_t uid;
-        gid_t gid;
-    } msg;
+RUNNER_CHILD_TEST(security_manager_21_fetch_app_manifest_invalid_params)
+{
+    int ret = security_manager_get_app_manifest_policy(nullptr, 0, nullptr, nullptr);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_ERROR_INPUT_PARAM, "Expected invalid input param, returned " << ret);
+}
 
-    int pipefd[2];
-    int pipefd2[2];
-    pid_t pid[2];
-    int result = 0;
-    ScopedProcessLabel keepLabel;
 
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
-    RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
+RUNNER_CHILD_TEST(security_manager_22_fetch_app_manifest_no_app)
+{
+    char **privileges;
+    size_t nPrivs = 0;
+    int ret = security_manager_get_app_manifest_policy("not_existing_app_id", 0, &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT, "Expected no such object error, returned " << ret);
+}
 
-    TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
+RUNNER_CHILD_TEST(security_manager_23_fetch_app_manifest_invalid_user)
+{
+    TemporaryTestUser user("sm_test_23_fetch_username", GUM_USERTYPE_NORMAL);
     user.create();
 
-    pid[0] = fork();
-    RUNNER_ASSERT_MSG(pid[0] >= 0, "fork failed");
-    if (pid[0] != 0)//parent process
-    {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
+    AppInstallHelper app("security_manager_23_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges(TEST_PRIVACY_PRIVILEGES[1]);
+    ScopedInstaller appInstall(app);
+
+    char **privileges;
+    size_t nPrivs = 0;
+    int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), 0, &privileges, &nPrivs);
+    // Should security-manager check if user exists?
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    RUNNER_ASSERT_MSG(nPrivs == 0, "Expected empty set of privileges, returned " << nPrivs);
+}
 
-        register_current_process_as_privilege_manager(user.getUid(), false);
+static void check_privileges_from_manifest(const AppInstallHelper &aih, char **privileges, size_t nPrivs)
+{
+    auto& aihPrivs = aih.getPrivileges();
+    RUNNER_ASSERT_MSG(nPrivs == aihPrivs.size(), "Expected privileges number: " << aihPrivs.size() << ", got " << nPrivs);
+    for (size_t i = 0; i < nPrivs; ++i) {
+        RUNNER_ASSERT_MSG(std::find(aihPrivs.begin(), aihPrivs.end(), std::string(privileges[i])) != aihPrivs.end(),
+                          "Privilege " << privileges[i] << " not found");
+    }
+}
 
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
+RUNNER_CHILD_TEST(security_manager_24_fetch_app_manifest_global_app)
+{
+    TemporaryTestUser user("sm_test_24_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+    AppInstallHelper app("security_manager_24_fetch");
+    app.setInstallType(SM_APP_INSTALL_GLOBAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
+
+    char **privileges;
+    size_t nPrivs = 0;
+
+    int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), 0, &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    check_privileges_from_manifest(app, privileges, nPrivs);
+    security_manager_privileges_free(privileges, nPrivs);
+
+    // since app is installed globally, also for our temporary user the returned list should be the same
+    nPrivs = 0;
+    ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    check_privileges_from_manifest(app, privileges, nPrivs);
+    security_manager_privileges_free(privileges, nPrivs);
+}
 
-        waitPid(pid[0]);
+RUNNER_CHILD_TEST(security_manager_25_fetch_app_manifest_local_app)
+{
+    TemporaryTestUser user("sm_test_25_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        admin.adminCheck(check_start_bucket, false, generateProcessLabel(update_app_id).c_str(),
-                std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
+    AppInstallHelper app("security_manager_25_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-        pid[1] = fork();
-        if (pid[1] != 0)//parent process
-        {
-            FdUniquePtr pipeptr(pipefd2+1);
-            close(pipefd2[0]);
+    char **privileges;
+    size_t nPrivs = 0;
 
-            //send info to child
-            msg.uid = user.getUid();
-            msg.gid = user.getGid();
+    int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    check_privileges_from_manifest(app, privileges, nPrivs);
+    security_manager_privileges_free(privileges, nPrivs);
 
-            ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
-            RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
+    // since app is installed locally, if we ask for other user (ie. root), we should get empty list of privileges
+    nPrivs = 0;
+    ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), 0, &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    RUNNER_ASSERT_MSG(nPrivs == 0, "Expected empty set of privileges, returned " << nPrivs);
+}
 
-            waitPid(pid[1]);
+RUNNER_CHILD_TEST(security_manager_26_fetch_app_manifest_both_apps)
+{
+    TemporaryTestUser user("sm_test_26_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-            admin.adminCheck(check_start_bucket, false, generateProcessLabel(update_app_id).c_str(),
-                    std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
-        }
-        if(pid[1] == 0)
-        {
-            FdUniquePtr pipeptr(pipefd2);
-            close(pipefd2[1]);
+    AppInstallHelper appGlobal("security_manager_26_fetch");
+    appGlobal.setInstallType(SM_APP_INSTALL_GLOBAL);
+    appGlobal.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE, PRIV_CONTACTS_READ});
+    ScopedInstaller appGlobalInstall(appGlobal);
 
-            ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
-            RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+    AppInstallHelper appLocal("security_manager_26_fetch", user.getUid());
+    appLocal.setInstallType(SM_APP_INSTALL_LOCAL);
+    appLocal.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appLocalInstall(appLocal);
 
-            result = drop_root_privileges(msg.uid, msg.gid);
-            RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
 
-            // delete this entry
-            PolicyRequest deletePolicyRequest;
-            PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
-            deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
+    char **privileges;
+    size_t nPrivs = 0;
 
-            deletePolicyRequest.addEntry(deleteEntry);
-            Api::sendPolicy(deletePolicyRequest);
-            exit(0);
-        }
-    }
-    if(pid[0] == 0)
-    {
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
+    int ret = security_manager_get_app_manifest_policy(appLocal.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+    check_privileges_from_manifest(appLocal, privileges, nPrivs);
+    security_manager_privileges_free(privileges, nPrivs);
 
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
+    nPrivs = 0;
+    ret = security_manager_get_app_manifest_policy(appGlobal.getAppId().c_str(), 0, &privileges, &nPrivs);
+    RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected succes, returned " << ret);
+    check_privileges_from_manifest(appGlobal, privileges, nPrivs);
+    security_manager_privileges_free(privileges, nPrivs);
+}
 
-        //become admin privacy manager manager
-        Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
+RUNNER_CHILD_TEST(security_manager_27_fetch_app_manifest_app_context_local_positive)
+{
+    TemporaryTestUser user("sm_test_27_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
-        entry.setLevel("Allow");
+    AppInstallHelper app("security_manager_27_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-        addPolicyRequest.addEntry(entry);
-        Api::sendPolicy(addPolicyRequest);
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
+        waitPid(pid);
+    } else { //child process
+        Api::setProcessLabel(app.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(
+                drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                "drop_root_privileges failed");
+        char **privileges;
+        size_t nPrivs = 0;
+        int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
         exit(0);
     }
 }
 
-RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
+RUNNER_CHILD_TEST(security_manager_28_fetch_app_manifest_app_context_global_positive)
 {
-    const std::string username("sm_test_17_user_name");
+    TemporaryTestUser user("sm_test_28_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-    struct message {
-        uid_t uid;
-        gid_t gid;
-        unsigned int privileges_count;
-    } msg;
+    AppInstallHelper app("security_manager_28_fetch");
+    app.setInstallType(SM_APP_INSTALL_GLOBAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-    int pipefd[2];
-    pid_t pid;
-    int result = 0;
-    ScopedProcessLabel keepLabel;
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
+        waitPid(pid);
+    } else { //child process
+        Api::setProcessLabel(app.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(
+                drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                "drop_root_privileges failed");
+        char **privileges;
+        size_t nPrivs = 0;
+        int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
+        exit(0);
+    }
+}
 
-    RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
+RUNNER_CHILD_TEST(security_manager_29_fetch_app_manifest_app_context_local_different_uid)
+{
+    TemporaryTestUser user("sm_test_29_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-    pid = fork();
-    RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
-    if (pid != 0)//parent process
-    {
-        FdUniquePtr pipeptr(pipefd+1);
-        close(pipefd[0]);
+    TemporaryTestUser user1("sm_test_29_fetch_username_1", GUM_USERTYPE_NORMAL);
+    user1.create();
 
-        TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
-        user.create();
+    AppInstallHelper app("security_manager_29_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-        unsigned int privileges_count = 0;
+    AppInstallHelper app1("security_manager_29_fetch", user1.getUid());
+    app1.setInstallType(SM_APP_INSTALL_LOCAL);
+    app1.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE, PRIV_CONTACTS_READ});
+    ScopedInstaller appInstall1(app1);
 
-        for(unsigned int i = 0; i < PM_MANY_APPS.size(); ++i) {
-            InstallRequest requestInst;
-            requestInst.setAppId(PM_MANY_APPS[i].c_str());
-            requestInst.setPkgId(PM_MANY_APPS_PKGS.at(PM_MANY_APPS[i]).package.c_str());
-            requestInst.setUid(user.getUid());
 
-            for (auto &priv : PM_MANY_APPS_PRIVILEGES.at(i)) {
-                requestInst.addPrivilege(priv.c_str());
-            };
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
+        waitPid(pid);
+    } else { //child process
+        Api::setProcessLabel(app1.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(
+                drop_root_privileges(user1.getUid(), user1.getGid()) == 0,
+                "drop_root_privileges failed");
+        char **privileges;
+        size_t nPrivs = 0;
+        int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED, "Expected auth failed, returned " << ret);
+
+        nPrivs = 0;
+        ret = security_manager_get_app_manifest_policy(app1.getAppId().c_str(), user1.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app1, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
+        exit(0);
+    }
+}
 
-            Api::install(requestInst);
-            privileges_count += PM_MANY_APPS_PRIVILEGES.at(i).size();
-        };
+RUNNER_CHILD_TEST(security_manager_30_fetch_app_manifest_app_context_local_different_label)
+{
+    TemporaryTestUser user("sm_test_30_fetch_username", GUM_USERTYPE_NORMAL);
+    user.create();
 
-        register_current_process_as_privilege_manager(user.getUid(), false);
-        //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
-        ++privileges_count;
+    AppInstallHelper app("security_manager_30_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-        //send info to child
-        msg.uid = user.getUid();
-        msg.gid = user.getGid();
-        msg.privileges_count = privileges_count;
+    AppInstallHelper app1("security_manager_30_fetch_1", user.getUid());
+    app1.setInstallType(SM_APP_INSTALL_LOCAL);
+    app1.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE, PRIV_CONTACTS_READ});
+    ScopedInstaller appInstall1(app1);
 
-        ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
 
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
         waitPid(pid);
+    } else { //child process
+        Api::setProcessLabel(app1.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(
+                drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                "drop_root_privileges failed");
+        char **privileges;
+        size_t nPrivs = 0;
+        int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED, "Expected auth failed, returned " << ret);
+
+        nPrivs = 0;
+        ret = security_manager_get_app_manifest_policy(app1.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app1, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
+        exit(0);
     }
-    if(pid == 0)
-    {
-        FdUniquePtr pipeptr(pipefd);
-        close(pipefd[1]);
-
-        ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
-        RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
-
-        //become admin privacy manager manager
-        Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
-        result = drop_root_privileges(msg.uid, msg.gid);
-        RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
-
-        // filter by privilege
-        std::vector<PolicyEntry> policyEntries;
-        PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
-        Api::getPolicy(filter, policyEntries);
+}
 
-        RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
+RUNNER_CHILD_TEST(security_manager_31_fetch_app_manifest_app_context_local_different_label_with_privilege)
+{
+    TemporaryTestUser user("sm_test_31_fetch_username", GUM_USERTYPE_ADMIN);
+    user.create();
 
-        // filter by other privilege
-        policyEntries.clear();
-        PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
-        Api::getPolicy(filter2, policyEntries);
+    AppInstallHelper app("security_manager_31_fetch", user.getUid());
+    app.setInstallType(SM_APP_INSTALL_LOCAL);
+    app.addPrivileges({PRIV_CALENDAR_READ, PRIV_CALENDAR_WRITE});
+    ScopedInstaller appInstall(app);
 
-        RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
+    AppInstallHelper app1("security_manager_31_fetch_1", user.getUid());
+    app1.setInstallType(SM_APP_INSTALL_LOCAL);
+    app1.addPrivileges({PRIV_CALENDAR_READ,
+                        PRIV_CALENDAR_WRITE,
+                        PRIV_CONTACTS_READ,
+                        PRIV_INTERNAL_USERMANAGEMENT});
+    ScopedInstaller appInstall1(app1);
 
-        // filter by appId
-        policyEntries.clear();
-        PolicyEntry filter3(PM_MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
-        Api::getPolicy(filter3, policyEntries);
 
-        RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
-        RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
+    pid_t pid = fork();
+    RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
+    if (pid != 0) { //parent process
+        waitPid(pid);
+    } else { //child process
+        Api::setProcessLabel(app1.getAppId());
+        RUNNER_ASSERT_ERRNO_MSG(
+                drop_root_privileges(user.getUid(), user.getGid()) == 0,
+                "drop_root_privileges failed");
+        char **privileges;
+        size_t nPrivs = 0;
+        int ret = security_manager_get_app_manifest_policy(app.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
+
+        nPrivs = 0;
+        ret = security_manager_get_app_manifest_policy(app1.getAppId().c_str(), user.getUid(), &privileges, &nPrivs);
+        RUNNER_ASSERT_MSG(ret == SECURITY_MANAGER_SUCCESS, "Expected success, returned " << ret);
+        check_privileges_from_manifest(app1, privileges, nPrivs);
+        security_manager_privileges_free(privileges, nPrivs);
+        exit(0);
     }
 }