1 /*
2  * Copyright (C) 2011 The Android Open Source Project
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 package com.android.server.pm;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 import static com.google.common.truth.Truth.assertWithMessage;
21 
22 import static org.junit.Assert.fail;
23 import static org.junit.Assume.assumeTrue;
24 import static org.testng.Assert.assertThrows;
25 
26 import android.annotation.UserIdInt;
27 import android.app.ActivityManager;
28 import android.content.BroadcastReceiver;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.IntentFilter;
32 import android.content.pm.PackageManager;
33 import android.content.pm.UserInfo;
34 import android.content.res.Resources;
35 import android.os.Bundle;
36 import android.os.UserHandle;
37 import android.os.UserManager;
38 import android.provider.Settings;
39 import android.test.suitebuilder.annotation.LargeTest;
40 import android.test.suitebuilder.annotation.MediumTest;
41 import android.test.suitebuilder.annotation.SmallTest;
42 import android.util.Slog;
43 
44 import androidx.test.InstrumentationRegistry;
45 import androidx.test.runner.AndroidJUnit4;
46 
47 import com.google.common.collect.Range;
48 
49 import org.junit.After;
50 import org.junit.Before;
51 import org.junit.Test;
52 import org.junit.runner.RunWith;
53 
54 import java.util.ArrayList;
55 import java.util.List;
56 import java.util.concurrent.ExecutorService;
57 import java.util.concurrent.Executors;
58 import java.util.concurrent.TimeUnit;
59 import java.util.concurrent.atomic.AtomicInteger;
60 
61 /** Test {@link UserManager} functionality. */
62 @RunWith(AndroidJUnit4.class)
63 public final class UserManagerTest {
64     // Taken from UserManagerService
65     private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // 30 years
66 
67     private static final int REMOVE_CHECK_INTERVAL_MILLIS = 500; // 0.5 seconds
68     private static final int REMOVE_TIMEOUT_MILLIS = 60 * 1000; // 60 seconds
69     private static final int SWITCH_USER_TIMEOUT_MILLIS = 40 * 1000; // 40 seconds
70 
71     // Packages which are used during tests.
72     private static final String[] PACKAGES = new String[] {
73             "com.android.egg",
74             "com.google.android.webview"
75     };
76     private static final String TAG = UserManagerTest.class.getSimpleName();
77 
78     private final Context mContext = InstrumentationRegistry.getInstrumentation().getContext();
79 
80     private final Object mUserRemoveLock = new Object();
81     private final Object mUserSwitchLock = new Object();
82 
83     private UserManager mUserManager = null;
84     private PackageManager mPackageManager;
85     private List<Integer> usersToRemove;
86 
87     @Before
setUp()88     public void setUp() throws Exception {
89         mUserManager = UserManager.get(mContext);
90         mPackageManager = mContext.getPackageManager();
91 
92         IntentFilter filter = new IntentFilter(Intent.ACTION_USER_REMOVED);
93         filter.addAction(Intent.ACTION_USER_SWITCHED);
94         mContext.registerReceiver(new BroadcastReceiver() {
95             @Override
96             public void onReceive(Context context, Intent intent) {
97                 switch (intent.getAction()) {
98                     case Intent.ACTION_USER_REMOVED:
99                         synchronized (mUserRemoveLock) {
100                             mUserRemoveLock.notifyAll();
101                         }
102                         break;
103                     case Intent.ACTION_USER_SWITCHED:
104                         synchronized (mUserSwitchLock) {
105                             mUserSwitchLock.notifyAll();
106                         }
107                         break;
108                 }
109             }
110         }, filter);
111 
112         removeExistingUsers();
113         usersToRemove = new ArrayList<>();
114     }
115 
116     @After
tearDown()117     public void tearDown() throws Exception {
118         for (Integer userId : usersToRemove) {
119             removeUser(userId);
120         }
121     }
122 
removeExistingUsers()123     private void removeExistingUsers() {
124         int currentUser = ActivityManager.getCurrentUser();
125         List<UserInfo> list = mUserManager.getUsers();
126         for (UserInfo user : list) {
127             // Keep system and current user
128             if (user.id != UserHandle.USER_SYSTEM && user.id != currentUser) {
129                 removeUser(user.id);
130             }
131         }
132     }
133 
134     @SmallTest
135     @Test
testHasSystemUser()136     public void testHasSystemUser() throws Exception {
137         assertThat(findUser(UserHandle.USER_SYSTEM)).isTrue();
138     }
139 
140     @MediumTest
141     @Test
testAddGuest()142     public void testAddGuest() throws Exception {
143         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
144         assertThat(userInfo).isNotNull();
145 
146         List<UserInfo> list = mUserManager.getUsers();
147         for (UserInfo user : list) {
148             if (user.id == userInfo.id && user.name.equals("Guest 1")
149                     && user.isGuest()
150                     && !user.isAdmin()
151                     && !user.isPrimary()) {
152                 return;
153             }
154         }
155         fail("Didn't find a guest: " + list);
156     }
157 
158     @MediumTest
159     @Test
testAdd2Users()160     public void testAdd2Users() throws Exception {
161         UserInfo user1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
162         UserInfo user2 = createUser("User 2", UserInfo.FLAG_ADMIN);
163 
164         assertThat(user1).isNotNull();
165         assertThat(user2).isNotNull();
166 
167         assertThat(findUser(UserHandle.USER_SYSTEM)).isTrue();
168         assertThat(findUser(user1.id)).isTrue();
169         assertThat(findUser(user2.id)).isTrue();
170     }
171 
172     @MediumTest
173     @Test
testRemoveUser()174     public void testRemoveUser() throws Exception {
175         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
176         removeUser(userInfo.id);
177 
178         assertThat(findUser(userInfo.id)).isFalse();
179     }
180 
181     @MediumTest
182     @Test
testRemoveUserByHandle()183     public void testRemoveUserByHandle() {
184         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
185         final UserHandle user = userInfo.getUserHandle();
186         synchronized (mUserRemoveLock) {
187             mUserManager.removeUser(user);
188             long time = System.currentTimeMillis();
189             while (mUserManager.getUserInfo(user.getIdentifier()) != null) {
190                 try {
191                     mUserRemoveLock.wait(REMOVE_CHECK_INTERVAL_MILLIS);
192                 } catch (InterruptedException ie) {
193                     Thread.currentThread().interrupt();
194                     return;
195                 }
196                 if (System.currentTimeMillis() - time > REMOVE_TIMEOUT_MILLIS) {
197                     fail("Timeout waiting for removeUser. userId = " + user.getIdentifier());
198                 }
199             }
200         }
201 
202         assertThat(findUser(userInfo.id)).isFalse();
203     }
204 
205     @MediumTest
206     @Test
testRemoveUserByHandle_ThrowsException()207     public void testRemoveUserByHandle_ThrowsException() {
208         assertThrows(IllegalArgumentException.class, () -> mUserManager.removeUser(null));
209     }
210 
211     /** Tests creating a FULL user via specifying userType. */
212     @MediumTest
213     @Test
testCreateUserViaTypes()214     public void testCreateUserViaTypes() throws Exception {
215         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_GUEST,
216                 UserInfo.FLAG_GUEST | UserInfo.FLAG_FULL);
217 
218         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_DEMO,
219                 UserInfo.FLAG_DEMO | UserInfo.FLAG_FULL);
220 
221         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_SECONDARY,
222                 UserInfo.FLAG_FULL);
223     }
224 
225     /** Tests creating a FULL user via specifying user flags. */
226     @MediumTest
227     @Test
testCreateUserViaFlags()228     public void testCreateUserViaFlags() throws Exception {
229         createUserWithFlagsAndCheckType(UserInfo.FLAG_GUEST, UserManager.USER_TYPE_FULL_GUEST,
230                 UserInfo.FLAG_FULL);
231 
232         createUserWithFlagsAndCheckType(0, UserManager.USER_TYPE_FULL_SECONDARY,
233                 UserInfo.FLAG_FULL);
234 
235         createUserWithFlagsAndCheckType(UserInfo.FLAG_FULL, UserManager.USER_TYPE_FULL_SECONDARY,
236                 0);
237 
238         createUserWithFlagsAndCheckType(UserInfo.FLAG_DEMO, UserManager.USER_TYPE_FULL_DEMO,
239                 UserInfo.FLAG_FULL);
240     }
241 
242     /** Creates a user of the given user type and checks that the result has the requiredFlags. */
createUserWithTypeAndCheckFlags(String userType, @UserIdInt int requiredFlags)243     private void createUserWithTypeAndCheckFlags(String userType,
244             @UserIdInt int requiredFlags) {
245         final UserInfo userInfo = createUser("Name", userType, 0);
246         assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(userType);
247         assertWithMessage("Flags %s did not contain expected %s", userInfo.flags, requiredFlags)
248                 .that(userInfo.flags & requiredFlags).isEqualTo(requiredFlags);
249         removeUser(userInfo.id);
250     }
251 
252     /**
253      * Creates a user of the given flags and checks that the result is of the expectedUserType type
254      * and that it has the expected flags (including both flags and any additionalRequiredFlags).
255      */
createUserWithFlagsAndCheckType(@serIdInt int flags, String expectedUserType, @UserIdInt int additionalRequiredFlags)256     private void createUserWithFlagsAndCheckType(@UserIdInt int flags, String expectedUserType,
257             @UserIdInt int additionalRequiredFlags) {
258         final UserInfo userInfo = createUser("Name", flags);
259         assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(expectedUserType);
260         additionalRequiredFlags |= flags;
261         assertWithMessage("Flags %s did not contain expected %s", userInfo.flags,
262                 additionalRequiredFlags).that(userInfo.flags & additionalRequiredFlags)
263                         .isEqualTo(additionalRequiredFlags);
264         removeUser(userInfo.id);
265     }
266 
267 
268     @MediumTest
269     @Test
testThereCanBeOnlyOneGuest()270     public void testThereCanBeOnlyOneGuest() throws Exception {
271         UserInfo userInfo1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
272         assertThat(userInfo1).isNotNull();
273         UserInfo userInfo2 = createUser("Guest 2", UserInfo.FLAG_GUEST);
274         assertThat(userInfo2).isNull();
275     }
276 
277     @MediumTest
278     @Test
testFindExistingGuest_guestExists()279     public void testFindExistingGuest_guestExists() throws Exception {
280         UserInfo userInfo1 = createUser("Guest", UserInfo.FLAG_GUEST);
281         assertThat(userInfo1).isNotNull();
282         UserInfo foundGuest = mUserManager.findCurrentGuestUser();
283         assertThat(foundGuest).isNotNull();
284     }
285 
286     @SmallTest
287     @Test
testFindExistingGuest_guestDoesNotExist()288     public void testFindExistingGuest_guestDoesNotExist() throws Exception {
289         UserInfo foundGuest = mUserManager.findCurrentGuestUser();
290         assertThat(foundGuest).isNull();
291     }
292 
293     @MediumTest
294     @Test
testSetUserAdmin()295     public void testSetUserAdmin() throws Exception {
296         UserInfo userInfo = createUser("SecondaryUser", /*flags=*/ 0);
297         assertThat(userInfo.isAdmin()).isFalse();
298 
299         mUserManager.setUserAdmin(userInfo.id);
300 
301         userInfo = mUserManager.getUserInfo(userInfo.id);
302         assertThat(userInfo.isAdmin()).isTrue();
303     }
304 
305     @MediumTest
306     @Test
testGetProfileParent()307     public void testGetProfileParent() throws Exception {
308         assumeManagedUsersSupported();
309         final int primaryUserId = mUserManager.getPrimaryUser().id;
310 
311         UserInfo userInfo = createProfileForUser("Profile",
312                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
313         assertThat(userInfo).isNotNull();
314         assertThat(mUserManager.getProfileParent(primaryUserId)).isNull();
315         UserInfo parentProfileInfo = mUserManager.getProfileParent(userInfo.id);
316         assertThat(parentProfileInfo).isNotNull();
317         assertThat(primaryUserId).isEqualTo(parentProfileInfo.id);
318         removeUser(userInfo.id);
319         assertThat(mUserManager.getProfileParent(primaryUserId)).isNull();
320     }
321 
322     /** Test that UserManager returns the correct badge information for a managed profile. */
323     @MediumTest
324     @Test
testProfileTypeInformation()325     public void testProfileTypeInformation() throws Exception {
326         assumeManagedUsersSupported();
327         final UserTypeDetails userTypeDetails =
328                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_MANAGED);
329         assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_MANAGED)
330                 .that(userTypeDetails).isNotNull();
331         assertThat(userTypeDetails.getName()).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
332 
333         final int primaryUserId = mUserManager.getPrimaryUser().id;
334         UserInfo userInfo = createProfileForUser("Managed",
335                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
336         assertThat(userInfo).isNotNull();
337         final int userId = userInfo.id;
338 
339         assertThat(mUserManager.hasBadge(userId)).isEqualTo(userTypeDetails.hasBadge());
340         assertThat(mUserManager.getUserIconBadgeResId(userId))
341                 .isEqualTo(userTypeDetails.getIconBadge());
342         assertThat(mUserManager.getUserBadgeResId(userId))
343                 .isEqualTo(userTypeDetails.getBadgePlain());
344         assertThat(mUserManager.getUserBadgeNoBackgroundResId(userId))
345                 .isEqualTo(userTypeDetails.getBadgeNoBackground());
346 
347         final int badgeIndex = userInfo.profileBadge;
348         assertThat(mUserManager.getUserBadgeColor(userId)).isEqualTo(
349                 Resources.getSystem().getColor(userTypeDetails.getBadgeColor(badgeIndex), null));
350         assertThat(mUserManager.getUserBadgeDarkColor(userId)).isEqualTo(
351                 Resources.getSystem().getColor(userTypeDetails.getDarkThemeBadgeColor(badgeIndex),
352                         null));
353 
354         assertThat(mUserManager.getBadgedLabelForUser("Test", asHandle(userId))).isEqualTo(
355                 Resources.getSystem().getString(userTypeDetails.getBadgeLabel(badgeIndex), "Test"));
356 
357         // Test @UserHandleAware methods
358         final UserManager userManagerForUser = UserManager.get(mContext.createPackageContextAsUser(
359                 "android", 0, asHandle(userId)));
360         assertThat(userManagerForUser.isUserOfType(userTypeDetails.getName())).isTrue();
361         assertThat(userManagerForUser.isProfile()).isEqualTo(userTypeDetails.isProfile());
362     }
363 
364     // Make sure only max managed profiles can be created
365     @MediumTest
366     @Test
testAddManagedProfile()367     public void testAddManagedProfile() throws Exception {
368         assumeManagedUsersSupported();
369         final int primaryUserId = mUserManager.getPrimaryUser().id;
370         UserInfo userInfo1 = createProfileForUser("Managed 1",
371                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
372         UserInfo userInfo2 = createProfileForUser("Managed 2",
373                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
374 
375         assertThat(userInfo1).isNotNull();
376         assertThat(userInfo2).isNull();
377 
378         assertThat(userInfo1.userType).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
379         int requiredFlags = UserInfo.FLAG_MANAGED_PROFILE | UserInfo.FLAG_PROFILE;
380         assertWithMessage("Wrong flags %s", userInfo1.flags).that(userInfo1.flags & requiredFlags)
381                 .isEqualTo(requiredFlags);
382 
383         // Verify that current user is not a managed profile
384         assertThat(mUserManager.isManagedProfile()).isFalse();
385     }
386 
387     // Verify that disallowed packages are not installed in the managed profile.
388     @MediumTest
389     @Test
testAddManagedProfile_withDisallowedPackages()390     public void testAddManagedProfile_withDisallowedPackages() throws Exception {
391         assumeManagedUsersSupported();
392         final int primaryUserId = mUserManager.getPrimaryUser().id;
393         UserInfo userInfo1 = createProfileForUser("Managed1",
394                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
395         // Verify that the packagesToVerify are installed by default.
396         for (String pkg : PACKAGES) {
397             if (!mPackageManager.isPackageAvailable(pkg)) {
398                 Slog.w(TAG, "Package is not available " + pkg);
399                 continue;
400             }
401 
402             assertWithMessage("Package should be installed in managed profile: %s", pkg)
403                     .that(isPackageInstalledForUser(pkg, userInfo1.id)).isTrue();
404         }
405         removeUser(userInfo1.id);
406 
407         UserInfo userInfo2 = createProfileForUser("Managed2",
408                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId, PACKAGES);
409         // Verify that the packagesToVerify are not installed by default.
410         for (String pkg : PACKAGES) {
411             if (!mPackageManager.isPackageAvailable(pkg)) {
412                 Slog.w(TAG, "Package is not available " + pkg);
413                 continue;
414             }
415 
416             assertWithMessage(
417                     "Package should not be installed in managed profile when disallowed: %s", pkg)
418                             .that(isPackageInstalledForUser(pkg, userInfo2.id)).isFalse();
419         }
420     }
421 
422     // Verify that if any packages are disallowed to install during creation of managed profile can
423     // still be installed later.
424     @MediumTest
425     @Test
testAddManagedProfile_disallowedPackagesInstalledLater()426     public void testAddManagedProfile_disallowedPackagesInstalledLater() throws Exception {
427         assumeManagedUsersSupported();
428         final int primaryUserId = mUserManager.getPrimaryUser().id;
429         UserInfo userInfo = createProfileForUser("Managed",
430                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId, PACKAGES);
431         // Verify that the packagesToVerify are not installed by default.
432         for (String pkg : PACKAGES) {
433             if (!mPackageManager.isPackageAvailable(pkg)) {
434                 Slog.w(TAG, "Package is not available " + pkg);
435                 continue;
436             }
437 
438             assertWithMessage("Pkg should not be installed in managed profile when disallowed: %s",
439                     pkg).that(isPackageInstalledForUser(pkg, userInfo.id)).isFalse();
440         }
441 
442         // Verify that the disallowed packages during profile creation can be installed now.
443         for (String pkg : PACKAGES) {
444             if (!mPackageManager.isPackageAvailable(pkg)) {
445                 Slog.w(TAG, "Package is not available " + pkg);
446                 continue;
447             }
448 
449             assertWithMessage("Package could not be installed: %s", pkg)
450                     .that(mPackageManager.installExistingPackageAsUser(pkg, userInfo.id))
451                     .isEqualTo(PackageManager.INSTALL_SUCCEEDED);
452         }
453     }
454 
455     // Make sure createUser would fail if we have DISALLOW_ADD_USER.
456     @MediumTest
457     @Test
testCreateUser_disallowAddUser()458     public void testCreateUser_disallowAddUser() throws Exception {
459         final int creatorId = ActivityManager.getCurrentUser();
460         final UserHandle creatorHandle = asHandle(creatorId);
461         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, creatorHandle);
462         try {
463             UserInfo createadInfo = createUser("SecondaryUser", /*flags=*/ 0);
464             assertThat(createadInfo).isNull();
465         } finally {
466             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
467                     creatorHandle);
468         }
469     }
470 
471     // Make sure createProfile would fail if we have DISALLOW_ADD_MANAGED_PROFILE.
472     @MediumTest
473     @Test
testCreateProfileForUser_disallowAddManagedProfile()474     public void testCreateProfileForUser_disallowAddManagedProfile() throws Exception {
475         assumeManagedUsersSupported();
476         final int primaryUserId = mUserManager.getPrimaryUser().id;
477         final UserHandle primaryUserHandle = asHandle(primaryUserId);
478         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
479                 primaryUserHandle);
480         try {
481             UserInfo userInfo = createProfileForUser("Managed",
482                     UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
483             assertThat(userInfo).isNull();
484         } finally {
485             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
486                     primaryUserHandle);
487         }
488     }
489 
490     // Make sure createProfileEvenWhenDisallowedForUser bypass DISALLOW_ADD_MANAGED_PROFILE.
491     @MediumTest
492     @Test
testCreateProfileForUserEvenWhenDisallowed()493     public void testCreateProfileForUserEvenWhenDisallowed() throws Exception {
494         assumeManagedUsersSupported();
495         final int primaryUserId = mUserManager.getPrimaryUser().id;
496         final UserHandle primaryUserHandle = asHandle(primaryUserId);
497         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
498                 primaryUserHandle);
499         try {
500             UserInfo userInfo = createProfileEvenWhenDisallowedForUser("Managed",
501                     UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
502             assertThat(userInfo).isNotNull();
503         } finally {
504             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
505                     primaryUserHandle);
506         }
507     }
508 
509     // createProfile succeeds even if DISALLOW_ADD_USER is set
510     @MediumTest
511     @Test
testCreateProfileForUser_disallowAddUser()512     public void testCreateProfileForUser_disallowAddUser() throws Exception {
513         assumeManagedUsersSupported();
514         final int primaryUserId = mUserManager.getPrimaryUser().id;
515         final UserHandle primaryUserHandle = asHandle(primaryUserId);
516         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, primaryUserHandle);
517         try {
518             UserInfo userInfo = createProfileForUser("Managed",
519                     UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
520             assertThat(userInfo).isNotNull();
521         } finally {
522             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
523                     primaryUserHandle);
524         }
525     }
526 
527     @MediumTest
528     @Test
testAddRestrictedProfile()529     public void testAddRestrictedProfile() throws Exception {
530         if (isAutomotive()) return;
531         assertWithMessage("There should be no associated restricted profiles before the test")
532                 .that(mUserManager.hasRestrictedProfiles()).isFalse();
533         UserInfo userInfo = createRestrictedProfile("Profile");
534         assertThat(userInfo).isNotNull();
535 
536         Bundle restrictions = mUserManager.getUserRestrictions(UserHandle.of(userInfo.id));
537         assertWithMessage(
538                 "Restricted profile should have DISALLOW_MODIFY_ACCOUNTS restriction by default")
539                         .that(restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS))
540                         .isTrue();
541         assertWithMessage(
542                 "Restricted profile should have DISALLOW_SHARE_LOCATION restriction by default")
543                         .that(restrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION))
544                         .isTrue();
545 
546         int locationMode = Settings.Secure.getIntForUser(mContext.getContentResolver(),
547                 Settings.Secure.LOCATION_MODE,
548                 Settings.Secure.LOCATION_MODE_HIGH_ACCURACY,
549                 userInfo.id);
550         assertWithMessage("Restricted profile should have setting LOCATION_MODE set to "
551                 + "LOCATION_MODE_OFF by default").that(locationMode)
552                         .isEqualTo(Settings.Secure.LOCATION_MODE_OFF);
553 
554         assertWithMessage("Newly created profile should be associated with the current user")
555                 .that(mUserManager.hasRestrictedProfiles()).isTrue();
556     }
557 
558     @MediumTest
559     @Test
testGetManagedProfileCreationTime()560     public void testGetManagedProfileCreationTime() throws Exception {
561         assumeManagedUsersSupported();
562         final int primaryUserId = mUserManager.getPrimaryUser().id;
563         final long startTime = System.currentTimeMillis();
564         UserInfo profile = createProfileForUser("Managed 1",
565                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
566         final long endTime = System.currentTimeMillis();
567         assertThat(profile).isNotNull();
568         if (System.currentTimeMillis() > EPOCH_PLUS_30_YEARS) {
569             assertWithMessage("creationTime must be set when the profile is created")
570                     .that(profile.creationTime).isIn(Range.closed(startTime, endTime));
571         } else {
572             assertWithMessage("creationTime must be 0 if the time is not > EPOCH_PLUS_30_years")
573                     .that(profile.creationTime).isEqualTo(0);
574         }
575         assertThat(mUserManager.getUserCreationTime(asHandle(profile.id)))
576                 .isEqualTo(profile.creationTime);
577 
578         long ownerCreationTime = mUserManager.getUserInfo(primaryUserId).creationTime;
579         assertThat(mUserManager.getUserCreationTime(asHandle(primaryUserId)))
580             .isEqualTo(ownerCreationTime);
581     }
582 
583     @MediumTest
584     @Test
testGetUserCreationTime()585     public void testGetUserCreationTime() throws Exception {
586         long startTime = System.currentTimeMillis();
587         UserInfo user = createUser("User", /* flags= */ 0);
588         long endTime = System.currentTimeMillis();
589         assertThat(user).isNotNull();
590         assertWithMessage("creationTime must be set when the user is created")
591             .that(user.creationTime).isIn(Range.closed(startTime, endTime));
592     }
593 
594     @SmallTest
595     @Test
testGetUserCreationTime_nonExistentUser()596     public void testGetUserCreationTime_nonExistentUser() throws Exception {
597         int noSuchUserId = 100500;
598         assertThrows(SecurityException.class,
599                 () -> mUserManager.getUserCreationTime(asHandle(noSuchUserId)));
600     }
601 
602     @SmallTest
603     @Test
testGetUserCreationTime_otherUser()604     public void testGetUserCreationTime_otherUser() throws Exception {
605         UserInfo user = createUser("User 1", 0);
606         assertThat(user).isNotNull();
607         assertThrows(SecurityException.class,
608                 () -> mUserManager.getUserCreationTime(asHandle(user.id)));
609     }
610 
findUser(int id)611     private boolean findUser(int id) {
612         List<UserInfo> list = mUserManager.getUsers();
613 
614         for (UserInfo user : list) {
615             if (user.id == id) {
616                 return true;
617             }
618         }
619         return false;
620     }
621 
622     @MediumTest
623     @Test
testSerialNumber()624     public void testSerialNumber() {
625         UserInfo user1 = createUser("User 1", 0);
626         int serialNumber1 = user1.serialNumber;
627         assertThat(mUserManager.getUserSerialNumber(user1.id)).isEqualTo(serialNumber1);
628         assertThat(mUserManager.getUserHandle(serialNumber1)).isEqualTo(user1.id);
629         UserInfo user2 = createUser("User 2", 0);
630         int serialNumber2 = user2.serialNumber;
631         assertThat(serialNumber1 == serialNumber2).isFalse();
632         assertThat(mUserManager.getUserSerialNumber(user2.id)).isEqualTo(serialNumber2);
633         assertThat(mUserManager.getUserHandle(serialNumber2)).isEqualTo(user2.id);
634     }
635 
636     @MediumTest
637     @Test
testGetSerialNumbersOfUsers()638     public void testGetSerialNumbersOfUsers() {
639         UserInfo user1 = createUser("User 1", 0);
640         UserInfo user2 = createUser("User 2", 0);
641         long[] serialNumbersOfUsers = mUserManager.getSerialNumbersOfUsers(false);
642         assertThat(serialNumbersOfUsers).asList().containsAllOf(
643                 (long) user1.serialNumber, (long) user2.serialNumber);
644     }
645 
646     @MediumTest
647     @Test
testMaxUsers()648     public void testMaxUsers() {
649         int N = UserManager.getMaxSupportedUsers();
650         int count = mUserManager.getUsers().size();
651         // Create as many users as permitted and make sure creation passes
652         while (count < N) {
653             UserInfo ui = createUser("User " + count, 0);
654             assertThat(ui).isNotNull();
655             count++;
656         }
657         // Try to create one more user and make sure it fails
658         UserInfo extra = createUser("One more", 0);
659         assertThat(extra).isNull();
660     }
661 
662     @MediumTest
663     @Test
testGetUserCount()664     public void testGetUserCount() {
665         int count = mUserManager.getUsers().size();
666         UserInfo user1 = createUser("User 1", 0);
667         assertThat(user1).isNotNull();
668         UserInfo user2 = createUser("User 2", 0);
669         assertThat(user2).isNotNull();
670         assertThat(mUserManager.getUserCount()).isEqualTo(count + 2);
671     }
672 
673     @MediumTest
674     @Test
testRestrictions()675     public void testRestrictions() {
676         UserInfo testUser = createUser("User 1", 0);
677 
678         mUserManager.setUserRestriction(
679                 UserManager.DISALLOW_INSTALL_APPS, true, asHandle(testUser.id));
680         mUserManager.setUserRestriction(
681                 UserManager.DISALLOW_CONFIG_WIFI, false, asHandle(testUser.id));
682 
683         Bundle stored = mUserManager.getUserRestrictions(asHandle(testUser.id));
684         // Note this will fail if DO already sets those restrictions.
685         assertThat(stored.getBoolean(UserManager.DISALLOW_CONFIG_WIFI)).isFalse();
686         assertThat(stored.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS)).isFalse();
687         assertThat(stored.getBoolean(UserManager.DISALLOW_INSTALL_APPS)).isTrue();
688     }
689 
690     @MediumTest
691     @Test
testDefaultRestrictionsApplied()692     public void testDefaultRestrictionsApplied() throws Exception {
693         final UserInfo userInfo = createUser("Useroid", UserManager.USER_TYPE_FULL_SECONDARY, 0);
694         final UserTypeDetails userTypeDetails =
695                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_FULL_SECONDARY);
696         final Bundle expectedRestrictions = userTypeDetails.getDefaultRestrictions();
697         // Note this can fail if DO unset those restrictions.
698         for (String restriction : expectedRestrictions.keySet()) {
699             if (expectedRestrictions.getBoolean(restriction)) {
700                 assertThat(mUserManager.hasUserRestriction(restriction, UserHandle.of(userInfo.id)))
701                         .isTrue();
702             }
703         }
704     }
705 
706     @MediumTest
707     @Test
testSetDefaultGuestRestrictions()708     public void testSetDefaultGuestRestrictions() {
709         final Bundle origGuestRestrictions = mUserManager.getDefaultGuestRestrictions();
710         Bundle restrictions = new Bundle();
711         restrictions.putBoolean(UserManager.DISALLOW_FUN, true);
712         mUserManager.setDefaultGuestRestrictions(restrictions);
713 
714         try {
715             UserInfo guest = createUser("Guest", UserInfo.FLAG_GUEST);
716             assertThat(guest).isNotNull();
717             assertThat(mUserManager.hasUserRestriction(UserManager.DISALLOW_FUN,
718                     guest.getUserHandle())).isTrue();
719         } finally {
720             mUserManager.setDefaultGuestRestrictions(origGuestRestrictions);
721         }
722     }
723 
724     @Test
testGetUserSwitchability()725     public void testGetUserSwitchability() {
726         int userSwitchable = mUserManager.getUserSwitchability();
727         assertWithMessage("Expected users to be switchable").that(userSwitchable)
728                 .isEqualTo(UserManager.SWITCHABILITY_STATUS_OK);
729     }
730 
731     @LargeTest
732     @Test
testSwitchUser()733     public void testSwitchUser() {
734         ActivityManager am = mContext.getSystemService(ActivityManager.class);
735         final int startUser = am.getCurrentUser();
736         UserInfo user = createUser("User", 0);
737         assertThat(user).isNotNull();
738         // Switch to the user just created.
739         switchUser(user.id, null, true);
740         // Switch back to the starting user.
741         switchUser(startUser, null, true);
742     }
743 
744     @LargeTest
745     @Test
testSwitchUserByHandle()746     public void testSwitchUserByHandle() {
747         ActivityManager am = mContext.getSystemService(ActivityManager.class);
748         final int startUser = am.getCurrentUser();
749         UserInfo user = createUser("User", 0);
750         assertThat(user).isNotNull();
751         // Switch to the user just created.
752         switchUser(-1, user.getUserHandle(), false);
753         // Switch back to the starting user.
754         switchUser(-1, UserHandle.of(startUser), false);
755     }
756 
757     @Test
testSwitchUserByHandle_ThrowsException()758     public void testSwitchUserByHandle_ThrowsException() {
759         ActivityManager am = mContext.getSystemService(ActivityManager.class);
760         assertThrows(IllegalArgumentException.class, () -> am.switchUser(null));
761     }
762 
763     @MediumTest
764     @Test
testConcurrentUserCreate()765     public void testConcurrentUserCreate() throws Exception {
766         int userCount = mUserManager.getUserCount();
767         int maxSupportedUsers = UserManager.getMaxSupportedUsers();
768         int canBeCreatedCount = maxSupportedUsers - userCount;
769         // Test exceeding the limit while running in parallel
770         int createUsersCount = canBeCreatedCount + 5;
771         ExecutorService es = Executors.newCachedThreadPool();
772         AtomicInteger created = new AtomicInteger();
773         for (int i = 0; i < createUsersCount; i++) {
774             final String userName = "testConcUser" + i;
775             es.submit(() -> {
776                 UserInfo user = mUserManager.createUser(userName, 0);
777                 if (user != null) {
778                     created.incrementAndGet();
779                     synchronized (mUserRemoveLock) {
780                         usersToRemove.add(user.id);
781                     }
782                 }
783             });
784         }
785         es.shutdown();
786         es.awaitTermination(20, TimeUnit.SECONDS);
787         assertThat(mUserManager.getUserCount()).isEqualTo(maxSupportedUsers);
788         assertThat(created.get()).isEqualTo(canBeCreatedCount);
789     }
790 
791     @MediumTest
792     @Test
testGetUserHandles_createNewUser_shouldFindNewUser()793     public void testGetUserHandles_createNewUser_shouldFindNewUser() {
794         UserInfo user = createUser("Guest 1", UserManager.USER_TYPE_FULL_GUEST, /*flags*/ 0);
795 
796         boolean found = false;
797         List<UserHandle> userHandles = mUserManager.getUserHandles(/* excludeDying= */ true);
798         for (UserHandle userHandle: userHandles) {
799             if (userHandle.getIdentifier() == user.id) {
800                 found = true;
801             }
802         }
803 
804         assertThat(found).isTrue();
805     }
806 
807     @Test
testCreateProfile_withContextUserId()808     public void testCreateProfile_withContextUserId() throws Exception {
809         assumeManagedUsersSupported();
810         final int primaryUserId = mUserManager.getPrimaryUser().id;
811 
812         UserInfo userProfile = createProfileForUser("Managed 1",
813                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
814         assertThat(userProfile).isNotNull();
815 
816         UserManager um = (UserManager) mContext.createPackageContextAsUser(
817                 "android", 0, mUserManager.getPrimaryUser().getUserHandle())
818                 .getSystemService(Context.USER_SERVICE);
819 
820         List<UserHandle> profiles = um.getAllProfiles();
821         assertThat(profiles.size()).isEqualTo(2);
822         assertThat(profiles.get(0).equals(userProfile.getUserHandle())
823                 || profiles.get(1).equals(userProfile.getUserHandle())).isTrue();
824     }
825 
826     @Test
testSetUserName_withContextUserId()827     public void testSetUserName_withContextUserId() throws Exception {
828         assumeManagedUsersSupported();
829         final int primaryUserId = mUserManager.getPrimaryUser().id;
830 
831         UserInfo userInfo1 = createProfileForUser("Managed 1",
832                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
833         assertThat(userInfo1).isNotNull();
834 
835         UserManager um = (UserManager) mContext.createPackageContextAsUser(
836                 "android", 0, userInfo1.getUserHandle())
837                 .getSystemService(Context.USER_SERVICE);
838 
839         final String newName = "Managed_user 1";
840         um.setUserName(newName);
841 
842         UserInfo userInfo = mUserManager.getUserInfo(userInfo1.id);
843         assertThat(userInfo.name).isEqualTo(newName);
844 
845         // get user name from getUserName using context.getUserId
846         assertThat(um.getUserName()).isEqualTo(newName);
847     }
848 
849     @Test
testGetUserName_withContextUserId()850     public void testGetUserName_withContextUserId() throws Exception {
851         final String userName = "User 2";
852         UserInfo user2 = createUser(userName, 0);
853         assertThat(user2).isNotNull();
854 
855         UserManager um = (UserManager) mContext.createPackageContextAsUser(
856                 "android", 0, user2.getUserHandle())
857                 .getSystemService(Context.USER_SERVICE);
858 
859         assertThat(um.getUserName()).isEqualTo(userName);
860     }
861 
862     @Test
testGetUserIcon_withContextUserId()863     public void testGetUserIcon_withContextUserId() throws Exception {
864         assumeManagedUsersSupported();
865         final int primaryUserId = mUserManager.getPrimaryUser().id;
866 
867         UserInfo userInfo1 = createProfileForUser("Managed 1",
868                 UserManager.USER_TYPE_PROFILE_MANAGED, primaryUserId);
869         assertThat(userInfo1).isNotNull();
870 
871         UserManager um = (UserManager) mContext.createPackageContextAsUser(
872                 "android", 0, userInfo1.getUserHandle())
873                 .getSystemService(Context.USER_SERVICE);
874 
875         final String newName = "Managed_user 1";
876         um.setUserName(newName);
877 
878         UserInfo userInfo = mUserManager.getUserInfo(userInfo1.id);
879         assertThat(userInfo.name).isEqualTo(newName);
880     }
881 
isPackageInstalledForUser(String packageName, int userId)882     private boolean isPackageInstalledForUser(String packageName, int userId) {
883         try {
884             return mPackageManager.getPackageInfoAsUser(packageName, 0, userId) != null;
885         } catch (PackageManager.NameNotFoundException e) {
886             return false;
887         }
888     }
889 
890     /**
891      * @param userId value will be used to call switchUser(int) only if ignoreHandle is false.
892      * @param user value will be used to call switchUser(UserHandle) only if ignoreHandle is true.
893      * @param ignoreHandle if true, switchUser(int) will be called with the provided userId,
894      *                     else, switchUser(UserHandle) will be called with the provided user.
895      */
switchUser(int userId, UserHandle user, boolean ignoreHandle)896     private void switchUser(int userId, UserHandle user, boolean ignoreHandle) {
897         synchronized (mUserSwitchLock) {
898             ActivityManager am = mContext.getSystemService(ActivityManager.class);
899             if (ignoreHandle) {
900                 am.switchUser(userId);
901             } else {
902                 am.switchUser(user);
903             }
904             long time = System.currentTimeMillis();
905             try {
906                 mUserSwitchLock.wait(SWITCH_USER_TIMEOUT_MILLIS);
907             } catch (InterruptedException ie) {
908                 Thread.currentThread().interrupt();
909                 return;
910             }
911             if (System.currentTimeMillis() - time > SWITCH_USER_TIMEOUT_MILLIS) {
912                 fail("Timeout waiting for the user switch to u"
913                         + (ignoreHandle ? userId : user.getIdentifier()));
914             }
915         }
916     }
917 
removeUser(int userId)918     private void removeUser(int userId) {
919         synchronized (mUserRemoveLock) {
920             mUserManager.removeUser(userId);
921             long time = System.currentTimeMillis();
922             while (mUserManager.getUserInfo(userId) != null) {
923                 try {
924                     mUserRemoveLock.wait(REMOVE_CHECK_INTERVAL_MILLIS);
925                 } catch (InterruptedException ie) {
926                     Thread.currentThread().interrupt();
927                     return;
928                 }
929                 if (System.currentTimeMillis() - time > REMOVE_TIMEOUT_MILLIS) {
930                     fail("Timeout waiting for removeUser. userId = " + userId);
931                 }
932             }
933         }
934     }
935 
createUser(String name, int flags)936     private UserInfo createUser(String name, int flags) {
937         UserInfo user = mUserManager.createUser(name, flags);
938         if (user != null) {
939             usersToRemove.add(user.id);
940         }
941         return user;
942     }
943 
createUser(String name, String userType, int flags)944     private UserInfo createUser(String name, String userType, int flags) {
945         UserInfo user = mUserManager.createUser(name, userType, flags);
946         if (user != null) {
947             usersToRemove.add(user.id);
948         }
949         return user;
950     }
951 
createProfileForUser(String name, String userType, int userHandle)952     private UserInfo createProfileForUser(String name, String userType, int userHandle) {
953         return createProfileForUser(name, userType, userHandle, null);
954     }
955 
createProfileForUser(String name, String userType, int userHandle, String[] disallowedPackages)956     private UserInfo createProfileForUser(String name, String userType, int userHandle,
957             String[] disallowedPackages) {
958         UserInfo profile = mUserManager.createProfileForUser(
959                 name, userType, 0, userHandle, disallowedPackages);
960         if (profile != null) {
961             usersToRemove.add(profile.id);
962         }
963         return profile;
964     }
965 
createProfileEvenWhenDisallowedForUser(String name, String userType, int userHandle)966     private UserInfo createProfileEvenWhenDisallowedForUser(String name, String userType,
967             int userHandle) {
968         UserInfo profile = mUserManager.createProfileForUserEvenWhenDisallowed(
969                 name, userType, 0, userHandle, null);
970         if (profile != null) {
971             usersToRemove.add(profile.id);
972         }
973         return profile;
974     }
975 
createRestrictedProfile(String name)976     private UserInfo createRestrictedProfile(String name) {
977         UserInfo profile = mUserManager.createRestrictedProfile(name);
978         if (profile != null) {
979             usersToRemove.add(profile.id);
980         }
981         return profile;
982     }
983 
assumeManagedUsersSupported()984     private void assumeManagedUsersSupported() {
985         // In Automotive, if headless system user is enabled, a managed user cannot be created
986         // under a primary user.
987         assumeTrue("device doesn't support managed users",
988                 mPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS)
989                 && (!isAutomotive() || !UserManager.isHeadlessSystemUserMode()));
990     }
991 
isAutomotive()992     private boolean isAutomotive() {
993         return mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
994     }
995 
asHandle(int userId)996     private static UserHandle asHandle(int userId) {
997         return new UserHandle(userId);
998     }
999 }
1000