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