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.assertTrue;
23 import static org.junit.Assert.fail;
24 import static org.junit.Assume.assumeTrue;
25 import static org.testng.Assert.assertEquals;
26 import static org.testng.Assert.assertThrows;
27 
28 import android.annotation.UserIdInt;
29 import android.app.ActivityManager;
30 import android.content.Context;
31 import android.content.pm.PackageManager;
32 import android.content.pm.UserInfo;
33 import android.content.pm.UserProperties;
34 import android.content.res.Resources;
35 import android.graphics.drawable.Drawable;
36 import android.os.Bundle;
37 import android.os.PersistableBundle;
38 import android.os.UserHandle;
39 import android.os.UserManager;
40 import android.platform.test.annotations.Postsubmit;
41 import android.platform.test.annotations.RequiresFlagsEnabled;
42 import android.provider.Settings;
43 import android.util.ArraySet;
44 import android.util.Slog;
45 
46 import androidx.annotation.Nullable;
47 import androidx.test.InstrumentationRegistry;
48 import androidx.test.filters.LargeTest;
49 import androidx.test.filters.MediumTest;
50 import androidx.test.filters.SmallTest;
51 import androidx.test.runner.AndroidJUnit4;
52 
53 import com.google.common.collect.ImmutableList;
54 import com.google.common.collect.Range;
55 
56 import org.junit.After;
57 import org.junit.Before;
58 import org.junit.Test;
59 import org.junit.runner.RunWith;
60 
61 import java.util.ArrayList;
62 import java.util.Arrays;
63 import java.util.List;
64 import java.util.concurrent.ExecutorService;
65 import java.util.concurrent.Executors;
66 import java.util.concurrent.TimeUnit;
67 import java.util.concurrent.atomic.AtomicInteger;
68 import java.util.stream.Collectors;
69 
70 /**
71  * Test {@link UserManager} functionality.
72  *
73  *  atest com.android.server.pm.UserManagerTest
74  */
75 @Postsubmit
76 @RunWith(AndroidJUnit4.class)
77 public final class UserManagerTest {
78     // Taken from UserManagerService
79     private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // 30 years
80 
81     private static final int SWITCH_USER_TIMEOUT_SECONDS = 180; // 180 seconds
82     private static final int REMOVE_USER_TIMEOUT_SECONDS = 180; // 180 seconds
83 
84     // Packages which are used during tests.
85     private static final String[] PACKAGES = new String[] {
86             "com.android.egg",
87             "com.google.android.webview"
88     };
89     private static final String TAG = UserManagerTest.class.getSimpleName();
90 
91     private final Context mContext = InstrumentationRegistry.getInstrumentation().getContext();
92 
93     private UserManager mUserManager = null;
94     private ActivityManager mActivityManager;
95     private PackageManager mPackageManager;
96     private ArraySet<Integer> mUsersToRemove;
97     private UserSwitchWaiter mUserSwitchWaiter;
98     private UserRemovalWaiter mUserRemovalWaiter;
99     private int mOriginalCurrentUserId;
100 
101     @Before
setUp()102     public void setUp() throws Exception {
103         mOriginalCurrentUserId = ActivityManager.getCurrentUser();
104         mUserManager = UserManager.get(mContext);
105         mActivityManager = mContext.getSystemService(ActivityManager.class);
106         mPackageManager = mContext.getPackageManager();
107         mUserSwitchWaiter = new UserSwitchWaiter(TAG, SWITCH_USER_TIMEOUT_SECONDS);
108         mUserRemovalWaiter = new UserRemovalWaiter(mContext, TAG, REMOVE_USER_TIMEOUT_SECONDS);
109 
110         mUsersToRemove = new ArraySet<>();
111         removeExistingUsers();
112     }
113 
114     @After
tearDown()115     public void tearDown() throws Exception {
116         if (mOriginalCurrentUserId != ActivityManager.getCurrentUser()) {
117             switchUser(mOriginalCurrentUserId);
118         }
119         mUserSwitchWaiter.close();
120 
121         // Making a copy of mUsersToRemove to avoid ConcurrentModificationException
122         mUsersToRemove.stream().toList().forEach(this::removeUser);
123         mUserRemovalWaiter.close();
124     }
125 
removeExistingUsers()126     private void removeExistingUsers() {
127         int currentUser = ActivityManager.getCurrentUser();
128 
129         UserHandle communalProfile = mUserManager.getCommunalProfile();
130         int communalProfileId = communalProfile != null
131                 ? communalProfile.getIdentifier() : UserHandle.USER_NULL;
132 
133         List<UserInfo> list = mUserManager.getUsers();
134         for (UserInfo user : list) {
135             // Keep system and current user
136             if (user.id != UserHandle.USER_SYSTEM &&
137                     user.id != currentUser &&
138                     user.id != communalProfileId &&
139                     !user.isMain()) {
140                 removeUser(user.id);
141             }
142         }
143     }
144 
145     @SmallTest
146     @Test
testHasSystemUser()147     public void testHasSystemUser() throws Exception {
148         assertThat(hasUser(UserHandle.USER_SYSTEM)).isTrue();
149     }
150 
151     @MediumTest
152     @Test
testAddGuest()153     public void testAddGuest() throws Exception {
154         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
155         assertThat(userInfo).isNotNull();
156 
157         List<UserInfo> list = mUserManager.getUsers();
158         for (UserInfo user : list) {
159             if (user.id == userInfo.id && user.name.equals("Guest 1")
160                     && user.isGuest()
161                     && !user.isAdmin()
162                     && !user.isPrimary()) {
163                 return;
164             }
165         }
166         fail("Didn't find a guest: " + list);
167     }
168 
169     @Test
testCloneUser()170     public void testCloneUser() throws Exception {
171         assumeCloneEnabled();
172         UserHandle mainUser = mUserManager.getMainUser();
173         assumeTrue("Main user is null", mainUser != null);
174         // Get the default properties for clone user type.
175         final UserTypeDetails userTypeDetails =
176                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_CLONE);
177         assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_CLONE)
178                 .that(userTypeDetails).isNotNull();
179         final UserProperties typeProps = userTypeDetails.getDefaultUserPropertiesReference();
180 
181         // Test that only one clone user can be created
182         final int mainUserId = mainUser.getIdentifier();
183         UserInfo cloneProfileUser = createProfileForUser("Clone user1",
184                 UserManager.USER_TYPE_PROFILE_CLONE,
185                 mainUserId);
186         assertThat(cloneProfileUser).isNotNull();
187         UserInfo cloneProfileUser2 = createProfileForUser("Clone user2",
188                 UserManager.USER_TYPE_PROFILE_CLONE,
189                 mainUserId);
190         assertThat(cloneProfileUser2).isNull();
191 
192         final Context profileUserContest = mContext.createPackageContextAsUser("system", 0,
193                 UserHandle.of(cloneProfileUser.id));
194         final UserManager profileUM = UserManager.get(profileUserContest);
195         assertThat(profileUserContest.getSystemService(
196                 UserManager.class).isMediaSharedWithParent()).isTrue();
197         assertThat(Settings.Secure.getInt(profileUserContest.getContentResolver(),
198                 Settings.Secure.USER_SETUP_COMPLETE, 0)).isEqualTo(1);
199 
200         List<UserInfo> list = mUserManager.getUsers();
201         List<UserInfo> cloneUsers = list.stream().filter(
202                 user -> (user.id == cloneProfileUser.id && user.name.equals("Clone user1")
203                         && user.isCloneProfile()))
204                 .collect(Collectors.toList());
205         assertThat(cloneUsers.size()).isEqualTo(1);
206 
207         // Check that the new clone user has the expected properties (relative to the defaults)
208         // provided that the test caller has the necessary permissions.
209         UserProperties cloneUserProperties =
210                 mUserManager.getUserProperties(UserHandle.of(cloneProfileUser.id));
211         assertThat(typeProps.getUseParentsContacts())
212                 .isEqualTo(cloneUserProperties.getUseParentsContacts());
213         assertThat(typeProps.getShowInLauncher())
214                 .isEqualTo(cloneUserProperties.getShowInLauncher());
215         assertThrows(SecurityException.class, cloneUserProperties::getStartWithParent);
216         assertThrows(SecurityException.class,
217                 cloneUserProperties::getCrossProfileIntentFilterAccessControl);
218         assertThrows(SecurityException.class,
219                 cloneUserProperties::getCrossProfileIntentResolutionStrategy);
220         assertThat(typeProps.isMediaSharedWithParent())
221                 .isEqualTo(cloneUserProperties.isMediaSharedWithParent());
222         assertThat(typeProps.isCredentialShareableWithParent())
223                 .isEqualTo(cloneUserProperties.isCredentialShareableWithParent());
224         assertThat(typeProps.getCrossProfileContentSharingStrategy())
225                 .isEqualTo(cloneUserProperties.getCrossProfileContentSharingStrategy());
226         assertThrows(SecurityException.class, cloneUserProperties::getDeleteAppWithParent);
227         assertThrows(SecurityException.class, cloneUserProperties::getAlwaysVisible);
228         assertThat(typeProps.getProfileApiVisibility()).isEqualTo(
229                 cloneUserProperties.getProfileApiVisibility());
230         compareDrawables(profileUM.getUserBadge(),
231                 Resources.getSystem().getDrawable(userTypeDetails.getBadgePlain()));
232 
233         // Verify clone user parent
234         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
235         UserInfo parentProfileInfo = mUserManager.getProfileParent(cloneProfileUser.id);
236         assertThat(parentProfileInfo).isNotNull();
237         assertThat(mainUserId).isEqualTo(parentProfileInfo.id);
238         removeUser(cloneProfileUser.id);
239         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
240         assertThat(mUserManager.getProfileAccessibilityString(cloneProfileUser.id)).isEqualTo(
241                 Resources.getSystem().getString(userTypeDetails.getAccessibilityString()));
242     }
243 
244     @Test
testCommunalProfile()245     public void testCommunalProfile() throws Exception {
246         assumeTrue("Device doesn't support communal profiles ",
247                 mUserManager.isUserTypeEnabled(UserManager.USER_TYPE_PROFILE_COMMUNAL));
248 
249         // Create communal profile if needed
250         if (mUserManager.getCommunalProfile() == null) {
251             Slog.i(TAG, "Attempting to create a communal profile for a test");
252             createUser("Communal", UserManager.USER_TYPE_PROFILE_COMMUNAL, /*flags*/ 0);
253         }
254         final UserHandle communal = mUserManager.getCommunalProfile();
255         assertWithMessage("Couldn't create communal profile").that(communal).isNotNull();
256 
257         final UserTypeDetails userTypeDetails =
258                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_COMMUNAL);
259         assertWithMessage("No communal user type on device").that(userTypeDetails).isNotNull();
260 
261         // Test that only one communal profile can be created
262         final UserInfo secondCommunalProfile =
263                 createUser("Communal", UserManager.USER_TYPE_PROFILE_COMMUNAL, /*flags*/ 0);
264         assertThat(secondCommunalProfile).isNull();
265 
266         // Verify that communal profile doesn't have a parent
267         assertThat(mUserManager.getProfileParent(communal.getIdentifier())).isNull();
268 
269         // Make sure that, when switching users, the communal profile remains visible.
270         final boolean isStarted = mActivityManager.startProfile(communal);
271         assertWithMessage("Unable to start communal profile").that(isStarted).isTrue();
272         final UserManager umCommunal = (UserManager) mContext.createPackageContextAsUser(
273                         "android", 0, communal).getSystemService(Context.USER_SERVICE);
274         final int originalCurrent = ActivityManager.getCurrentUser();
275         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
276         assertWithMessage("Communal profile not visible").that(umCommunal.isUserVisible()).isTrue();
277         switchUser(testUser.id);
278         assertWithMessage("Communal profile not visible").that(umCommunal.isUserVisible()).isTrue();
279         switchUser(originalCurrent);
280         assertWithMessage("Communal profile not visible").that(umCommunal.isUserVisible()).isTrue();
281         assertThat(mUserManager.getProfileAccessibilityString(communal.getIdentifier()))
282                 .isEqualTo(Resources.getSystem()
283                         .getString(userTypeDetails.getAccessibilityString()));
284     }
285 
286     @Test
287     @RequiresFlagsEnabled(android.multiuser.Flags.FLAG_SUPPORT_COMMUNAL_PROFILE)
testGetProfilesIncludingCommunal()288     public void testGetProfilesIncludingCommunal() throws Exception {
289         int mainUserId = mUserManager.getMainUser().getIdentifier();
290         final UserInfo otherUser = createUser("TestUser", /* flags= */ 0);
291         final UserInfo profile = createProfileForUser("Profile",
292                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
293 
294         final UserHandle communalProfile = mUserManager.getCommunalProfile();
295 
296         final List<UserInfo> mainsActual = mUserManager.getProfilesIncludingCommunal(mainUserId);
297         final List<UserInfo> othersActual = mUserManager.getProfilesIncludingCommunal(otherUser.id);
298 
299         final List<Integer> mainsExpected = new ArrayList<>();
300         mainsExpected.add(mainUserId);
301         if (profile != null) mainsExpected.add(profile.id);
302         if (communalProfile != null) mainsExpected.add(communalProfile.getIdentifier());
303         assertEquals(mainsExpected.stream().sorted().toList(),
304                 mainsActual.stream().map(ui -> ui.id).sorted().toList());
305 
306 
307         final List<Integer> othersExpected = new ArrayList<>();
308         othersExpected.add(otherUser.id);
309         if (communalProfile != null) othersExpected.add(communalProfile.getIdentifier());
310         assertEquals(othersExpected.stream().sorted().toList(),
311                 othersActual.stream().map(ui -> ui.id).sorted().toList());
312     }
313 
314     @Test
testPrivateProfile()315     public void testPrivateProfile() throws Exception {
316         UserHandle mainUser = mUserManager.getMainUser();
317         assumeTrue("Main user is null", mainUser != null);
318         // Get the default properties for private profile user type.
319         final UserTypeDetails userTypeDetails =
320                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_PRIVATE);
321         assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_PRIVATE)
322                 .that(userTypeDetails).isNotNull();
323         final UserProperties typeProps = userTypeDetails.getDefaultUserPropertiesReference();
324 
325         // Only run the test if private profile creation is enabled on the device
326         assumeTrue("Private profile not enabled on the device",
327                 mUserManager.canAddPrivateProfile());
328 
329         // Test that only one private profile  can be created
330         final int mainUserId = mainUser.getIdentifier();
331         UserInfo privateProfileUser = createProfileForUser("Private profile1",
332                 UserManager.USER_TYPE_PROFILE_PRIVATE,
333                 mainUserId);
334         assertThat(privateProfileUser).isNotNull();
335         UserInfo privateProfileUser2 = createProfileForUser("Private profile2",
336                 UserManager.USER_TYPE_PROFILE_PRIVATE,
337                 mainUserId);
338         assertThat(privateProfileUser2).isNull();
339         final UserManager profileUM = UserManager.get(
340                 mContext.createPackageContextAsUser("android", 0,
341                         UserHandle.of(privateProfileUser.id)));
342 
343         // Check that the new private profile has the expected properties (relative to the defaults)
344         // provided that the test caller has the necessary permissions.
345         UserProperties privateProfileUserProperties =
346                 mUserManager.getUserProperties(UserHandle.of(privateProfileUser.id));
347         assertThat(typeProps.getShowInLauncher())
348                 .isEqualTo(privateProfileUserProperties.getShowInLauncher());
349         assertThrows(SecurityException.class, privateProfileUserProperties::getStartWithParent);
350         assertThrows(SecurityException.class,
351                 privateProfileUserProperties::getCrossProfileIntentFilterAccessControl);
352         assertThat(typeProps.isMediaSharedWithParent())
353                 .isEqualTo(privateProfileUserProperties.isMediaSharedWithParent());
354         assertThat(typeProps.isCredentialShareableWithParent())
355                 .isEqualTo(privateProfileUserProperties.isCredentialShareableWithParent());
356         assertThat(typeProps.isAuthAlwaysRequiredToDisableQuietMode())
357                 .isEqualTo(privateProfileUserProperties
358                         .isAuthAlwaysRequiredToDisableQuietMode());
359         assertThat(typeProps.getCrossProfileContentSharingStrategy())
360                 .isEqualTo(privateProfileUserProperties.getCrossProfileContentSharingStrategy());
361         assertThrows(SecurityException.class, privateProfileUserProperties::getDeleteAppWithParent);
362         assertThrows(SecurityException.class,
363                 privateProfileUserProperties::getAllowStoppingUserWithDelayedLocking);
364         assertThat(typeProps.getProfileApiVisibility()).isEqualTo(
365                 privateProfileUserProperties.getProfileApiVisibility());
366         assertThat(typeProps.areItemsRestrictedOnHomeScreen())
367                 .isEqualTo(privateProfileUserProperties.areItemsRestrictedOnHomeScreen());
368         compareDrawables(profileUM.getUserBadge(),
369                 Resources.getSystem().getDrawable(userTypeDetails.getBadgePlain()));
370 
371         // Verify private profile parent
372         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
373         UserInfo parentProfileInfo = mUserManager.getProfileParent(privateProfileUser.id);
374         assertThat(parentProfileInfo).isNotNull();
375         assertThat(mainUserId).isEqualTo(parentProfileInfo.id);
376         removeUser(privateProfileUser.id);
377         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
378         assertThat(profileUM.getProfileLabel()).isEqualTo(
379                 Resources.getSystem().getString(userTypeDetails.getLabel(0)));
380         assertThat(mUserManager.getProfileAccessibilityString(privateProfileUser.id)).isEqualTo(
381                 Resources.getSystem().getString(userTypeDetails.getAccessibilityString()));
382     }
383 
384     @Test
testGetProfileAccessibilityString_throwsExceptionForNonProfileUser()385     public void testGetProfileAccessibilityString_throwsExceptionForNonProfileUser() {
386         UserInfo user1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
387         assertThat(user1).isNotNull();
388         assertThrows(Resources.NotFoundException.class,
389                 () -> mUserManager.getProfileAccessibilityString(user1.id));
390         assertThrows(Resources.NotFoundException.class,
391                 () -> mUserManager.getProfileAccessibilityString(UserHandle.USER_SYSTEM));
392     }
393 
394     @MediumTest
395     @Test
testAdd2Users()396     public void testAdd2Users() throws Exception {
397         UserInfo user1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
398         UserInfo user2 = createUser("User 2", UserInfo.FLAG_ADMIN);
399 
400         assertThat(user1).isNotNull();
401         assertThat(user2).isNotNull();
402 
403         assertThat(hasUser(UserHandle.USER_SYSTEM)).isTrue();
404         assertThat(hasUser(user1.id)).isTrue();
405         assertThat(hasUser(user2.id)).isTrue();
406     }
407 
408     /**
409      * Tests that UserManager knows how many users can be created.
410      *
411      * We can only test this with regular secondary users, since some other user types have weird
412      * rules about when or if they count towards the max.
413      */
414     @MediumTest
415     @Test
testAddTooManyUsers()416     public void testAddTooManyUsers() throws Exception {
417         final String userType = UserManager.USER_TYPE_FULL_SECONDARY;
418         final UserTypeDetails userTypeDetails = UserTypeFactory.getUserTypes().get(userType);
419 
420         final int maxUsersForType = userTypeDetails.getMaxAllowed();
421         final int maxUsersOverall = UserManager.getMaxSupportedUsers();
422 
423         int currentUsersOfType = 0;
424         int currentUsersOverall = 0;
425         final List<UserInfo> userList = mUserManager.getAliveUsers();
426         for (UserInfo user : userList) {
427             currentUsersOverall++;
428             if (userType.equals(user.userType)) {
429                 currentUsersOfType++;
430             }
431         }
432 
433         final int remainingUserType = maxUsersForType == UserTypeDetails.UNLIMITED_NUMBER_OF_USERS ?
434                 Integer.MAX_VALUE : maxUsersForType - currentUsersOfType;
435         final int remainingOverall = maxUsersOverall - currentUsersOverall;
436         final int remaining = Math.min(remainingUserType, remainingOverall);
437 
438         Slog.v(TAG, "maxUsersForType=" + maxUsersForType
439                 + ", maxUsersOverall=" + maxUsersOverall
440                 + ", currentUsersOfType=" + currentUsersOfType
441                 + ", currentUsersOverall=" + currentUsersOverall
442                 + ", remaining=" + remaining);
443 
444         assumeTrue("Device supports too many users for this test to be practical", remaining < 20);
445 
446         int usersAdded;
447         for (usersAdded = 0; usersAdded < remaining; usersAdded++) {
448             Slog.v(TAG, "Adding user " + usersAdded);
449             assertThat(mUserManager.canAddMoreUsers()).isTrue();
450             assertThat(mUserManager.canAddMoreUsers(userType)).isTrue();
451 
452             final UserInfo user = createUser("User " + usersAdded, userType, 0);
453             assertThat(user).isNotNull();
454             assertThat(hasUser(user.id)).isTrue();
455         }
456         Slog.v(TAG, "Added " + usersAdded + " users.");
457 
458         assertWithMessage("Still thinks more users of that type can be added")
459                 .that(mUserManager.canAddMoreUsers(userType)).isFalse();
460         if (currentUsersOverall + usersAdded >= maxUsersOverall) {
461             assertThat(mUserManager.canAddMoreUsers()).isFalse();
462         }
463 
464         assertThat(createUser("User beyond", userType, 0)).isNull();
465 
466         assertThat(mUserManager.canAddMoreUsers(mUserManager.USER_TYPE_FULL_GUEST)).isTrue();
467     }
468 
469     @MediumTest
470     @Test
testRemoveUser()471     public void testRemoveUser() throws Exception {
472         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
473         removeUser(userInfo.id);
474 
475         assertThat(hasUser(userInfo.id)).isFalse();
476     }
477 
478     @MediumTest
479     @Test
testRemoveUserByHandle()480     public void testRemoveUserByHandle() {
481         UserInfo userInfo = createUser("Guest 1", UserInfo.FLAG_GUEST);
482 
483         removeUser(userInfo.getUserHandle());
484 
485         assertThat(hasUser(userInfo.id)).isFalse();
486     }
487 
488     @MediumTest
489     @Test
testRemoveUserByHandle_ThrowsException()490     public void testRemoveUserByHandle_ThrowsException() {
491         assertThrows(IllegalArgumentException.class, () -> mUserManager.removeUser(null));
492     }
493 
494     @MediumTest
495     @Test
testRemoveUserShouldNotRemoveCurrentUser()496     public void testRemoveUserShouldNotRemoveCurrentUser() {
497         final int startUser = ActivityManager.getCurrentUser();
498         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
499         // Switch to the user just created.
500         switchUser(testUser.id);
501 
502         assertWithMessage("Current user should not be removed")
503                 .that(mUserManager.removeUser(testUser.id))
504                 .isFalse();
505 
506         // Switch back to the starting user.
507         switchUser(startUser);
508 
509         // Now we can remove the user
510         removeUser(testUser.id);
511     }
512 
513     @MediumTest
514     @Test
testRemoveUserShouldNotRemoveCurrentUser_DuringUserSwitch()515     public void testRemoveUserShouldNotRemoveCurrentUser_DuringUserSwitch() {
516         final int startUser = ActivityManager.getCurrentUser();
517         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
518         // Switch to the user just created.
519         switchUser(testUser.id);
520 
521         switchUserThenRun(startUser, () -> {
522             // While the user switch is happening, call removeUser for the current user.
523             assertWithMessage("Current user should not be removed during user switch")
524                     .that(mUserManager.removeUser(testUser.id))
525                     .isFalse();
526         });
527         assertThat(hasUser(testUser.id)).isTrue();
528 
529         // Now we can remove the user
530         removeUser(testUser.id);
531     }
532 
533     @MediumTest
534     @Test
testRemoveUserShouldNotRemoveTargetUser_DuringUserSwitch()535     public void testRemoveUserShouldNotRemoveTargetUser_DuringUserSwitch() {
536         final int startUser = ActivityManager.getCurrentUser();
537         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
538 
539         switchUserThenRun(testUser.id, () -> {
540             // While the user switch is happening, call removeUser for the target user.
541             assertWithMessage("Target user should not be removed during user switch")
542                     .that(mUserManager.removeUser(testUser.id))
543                     .isFalse();
544         });
545         assertThat(hasUser(testUser.id)).isTrue();
546 
547         // Switch back to the starting user.
548         switchUser(startUser);
549 
550         // Now we can remove the user
551         removeUser(testUser.id);
552     }
553 
554     @MediumTest
555     @Test
testRemoveUserWhenPossible_restrictedReturnsError()556     public void testRemoveUserWhenPossible_restrictedReturnsError() throws Exception {
557         final int currentUser = ActivityManager.getCurrentUser();
558         final UserInfo user1 = createUser("User 1", /* flags= */ 0);
559         mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_USER, /* value= */ true,
560                 asHandle(currentUser));
561         try {
562             assertThat(mUserManager.removeUserWhenPossible(user1.getUserHandle(),
563                     /* overrideDevicePolicy= */ false))
564                             .isEqualTo(UserManager.REMOVE_RESULT_ERROR_USER_RESTRICTION);
565         } finally {
566             mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_USER, /* value= */ false,
567                     asHandle(currentUser));
568         }
569 
570         assertThat(hasUser(user1.id)).isTrue();
571         assertThat(getUser(user1.id).isEphemeral()).isFalse();
572     }
573 
574     @MediumTest
575     @Test
testRemoveUserWhenPossible_evenWhenRestricted()576     public void testRemoveUserWhenPossible_evenWhenRestricted() throws Exception {
577         final int currentUser = ActivityManager.getCurrentUser();
578         final UserInfo user1 = createUser("User 1", /* flags= */ 0);
579         mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_USER, /* value= */ true,
580                 asHandle(currentUser));
581         try {
582             assertThat(mUserManager.removeUserWhenPossible(user1.getUserHandle(),
583                     /* overrideDevicePolicy= */ true))
584                     .isEqualTo(UserManager.REMOVE_RESULT_REMOVED);
585             waitForUserRemoval(user1.id);
586         } finally {
587             mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_USER, /* value= */ false,
588                     asHandle(currentUser));
589         }
590 
591         assertThat(hasUser(user1.id)).isFalse();
592     }
593 
594     @MediumTest
595     @Test
testRemoveUserWhenPossible_systemUserReturnsError()596     public void testRemoveUserWhenPossible_systemUserReturnsError() throws Exception {
597         assertThat(mUserManager.removeUserWhenPossible(UserHandle.SYSTEM,
598                 /* overrideDevicePolicy= */ false))
599                         .isEqualTo(UserManager.REMOVE_RESULT_ERROR_SYSTEM_USER);
600 
601         assertThat(hasUser(UserHandle.USER_SYSTEM)).isTrue();
602     }
603 
604     @MediumTest
605     @Test
testRemoveUserWhenPossible_permanentAdminMainUserReturnsError()606     public void testRemoveUserWhenPossible_permanentAdminMainUserReturnsError() throws Exception {
607         assumeHeadlessModeEnabled();
608         assumeTrue("Main user is not permanent admin", isMainUserPermanentAdmin());
609 
610         int currentUser = ActivityManager.getCurrentUser();
611         final UserInfo otherUser = createUser("User 1", /* flags= */ UserInfo.FLAG_ADMIN);
612         UserHandle mainUser = mUserManager.getMainUser();
613 
614         switchUser(otherUser.id);
615 
616         assertThat(mUserManager.removeUserWhenPossible(mainUser,
617                 /* overrideDevicePolicy= */ false))
618                 .isEqualTo(UserManager.REMOVE_RESULT_ERROR_MAIN_USER_PERMANENT_ADMIN);
619 
620 
621         assertThat(hasUser(mainUser.getIdentifier())).isTrue();
622 
623         // Switch back to the starting user.
624         switchUser(currentUser);
625     }
626 
627     @MediumTest
628     @Test
testRemoveUserWhenPossible_invalidUserReturnsError()629     public void testRemoveUserWhenPossible_invalidUserReturnsError() throws Exception {
630         assertThat(hasUser(Integer.MAX_VALUE)).isFalse();
631         assertThat(mUserManager.removeUserWhenPossible(UserHandle.of(Integer.MAX_VALUE),
632                 /* overrideDevicePolicy= */ false))
633                         .isEqualTo(UserManager.REMOVE_RESULT_ERROR_USER_NOT_FOUND);
634     }
635 
636     @MediumTest
637     @Test
testRemoveUserWhenPossible_currentUserSetEphemeral()638     public void testRemoveUserWhenPossible_currentUserSetEphemeral() throws Exception {
639         final int startUser = ActivityManager.getCurrentUser();
640         final UserInfo user1 = createUser("User 1", /* flags= */ 0);
641         // Switch to the user just created.
642         switchUser(user1.id);
643 
644         assertThat(mUserManager.removeUserWhenPossible(user1.getUserHandle(),
645                 /* overrideDevicePolicy= */ false)).isEqualTo(UserManager.REMOVE_RESULT_DEFERRED);
646 
647         assertThat(hasUser(user1.id)).isTrue();
648         assertThat(getUser(user1.id).isEphemeral()).isTrue();
649 
650         // Switch back to the starting user.
651         switchUser(startUser);
652         // User will be removed once switch is complete
653         waitForUserRemoval(user1.id);
654 
655         assertThat(hasUser(user1.id)).isFalse();
656     }
657 
658     @MediumTest
659     @Test
testRemoveUserWhenPossible_currentUserSetEphemeral_duringUserSwitch()660     public void testRemoveUserWhenPossible_currentUserSetEphemeral_duringUserSwitch() {
661         final int startUser = ActivityManager.getCurrentUser();
662         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
663         // Switch to the user just created.
664         switchUser(testUser.id);
665 
666         switchUserThenRun(startUser, () -> {
667             // While the switch is happening, call removeUserWhenPossible for the current user.
668             assertThat(mUserManager.removeUserWhenPossible(testUser.getUserHandle(),
669                     /* overrideDevicePolicy= */ false))
670                     .isEqualTo(UserManager.REMOVE_RESULT_DEFERRED);
671 
672             assertThat(hasUser(testUser.id)).isTrue();
673             assertThat(getUser(testUser.id).isEphemeral()).isTrue();
674         }); // wait for user switch - startUser
675         // User will be removed once switch is complete
676         waitForUserRemoval(testUser.id);
677 
678         assertThat(hasUser(testUser.id)).isFalse();
679     }
680 
681     @MediumTest
682     @Test
testRemoveUserWhenPossible_targetUserSetEphemeral_duringUserSwitch()683     public void testRemoveUserWhenPossible_targetUserSetEphemeral_duringUserSwitch() {
684         final int startUser = ActivityManager.getCurrentUser();
685         final UserInfo testUser = createUser("TestUser", /* flags= */ 0);
686 
687         switchUserThenRun(testUser.id, () -> {
688             // While the user switch is happening, call removeUserWhenPossible for the target user.
689             assertThat(mUserManager.removeUserWhenPossible(testUser.getUserHandle(),
690                     /* overrideDevicePolicy= */ false))
691                     .isEqualTo(UserManager.REMOVE_RESULT_DEFERRED);
692 
693             assertThat(hasUser(testUser.id)).isTrue();
694             assertThat(getUser(testUser.id).isEphemeral()).isTrue();
695         }); // wait for user switch - testUser
696 
697         // Switch back to the starting user.
698         switchUser(startUser);
699         // User will be removed once switch is complete
700         waitForUserRemoval(testUser.id);
701 
702         assertThat(hasUser(testUser.id)).isFalse();
703     }
704 
705     @MediumTest
706     @Test
testRemoveUserWhenPossible_nonCurrentUserRemoved()707     public void testRemoveUserWhenPossible_nonCurrentUserRemoved() throws Exception {
708         final UserInfo user1 = createUser("User 1", /* flags= */ 0);
709 
710         assertThat(mUserManager.removeUserWhenPossible(user1.getUserHandle(),
711                 /* overrideDevicePolicy= */ false))
712                 .isEqualTo(UserManager.REMOVE_RESULT_REMOVED);
713         waitForUserRemoval(user1.id);
714 
715         assertThat(hasUser(user1.id)).isFalse();
716     }
717 
718     @MediumTest
719     @Test
testRemoveUserWhenPossible_withProfiles()720     public void testRemoveUserWhenPossible_withProfiles() throws Exception {
721         assumeHeadlessModeEnabled();
722         assumeCloneEnabled();
723         final List<String> profileTypesToCreate = Arrays.asList(
724                 UserManager.USER_TYPE_PROFILE_CLONE,
725                 UserManager.USER_TYPE_PROFILE_MANAGED
726         );
727 
728         final UserInfo parentUser = createUser("Human User", /* flags= */ 0);
729         assertWithMessage("Could not create parent user")
730                 .that(parentUser).isNotNull();
731 
732         final List<Integer> profileIds = new ArrayList<>();
733         for (String profileType : profileTypesToCreate) {
734             final String name = profileType.substring(profileType.lastIndexOf('.') + 1);
735             if (mUserManager.canAddMoreProfilesToUser(profileType, parentUser.id)) {
736                 final UserInfo profile = createProfileForUser(name, profileType, parentUser.id);
737                 assertWithMessage("Could not create " + name)
738                         .that(profile).isNotNull();
739                 profileIds.add(profile.id);
740             } else {
741                 Slog.w(TAG, "Can not add " + name + " to user #" + parentUser.id);
742             }
743         }
744 
745         // Test shouldn't pass or fail unless it's allowed to add profiles to secondary users.
746         assumeTrue("Not possible to create any profiles to user #" + parentUser.id,
747                 profileIds.size() > 0);
748 
749         assertThat(mUserManager.removeUserWhenPossible(parentUser.getUserHandle(),
750                 /* overrideDevicePolicy= */ false))
751                 .isEqualTo(UserManager.REMOVE_RESULT_REMOVED);
752         waitForUserRemoval(parentUser.id);
753 
754         assertWithMessage("Parent user still exists")
755                 .that(hasUser(parentUser.id)).isFalse();
756         profileIds.forEach(id ->
757                 assertWithMessage("Profile still exists")
758                         .that(hasUser(id)).isFalse());
759     }
760 
761     /** Tests creating a FULL user via specifying userType. */
762     @MediumTest
763     @Test
testCreateUserViaTypes()764     public void testCreateUserViaTypes() throws Exception {
765         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_GUEST,
766                 UserInfo.FLAG_GUEST | UserInfo.FLAG_FULL);
767 
768         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_DEMO,
769                 UserInfo.FLAG_DEMO | UserInfo.FLAG_FULL);
770 
771         createUserWithTypeAndCheckFlags(UserManager.USER_TYPE_FULL_SECONDARY,
772                 UserInfo.FLAG_FULL);
773     }
774 
775     /** Tests creating a FULL user via specifying user flags. */
776     @MediumTest
777     @Test
testCreateUserViaFlags()778     public void testCreateUserViaFlags() throws Exception {
779         createUserWithFlagsAndCheckType(UserInfo.FLAG_GUEST, UserManager.USER_TYPE_FULL_GUEST,
780                 UserInfo.FLAG_FULL);
781 
782         createUserWithFlagsAndCheckType(0, UserManager.USER_TYPE_FULL_SECONDARY,
783                 UserInfo.FLAG_FULL);
784 
785         createUserWithFlagsAndCheckType(UserInfo.FLAG_FULL, UserManager.USER_TYPE_FULL_SECONDARY,
786                 0);
787 
788         createUserWithFlagsAndCheckType(UserInfo.FLAG_DEMO, UserManager.USER_TYPE_FULL_DEMO,
789                 UserInfo.FLAG_FULL);
790     }
791 
792     /** Creates a user of the given user type and checks that the result has the requiredFlags. */
createUserWithTypeAndCheckFlags(String userType, @UserIdInt int requiredFlags)793     private void createUserWithTypeAndCheckFlags(String userType,
794             @UserIdInt int requiredFlags) {
795         final UserInfo userInfo = createUser("Name", userType, 0);
796         assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(userType);
797         assertWithMessage("Flags %s did not contain expected %s", userInfo.flags, requiredFlags)
798                 .that(userInfo.flags & requiredFlags).isEqualTo(requiredFlags);
799         removeUser(userInfo.id);
800     }
801 
802     /**
803      * Creates a user of the given flags and checks that the result is of the expectedUserType type
804      * and that it has the expected flags (including both flags and any additionalRequiredFlags).
805      */
createUserWithFlagsAndCheckType(@serIdInt int flags, String expectedUserType, @UserIdInt int additionalRequiredFlags)806     private void createUserWithFlagsAndCheckType(@UserIdInt int flags, String expectedUserType,
807             @UserIdInt int additionalRequiredFlags) {
808         final UserInfo userInfo = createUser("Name", flags);
809         assertWithMessage("Wrong user type").that(userInfo.userType).isEqualTo(expectedUserType);
810         additionalRequiredFlags |= flags;
811         assertWithMessage("Flags %s did not contain expected %s", userInfo.flags,
812                 additionalRequiredFlags).that(userInfo.flags & additionalRequiredFlags)
813                         .isEqualTo(additionalRequiredFlags);
814         removeUser(userInfo.id);
815     }
816 
requireSingleGuest()817     private void requireSingleGuest() throws Exception {
818         assumeTrue("device supports single guest",
819                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_FULL_GUEST)
820                 .getMaxAllowed() == 1);
821     }
822 
requireMultipleGuests()823     private void requireMultipleGuests() throws Exception {
824         assumeTrue("device supports multiple guests",
825                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_FULL_GUEST)
826                 .getMaxAllowed() > 1);
827     }
828 
829     @MediumTest
830     @Test
testThereCanBeOnlyOneGuest_singleGuest()831     public void testThereCanBeOnlyOneGuest_singleGuest() throws Exception {
832         requireSingleGuest();
833         assertThat(mUserManager.canAddMoreUsers(mUserManager.USER_TYPE_FULL_GUEST)).isTrue();
834         UserInfo userInfo1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
835         assertThat(userInfo1).isNotNull();
836         assertThat(mUserManager.canAddMoreUsers(mUserManager.USER_TYPE_FULL_GUEST)).isFalse();
837         UserInfo userInfo2 = createUser("Guest 2", UserInfo.FLAG_GUEST);
838         assertThat(userInfo2).isNull();
839     }
840 
841     @MediumTest
842     @Test
testThereCanBeMultipleGuests_multipleGuests()843     public void testThereCanBeMultipleGuests_multipleGuests() throws Exception {
844         requireMultipleGuests();
845         assertThat(mUserManager.canAddMoreUsers(mUserManager.USER_TYPE_FULL_GUEST)).isTrue();
846         UserInfo userInfo1 = createUser("Guest 1", UserInfo.FLAG_GUEST);
847         assertThat(userInfo1).isNotNull();
848         assertThat(mUserManager.canAddMoreUsers(mUserManager.USER_TYPE_FULL_GUEST)).isTrue();
849         UserInfo userInfo2 = createUser("Guest 2", UserInfo.FLAG_GUEST);
850         assertThat(userInfo2).isNotNull();
851     }
852 
853     @MediumTest
854     @Test
testFindExistingGuest_guestExists()855     public void testFindExistingGuest_guestExists() throws Exception {
856         UserInfo userInfo1 = createUser("Guest", UserInfo.FLAG_GUEST);
857         assertThat(userInfo1).isNotNull();
858         UserInfo foundGuest = mUserManager.findCurrentGuestUser();
859         assertThat(foundGuest).isNotNull();
860     }
861 
862     @MediumTest
863     @Test
testGetGuestUsers_singleGuest()864     public void testGetGuestUsers_singleGuest() throws Exception {
865         requireSingleGuest();
866         UserInfo userInfo1 = createUser("Guest1", UserInfo.FLAG_GUEST);
867         assertThat(userInfo1).isNotNull();
868         List<UserInfo> guestsFound = mUserManager.getGuestUsers();
869         assertThat(guestsFound).hasSize(1);
870         assertThat(guestsFound.get(0).name).isEqualTo("Guest1");
871     }
872 
873     @MediumTest
874     @Test
testGetGuestUsers_multipleGuests()875     public void testGetGuestUsers_multipleGuests() throws Exception {
876         requireMultipleGuests();
877         UserInfo userInfo1 = createUser("Guest1", UserInfo.FLAG_GUEST);
878         assertThat(userInfo1).isNotNull();
879         UserInfo userInfo2 = createUser("Guest2", UserInfo.FLAG_GUEST);
880         assertThat(userInfo2).isNotNull();
881 
882         List<UserInfo> guestsFound = mUserManager.getGuestUsers();
883         assertThat(guestsFound).hasSize(2);
884         assertThat(ImmutableList.of(guestsFound.get(0).name, guestsFound.get(1).name))
885             .containsExactly("Guest1", "Guest2");
886     }
887 
888     @MediumTest
889     @Test
testGetGuestUsers_markGuestForDeletion()890     public void testGetGuestUsers_markGuestForDeletion() throws Exception {
891         requireMultipleGuests();
892         UserInfo userInfo1 = createUser("Guest1", UserInfo.FLAG_GUEST);
893         assertThat(userInfo1).isNotNull();
894         UserInfo userInfo2 = createUser("Guest2", UserInfo.FLAG_GUEST);
895         assertThat(userInfo2).isNotNull();
896 
897         boolean markedForDeletion1 = mUserManager.markGuestForDeletion(userInfo1.id);
898         assertThat(markedForDeletion1).isTrue();
899 
900         List<UserInfo> guestsFound = mUserManager.getGuestUsers();
901         assertThat(guestsFound.size()).isEqualTo(1);
902 
903         boolean markedForDeletion2 = mUserManager.markGuestForDeletion(userInfo2.id);
904         assertThat(markedForDeletion2).isTrue();
905 
906         guestsFound = mUserManager.getGuestUsers();
907         assertThat(guestsFound).isEmpty();
908     }
909 
910     @SmallTest
911     @Test
testFindExistingGuest_guestDoesNotExist()912     public void testFindExistingGuest_guestDoesNotExist() throws Exception {
913         UserInfo foundGuest = mUserManager.findCurrentGuestUser();
914         assertThat(foundGuest).isNull();
915     }
916 
917     @SmallTest
918     @Test
testGetGuestUsers_guestDoesNotExist()919     public void testGetGuestUsers_guestDoesNotExist() throws Exception {
920         List<UserInfo> guestsFound = mUserManager.getGuestUsers();
921         assertThat(guestsFound).isEmpty();
922     }
923 
924     @MediumTest
925     @Test
testSetUserAdmin()926     public void testSetUserAdmin() throws Exception {
927         UserInfo userInfo = createUser("SecondaryUser", /*flags=*/ 0);
928         assertThat(userInfo.isAdmin()).isFalse();
929 
930         mUserManager.setUserAdmin(userInfo.id);
931 
932         userInfo = mUserManager.getUserInfo(userInfo.id);
933         assertThat(userInfo.isAdmin()).isTrue();
934     }
935 
936     @MediumTest
937     @Test
testRevokeUserAdmin()938     public void testRevokeUserAdmin() throws Exception {
939         UserInfo userInfo = createUser("Admin", /*flags=*/ UserInfo.FLAG_ADMIN);
940         assertThat(userInfo.isAdmin()).isTrue();
941 
942         mUserManager.revokeUserAdmin(userInfo.id);
943 
944         userInfo = mUserManager.getUserInfo(userInfo.id);
945         assertThat(userInfo.isAdmin()).isFalse();
946     }
947 
948     @MediumTest
949     @Test
testRevokeUserAdminFromNonAdmin()950     public void testRevokeUserAdminFromNonAdmin() throws Exception {
951         UserInfo userInfo = createUser("NonAdmin", /*flags=*/ 0);
952         assertThat(userInfo.isAdmin()).isFalse();
953 
954         mUserManager.revokeUserAdmin(userInfo.id);
955 
956         userInfo = mUserManager.getUserInfo(userInfo.id);
957         assertThat(userInfo.isAdmin()).isFalse();
958     }
959 
960     @MediumTest
961     @Test
testGetProfileParent()962     public void testGetProfileParent() throws Exception {
963         assumeManagedUsersSupported();
964         int mainUserId = mUserManager.getMainUser().getIdentifier();
965         UserInfo userInfo = createProfileForUser("Profile",
966                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
967         assertThat(userInfo).isNotNull();
968         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
969         UserInfo parentProfileInfo = mUserManager.getProfileParent(userInfo.id);
970         assertThat(parentProfileInfo).isNotNull();
971         assertThat(mainUserId).isEqualTo(parentProfileInfo.id);
972         removeUser(userInfo.id);
973         assertThat(mUserManager.getProfileParent(mainUserId)).isNull();
974     }
975 
976     /** Test that UserManager returns the correct badge information for a managed profile. */
977     @MediumTest
978     @Test
testProfileTypeInformation()979     public void testProfileTypeInformation() throws Exception {
980         assumeManagedUsersSupported();
981         final UserTypeDetails userTypeDetails =
982                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_MANAGED);
983         assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_MANAGED)
984                 .that(userTypeDetails).isNotNull();
985         assertThat(userTypeDetails.getName()).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
986 
987         int mainUserId = mUserManager.getMainUser().getIdentifier();
988         UserInfo managedProfileUser = createProfileForUser("Managed",
989                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
990         assertThat(managedProfileUser).isNotNull();
991         final int userId = managedProfileUser.id;
992         final UserManager profileUM = UserManager.get(
993                 mContext.createPackageContextAsUser("android", 0,
994                         UserHandle.of(managedProfileUser.id)));
995 
996         assertThat(mUserManager.hasBadge(userId)).isEqualTo(userTypeDetails.hasBadge());
997         assertThat(mUserManager.getUserIconBadgeResId(userId))
998                 .isEqualTo(userTypeDetails.getIconBadge());
999         assertThat(mUserManager.getUserBadgeResId(userId))
1000                 .isEqualTo(userTypeDetails.getBadgePlain());
1001         assertThat(mUserManager.getUserBadgeNoBackgroundResId(userId))
1002                 .isEqualTo(userTypeDetails.getBadgeNoBackground());
1003         assertThat(mUserManager.getUserStatusBarIconResId(userId))
1004                 .isEqualTo(userTypeDetails.getStatusBarIcon());
1005         compareDrawables(profileUM.getUserBadge(),
1006                 Resources.getSystem().getDrawable(userTypeDetails.getBadgePlain()));
1007 
1008         final int badgeIndex = managedProfileUser.profileBadge;
1009         assertThat(mUserManager.getUserBadgeColor(userId)).isEqualTo(
1010                 Resources.getSystem().getColor(userTypeDetails.getBadgeColor(badgeIndex), null));
1011         assertThat(mUserManager.getUserBadgeDarkColor(userId)).isEqualTo(
1012                 Resources.getSystem().getColor(userTypeDetails.getDarkThemeBadgeColor(badgeIndex),
1013                         null));
1014 
1015         assertThat(mUserManager.getBadgedLabelForUser("Test", asHandle(userId))).isEqualTo(
1016                 Resources.getSystem().getString(userTypeDetails.getBadgeLabel(badgeIndex), "Test"));
1017 
1018         // Test @UserHandleAware methods
1019         final UserManager userManagerForUser = UserManager.get(mContext.createPackageContextAsUser(
1020                 "android", 0, asHandle(userId)));
1021         assertThat(userManagerForUser.isUserOfType(userTypeDetails.getName())).isTrue();
1022         assertThat(userManagerForUser.isProfile()).isEqualTo(userTypeDetails.isProfile());
1023         assertThat(mUserManager.getProfileAccessibilityString(managedProfileUser.id)).isEqualTo(
1024                 Resources.getSystem().getString(userTypeDetails.getAccessibilityString()));
1025     }
1026 
1027     /** Test that UserManager returns the correct UserProperties for a new managed profile. */
1028     @MediumTest
1029     @Test
testUserProperties()1030     public void testUserProperties() throws Exception {
1031         assumeManagedUsersSupported();
1032 
1033         // Get the default properties for a user type.
1034         final UserTypeDetails userTypeDetails =
1035                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_PROFILE_MANAGED);
1036         assertWithMessage("No %s type on device", UserManager.USER_TYPE_PROFILE_MANAGED)
1037                 .that(userTypeDetails).isNotNull();
1038         final UserProperties typeProps = userTypeDetails.getDefaultUserPropertiesReference();
1039 
1040         // Create an actual user (of this user type) and get its properties.
1041         int mainUserId = mUserManager.getMainUser().getIdentifier();
1042         final UserInfo managedProfileUser = createProfileForUser("Managed",
1043                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1044         assertThat(managedProfileUser).isNotNull();
1045         final int userId = managedProfileUser.id;
1046         final UserProperties userProps = mUserManager.getUserProperties(UserHandle.of(userId));
1047 
1048         // Check that this new user has the expected properties (relative to the defaults)
1049         // provided that the test caller has the necessary permissions.
1050         assertThat(userProps.getShowInLauncher()).isEqualTo(typeProps.getShowInLauncher());
1051         assertThat(userProps.getShowInSettings()).isEqualTo(typeProps.getShowInSettings());
1052         assertThat(userProps.getUseParentsContacts()).isFalse();
1053         assertThrows(SecurityException.class, userProps::getCrossProfileIntentFilterAccessControl);
1054         assertThrows(SecurityException.class, userProps::getCrossProfileIntentResolutionStrategy);
1055         assertThrows(SecurityException.class, userProps::getStartWithParent);
1056         assertThrows(SecurityException.class, userProps::getInheritDevicePolicy);
1057         assertThat(userProps.isMediaSharedWithParent()).isFalse();
1058         assertThat(userProps.isCredentialShareableWithParent()).isTrue();
1059         assertThrows(SecurityException.class, userProps::getDeleteAppWithParent);
1060         assertThrows(SecurityException.class, userProps::getAlwaysVisible);
1061     }
1062 
1063     // Make sure only max managed profiles can be created
1064     @MediumTest
1065     @Test
testAddManagedProfile()1066     public void testAddManagedProfile() throws Exception {
1067         assumeManagedUsersSupported();
1068         int mainUserId = mUserManager.getMainUser().getIdentifier();
1069         UserInfo userInfo1 = createProfileForUser("Managed 1",
1070                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1071         UserInfo userInfo2 = createProfileForUser("Managed 2",
1072                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1073 
1074         assertThat(userInfo1).isNotNull();
1075         assertThat(userInfo2).isNull();
1076 
1077         assertThat(userInfo1.userType).isEqualTo(UserManager.USER_TYPE_PROFILE_MANAGED);
1078         int requiredFlags = UserInfo.FLAG_MANAGED_PROFILE | UserInfo.FLAG_PROFILE;
1079         assertWithMessage("Wrong flags %s", userInfo1.flags).that(userInfo1.flags & requiredFlags)
1080                 .isEqualTo(requiredFlags);
1081 
1082         // Verify that current user is not a managed profile
1083         assertThat(mUserManager.isManagedProfile()).isFalse();
1084     }
1085 
1086     // Verify that disallowed packages are not installed in the managed profile.
1087     @MediumTest
1088     @Test
testAddManagedProfile_withDisallowedPackages()1089     public void testAddManagedProfile_withDisallowedPackages() throws Exception {
1090         assumeManagedUsersSupported();
1091         int mainUserId = mUserManager.getMainUser().getIdentifier();
1092         UserInfo userInfo1 = createProfileForUser("Managed1",
1093                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1094         // Verify that the packagesToVerify are installed by default.
1095         for (String pkg : PACKAGES) {
1096             if (!mPackageManager.isPackageAvailable(pkg)) {
1097                 Slog.w(TAG, "Package is not available " + pkg);
1098                 continue;
1099             }
1100 
1101             assertWithMessage("Package should be installed in managed profile: %s", pkg)
1102                     .that(isPackageInstalledForUser(pkg, userInfo1.id)).isTrue();
1103         }
1104         removeUser(userInfo1.id);
1105 
1106         UserInfo userInfo2 = createProfileForUser("Managed2",
1107                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId, PACKAGES);
1108         // Verify that the packagesToVerify are not installed by default.
1109         for (String pkg : PACKAGES) {
1110             if (!mPackageManager.isPackageAvailable(pkg)) {
1111                 Slog.w(TAG, "Package is not available " + pkg);
1112                 continue;
1113             }
1114 
1115             assertWithMessage(
1116                     "Package should not be installed in managed profile when disallowed: %s", pkg)
1117                             .that(isPackageInstalledForUser(pkg, userInfo2.id)).isFalse();
1118         }
1119     }
1120 
1121     // Verify that if any packages are disallowed to install during creation of managed profile can
1122     // still be installed later.
1123     @MediumTest
1124     @Test
testAddManagedProfile_disallowedPackagesInstalledLater()1125     public void testAddManagedProfile_disallowedPackagesInstalledLater() throws Exception {
1126         assumeManagedUsersSupported();
1127         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1128         UserInfo userInfo = createProfileForUser("Managed",
1129                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId, PACKAGES);
1130         // Verify that the packagesToVerify are not installed by default.
1131         for (String pkg : PACKAGES) {
1132             if (!mPackageManager.isPackageAvailable(pkg)) {
1133                 Slog.w(TAG, "Package is not available " + pkg);
1134                 continue;
1135             }
1136 
1137             assertWithMessage("Pkg should not be installed in managed profile when disallowed: %s",
1138                     pkg).that(isPackageInstalledForUser(pkg, userInfo.id)).isFalse();
1139         }
1140 
1141         // Verify that the disallowed packages during profile creation can be installed now.
1142         for (String pkg : PACKAGES) {
1143             if (!mPackageManager.isPackageAvailable(pkg)) {
1144                 Slog.w(TAG, "Package is not available " + pkg);
1145                 continue;
1146             }
1147 
1148             assertWithMessage("Package could not be installed: %s", pkg)
1149                     .that(mPackageManager.installExistingPackageAsUser(pkg, userInfo.id))
1150                     .isEqualTo(PackageManager.INSTALL_SUCCEEDED);
1151         }
1152     }
1153 
1154     // Make sure createUser would fail if we have DISALLOW_ADD_USER.
1155     @MediumTest
1156     @Test
testCreateUser_disallowAddUser()1157     public void testCreateUser_disallowAddUser() throws Exception {
1158         final int creatorId = ActivityManager.getCurrentUser();
1159         final UserHandle creatorHandle = asHandle(creatorId);
1160         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, creatorHandle);
1161         try {
1162             UserInfo createadInfo = createUser("SecondaryUser", /*flags=*/ 0);
1163             assertThat(createadInfo).isNull();
1164         } finally {
1165             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
1166                     creatorHandle);
1167         }
1168     }
1169 
1170     // Make sure createProfile would fail if we have DISALLOW_ADD_CLONE_PROFILE.
1171     @MediumTest
1172     @Test
testCreateUser_disallowAddClonedUserProfile()1173     public void testCreateUser_disallowAddClonedUserProfile() throws Exception {
1174         final int mainUserId = ActivityManager.getCurrentUser();
1175         final UserHandle mainUserHandle = asHandle(mainUserId);
1176         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
1177                 true, mainUserHandle);
1178         try {
1179             UserInfo cloneProfileUserInfo = createProfileForUser("Clone",
1180                     UserManager.USER_TYPE_PROFILE_CLONE, mainUserId);
1181             assertThat(cloneProfileUserInfo).isNull();
1182         } finally {
1183             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, false,
1184                     mainUserHandle);
1185         }
1186     }
1187 
1188     // Make sure createProfile would fail if we have DISALLOW_ADD_MANAGED_PROFILE.
1189     @MediumTest
1190     @Test
testCreateProfileForUser_disallowAddManagedProfile()1191     public void testCreateProfileForUser_disallowAddManagedProfile() throws Exception {
1192         assumeManagedUsersSupported();
1193         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1194         final UserHandle currentUserHandle = asHandle(ActivityManager.getCurrentUser());
1195         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
1196                 currentUserHandle);
1197         try {
1198             UserInfo userInfo = createProfileForUser("Managed",
1199                     UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1200             assertThat(userInfo).isNull();
1201         } finally {
1202             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
1203                     currentUserHandle);
1204         }
1205     }
1206 
1207     // Make sure createProfileEvenWhenDisallowedForUser bypass DISALLOW_ADD_MANAGED_PROFILE.
1208     @MediumTest
1209     @Test
testCreateProfileForUserEvenWhenDisallowed()1210     public void testCreateProfileForUserEvenWhenDisallowed() throws Exception {
1211         assumeManagedUsersSupported();
1212         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1213         final UserHandle mainUserHandle = asHandle(mainUserId);
1214         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
1215                 mainUserHandle);
1216         try {
1217             UserInfo userInfo = createProfileEvenWhenDisallowedForUser("Managed",
1218                     UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1219             assertThat(userInfo).isNotNull();
1220         } finally {
1221             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
1222                     mainUserHandle);
1223         }
1224     }
1225 
1226     // createProfile succeeds even if DISALLOW_ADD_USER is set
1227     @MediumTest
1228     @Test
testCreateProfileForUser_disallowAddUser()1229     public void testCreateProfileForUser_disallowAddUser() throws Exception {
1230         assumeManagedUsersSupported();
1231         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1232         final UserHandle mainUserHandle = asHandle(mainUserId);
1233         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, mainUserHandle);
1234         try {
1235             UserInfo userInfo = createProfileForUser("Managed",
1236                     UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1237             assertThat(userInfo).isNotNull();
1238         } finally {
1239             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
1240                     mainUserHandle);
1241         }
1242     }
1243 
1244     // Make sure the creation of a private profile fails if DISALLOW_ADD_PRIVATE_PROFILE is true.
1245     @MediumTest
1246     @Test
testCreateProfileForUser_disallowAddPrivateProfile()1247     public void testCreateProfileForUser_disallowAddPrivateProfile() {
1248         final int mainUserId = ActivityManager.getCurrentUser();
1249         final UserHandle mainUserHandle = asHandle(mainUserId);
1250         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
1251                 true, mainUserHandle);
1252         try {
1253             UserInfo privateProfileInfo = createProfileForUser("Private",
1254                     UserManager.USER_TYPE_PROFILE_PRIVATE, mainUserId);
1255             assertThat(privateProfileInfo).isNull();
1256         } finally {
1257             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE, false,
1258                     mainUserHandle);
1259         }
1260     }
1261 
1262     @MediumTest
1263     @Test
testPrivateProfileCreationRestrictions()1264     public void testPrivateProfileCreationRestrictions() {
1265         assumeTrue(mUserManager.canAddPrivateProfile());
1266         final int mainUserId = ActivityManager.getCurrentUser();
1267         try {
1268             UserInfo privateProfileInfo = createProfileForUser("Private",
1269                             UserManager.USER_TYPE_PROFILE_PRIVATE, mainUserId);
1270             assertThat(privateProfileInfo).isNotNull();
1271         } catch (Exception e) {
1272             fail("Creation of private profile failed due to " + e.getMessage());
1273         }
1274     }
1275 
1276     @MediumTest
1277     @Test
testDefaultUserRestrictionsForPrivateProfile()1278     public void testDefaultUserRestrictionsForPrivateProfile() {
1279         assumeTrue(mUserManager.canAddPrivateProfile());
1280         final int currentUserId = ActivityManager.getCurrentUser();
1281         UserInfo privateProfileInfo = null;
1282         try {
1283             privateProfileInfo = createProfileForUser("Private",
1284                     UserManager.USER_TYPE_PROFILE_PRIVATE, currentUserId);
1285             assertThat(privateProfileInfo).isNotNull();
1286         } catch (Exception e) {
1287             fail("Creation of private profile failed due to " + e.getMessage());
1288         }
1289         assertDefaultPrivateProfileRestrictions(privateProfileInfo.getUserHandle());
1290     }
1291 
assertDefaultPrivateProfileRestrictions(UserHandle userHandle)1292     private void assertDefaultPrivateProfileRestrictions(UserHandle userHandle) {
1293         Bundle defaultPrivateProfileRestrictions =
1294                 UserTypeFactory.getDefaultPrivateProfileRestrictions();
1295         for (String restriction : defaultPrivateProfileRestrictions.keySet()) {
1296             assertThat(mUserManager.hasUserRestrictionForUser(restriction, userHandle)).isTrue();
1297         }
1298     }
1299 
1300     @MediumTest
1301     @Test
testAddRestrictedProfile()1302     public void testAddRestrictedProfile() throws Exception {
1303         if (isAutomotive() || UserManager.isHeadlessSystemUserMode()) return;
1304         assertWithMessage("There should be no associated restricted profiles before the test")
1305                 .that(mUserManager.hasRestrictedProfiles()).isFalse();
1306         UserInfo userInfo = createRestrictedProfile("Profile");
1307         assertThat(userInfo).isNotNull();
1308 
1309         Bundle restrictions = mUserManager.getUserRestrictions(UserHandle.of(userInfo.id));
1310         assertWithMessage(
1311                 "Restricted profile should have DISALLOW_MODIFY_ACCOUNTS restriction by default")
1312                         .that(restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS))
1313                         .isTrue();
1314         assertWithMessage(
1315                 "Restricted profile should have DISALLOW_SHARE_LOCATION restriction by default")
1316                         .that(restrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION))
1317                         .isTrue();
1318 
1319         int locationMode = Settings.Secure.getIntForUser(mContext.getContentResolver(),
1320                 Settings.Secure.LOCATION_MODE,
1321                 Settings.Secure.LOCATION_MODE_HIGH_ACCURACY,
1322                 userInfo.id);
1323         assertWithMessage("Restricted profile should have setting LOCATION_MODE set to "
1324                 + "LOCATION_MODE_OFF by default").that(locationMode)
1325                         .isEqualTo(Settings.Secure.LOCATION_MODE_OFF);
1326 
1327         assertWithMessage("Newly created profile should be associated with the current user")
1328                 .that(mUserManager.hasRestrictedProfiles()).isTrue();
1329     }
1330 
1331     @MediumTest
1332     @Test
testGetManagedProfileCreationTime()1333     public void testGetManagedProfileCreationTime() throws Exception {
1334         assumeManagedUsersSupported();
1335         assumeTrue("User does not have access to creation time", mUserManager.isMainUser());
1336         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1337         final long startTime = System.currentTimeMillis();
1338         UserInfo profile = createProfileForUser("Managed 1",
1339                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1340         final long endTime = System.currentTimeMillis();
1341         assertThat(profile).isNotNull();
1342         if (System.currentTimeMillis() > EPOCH_PLUS_30_YEARS) {
1343             assertWithMessage("creationTime must be set when the profile is created")
1344                     .that(profile.creationTime).isIn(Range.closed(startTime, endTime));
1345         } else {
1346             assertWithMessage("creationTime must be 0 if the time is not > EPOCH_PLUS_30_years")
1347                     .that(profile.creationTime).isEqualTo(0);
1348         }
1349         assertThat(mUserManager.getUserCreationTime(asHandle(profile.id)))
1350                 .isEqualTo(profile.creationTime);
1351 
1352         long ownerCreationTime = mUserManager.getUserInfo(mainUserId).creationTime;
1353         assertThat(mUserManager.getUserCreationTime(asHandle(mainUserId)))
1354             .isEqualTo(ownerCreationTime);
1355     }
1356 
1357     @MediumTest
1358     @Test
testGetUserCreationTime()1359     public void testGetUserCreationTime() throws Exception {
1360         long startTime = System.currentTimeMillis();
1361         UserInfo user = createUser("User", /* flags= */ 0);
1362         long endTime = System.currentTimeMillis();
1363         assertThat(user).isNotNull();
1364         assertWithMessage("creationTime must be set when the user is created")
1365             .that(user.creationTime).isIn(Range.closed(startTime, endTime));
1366     }
1367 
1368     @SmallTest
1369     @Test
testGetUserCreationTime_nonExistentUser()1370     public void testGetUserCreationTime_nonExistentUser() throws Exception {
1371         int noSuchUserId = 100500;
1372         assertThrows(SecurityException.class,
1373                 () -> mUserManager.getUserCreationTime(asHandle(noSuchUserId)));
1374     }
1375 
1376     @SmallTest
1377     @Test
testGetUserCreationTime_otherUser()1378     public void testGetUserCreationTime_otherUser() throws Exception {
1379         UserInfo user = createUser("User 1", 0);
1380         assertThat(user).isNotNull();
1381         assertThrows(SecurityException.class,
1382                 () -> mUserManager.getUserCreationTime(asHandle(user.id)));
1383     }
1384 
1385     @Nullable
getUser(int id)1386     private UserInfo getUser(int id) {
1387         List<UserInfo> list = mUserManager.getUsers();
1388 
1389         for (UserInfo user : list) {
1390             if (user.id == id) {
1391                 return user;
1392             }
1393         }
1394         return null;
1395     }
1396 
hasUser(int id)1397     private boolean hasUser(int id) {
1398         return getUser(id) != null;
1399     }
1400 
1401     @MediumTest
1402     @Test
testSerialNumber()1403     public void testSerialNumber() {
1404         UserInfo user1 = createUser("User 1", 0);
1405         int serialNumber1 = user1.serialNumber;
1406         assertThat(mUserManager.getUserSerialNumber(user1.id)).isEqualTo(serialNumber1);
1407         assertThat(mUserManager.getUserHandle(serialNumber1)).isEqualTo(user1.id);
1408         UserInfo user2 = createUser("User 2", 0);
1409         int serialNumber2 = user2.serialNumber;
1410         assertThat(serialNumber1 == serialNumber2).isFalse();
1411         assertThat(mUserManager.getUserSerialNumber(user2.id)).isEqualTo(serialNumber2);
1412         assertThat(mUserManager.getUserHandle(serialNumber2)).isEqualTo(user2.id);
1413     }
1414 
1415     @MediumTest
1416     @Test
testGetSerialNumbersOfUsers()1417     public void testGetSerialNumbersOfUsers() {
1418         UserInfo user1 = createUser("User 1", 0);
1419         UserInfo user2 = createUser("User 2", 0);
1420         long[] serialNumbersOfUsers = mUserManager.getSerialNumbersOfUsers(false);
1421         assertThat(serialNumbersOfUsers).asList().containsAtLeast(
1422                 (long) user1.serialNumber, (long) user2.serialNumber);
1423     }
1424 
1425     @MediumTest
1426     @Test
testMaxUsers()1427     public void testMaxUsers() {
1428         int N = UserManager.getMaxSupportedUsers();
1429         int count = mUserManager.getUsers().size();
1430         // Create as many users as permitted and make sure creation passes
1431         while (count < N) {
1432             UserInfo ui = createUser("User " + count, 0);
1433             assertThat(ui).isNotNull();
1434             count++;
1435         }
1436         // Try to create one more user and make sure it fails
1437         UserInfo extra = createUser("One more", 0);
1438         assertThat(extra).isNull();
1439     }
1440 
1441     @MediumTest
1442     @Test
testGetUserCount()1443     public void testGetUserCount() {
1444         int count = mUserManager.getUsers().size();
1445         UserInfo user1 = createUser("User 1", 0);
1446         assertThat(user1).isNotNull();
1447         UserInfo user2 = createUser("User 2", 0);
1448         assertThat(user2).isNotNull();
1449         assertThat(mUserManager.getUserCount()).isEqualTo(count + 2);
1450     }
1451 
1452     @MediumTest
1453     @Test
testRestrictions()1454     public void testRestrictions() {
1455         UserInfo testUser = createUser("User 1", 0);
1456 
1457         mUserManager.setUserRestriction(
1458                 UserManager.DISALLOW_INSTALL_APPS, true, asHandle(testUser.id));
1459         mUserManager.setUserRestriction(
1460                 UserManager.DISALLOW_CONFIG_WIFI, false, asHandle(testUser.id));
1461 
1462         Bundle stored = mUserManager.getUserRestrictions(asHandle(testUser.id));
1463         // Note this will fail if DO already sets those restrictions.
1464         assertThat(stored.getBoolean(UserManager.DISALLOW_CONFIG_WIFI)).isFalse();
1465         assertThat(stored.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS)).isFalse();
1466         assertThat(stored.getBoolean(UserManager.DISALLOW_INSTALL_APPS)).isTrue();
1467     }
1468 
1469     @MediumTest
1470     @Test
testDefaultRestrictionsApplied()1471     public void testDefaultRestrictionsApplied() throws Exception {
1472         final UserInfo userInfo = createUser("Useroid", UserManager.USER_TYPE_FULL_SECONDARY, 0);
1473         final UserTypeDetails userTypeDetails =
1474                 UserTypeFactory.getUserTypes().get(UserManager.USER_TYPE_FULL_SECONDARY);
1475         final Bundle expectedRestrictions = userTypeDetails.getDefaultRestrictions();
1476         // Note this can fail if DO unset those restrictions.
1477         for (String restriction : expectedRestrictions.keySet()) {
1478             if (expectedRestrictions.getBoolean(restriction)) {
1479                 assertThat(mUserManager.hasUserRestriction(restriction, UserHandle.of(userInfo.id)))
1480                         .isTrue();
1481             }
1482         }
1483     }
1484 
1485     @MediumTest
1486     @Test
testSetDefaultGuestRestrictions()1487     public void testSetDefaultGuestRestrictions() {
1488         final Bundle origGuestRestrictions = mUserManager.getDefaultGuestRestrictions();
1489         Bundle restrictions = new Bundle();
1490         restrictions.putBoolean(UserManager.DISALLOW_FUN, true);
1491         mUserManager.setDefaultGuestRestrictions(restrictions);
1492 
1493         try {
1494             UserInfo guest = createUser("Guest", UserInfo.FLAG_GUEST);
1495             assertThat(guest).isNotNull();
1496             assertThat(mUserManager.hasUserRestriction(UserManager.DISALLOW_FUN,
1497                     guest.getUserHandle())).isTrue();
1498         } finally {
1499             mUserManager.setDefaultGuestRestrictions(origGuestRestrictions);
1500         }
1501     }
1502 
1503     @Test
testGetUserSwitchability()1504     public void testGetUserSwitchability() {
1505         int userSwitchable = mUserManager.getUserSwitchability();
1506         assertWithMessage("Expected users to be switchable").that(userSwitchable)
1507                 .isEqualTo(UserManager.SWITCHABILITY_STATUS_OK);
1508     }
1509 
1510     @LargeTest
1511     @Test
testSwitchUser()1512     public void testSwitchUser() {
1513         final int startUser = ActivityManager.getCurrentUser();
1514         UserInfo user = createUser("User", 0);
1515         assertThat(user).isNotNull();
1516         // Switch to the user just created.
1517         switchUser(user.id);
1518         // Switch back to the starting user.
1519         switchUser(startUser);
1520     }
1521 
1522     @LargeTest
1523     @Test
testSwitchUserByHandle()1524     public void testSwitchUserByHandle() {
1525         final int startUser = ActivityManager.getCurrentUser();
1526         UserInfo user = createUser("User", 0);
1527         assertThat(user).isNotNull();
1528         // Switch to the user just created.
1529         switchUser(user.getUserHandle());
1530         // Switch back to the starting user.
1531         switchUser(UserHandle.of(startUser));
1532     }
1533 
1534     @Test
testSwitchUserByHandle_ThrowsException()1535     public void testSwitchUserByHandle_ThrowsException() {
1536         assertThrows(IllegalArgumentException.class, () -> mActivityManager.switchUser(null));
1537     }
1538 
1539     @MediumTest
1540     @Test
testConcurrentUserSwitch()1541     public void testConcurrentUserSwitch() {
1542         final int startUser = ActivityManager.getCurrentUser();
1543         final UserInfo user1 = createUser("User 1", 0);
1544         assertThat(user1).isNotNull();
1545         final UserInfo user2 = createUser("User 2", 0);
1546         assertThat(user2).isNotNull();
1547         final UserInfo user3 = createUser("User 3", 0);
1548         assertThat(user3).isNotNull();
1549 
1550         // Switch to the users just created without waiting for the completion of the previous one.
1551         switchUserThenRun(user1.id, () -> switchUserThenRun(user2.id, () -> switchUser(user3.id)));
1552 
1553         // Switch back to the starting user.
1554         switchUser(startUser);
1555     }
1556 
1557     @MediumTest
1558     @Test
testConcurrentUserCreate()1559     public void testConcurrentUserCreate() throws Exception {
1560         int userCount = mUserManager.getUsers().size();
1561         int maxSupportedUsers = UserManager.getMaxSupportedUsers();
1562         int canBeCreatedCount = maxSupportedUsers - userCount;
1563         // Test exceeding the limit while running in parallel
1564         int createUsersCount = canBeCreatedCount + 5;
1565         ExecutorService es = Executors.newCachedThreadPool();
1566         AtomicInteger created = new AtomicInteger();
1567         for (int i = 0; i < createUsersCount; i++) {
1568             final String userName = "testConcUser" + i;
1569             es.submit(() -> {
1570                 UserInfo user = mUserManager.createUser(userName, 0);
1571                 if (user != null) {
1572                     created.incrementAndGet();
1573                     mUsersToRemove.add(user.id);
1574                 }
1575             });
1576         }
1577         es.shutdown();
1578         int timeout = createUsersCount * 20;
1579         assertWithMessage(
1580                 "Could not create " + createUsersCount + " users in " + timeout + " seconds")
1581                 .that(es.awaitTermination(timeout, TimeUnit.SECONDS))
1582                 .isTrue();
1583         assertThat(mUserManager.getUsers().size()).isEqualTo(maxSupportedUsers);
1584         assertThat(created.get()).isEqualTo(canBeCreatedCount);
1585     }
1586 
1587     @MediumTest
1588     @Test
testGetUserHandles_createNewUser_shouldFindNewUser()1589     public void testGetUserHandles_createNewUser_shouldFindNewUser() {
1590         UserInfo user = createUser("Guest 1", UserManager.USER_TYPE_FULL_GUEST, /*flags*/ 0);
1591 
1592         boolean found = false;
1593         List<UserHandle> userHandles = mUserManager.getUserHandles(/* excludeDying= */ true);
1594         for (UserHandle userHandle: userHandles) {
1595             if (userHandle.getIdentifier() == user.id) {
1596                 found = true;
1597             }
1598         }
1599 
1600         assertThat(found).isTrue();
1601     }
1602 
1603     @Test
testCreateProfile_withContextUserId()1604     public void testCreateProfile_withContextUserId() throws Exception {
1605         assumeManagedUsersSupported();
1606         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1607 
1608         UserInfo userProfile = createProfileForUser("Managed 1",
1609                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1610         assertThat(userProfile).isNotNull();
1611 
1612         UserManager um = (UserManager) mContext.createPackageContextAsUser(
1613                 "android", 0, mUserManager.getMainUser())
1614                 .getSystemService(Context.USER_SERVICE);
1615 
1616         List<UserHandle> profiles = um.getAllProfiles();
1617         assertThat(profiles.size()).isEqualTo(2);
1618         assertThat(profiles.get(0).equals(userProfile.getUserHandle())
1619                 || profiles.get(1).equals(userProfile.getUserHandle())).isTrue();
1620     }
1621 
1622     @Test
testSetUserName_withContextUserId()1623     public void testSetUserName_withContextUserId() throws Exception {
1624         assumeManagedUsersSupported();
1625         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1626 
1627         UserInfo userInfo1 = createProfileForUser("Managed 1",
1628                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1629         assertThat(userInfo1).isNotNull();
1630 
1631         UserManager um = (UserManager) mContext.createPackageContextAsUser(
1632                 "android", 0, userInfo1.getUserHandle())
1633                 .getSystemService(Context.USER_SERVICE);
1634 
1635         final String newName = "Managed_user 1";
1636         um.setUserName(newName);
1637 
1638         UserInfo userInfo = mUserManager.getUserInfo(userInfo1.id);
1639         assertThat(userInfo.name).isEqualTo(newName);
1640 
1641         // get user name from getUserName using context.getUserId
1642         assertThat(um.getUserName()).isEqualTo(newName);
1643     }
1644 
1645     @Test
testGetUserName_withContextUserId()1646     public void testGetUserName_withContextUserId() throws Exception {
1647         final String userName = "User 2";
1648         UserInfo user2 = createUser(userName, 0);
1649         assertThat(user2).isNotNull();
1650 
1651         UserManager um = (UserManager) mContext.createPackageContextAsUser(
1652                 "android", 0, user2.getUserHandle())
1653                 .getSystemService(Context.USER_SERVICE);
1654 
1655         assertThat(um.getUserName()).isEqualTo(userName);
1656     }
1657 
1658     @Test
testGetUserName_shouldReturnTranslatedTextForNullNamedGuestUser()1659     public void testGetUserName_shouldReturnTranslatedTextForNullNamedGuestUser() throws Exception {
1660         UserInfo guestWithNullName = createUser(null, UserManager.USER_TYPE_FULL_GUEST, 0);
1661         assertThat(guestWithNullName).isNotNull();
1662 
1663         UserManager um = (UserManager) mContext.createPackageContextAsUser(
1664                 "android", 0, guestWithNullName.getUserHandle())
1665                 .getSystemService(Context.USER_SERVICE);
1666 
1667         assertThat(um.getUserName()).isEqualTo(
1668                 mContext.getString(com.android.internal.R.string.guest_name));
1669     }
1670 
1671     @Test
testGetUserIcon_withContextUserId()1672     public void testGetUserIcon_withContextUserId() throws Exception {
1673         assumeManagedUsersSupported();
1674         final int mainUserId = mUserManager.getMainUser().getIdentifier();
1675 
1676         UserInfo userInfo1 = createProfileForUser("Managed 1",
1677                 UserManager.USER_TYPE_PROFILE_MANAGED, mainUserId);
1678         assertThat(userInfo1).isNotNull();
1679 
1680         UserManager um = (UserManager) mContext.createPackageContextAsUser(
1681                 "android", 0, userInfo1.getUserHandle())
1682                 .getSystemService(Context.USER_SERVICE);
1683 
1684         final String newName = "Managed_user 1";
1685         um.setUserName(newName);
1686 
1687         UserInfo userInfo = mUserManager.getUserInfo(userInfo1.id);
1688         assertThat(userInfo.name).isEqualTo(newName);
1689     }
1690 
1691     @Test
testCannotCreateAdditionalMainUser()1692     public void testCannotCreateAdditionalMainUser() {
1693         UserHandle mainUser = mUserManager.getMainUser();
1694         assumeTrue("There is no main user", mainUser != null);
1695 
1696         // Users with FLAG_MAIN can't be removed, so no point using the local createUser method.
1697         UserInfo newMainUser = mUserManager.createUser("test", UserInfo.FLAG_MAIN);
1698         assertThat(newMainUser).isNull();
1699 
1700         List<UserInfo> users = mUserManager.getUsers();
1701         int mainUserCount = 0;
1702         for (UserInfo user : users) {
1703             if (user.isMain()) {
1704                 mainUserCount++;
1705             }
1706         }
1707         assertThat(mainUserCount).isEqualTo(1);
1708     }
1709 
1710     @Test
testAddUserAccountData_validStringValuesAreSaved_validBundleIsSaved()1711     public void testAddUserAccountData_validStringValuesAreSaved_validBundleIsSaved() {
1712         assumeManagedUsersSupported();
1713 
1714         String userName = "User";
1715         String accountName = "accountName";
1716         String accountType = "accountType";
1717         String arrayKey = "StringArrayKey";
1718         String stringKey = "StringKey";
1719         String intKey = "IntKey";
1720         String nestedBundleKey = "PersistableBundleKey";
1721         String value1 = "Value 1";
1722         String value2 = "Value 2";
1723         String value3 = "Value 3";
1724 
1725         UserInfo userInfo = mUserManager.createUser(userName,
1726                 UserManager.USER_TYPE_FULL_SECONDARY, 0);
1727 
1728         PersistableBundle accountOptions = new PersistableBundle();
1729         String[] stringArray = {value1, value2};
1730         accountOptions.putInt(intKey, 1234);
1731         PersistableBundle nested = new PersistableBundle();
1732         nested.putString(stringKey, value3);
1733         accountOptions.putPersistableBundle(nestedBundleKey, nested);
1734         accountOptions.putStringArray(arrayKey, stringArray);
1735 
1736         mUserManager.clearSeedAccountData();
1737         mUserManager.setSeedAccountData(mContext.getUserId(), accountName,
1738                 accountType, accountOptions);
1739 
1740         //assert userName accountName and accountType were saved correctly
1741         assertTrue(mUserManager.getUserInfo(userInfo.id).name.equals(userName));
1742         assertTrue(mUserManager.getSeedAccountName().equals(accountName));
1743         assertTrue(mUserManager.getSeedAccountType().equals(accountType));
1744 
1745         //assert bundle with correct values was added
1746         assertThat(mUserManager.getSeedAccountOptions().containsKey(arrayKey)).isTrue();
1747         assertThat(mUserManager.getSeedAccountOptions().getPersistableBundle(nestedBundleKey)
1748                 .getString(stringKey)).isEqualTo(value3);
1749         assertThat(mUserManager.getSeedAccountOptions().getStringArray(arrayKey)[0])
1750                 .isEqualTo(value1);
1751 
1752         mUserManager.removeUser(userInfo.id);
1753     }
1754 
1755     @Test
testAddUserAccountData_invalidStringValuesAreTruncated_invalidBundleIsDropped()1756     public void testAddUserAccountData_invalidStringValuesAreTruncated_invalidBundleIsDropped() {
1757         assumeManagedUsersSupported();
1758 
1759         String tooLongString = generateLongString();
1760         String userName = "User " + tooLongString;
1761         String accountType = "Account Type " + tooLongString;
1762         String accountName = "accountName " + tooLongString;
1763         String arrayKey = "StringArrayKey";
1764         String stringKey = "StringKey";
1765         String intKey = "IntKey";
1766         String nestedBundleKey = "PersistableBundleKey";
1767         String value1 = "Value 1";
1768         String value2 = "Value 2";
1769 
1770         UserInfo userInfo = mUserManager.createUser(userName,
1771                 UserManager.USER_TYPE_FULL_SECONDARY, 0);
1772 
1773         PersistableBundle accountOptions = new PersistableBundle();
1774         String[] stringArray = {value1, value2};
1775         accountOptions.putInt(intKey, 1234);
1776         PersistableBundle nested = new PersistableBundle();
1777         nested.putString(stringKey, tooLongString);
1778         accountOptions.putPersistableBundle(nestedBundleKey, nested);
1779         accountOptions.putStringArray(arrayKey, stringArray);
1780         mUserManager.clearSeedAccountData();
1781         mUserManager.setSeedAccountData(mContext.getUserId(), accountName,
1782                 accountType, accountOptions);
1783 
1784         //assert userName was truncated
1785         assertTrue(mUserManager.getUserInfo(userInfo.id).name.length()
1786                 == UserManager.MAX_USER_NAME_LENGTH);
1787 
1788         //assert accountName and accountType got truncated
1789         assertTrue(mUserManager.getSeedAccountName().length()
1790                 == UserManager.MAX_ACCOUNT_STRING_LENGTH);
1791         assertTrue(mUserManager.getSeedAccountType().length()
1792                 == UserManager.MAX_ACCOUNT_STRING_LENGTH);
1793 
1794         //assert bundle with invalid values was dropped
1795         assertThat(mUserManager.getSeedAccountOptions() == null).isTrue();
1796 
1797         mUserManager.removeUser(userInfo.id);
1798     }
1799 
1800     @Test
1801     @RequiresFlagsEnabled(android.multiuser.Flags.FLAG_ENABLE_HIDING_PROFILES)
testGetProfileIdsExcludingHidden()1802     public void testGetProfileIdsExcludingHidden() throws Exception {
1803         int mainUserId = mUserManager.getMainUser().getIdentifier();
1804         final UserInfo profile = createProfileForUser("Profile",
1805                 UserManager.USER_TYPE_PROFILE_PRIVATE, mainUserId);
1806 
1807         final int[] allProfiles = mUserManager.getProfileIds(mainUserId, /* enabledOnly */ false);
1808         final int[] profilesExcludingHidden = mUserManager.getProfileIdsExcludingHidden(
1809                 mainUserId, /* enabledOnly */ false);
1810 
1811         assertThat(allProfiles).asList().contains(profile.id);
1812         assertThat(profilesExcludingHidden).asList().doesNotContain(profile.id);
1813     }
1814 
generateLongString()1815     private String generateLongString() {
1816         String partialString = "Test Name Test Name Test Name Test Name Test Name Test Name Test "
1817                 + "Name Test Name Test Name Test Name "; //String of length 100
1818         StringBuilder resultString = new StringBuilder();
1819         for (int i = 0; i < 600; i++) {
1820             resultString.append(partialString);
1821         }
1822         return resultString.toString();
1823     }
1824 
isPackageInstalledForUser(String packageName, int userId)1825     private boolean isPackageInstalledForUser(String packageName, int userId) {
1826         try {
1827             return mPackageManager.getPackageInfoAsUser(packageName, 0, userId) != null;
1828         } catch (PackageManager.NameNotFoundException e) {
1829             return false;
1830         }
1831     }
1832 
1833     /**
1834      * Starts the given user in the foreground. And waits for the user switch to be complete.
1835      **/
switchUser(UserHandle user)1836     private void switchUser(UserHandle user) {
1837         final int userId = user.getIdentifier();
1838         Slog.d(TAG, "Switching to user " + userId);
1839 
1840         mUserSwitchWaiter.runThenWaitUntilSwitchCompleted(userId, () -> {
1841             assertWithMessage("Could not start switching to user " + userId)
1842                     .that(mActivityManager.switchUser(user)).isTrue();
1843         }, /* onFail= */ () -> {
1844             throw new AssertionError("Could not complete switching to user " + userId);
1845         });
1846     }
1847 
1848     /**
1849      * Starts the given user in the foreground. And waits for the user switch to be complete.
1850      **/
switchUser(int userId)1851     private void switchUser(int userId) {
1852         switchUserThenRun(userId, null);
1853     }
1854 
1855     /**
1856      * Starts the given user in the foreground. And runs the given Runnable right after
1857      * am.switchUser call, before waiting for the actual user switch to be complete.
1858      **/
switchUserThenRun(int userId, Runnable runAfterSwitchBeforeWait)1859     private void switchUserThenRun(int userId, Runnable runAfterSwitchBeforeWait) {
1860         Slog.d(TAG, "Switching to user " + userId);
1861         mUserSwitchWaiter.runThenWaitUntilSwitchCompleted(userId, () -> {
1862             // Start switching to user
1863             assertWithMessage("Could not start switching to user " + userId)
1864                     .that(mActivityManager.switchUser(userId)).isTrue();
1865 
1866             // While the user switch is happening, call runAfterSwitchBeforeWait.
1867             if (runAfterSwitchBeforeWait != null) {
1868                 runAfterSwitchBeforeWait.run();
1869             }
1870         }, () -> fail("Could not complete switching to user " + userId));
1871     }
1872 
removeUser(UserHandle userHandle)1873     private void removeUser(UserHandle userHandle) {
1874         mUserManager.removeUser(userHandle);
1875         waitForUserRemoval(userHandle.getIdentifier());
1876     }
1877 
removeUser(int userId)1878     private void removeUser(int userId) {
1879         mUserManager.removeUser(userId);
1880         waitForUserRemoval(userId);
1881     }
1882 
waitForUserRemoval(int userId)1883     private void waitForUserRemoval(int userId) {
1884         mUserRemovalWaiter.waitFor(userId);
1885         mUsersToRemove.remove(userId);
1886     }
1887 
createUser(String name, int flags)1888     private UserInfo createUser(String name, int flags) {
1889         UserInfo user = mUserManager.createUser(name, flags);
1890         if (user != null) {
1891             mUsersToRemove.add(user.id);
1892         }
1893         return user;
1894     }
1895 
createUser(String name, String userType, int flags)1896     private UserInfo createUser(String name, String userType, int flags) {
1897         UserInfo user = mUserManager.createUser(name, userType, flags);
1898         if (user != null) {
1899             mUsersToRemove.add(user.id);
1900         }
1901         return user;
1902     }
1903 
createProfileForUser(String name, String userType, int userHandle)1904     private UserInfo createProfileForUser(String name, String userType, int userHandle) {
1905         return createProfileForUser(name, userType, userHandle, null);
1906     }
1907 
createProfileForUser(String name, String userType, int userHandle, String[] disallowedPackages)1908     private UserInfo createProfileForUser(String name, String userType, int userHandle,
1909             String[] disallowedPackages) {
1910         UserInfo profile = mUserManager.createProfileForUser(
1911                 name, userType, 0, userHandle, disallowedPackages);
1912         if (profile != null) {
1913             mUsersToRemove.add(profile.id);
1914         }
1915         return profile;
1916     }
1917 
createProfileEvenWhenDisallowedForUser(String name, String userType, int userHandle)1918     private UserInfo createProfileEvenWhenDisallowedForUser(String name, String userType,
1919             int userHandle) {
1920         UserInfo profile = mUserManager.createProfileForUserEvenWhenDisallowed(
1921                 name, userType, 0, userHandle, null);
1922         if (profile != null) {
1923             mUsersToRemove.add(profile.id);
1924         }
1925         return profile;
1926     }
1927 
createRestrictedProfile(String name)1928     private UserInfo createRestrictedProfile(String name) {
1929         UserInfo profile = mUserManager.createRestrictedProfile(name);
1930         if (profile != null) {
1931             mUsersToRemove.add(profile.id);
1932         }
1933         return profile;
1934     }
1935 
assumeManagedUsersSupported()1936     private void assumeManagedUsersSupported() {
1937         // In Automotive, if headless system user is enabled, a managed user cannot be created
1938         // under a primary user.
1939         assumeTrue("device doesn't support managed users",
1940                 mPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS)
1941                 && (!isAutomotive() || !UserManager.isHeadlessSystemUserMode()));
1942     }
1943 
assumeHeadlessModeEnabled()1944     private void assumeHeadlessModeEnabled() {
1945         // assume headless mode is enabled
1946         assumeTrue("Device doesn't have headless mode enabled",
1947                 UserManager.isHeadlessSystemUserMode());
1948     }
1949 
assumeCloneEnabled()1950     private void assumeCloneEnabled() {
1951         // assume clone profile is supported on the device
1952         assumeTrue("Device doesn't support clone profiles ",
1953                 mUserManager.isUserTypeEnabled(UserManager.USER_TYPE_PROFILE_CLONE));
1954     }
1955 
isAutomotive()1956     private boolean isAutomotive() {
1957         return mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
1958     }
1959 
asHandle(int userId)1960     private static UserHandle asHandle(int userId) {
1961         return new UserHandle(userId);
1962     }
1963 
isMainUserPermanentAdmin()1964     private boolean isMainUserPermanentAdmin() {
1965         return Resources.getSystem()
1966                 .getBoolean(com.android.internal.R.bool.config_isMainUserPermanentAdmin);
1967     }
1968 
compareDrawables(Drawable actual, Drawable expected)1969     private void compareDrawables(Drawable actual, Drawable expected){
1970         assertEquals(actual.getIntrinsicWidth(), expected.getIntrinsicWidth());
1971         assertEquals(actual.getIntrinsicHeight(), expected.getIntrinsicHeight());
1972         assertEquals(actual.getLevel(), expected.getLevel());
1973     }
1974 
1975 }
1976