security-manager: fix tests related to privacy privileges
[platform/core/test/security-tests.git] / src / security-manager-tests / test_cases_privacy_manager.cpp
1 /*
2  * Copyright (c) 2016-2018 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16
17 #include <algorithm>
18 #include <cstdlib>
19 #include <map>
20 #include <string>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <unordered_set>
24 #include <utility>
25 #include <vector>
26
27 #include <app_install_helper.h>
28 #include <cynara_test_admin.h>
29 #include <dpl/test/test_runner.h>
30 #include <dpl/test/test_runner_child.h>
31 #include <pkg_privacy_privileges.h>
32 #include <policy_configuration.h>
33 #include <scoped_installer.h>
34 #include <sm_api.h>
35 #include <sm_commons.h>
36 #include <sm_policy_request.h>
37 #include <sm_request.h>
38 #include <synchronization_pipe.h>
39 #include <temp_test_user.h>
40 #include <tests_common.h>
41
42 using namespace SecurityManagerTest;
43 namespace {
44 struct UserInfo {
45     std::string userName;
46     GumUserType userType;
47 };
48
49 // Privileges required for having permission to self/admin get/set policies.
50 const std::string SELF_PRIVILEGE = "http://tizen.org/privilege/notexist";
51 const std::string ADMIN_PRIVILEGE = "http://tizen.org/privilege/internal/usermanagement";
52
53 typedef std::vector<std::string> Privileges;
54 const std::vector<Privileges> TEST_PRIVILEGES = {
55     {
56         "http://tizen.org/privilege/internet",
57         "http://tizen.org/privilege/display"
58     },
59     {
60         "http://tizen.org/privilege/telephony",
61         "http://tizen.org/privilege/datasharing"
62     },
63     {
64         "http://tizen.org/privilege/content.write",
65         "http://tizen.org/privilege/led",
66         "http://tizen.org/privilege/email"
67     },
68     {
69         "http://tizen.org/privilege/led",
70         "http://tizen.org/privilege/email",
71         "http://tizen.org/privilege/telephony",
72         "http://tizen.org/privilege/datasharing"
73     },
74     {
75         "http://tizen.org/privilege/internet",
76         "http://tizen.org/privilege/display",
77         "http://tizen.org/privilege/led",
78         "http://tizen.org/privilege/email"
79     }
80 };
81
82 const PrivilegeVector TEST_PRIVACY_PRIVILEGES[] = {
83     {
84         Privilege("http://tizen.org/privilege/telephony"),
85         Privilege("http://tizen.org/privilege/led"),
86         Privilege("http://tizen.org/privilege/callhistory.read", Privilege::PRIVACY),
87         Privilege("http://tizen.org/privilege/account.read", Privilege::PRIVACY),
88         Privilege("http://tizen.org/privilege/healthinfo", Privilege::PRIVACY),
89     },
90     {
91         Privilege("http://tizen.org/privilege/telephony"),
92         Privilege("http://tizen.org/privilege/led"),
93         Privilege("http://tizen.org/privilege/callhistory.read", Privilege::PRIVACY),
94     }
95 };
96
97 }
98
99 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_PRIVACY_MANAGER)
100
101 RUNNER_CHILD_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
102 {
103     TemporaryTestUser tmpUser("sm_test_10_user_name", GUM_USERTYPE_NORMAL, false);
104     tmpUser.create();
105
106     unsigned expectedPolicyCount = 0;
107     std::map<std::string, AppInstallHelper> appIdToAIH;
108     for (unsigned i = 0; i < TEST_PRIVILEGES.size(); i++) {
109         AppInstallHelper app("sm_test_10_" + std::to_string(i), tmpUser.getUid());
110         app.addPrivileges(TEST_PRIVILEGES[i]);
111         expectedPolicyCount += app.getPrivileges().size();
112         appIdToAIH.emplace(app.getAppId(), std::move(app));
113     }
114
115     AppInstallHelper privManager("sm_test_10_privilege_manager", tmpUser.getUid());
116     std::string privManagerAppId = privManager.getAppId();
117     privManager.addPrivilege(SELF_PRIVILEGE);
118     expectedPolicyCount += privManager.getPrivileges().size();
119     appIdToAIH.emplace(privManager.getAppId(), std::move(privManager));
120
121     std::vector<ScopedInstaller> scopedInstallations;
122     for (const auto &appIdAIH : appIdToAIH) {
123         scopedInstallations.emplace_back(ScopedInstaller(appIdAIH.second));
124     }
125
126     pid_t pid = fork();
127     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
128     if (pid != 0) { //parent process
129         waitPid(pid);
130     } else { //child process
131         Api::setProcessLabel(privManagerAppId);
132         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(tmpUser.getUid(), tmpUser.getGid()) == 0,
133                                 "drop_root_privileges failed");
134
135         std::vector<PolicyEntry> policyEntries;
136         Api::getPolicy(PolicyEntry(), policyEntries);
137
138         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
139         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
140                           "Number of policies doesn't match - should be: " << expectedPolicyCount
141                           << " and is " << policyEntries.size());
142
143         for (const auto &policyEntry : policyEntries) {
144             std::string user = policyEntry.getUser();
145             std::string app = policyEntry.getAppId();
146             std::string privilege = policyEntry.getPrivilege();
147
148             RUNNER_ASSERT_MSG(user == tmpUser.getUidString(), "Unexpected user: " << user);
149
150             auto appIt = appIdToAIH.find(app);
151             RUNNER_ASSERT_MSG(appIt != appIdToAIH.end(), "Policy returned unexpected app: " << app);
152
153             AppInstallHelper &aih = appIt->second;
154             auto appPrivileges = aih.getPrivilegesNames();
155             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
156             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
157                               "Unexpected privilege " << privilege << " for app " << app);
158         }
159         exit(0);
160     }
161 }
162
163 RUNNER_CHILD_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
164 {
165     const std::string normalNameToSwitch = "sm_test_11_user_name_normal";
166     const std::vector<UserInfo> userInfos = {{normalNameToSwitch, GUM_USERTYPE_NORMAL},
167                                              {"sm_test_11_user_name_admin", GUM_USERTYPE_ADMIN}};
168
169     std::map<std::string, TemporaryTestUser> usernameToTTU;
170     // uid + app_id -> AppInstallHelper (different users can have same app_id installed)
171     std::map<std::pair<uid_t,std::string>, AppInstallHelper> userAppIdToAIH;
172     unsigned expectedPolicyCount = 0;
173
174     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
175         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
176         user.create();
177
178         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
179             AppInstallHelper app("sm_test_11_" + std::to_string(p_i), user.getUid());
180             app.addPrivileges(TEST_PRIVILEGES[p_i]);
181             if (user.getUserName() == normalNameToSwitch) // Only entries for this user should be fetched
182                 expectedPolicyCount += app.getPrivileges().size();
183             userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
184         };
185
186         usernameToTTU.emplace(userInfos[u_i].userName, std::move(user));
187     };
188
189     TemporaryTestUser &normalUserToSwitch = usernameToTTU.at(normalNameToSwitch);
190
191     AppInstallHelper privManager("sm_test_11_priv_manager", normalUserToSwitch.getUid());
192     std::string privManagerAppId = privManager.getAppId();
193     privManager.addPrivilege(SELF_PRIVILEGE);
194     expectedPolicyCount += privManager.getPrivileges().size();
195     userAppIdToAIH.emplace(std::make_pair(normalUserToSwitch.getUid(), privManager.getAppId()),
196                            std::move(privManager));
197
198     std::vector<ScopedInstaller> scopedInstallations;
199     for (const auto &userAppIdAIH : userAppIdToAIH) {
200         scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
201     }
202
203     pid_t pid = fork();
204     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
205     if (pid != 0) { //parent process
206         waitPid(pid);
207     } else { //child process
208         Api::setProcessLabel(privManagerAppId);
209         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUserToSwitch.getUid(),
210                                                      normalUserToSwitch.getGid()) == 0,
211                                 "drop_root_privileges failed");
212
213         std::vector<PolicyEntry> policyEntries;
214         Api::getPolicy(PolicyEntry(), policyEntries);
215
216         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
217         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
218                           "Number of policies doesn't match - should be: " << expectedPolicyCount
219                           << " and is " << policyEntries.size());
220
221         for (const auto &policyEntry : policyEntries) {
222             // Expect policy only for current process user
223             std::string user = policyEntry.getUser();
224             std::string app = policyEntry.getAppId();
225             std::string privilege = policyEntry.getPrivilege();
226
227             RUNNER_ASSERT_MSG(normalUserToSwitch.getUidString() == user, "Unexpected user: " << user);
228             auto userAppIdToAIHIt = userAppIdToAIH.find(std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
229             RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
230                               "Unknown app " << app << " for user " << user);
231
232             AppInstallHelper &aih = userAppIdToAIHIt->second;
233             auto privs = aih.getPrivileges();
234
235             auto appPrivileges = aih.getPrivilegesNames();
236             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
237             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
238                               "Unexpected privilege " << privilege << " for app " << app);
239         }
240         exit(0);
241     }
242 }
243
244 RUNNER_CHILD_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
245 {
246     std::vector<PolicyEntry> oldPolicyVec;
247     Api::getPolicy(PolicyEntry(), oldPolicyVec);
248     std::unordered_set<PolicyEntry> oldPolicySet(oldPolicyVec.begin(), oldPolicyVec.end());
249
250     std::string adminNameToSwitch = "sm_test_12_user_name_admin";
251     const std::vector<UserInfo> userInfos = {{"sm_test_12_user_name_normal",GUM_USERTYPE_NORMAL},
252                                              {adminNameToSwitch, GUM_USERTYPE_ADMIN}};
253
254     std::map<std::string, TemporaryTestUser> usernameToTTU;
255     std::vector<std::string> uidStrings;
256     // uidstring + app_id -> AppInstallHelper
257     std::map<std::pair<uid_t, std::string>, AppInstallHelper> userAppIdToAIH;
258     unsigned expectedPolicyCount = oldPolicyVec.size();
259
260     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
261         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
262         user.create();
263         uidStrings.push_back(user.getUidString());
264
265         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
266             AppInstallHelper app("sm_test_12_" + std::to_string(p_i), user.getUid());
267             // Shift privileges, so same app_id for different users doesn't have same privileges
268             app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
269             expectedPolicyCount += app.getPrivileges().size();
270             userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
271         };
272         usernameToTTU.emplace(user.getUserName(), std::move(user));
273     };
274
275     TemporaryTestUser &adminUserToSwitch = usernameToTTU.at(adminNameToSwitch);
276
277     AppInstallHelper privManager("sm_test_12_priv_manager", adminUserToSwitch.getUid());
278     std::string privManagerAppId = privManager.getAppId();
279     privManager.addPrivilege(SELF_PRIVILEGE);
280     privManager.addPrivilege(ADMIN_PRIVILEGE);
281     expectedPolicyCount += privManager.getPrivileges().size();
282
283     userAppIdToAIH.emplace(std::make_pair(adminUserToSwitch.getUid(), privManager.getAppId()),
284                            std::move(privManager));
285
286     std::vector<ScopedInstaller> scopedInstallations;
287     for (const auto &userAppIdAIH : userAppIdToAIH) {
288         scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
289     }
290
291     pid_t pid = fork();
292     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
293     if (pid != 0) { //parent process
294         waitPid(pid);
295     } else { //child process
296         Api::setProcessLabel(privManagerAppId);
297         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
298                                                      adminUserToSwitch.getGid()) == 0,
299                                 "drop_root_privileges failed");
300
301         std::vector<PolicyEntry> policyEntries;
302         Api::getPolicy(PolicyEntry(), policyEntries);
303         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
304         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
305                           "Number of policies doesn't match - should be: " << expectedPolicyCount
306                           << " and is " << policyEntries.size());
307
308         for (const auto &policyEntry : policyEntries) {
309             // Expect policy for all users to be returned
310             if (oldPolicySet.count(policyEntry))
311                 continue;
312             std::string user = policyEntry.getUser();
313             std::string app = policyEntry.getAppId();
314             std::string privilege = policyEntry.getPrivilege();
315
316             auto uidStringIt = std::find(uidStrings.begin(), uidStrings.end(), user);
317             RUNNER_ASSERT_MSG(uidStringIt != uidStrings.end(), "Unexpected user: " << user);
318
319             auto userAppIdToAIHIt = userAppIdToAIH.find(
320                     std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
321             RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
322                               "Unknown app " << app << " for user " << user);
323
324             AppInstallHelper &aih = userAppIdToAIHIt->second;
325             auto privs = aih.getPrivileges();
326
327             auto appPrivileges = aih.getPrivilegesNames();
328             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
329             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
330                               "Unexpected privilege " << privilege << " for app " << app);
331         };
332         exit(0);
333     };
334 }
335
336 RUNNER_CHILD_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
337 {
338     std::string normalName = "sm_test_13_user_name_normal";
339     std::string adminName = "sm_test_13_user_name_admin";
340     const std::vector<UserInfo> userInfos = {{normalName,GUM_USERTYPE_NORMAL},
341                                              {adminName, GUM_USERTYPE_ADMIN}};
342
343     std::map<std::string, TemporaryTestUser> usernameToTTU;
344     std::map<uid_t, std::vector<AppInstallHelper>> uidToAIHs;
345     unsigned expectedPolicyCount = 0;
346     std::string privManagerAppId;
347
348     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
349         //Only entries for one of the users will be listed
350         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
351         user.create();
352
353         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
354             AppInstallHelper app("sm_test_13_" + std::to_string(p_i), user.getUid());
355             // Shift privileges, so same app_id for different user doesn't have same privileges
356             app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
357             expectedPolicyCount += app.getPrivileges().size();
358             uidToAIHs[user.getUid()].emplace_back(std::move(app));
359         };
360         AppInstallHelper privManager("sm_test_13_priv_manager", user.getUid());
361         privManagerAppId = privManager.getAppId();
362         privManager.addPrivilege(SELF_PRIVILEGE);
363         expectedPolicyCount += privManager.getPrivileges().size();
364         uidToAIHs[user.getUid()].emplace_back(std::move(privManager));
365
366         usernameToTTU.emplace(user.getUserName(), std::move(user));
367     };
368
369     std::vector<ScopedInstaller> scopedInstallations;
370     for (const auto &userAIHs : uidToAIHs) {
371         for (const auto &aih : userAIHs.second)
372         scopedInstallations.emplace_back(ScopedInstaller(aih));
373     }
374
375     TemporaryTestUser &adminUser = usernameToTTU.at(adminName);
376     TemporaryTestUser &normalUser = usernameToTTU.at(normalName);
377
378     pid_t pid = fork();
379     RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
380     if (pid == 0) { //child #1 process
381         Api::setProcessLabel(privManagerAppId);
382         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUser.getUid(), normalUser.getGid()) == 0,
383                                 "drop_root_privileges failed");
384         auto &app1 = uidToAIHs[normalUser.getUid()][0];
385         auto &app2 = uidToAIHs[normalUser.getUid()][0];
386         PolicyRequest policyRequest;
387         PolicyEntry policyEntry(
388                 app1.getAppId(),
389                 normalUser.getUidString(),
390                 app1.getPrivileges()[0]
391                 );
392         policyEntry.setLevel("Deny");
393
394         policyRequest.addEntry(policyEntry);
395         policyEntry = PolicyEntry(
396                 app2.getAppId(),
397                 normalUser.getUidString(),
398                 app1.getPrivileges()[1]
399                 );
400         policyEntry.setLevel("Deny");
401         policyRequest.addEntry(policyEntry);
402         Api::sendPolicy(policyRequest);
403
404         exit(0);
405     } else {
406         waitPid(pid);
407         pid = fork();
408         RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
409         if (pid == 0) { //child #2 process
410             Api::setProcessLabel(privManagerAppId);
411             // Admin user, but in context of app, which doesn't have usermanagement privilege
412             RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
413                               "drop_root_privileges failed");
414
415             PolicyEntry filter = PolicyEntry(
416                         SECURITY_MANAGER_ANY,
417                         normalUser.getUidString(),
418                         SECURITY_MANAGER_ANY
419                         );
420             std::vector<PolicyEntry> policyEntries;
421             //U2 requests contents of U1 privacy manager - should fail
422             Api::getPolicyForSelf(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
423             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
424                               << policyEntries.size() << " entries");
425
426             filter = PolicyEntry(
427                         SECURITY_MANAGER_ANY,
428                         SECURITY_MANAGER_ANY,
429                         SECURITY_MANAGER_ANY
430                         );
431
432             policyEntries.clear();
433
434             //U2 requests contents of ADMIN bucket - should fail
435             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
436             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
437                               << policyEntries.size() << " entries");
438             exit(0);
439         } else {
440             waitPid(pid);
441         }
442     }
443 }
444
445 RUNNER_CHILD_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
446 {
447     TemporaryTestUser adminUserToSwitch("sm_test_14_user_name_admin", GUM_USERTYPE_ADMIN);
448     adminUserToSwitch.create();
449
450     AppInstallHelper privManager("sm_test_14_priv_manager", adminUserToSwitch.getUid());
451     privManager.addPrivilege(ADMIN_PRIVILEGE);
452
453     ScopedInstaller privManagerInstall(privManager);
454
455     pid_t pid = fork();
456     if (pid != 0) {
457         waitPid(pid);
458     } else { //child process
459         Api::setProcessLabel(privManager.getAppId());
460         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
461                                                      adminUserToSwitch.getGid()) == 0,
462                                 "drop_root_privileges failed");
463
464         PolicyRequest setPolicyRequest;
465         std::vector<PolicyEntry> policyEntries;
466
467         const std::string internetPriv = "http://tizen.org/privilege/internet";
468         const std::string displayPriv = "http://tizen.org/privilege/display";
469
470         PolicyEntry internetPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, internetPriv);
471         internetPolicyEntry.setMaxLevel("Deny");
472         setPolicyRequest.addEntry(internetPolicyEntry);
473
474         PolicyEntry displayPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, displayPriv);
475         displayPolicyEntry.setMaxLevel("Deny");
476         setPolicyRequest.addEntry(displayPolicyEntry);
477
478         Api::sendPolicy(setPolicyRequest);
479
480         Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
481         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2"
482                                                      " and is " << policyEntries.size());
483
484         PolicyRequest delPolicyRequest;
485
486         internetPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
487         delPolicyRequest.addEntry(internetPolicyEntry);
488
489         displayPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
490         delPolicyRequest.addEntry(displayPolicyEntry);
491
492         Api::sendPolicy(delPolicyRequest);
493
494         policyEntries.clear();
495         Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
496         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0"
497                                                      " and is " << policyEntries.size());
498         exit(0);
499     };
500 }
501
502 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
503 {
504     const std::string updatePriv = "http://tizen.org/privilege/led";
505
506     TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
507     adminUser.create();
508
509     AppInstallHelper updatedApp("security_manager_15_update");
510     ScopedInstaller updatedAppInstall(updatedApp);
511
512     AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
513     privManager.addPrivilege(ADMIN_PRIVILEGE);
514     ScopedInstaller privManagerInstall(privManager);
515
516     pid_t pid = fork();
517     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
518     if (pid != 0) { //parent process
519         waitPid(pid);
520         CynaraTestAdmin::Admin admin;
521         admin.adminCheck("ADMIN", false, updatedApp.generateAppLabel().c_str(),
522                          adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
523                          nullptr);
524     } else {
525         Api::setProcessLabel(privManager.getAppId());
526
527         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
528                                 "drop_root_privileges failed");
529
530         PolicyEntry entry(updatedApp.getAppId(), adminUser.getUidString(), updatePriv);
531         entry.setMaxLevel("Allow");
532         PolicyRequest addPolicyRequest;
533         addPolicyRequest.addEntry(entry);
534         Api::sendPolicy(addPolicyRequest);
535         exit(0);
536     }
537 }
538
539 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
540 {
541     const std::string updatePriv = "http://tizen.org/privilege/led";
542
543     TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
544     adminUser.create();
545
546     AppInstallHelper app("security_manager_15");
547     ScopedInstaller appInstall(app);
548
549     AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
550     privManager.addPrivilege(ADMIN_PRIVILEGE);
551     ScopedInstaller privManagerInstall(privManager);
552
553     pid_t pid = fork();
554     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
555     if (pid != 0) {
556         waitPid(pid);
557         CynaraTestAdmin::Admin admin;
558         admin.adminCheck("ADMIN", false, app.generateAppLabel().c_str(),
559                          adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
560                          nullptr);
561     } else {
562         Api::setProcessLabel(privManager.getAppId());
563         RUNNER_ASSERT_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
564                           "drop_root_privileges failed");
565
566         PolicyEntry entry(SECURITY_MANAGER_ANY, adminUser.getUidString(), updatePriv);
567         entry.setMaxLevel("Allow");
568
569         PolicyRequest addPolicyRequest;
570         addPolicyRequest.addEntry(entry);
571         Api::sendPolicy(addPolicyRequest);
572         exit(0);
573     }
574 }
575
576 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
577 {
578     const std::string updatePriv = "http://tizen.org/privilege/led";
579
580     TemporaryTestUser user("sm_test_15_username", GUM_USERTYPE_NORMAL);
581     user.create();
582
583     AppInstallHelper app("security_manager_15");
584     ScopedInstaller appInstall(app);
585
586     AppInstallHelper privManager("security_manager_15_priv_manager", user.getUid());
587     privManager.addPrivilege(SELF_PRIVILEGE);
588     ScopedInstaller privManagerInstall(privManager);
589
590     pid_t pid = fork();
591     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
592     if (pid != 0) {
593         waitPid(pid);
594         CynaraTestAdmin::Admin admin;
595         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
596                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
597     } else {
598         Api::setProcessLabel(privManager.getAppId());
599         RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
600                           "drop_root_privileges failed");
601
602         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
603         entry.setLevel("Allow");
604
605         PolicyRequest addPolicyRequest;
606         addPolicyRequest.addEntry(entry);
607         Api::sendPolicy(addPolicyRequest);
608         exit(0);
609     }
610 }
611
612 RUNNER_CHILD_TEST(security_manager_16_policy_levels_get)
613 {
614     TemporaryTestUser user("sm_test_16_user_name", GUM_USERTYPE_NORMAL);
615     user.create();
616
617     pid_t pid = fork();
618     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
619     if (pid != 0) {
620         waitPid(pid);
621     } else {
622         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
623                           "drop_root_privileges failed");
624
625         char** levels;
626         size_t count;
627         int ret = security_manager_policy_levels_get(&levels, &count);
628         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
629                 "Invlid return code: " << ret);
630         std::unique_ptr<char *, std::function<void(char**)>> descriptionsPtr(levels,
631                 [count](char **levels) { security_manager_policy_levels_free(levels, count);});
632
633         RUNNER_ASSERT_MSG(count >= 2, "Invalid number of policy levels. Should be 3,"
634                                       " instead there is: " << count);
635
636         std::string denyPolicy = std::string(levels[0]);
637         std::string allowPolicy = std::string(levels[count-1]);
638
639         // first should always be Deny
640         RUNNER_ASSERT_MSG(denyPolicy.compare("Deny") == 0,
641                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
642
643         // last should always be Allow
644         RUNNER_ASSERT_MSG(allowPolicy.compare("Allow") == 0,
645                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
646         exit(0);
647     }
648 }
649
650 RUNNER_CHILD_TEST(security_manager_17a_privacy_manager_delete_policy_for_self)
651 {
652     const std::string updatePriv = "http://tizen.org/privilege/led";
653
654     TemporaryTestUser user("sm_test_17a_username", GUM_USERTYPE_NORMAL);
655     user.create();
656
657     AppInstallHelper app("security_manager_17a");
658     ScopedInstaller appInstall(app);
659
660     SynchronizationPipe synchPipe;
661     pid_t pid = fork();
662     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
663     if (pid != 0) {
664         synchPipe.claimParentEp();
665
666         synchPipe.wait();
667         CynaraTestAdmin::Admin admin;
668         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
669                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
670         synchPipe.post();
671
672         synchPipe.wait();
673         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
674                          updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
675         waitPid(pid);
676     } else {
677         synchPipe.claimChildEp();
678         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
679                                             "drop_root_privileges failed");
680
681         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
682         entry.setLevel("Allow");
683         PolicyRequest addPolicyRequest;
684         addPolicyRequest.addEntry(entry);
685         Api::sendPolicy(addPolicyRequest);
686         synchPipe.post();
687
688         synchPipe.wait();
689         PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
690         deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
691         PolicyRequest deletePolicyRequest;
692         deletePolicyRequest.addEntry(deleteEntry);
693         Api::sendPolicy(deletePolicyRequest);
694         synchPipe.post();
695
696         exit(0);
697     }
698 }
699
700 RUNNER_CHILD_TEST(security_manager_17b_privacy_manager_delete_policy_for_self)
701 {
702     const std::string updatePriv = "http://tizen.org/privilege/led";
703
704     TemporaryTestUser user("sm_test_17b_username", GUM_USERTYPE_NORMAL);
705     user.create();
706
707     AppInstallHelper app("security_manager_17b");
708     ScopedInstaller appInstall(app);
709
710     AppInstallHelper privManager("security_manager_17b_priv_manager", user.getUid());
711     privManager.addPrivilege(SELF_PRIVILEGE);
712     ScopedInstaller privManagerInstall(privManager);
713
714     SynchronizationPipe synchPipe;
715     pid_t pid = fork();
716     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
717     if (pid != 0) {
718         synchPipe.claimParentEp();
719         synchPipe.wait();
720         CynaraTestAdmin::Admin admin;
721         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
722                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
723         synchPipe.post();
724
725         synchPipe.wait();
726         admin.adminCheck("", false, app.generateAppLabel().c_str(),
727                          user.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
728         waitPid(pid);
729
730     } else {
731         synchPipe.claimChildEp();
732         Api::setProcessLabel(privManager.getAppId());
733         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
734                                 "drop_root_privileges failed");
735
736         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
737         entry.setLevel("Allow");
738         PolicyRequest addPolicyRequest;
739         addPolicyRequest.addEntry(entry);
740         Api::sendPolicy(addPolicyRequest);
741         synchPipe.post();
742
743         synchPipe.wait();
744         PolicyRequest deletePolicyRequest;
745         PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
746         deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
747         deletePolicyRequest.addEntry(deleteEntry);
748         Api::sendPolicy(deletePolicyRequest);
749         synchPipe.post();
750         exit(0);
751     }
752 }
753
754 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
755 {
756     const std::string username("sm_test_17_user_name");
757     std::vector<AppInstallHelper> appHelpers;
758     std::vector<ScopedInstaller> scopedInstallations;
759     std::map<std::string, unsigned> privToCount;
760     unsigned policyCount = 0;
761
762     TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
763     user.create();
764
765     for (unsigned int i = 0; i < TEST_PRIVILEGES.size(); i++) {
766         AppInstallHelper app("sm_test_17_" + std::to_string(i), user.getUid());
767         app.addPrivileges(TEST_PRIVILEGES[i]);
768         policyCount += app.getPrivileges().size();
769
770         appHelpers.emplace_back(std::move(app));
771         for (auto &priv: TEST_PRIVILEGES[i]) {
772             privToCount[priv]++;
773         }
774     }
775
776     AppInstallHelper privManager("sm_test_17_priv_manager", user.getUid());
777     std::string privManagerAppId = privManager.getAppId();
778     privManager.addPrivilege(SELF_PRIVILEGE);
779     privToCount[SELF_PRIVILEGE]++;
780     policyCount += privManager.getPrivileges().size();
781
782     appHelpers.emplace_back(std::move(privManager));
783     for (const auto &app : appHelpers)
784         scopedInstallations.emplace_back(std::move(ScopedInstaller(app)));
785
786     pid_t pid = fork();
787     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
788     if (pid != 0)//parent process
789     {
790         waitPid(pid);
791     } else {
792         Api::setProcessLabel(privManagerAppId);
793         RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
794                           "drop_root_privileges failed");
795
796         for (const auto &privCount : privToCount) {
797             std::vector<PolicyEntry> policyEntries;
798             PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, privCount.first);
799             Api::getPolicy(filter, policyEntries);
800             RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
801             RUNNER_ASSERT_MSG(policyEntries.size() == privCount.second,
802                               "Number of policies doesn't match - should be: " << privCount.second
803                                << " and is " << policyEntries.size());
804         }
805
806         for (const auto &app : appHelpers) {
807             std::vector<PolicyEntry> policyEntries;
808             PolicyEntry filter(app.getAppId(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
809             Api::getPolicy(filter, policyEntries);
810             RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
811             RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
812                               "Number of policies doesn't match - should be: " << app.getPrivileges().size()
813                               << " and is " << policyEntries.size());
814         }
815
816         std::vector<PolicyEntry> policyEntries;
817         PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
818         Api::getPolicy(filter, policyEntries);
819         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
820         RUNNER_ASSERT_MSG(policyEntries.size() == policyCount,
821                           "Number of policies doesn't match - should be: " << policyCount
822                           << " and is " << policyEntries.size());
823
824         exit(0);
825     }
826 }
827
828 RUNNER_CHILD_TEST(security_manager_18_privacy_manager_privacy_related_privileges_policy_install_remove)
829 {
830     const std::string askUserDescription = "Ask user";
831     TemporaryTestUser user("sm_test_18_username", GUM_USERTYPE_NORMAL);
832     user.create();
833
834     AppInstallHelper app("sm_test_18", user.getUid());
835     app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
836
837     PolicyEntry filter (app.getAppId(), user.getUidString(), SECURITY_MANAGER_ANY);
838     std::vector<PolicyEntry> policyEntries;
839     {
840         PkgPrivacyPrivileges setupPrivacyPrivs(app);
841         ScopedInstaller installer(app);
842         unsigned int privacyNum = countPrivacyPrivileges(app.getPrivileges());
843
844         Api::getPolicy(filter, policyEntries);
845
846         RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
847             "Number of policy entries doesn't match; should be " << app.getPrivileges().size()
848             << " but is " << policyEntries.size());
849
850         if (PolicyConfiguration::getIsAskuserEnabled() ) {
851             unsigned int privacyActNum = 0;
852             for (auto &entry : policyEntries)
853                 if (isPrivilegePrivacy(entry.getPrivilege())) {
854                     RUNNER_ASSERT_MSG(entry.getCurrentLevel() == askUserDescription,
855                                       "Invalid policy setup; policy should be \"Ask user\" but is "
856                                       << entry.getCurrentLevel());
857                     ++privacyActNum;
858                 }
859             RUNNER_ASSERT_MSG(privacyActNum == privacyNum,
860                               "Should be " << privacyNum << " privacy privileges,"
861                               "but is " << privacyActNum);
862         }
863     }
864
865     policyEntries.clear();
866     Api::getPolicy(filter, policyEntries);
867     RUNNER_ASSERT_MSG(policyEntries.size() == 0,
868                       "After deinstallation, policy entries size should be 0,"
869                       "but is: "  << policyEntries.size());
870 }
871
872 void test_privacy_related_privileges(bool isHybrid) {
873     const std::string askUserDescription = "Ask user";
874     TemporaryTestUser user("sm_test_19_username", GUM_USERTYPE_NORMAL);
875     user.create();
876
877     const std::string pkgId = "sm_test_19_pkg_id";
878
879     AppInstallHelper app1("sm_test_19_app_id_1", pkgId, user.getUid());
880     if (isHybrid)
881         app1.setHybrid();
882     app1.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
883     PkgPrivacyPrivileges setupPrivacyPrivs1(app1);
884     ScopedInstaller installer1(app1);
885
886     AppInstallHelper app2("sm_test_19_app_id_2", pkgId, user.getUid());
887     if (isHybrid)
888         app2.setHybrid();
889     app2.addPrivileges(TEST_PRIVACY_PRIVILEGES[1]);
890     PkgPrivacyPrivileges setupPrivacyPrivs2(app2);
891     ScopedInstaller installer2(app2);
892
893     int privacyCount1, privacyCount2;
894     if (!PolicyConfiguration::getIsAskuserEnabled()) {
895         privacyCount1 = 0;
896         privacyCount2 = 0;
897     } else if (isHybrid) {
898         privacyCount1 = countPrivacyPrivileges(app1.getPrivileges());
899         privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
900     } else {
901         privacyCount1 = privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
902     }
903
904     std::vector<PolicyEntry> policyEntries;
905     PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
906     Api::getPolicy(filter, policyEntries);
907
908     int privacyAct1 = 0, privacyAct2 = 0;
909     for (auto &entry : policyEntries) {
910         RUNNER_ASSERT_MSG(entry.getAppId() == app1.getAppId() || entry.getAppId() == app2.getAppId(),
911                           "Invalid appId: should be either " << app1.getAppId() << " or "
912                           << app2.getAppId() << " but is " << entry.getAppId());
913         if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(entry.getPrivilege())) {
914             RUNNER_ASSERT_MSG(entry.getCurrentLevel() == askUserDescription,
915                               "Invalid policy setup; policy should be \"Ask user\" but is "
916                               << entry.getCurrentLevel());
917             if (entry.getAppId() == app1.getAppId())
918                 ++privacyAct1;
919             else
920                 ++privacyAct2;
921         }
922     }
923     RUNNER_ASSERT_MSG(privacyCount1 == privacyAct1, "Should be " << privacyCount1
924                       << " privacy privileges, but is " << privacyAct1);
925     RUNNER_ASSERT_MSG(privacyCount2 == privacyAct2, "Should be " << privacyCount2
926                       << " privacy privileges, but is " << privacyAct2);
927 }
928
929 RUNNER_CHILD_TEST(security_manager_19a_privacy_manager_privacy_related_privileges_policy_hybrid)
930 {
931     test_privacy_related_privileges(true);
932 }
933
934 RUNNER_CHILD_TEST(security_manager_19b_privacy_manager_privacy_related_privileges_policy_no_hybrid)
935 {
936     test_privacy_related_privileges(false);
937 }
938
939 RUNNER_CHILD_TEST(security_manager_20_privacy_manager_privacy_related_privileges_policy_admin_check)
940 {
941     const std::string askUserDescription = "Ask user";
942     TemporaryTestUser user("sm_test_20_username", GUM_USERTYPE_NORMAL);
943     user.create();
944
945     AppInstallHelper app("sm_test_20", user.getUid());
946     app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
947
948     PkgPrivacyPrivileges setupPrivacyPrivs(app);
949     ScopedInstaller installer(app);
950
951     CynaraTestAdmin::Admin admin;
952     int policyType = CYNARA_ADMIN_ALLOW;
953     int privacyPolicyType = -1;
954     if (PolicyConfiguration::getIsAskuserEnabled())
955         admin.getPolicyTypeForDescription(askUserDescription, privacyPolicyType);
956
957     for (auto &priv : app.getPrivileges()) {
958         if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(priv)) {
959             admin.adminCheck("", true, app.generateAppLabel().c_str(),
960                              user.getUidString().c_str(), priv, privacyPolicyType,
961                              nullptr);
962         } else {
963             admin.adminCheck("", true, app.generateAppLabel().c_str(),
964                              user.getUidString().c_str(), priv, policyType, nullptr);
965         }
966     }
967 }