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