1 /* 2 * Copyright (C) 2016 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.am; 18 19 import static android.Manifest.permission.INTERACT_ACROSS_PROFILES; 20 import static android.Manifest.permission.INTERACT_ACROSS_USERS; 21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 22 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY; 23 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL; 24 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE; 25 import static android.app.ActivityManagerInternal.ALLOW_PROFILES_OR_NON_FULL; 26 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 27 import static android.testing.DexmakerShareClassLoaderRule.runWithDexmakerShareClassLoader; 28 29 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; 30 31 import static com.android.server.am.UserController.CLEAR_USER_JOURNEY_SESSION_MSG; 32 import static com.android.server.am.UserController.COMPLETE_USER_SWITCH_MSG; 33 import static com.android.server.am.UserController.CONTINUE_USER_SWITCH_MSG; 34 import static com.android.server.am.UserController.REPORT_LOCKED_BOOT_COMPLETE_MSG; 35 import static com.android.server.am.UserController.REPORT_USER_SWITCH_COMPLETE_MSG; 36 import static com.android.server.am.UserController.REPORT_USER_SWITCH_MSG; 37 import static com.android.server.am.UserController.USER_COMPLETED_EVENT_MSG; 38 import static com.android.server.am.UserController.USER_CURRENT_MSG; 39 import static com.android.server.am.UserController.USER_START_MSG; 40 import static com.android.server.am.UserController.USER_SWITCH_TIMEOUT_MSG; 41 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND; 42 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; 43 44 import static com.google.android.collect.Lists.newArrayList; 45 import static com.google.android.collect.Sets.newHashSet; 46 import static com.google.common.truth.Truth.assertThat; 47 import static com.google.common.truth.Truth.assertWithMessage; 48 49 import static org.junit.Assert.assertEquals; 50 import static org.junit.Assert.assertFalse; 51 import static org.junit.Assert.assertNotNull; 52 import static org.junit.Assert.assertNull; 53 import static org.junit.Assert.assertThrows; 54 import static org.junit.Assert.assertTrue; 55 import static org.mockito.ArgumentMatchers.anyString; 56 import static org.mockito.Matchers.any; 57 import static org.mockito.Matchers.anyBoolean; 58 import static org.mockito.Matchers.anyInt; 59 import static org.mockito.Matchers.eq; 60 import static org.mockito.Mockito.doAnswer; 61 import static org.mockito.Mockito.doCallRealMethod; 62 import static org.mockito.Mockito.doNothing; 63 import static org.mockito.Mockito.doReturn; 64 import static org.mockito.Mockito.mock; 65 import static org.mockito.Mockito.never; 66 import static org.mockito.Mockito.spy; 67 import static org.mockito.Mockito.times; 68 import static org.mockito.Mockito.validateMockitoUsage; 69 import static org.mockito.Mockito.verify; 70 import static org.mockito.Mockito.when; 71 72 import android.annotation.Nullable; 73 import android.annotation.UserIdInt; 74 import android.app.ActivityManager; 75 import android.app.IUserSwitchObserver; 76 import android.app.KeyguardManager; 77 import android.content.Context; 78 import android.content.IIntentReceiver; 79 import android.content.Intent; 80 import android.content.pm.PackageManager; 81 import android.content.pm.UserInfo; 82 import android.content.pm.UserInfo.UserInfoFlag; 83 import android.os.Binder; 84 import android.os.Bundle; 85 import android.os.Handler; 86 import android.os.HandlerThread; 87 import android.os.IRemoteCallback; 88 import android.os.Looper; 89 import android.os.Message; 90 import android.os.RemoteException; 91 import android.os.UserHandle; 92 import android.os.UserManager; 93 import android.os.storage.IStorageManager; 94 import android.platform.test.annotations.Presubmit; 95 import android.util.Log; 96 import android.view.Display; 97 98 import androidx.test.filters.SmallTest; 99 100 import com.android.internal.widget.LockPatternUtils; 101 import com.android.server.FgThread; 102 import com.android.server.SystemService; 103 import com.android.server.am.UserState.KeyEvictedCallback; 104 import com.android.server.pm.UserJourneyLogger; 105 import com.android.server.pm.UserManagerInternal; 106 import com.android.server.pm.UserManagerService; 107 import com.android.server.wm.ActivityTaskManagerInternal; 108 import com.android.server.wm.WindowManagerService; 109 110 import org.junit.After; 111 import org.junit.Before; 112 import org.junit.Test; 113 import org.mockito.ArgumentCaptor; 114 115 import java.util.ArrayList; 116 import java.util.Arrays; 117 import java.util.Collections; 118 import java.util.HashMap; 119 import java.util.LinkedHashSet; 120 import java.util.List; 121 import java.util.Set; 122 import java.util.stream.Collectors; 123 import java.util.stream.Stream; 124 125 /** 126 * Tests for {@link UserController}. 127 * 128 * Build/Install/Run: 129 * atest FrameworksServicesTests:UserControllerTest 130 */ 131 @SmallTest 132 @Presubmit 133 134 public class UserControllerTest { 135 // Use big enough user id to avoid picking up already active user id. 136 private static final int TEST_USER_ID = 100; 137 private static final int TEST_USER_ID1 = 101; 138 private static final int TEST_USER_ID2 = 102; 139 private static final int TEST_USER_ID3 = 103; 140 private static final int SYSTEM_USER_ID = UserHandle.SYSTEM.getIdentifier(); 141 private static final int NONEXIST_USER_ID = 2; 142 private static final int TEST_PRE_CREATED_USER_ID = 103; 143 144 private static final int NO_USERINFO_FLAGS = 0; 145 146 private static final String TAG = UserControllerTest.class.getSimpleName(); 147 148 private static final long HANDLER_WAIT_TIME_MS = 100; 149 150 private UserController mUserController; 151 private TestInjector mInjector; 152 private final HashMap<Integer, UserState> mUserStates = new HashMap<>(); 153 154 private final KeyEvictedCallback mKeyEvictedCallback = (userId) -> { /* ignore */ }; 155 156 private static final List<String> START_FOREGROUND_USER_ACTIONS = newArrayList( 157 Intent.ACTION_USER_STARTED, 158 Intent.ACTION_USER_STARTING); 159 160 private static final List<String> START_FOREGROUND_USER_DEFERRED_ACTIONS = newArrayList( 161 Intent.ACTION_USER_SWITCHED); 162 163 private static final List<String> START_BACKGROUND_USER_ACTIONS = newArrayList( 164 Intent.ACTION_USER_STARTED, 165 Intent.ACTION_LOCKED_BOOT_COMPLETED, 166 Intent.ACTION_USER_STARTING); 167 168 private static final Set<Integer> START_FOREGROUND_USER_MESSAGE_CODES = newHashSet( 169 REPORT_USER_SWITCH_MSG, 170 USER_SWITCH_TIMEOUT_MSG, 171 USER_START_MSG, 172 USER_CURRENT_MSG); 173 174 private static final Set<Integer> START_BACKGROUND_USER_MESSAGE_CODES = newHashSet( 175 USER_START_MSG, 176 REPORT_LOCKED_BOOT_COMPLETE_MSG); 177 178 @Before setUp()179 public void setUp() throws Exception { 180 runWithDexmakerShareClassLoader(() -> { 181 mInjector = spy(new TestInjector(getInstrumentation().getTargetContext())); 182 doNothing().when(mInjector).clearAllLockedTasks(anyString()); 183 doNothing().when(mInjector).startHomeActivity(anyInt(), anyString()); 184 doReturn(false).when(mInjector).taskSupervisorSwitchUser(anyInt(), any()); 185 doNothing().when(mInjector).taskSupervisorResumeFocusedStackTopActivity(); 186 doNothing().when(mInjector).systemServiceManagerOnUserStopped(anyInt()); 187 doNothing().when(mInjector).systemServiceManagerOnUserCompletedEvent( 188 anyInt(), anyInt()); 189 doNothing().when(mInjector).activityManagerForceStopPackage(anyInt(), anyString()); 190 doNothing().when(mInjector).activityManagerOnUserStopped(anyInt()); 191 doNothing().when(mInjector).clearBroadcastQueueForUser(anyInt()); 192 doNothing().when(mInjector).taskSupervisorRemoveUser(anyInt()); 193 doNothing().when(mInjector).lockDeviceNowAndWaitForKeyguardShown(); 194 mockIsUsersOnSecondaryDisplaysEnabled(false); 195 // All UserController params are set to default. 196 197 // Starts with a generic assumption that the user starts visible, but on tests where 198 // that's not the case, the test should call mockAssignUserToMainDisplay() 199 doReturn(UserManagerInternal.USER_ASSIGNMENT_RESULT_SUCCESS_VISIBLE) 200 .when(mInjector.mUserManagerInternalMock) 201 .assignUserToDisplayOnStart(anyInt(), anyInt(), anyInt(), anyInt()); 202 203 mUserController = new UserController(mInjector); 204 mUserController.setAllowUserUnlocking(true); 205 setUpUser(TEST_USER_ID, NO_USERINFO_FLAGS); 206 setUpUser(TEST_PRE_CREATED_USER_ID, NO_USERINFO_FLAGS, /* preCreated= */ true, null); 207 mInjector.mRelevantUser = null; 208 }); 209 } 210 211 @After tearDown()212 public void tearDown() throws Exception { 213 mInjector.mHandlerThread.quit(); 214 validateMockitoUsage(); 215 } 216 217 @Test testStartUser_foreground()218 public void testStartUser_foreground() { 219 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 220 verify(mInjector, never()).dismissUserSwitchingDialog(any()); 221 verify(mInjector.getWindowManager(), times(1)).setSwitchingUser(anyBoolean()); 222 verify(mInjector.getWindowManager()).setSwitchingUser(true); 223 verify(mInjector).clearAllLockedTasks(anyString()); 224 startForegroundUserAssertions(); 225 verifyUserAssignedToDisplay(TEST_USER_ID, Display.DEFAULT_DISPLAY); 226 } 227 228 @Test testStartUser_background()229 public void testStartUser_background() { 230 boolean started = mUserController.startUser(TEST_USER_ID, USER_START_MODE_BACKGROUND); 231 assertWithMessage("startUser(%s, foreground=false)", TEST_USER_ID).that(started).isTrue(); 232 verify(mInjector, never()).showUserSwitchingDialog( 233 any(), any(), anyString(), anyString(), any()); 234 verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); 235 verify(mInjector, never()).clearAllLockedTasks(anyString()); 236 startBackgroundUserAssertions(); 237 verifyUserAssignedToDisplay(TEST_USER_ID, Display.DEFAULT_DISPLAY); 238 } 239 240 @Test testStartUser_background_duringBootHsum()241 public void testStartUser_background_duringBootHsum() { 242 mockIsHeadlessSystemUserMode(true); 243 mUserController.setAllowUserUnlocking(false); 244 mInjector.mRelevantUser = TEST_USER_ID; 245 boolean started = mUserController.startUser(TEST_USER_ID, USER_START_MODE_BACKGROUND); 246 assertWithMessage("startUser(%s, foreground=false)", TEST_USER_ID).that(started).isTrue(); 247 248 // ACTION_LOCKED_BOOT_COMPLETED not sent yet 249 startUserAssertions(newArrayList(Intent.ACTION_USER_STARTED, Intent.ACTION_USER_STARTING), 250 START_BACKGROUND_USER_MESSAGE_CODES); 251 252 mUserController.onBootComplete(null); 253 254 startUserAssertions(newArrayList(Intent.ACTION_USER_STARTED, Intent.ACTION_USER_STARTING, 255 Intent.ACTION_LOCKED_BOOT_COMPLETED), 256 START_BACKGROUND_USER_MESSAGE_CODES); 257 } 258 259 @Test testStartUser_sendsNoBroadcastsForSystemUserInNonHeadlessMode()260 public void testStartUser_sendsNoBroadcastsForSystemUserInNonHeadlessMode() { 261 setUpUser(SYSTEM_USER_ID, UserInfo.FLAG_SYSTEM, /* preCreated= */ false, 262 UserManager.USER_TYPE_FULL_SYSTEM); 263 mockIsHeadlessSystemUserMode(false); 264 265 mUserController.startUser(SYSTEM_USER_ID, USER_START_MODE_FOREGROUND); 266 267 assertWithMessage("Broadcasts for starting the system user in non-headless mode") 268 .that(mInjector.mSentIntents).isEmpty(); 269 } 270 271 @Test testStartUser_sendsBroadcastsForSystemUserInHeadlessMode()272 public void testStartUser_sendsBroadcastsForSystemUserInHeadlessMode() { 273 setUpUser(SYSTEM_USER_ID, UserInfo.FLAG_SYSTEM, /* preCreated= */ false, 274 UserManager.USER_TYPE_SYSTEM_HEADLESS); 275 mockIsHeadlessSystemUserMode(true); 276 277 mUserController.startUser(SYSTEM_USER_ID, USER_START_MODE_FOREGROUND); 278 279 assertWithMessage("Broadcasts for starting the system user in headless mode") 280 .that(getActions(mInjector.mSentIntents)).containsExactly( 281 Intent.ACTION_USER_STARTED, Intent.ACTION_USER_STARTING); 282 } 283 284 @Test testStartUser_displayAssignmentFailed()285 public void testStartUser_displayAssignmentFailed() { 286 doReturn(UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE) 287 .when(mInjector.mUserManagerInternalMock) 288 .assignUserToDisplayOnStart(eq(TEST_USER_ID), anyInt(), 289 eq(USER_START_MODE_FOREGROUND), anyInt()); 290 291 boolean started = mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 292 293 assertWithMessage("startUser(%s, foreground=true)", TEST_USER_ID).that(started).isFalse(); 294 } 295 296 @Test testStartUserVisibleOnDisplay()297 public void testStartUserVisibleOnDisplay() { 298 boolean started = mUserController.startUserVisibleOnDisplay(TEST_USER_ID, 42, 299 /* unlockProgressListener= */ null); 300 301 assertWithMessage("startUserOnDisplay(%s, %s)", TEST_USER_ID, 42).that(started).isTrue(); 302 verifyUserAssignedToDisplay(TEST_USER_ID, 42); 303 304 verify(mInjector, never()).showUserSwitchingDialog( 305 any(), any(), anyString(), anyString(), any()); 306 verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); 307 verify(mInjector, never()).clearAllLockedTasks(anyString()); 308 startBackgroundUserAssertions(); 309 } 310 311 @Test testStartUserUIDisabled()312 public void testStartUserUIDisabled() { 313 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ false, 314 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 315 316 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 317 verify(mInjector, never()).showUserSwitchingDialog( 318 any(), any(), anyString(), anyString(), any()); 319 verify(mInjector, never()).dismissUserSwitchingDialog(any()); 320 verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); 321 startForegroundUserAssertions(); 322 } 323 324 @Test testStartPreCreatedUser_foreground()325 public void testStartPreCreatedUser_foreground() { 326 assertFalse( 327 mUserController.startUser(TEST_PRE_CREATED_USER_ID, USER_START_MODE_FOREGROUND)); 328 // Make sure no intents have been fired for pre-created users. 329 assertTrue(mInjector.mSentIntents.isEmpty()); 330 331 verifyUserNeverAssignedToDisplay(); 332 } 333 334 @Test testStartPreCreatedUser_background()335 public void testStartPreCreatedUser_background() throws Exception { 336 assertTrue(mUserController.startUser(TEST_PRE_CREATED_USER_ID, USER_START_MODE_BACKGROUND)); 337 // Make sure no intents have been fired for pre-created users. 338 assertTrue(mInjector.mSentIntents.isEmpty()); 339 340 verify(mInjector, never()).showUserSwitchingDialog( 341 any(), any(), anyString(), anyString(), any()); 342 verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); 343 verify(mInjector, never()).clearAllLockedTasks(anyString()); 344 345 assertWithMessage("should not have received intents") 346 .that(getActions(mInjector.mSentIntents)).isEmpty(); 347 // TODO(b/140868593): should have received a USER_UNLOCK_MSG message as well, but it doesn't 348 // because StorageManager.isUserKeyUnlocked(TEST_PRE_CREATED_USER_ID) returns false - to 349 // properly fix it, we'd need to move this class to FrameworksMockingServicesTests so we can 350 // mock static methods (but moving this class would involve changing the presubmit tests, 351 // and the cascade effect goes on...). In fact, a better approach would to not assert the 352 // binder calls, but their side effects (in this case, that the user is stopped right away) 353 assertWithMessage("wrong binder message calls").that(mInjector.mHandler.getMessageCodes()) 354 .containsExactly(USER_START_MSG); 355 } 356 startUserAssertions( List<String> expectedActions, Set<Integer> expectedMessageCodes)357 private void startUserAssertions( 358 List<String> expectedActions, Set<Integer> expectedMessageCodes) { 359 assertEquals(expectedActions, getActions(mInjector.mSentIntents)); 360 Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); 361 assertEquals("Unexpected message sent", expectedMessageCodes, actualCodes); 362 } 363 startBackgroundUserAssertions()364 private void startBackgroundUserAssertions() { 365 startUserAssertions(START_BACKGROUND_USER_ACTIONS, START_BACKGROUND_USER_MESSAGE_CODES); 366 } 367 startForegroundUserAssertions()368 private void startForegroundUserAssertions() { 369 startUserAssertions(START_FOREGROUND_USER_ACTIONS, START_FOREGROUND_USER_MESSAGE_CODES); 370 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 371 assertNotNull(reportMsg); 372 UserState userState = (UserState) reportMsg.obj; 373 assertNotNull(userState); 374 assertEquals(TEST_USER_ID, userState.mHandle.getIdentifier()); 375 assertEquals("User must be in STATE_BOOTING", UserState.STATE_BOOTING, userState.state); 376 assertEquals("Unexpected old user id", 0, reportMsg.arg1); 377 assertEquals("Unexpected new user id", TEST_USER_ID, reportMsg.arg2); 378 verifyUserAssignedToDisplay(TEST_USER_ID, Display.DEFAULT_DISPLAY); 379 } 380 381 @Test testFailedStartUserInForeground()382 public void testFailedStartUserInForeground() { 383 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ false, 384 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 385 386 mUserController.startUserInForeground(NONEXIST_USER_ID); 387 verify(mInjector.getWindowManager(), times(1)).setSwitchingUser(anyBoolean()); 388 verify(mInjector.getWindowManager()).setSwitchingUser(false); 389 390 verifyUserNeverAssignedToDisplay(); 391 } 392 393 @Test testDispatchUserSwitch()394 public void testDispatchUserSwitch() throws RemoteException { 395 // Prepare mock observer and register it 396 IUserSwitchObserver observer = mock(IUserSwitchObserver.class); 397 when(observer.asBinder()).thenReturn(new Binder()); 398 doAnswer(invocation -> { 399 IRemoteCallback callback = (IRemoteCallback) invocation.getArguments()[1]; 400 callback.sendResult(null); 401 return null; 402 }).when(observer).onUserSwitching(anyInt(), any()); 403 mUserController.registerUserSwitchObserver(observer, "mock"); 404 // Start user -- this will update state of mUserController 405 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 406 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 407 assertNotNull(reportMsg); 408 UserState userState = (UserState) reportMsg.obj; 409 int oldUserId = reportMsg.arg1; 410 int newUserId = reportMsg.arg2; 411 // Call dispatchUserSwitch and verify that observer was called only once 412 mInjector.mHandler.clearAllRecordedMessages(); 413 mUserController.dispatchUserSwitch(userState, oldUserId, newUserId); 414 verify(observer, times(1)).onBeforeUserSwitching(eq(TEST_USER_ID)); 415 verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any()); 416 Set<Integer> expectedCodes = Collections.singleton(CONTINUE_USER_SWITCH_MSG); 417 Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); 418 assertEquals("Unexpected message sent", expectedCodes, actualCodes); 419 Message conMsg = mInjector.mHandler.getMessageForCode(CONTINUE_USER_SWITCH_MSG); 420 assertNotNull(conMsg); 421 userState = (UserState) conMsg.obj; 422 assertNotNull(userState); 423 assertEquals(TEST_USER_ID, userState.mHandle.getIdentifier()); 424 assertEquals("User must be in STATE_BOOTING", UserState.STATE_BOOTING, userState.state); 425 assertEquals("Unexpected old user id", 0, conMsg.arg1); 426 assertEquals("Unexpected new user id", TEST_USER_ID, conMsg.arg2); 427 } 428 429 @Test testDispatchUserSwitchBadReceiver()430 public void testDispatchUserSwitchBadReceiver() throws RemoteException { 431 // Prepare mock observer which doesn't notify the callback and register it 432 IUserSwitchObserver observer = mock(IUserSwitchObserver.class); 433 when(observer.asBinder()).thenReturn(new Binder()); 434 mUserController.registerUserSwitchObserver(observer, "mock"); 435 // Start user -- this will update state of mUserController 436 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 437 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 438 assertNotNull(reportMsg); 439 UserState userState = (UserState) reportMsg.obj; 440 int oldUserId = reportMsg.arg1; 441 int newUserId = reportMsg.arg2; 442 // Call dispatchUserSwitch and verify that observer was called only once 443 mInjector.mHandler.clearAllRecordedMessages(); 444 mUserController.dispatchUserSwitch(userState, oldUserId, newUserId); 445 verify(observer, times(1)).onBeforeUserSwitching(eq(TEST_USER_ID)); 446 verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any()); 447 // Verify that CONTINUE_USER_SWITCH_MSG is not sent (triggers timeout) 448 Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); 449 assertWithMessage("No messages should be sent").that(actualCodes).isEmpty(); 450 } 451 continueAndCompleteUserSwitch(UserState userState, int oldUserId, int newUserId)452 private void continueAndCompleteUserSwitch(UserState userState, int oldUserId, int newUserId) { 453 mUserController.continueUserSwitch(userState, oldUserId, newUserId); 454 mInjector.mHandler.removeMessages(UserController.COMPLETE_USER_SWITCH_MSG); 455 mUserController.completeUserSwitch(oldUserId, newUserId); 456 } 457 458 @Test testContinueUserSwitch()459 public void testContinueUserSwitch() { 460 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 461 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 462 // Start user -- this will update state of mUserController 463 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 464 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 465 assertNotNull(reportMsg); 466 UserState userState = (UserState) reportMsg.obj; 467 int oldUserId = reportMsg.arg1; 468 int newUserId = reportMsg.arg2; 469 mInjector.mHandler.clearAllRecordedMessages(); 470 // Verify that continueUserSwitch worked as expected 471 continueAndCompleteUserSwitch(userState, oldUserId, newUserId); 472 verify(mInjector, times(0)).dismissKeyguard(any()); 473 verify(mInjector, times(1)).dismissUserSwitchingDialog(any()); 474 continueUserSwitchAssertions(oldUserId, TEST_USER_ID, false); 475 verifySystemUserVisibilityChangesNeverNotified(); 476 } 477 478 @Test testContinueUserSwitchDismissKeyguard()479 public void testContinueUserSwitchDismissKeyguard() { 480 when(mInjector.mKeyguardManagerMock.isDeviceSecure(anyInt())).thenReturn(false); 481 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 482 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 483 // Start user -- this will update state of mUserController 484 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 485 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 486 assertNotNull(reportMsg); 487 UserState userState = (UserState) reportMsg.obj; 488 int oldUserId = reportMsg.arg1; 489 int newUserId = reportMsg.arg2; 490 mInjector.mHandler.clearAllRecordedMessages(); 491 // Verify that continueUserSwitch worked as expected 492 continueAndCompleteUserSwitch(userState, oldUserId, newUserId); 493 verify(mInjector, times(1)).dismissKeyguard(any()); 494 verify(mInjector, times(1)).dismissUserSwitchingDialog(any()); 495 continueUserSwitchAssertions(oldUserId, TEST_USER_ID, false); 496 verifySystemUserVisibilityChangesNeverNotified(); 497 } 498 499 @Test testContinueUserSwitchUIDisabled()500 public void testContinueUserSwitchUIDisabled() { 501 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ false, 502 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 503 504 // Start user -- this will update state of mUserController 505 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 506 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 507 assertNotNull(reportMsg); 508 UserState userState = (UserState) reportMsg.obj; 509 int oldUserId = reportMsg.arg1; 510 int newUserId = reportMsg.arg2; 511 mInjector.mHandler.clearAllRecordedMessages(); 512 // Verify that continueUserSwitch worked as expected 513 continueAndCompleteUserSwitch(userState, oldUserId, newUserId); 514 verify(mInjector, never()).dismissUserSwitchingDialog(any()); 515 continueUserSwitchAssertions(oldUserId, TEST_USER_ID, false); 516 } 517 continueUserSwitchAssertions(int expectedOldUserId, int expectedNewUserId, boolean backgroundUserStopping)518 private void continueUserSwitchAssertions(int expectedOldUserId, int expectedNewUserId, 519 boolean backgroundUserStopping) { 520 Set<Integer> expectedCodes = new LinkedHashSet<>(); 521 expectedCodes.add(COMPLETE_USER_SWITCH_MSG); 522 expectedCodes.add(REPORT_USER_SWITCH_COMPLETE_MSG); 523 if (backgroundUserStopping) { 524 expectedCodes.add(CLEAR_USER_JOURNEY_SESSION_MSG); 525 expectedCodes.add(0); // this is for directly posting in stopping. 526 } 527 Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); 528 assertEquals("Unexpected message sent", expectedCodes, actualCodes); 529 Message msg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_COMPLETE_MSG); 530 assertNotNull(msg); 531 assertEquals("Unexpected oldUserId", expectedOldUserId, msg.arg1); 532 assertEquals("Unexpected newUserId", expectedNewUserId, msg.arg2); 533 } 534 535 @Test testDispatchUserSwitchComplete()536 public void testDispatchUserSwitchComplete() throws RemoteException { 537 // Prepare mock observer and register it 538 IUserSwitchObserver observer = mock(IUserSwitchObserver.class); 539 when(observer.asBinder()).thenReturn(new Binder()); 540 mUserController.registerUserSwitchObserver(observer, "mock"); 541 // Start user -- this will update state of mUserController 542 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 543 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 544 assertNotNull(reportMsg); 545 int oldUserId = reportMsg.arg1; 546 int newUserId = reportMsg.arg2; 547 mInjector.mHandler.clearAllRecordedMessages(); 548 // Mockito can't reset only interactions, so just verify that this hasn't been 549 // called with 'false' until after dispatchUserSwitchComplete. 550 verify(mInjector.getWindowManager(), never()).setSwitchingUser(false); 551 // Call dispatchUserSwitchComplete 552 mUserController.dispatchUserSwitchComplete(oldUserId, newUserId); 553 verify(observer, times(1)).onUserSwitchComplete(anyInt()); 554 verify(observer).onUserSwitchComplete(TEST_USER_ID); 555 verify(mInjector.getWindowManager(), times(1)).setSwitchingUser(false); 556 startUserAssertions(Stream.concat( 557 START_FOREGROUND_USER_ACTIONS.stream(), 558 START_FOREGROUND_USER_DEFERRED_ACTIONS.stream() 559 ).collect(Collectors.toList()), Collections.emptySet()); 560 } 561 562 @Test testExplicitSystemUserStartInBackground()563 public void testExplicitSystemUserStartInBackground() { 564 setUpUser(UserHandle.USER_SYSTEM, 0); 565 assertFalse(mUserController.isSystemUserStarted()); 566 assertTrue(mUserController.startUser(UserHandle.USER_SYSTEM, USER_START_MODE_BACKGROUND, 567 null)); 568 assertTrue(mUserController.isSystemUserStarted()); 569 } 570 571 /** 572 * Test stopping of user from max running users limit. 573 */ 574 @Test testUserLockingFromUserSwitchingForMultipleUsersNonDelayedLocking()575 public void testUserLockingFromUserSwitchingForMultipleUsersNonDelayedLocking() 576 throws InterruptedException, RemoteException { 577 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 578 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 579 580 setUpUser(TEST_USER_ID1, 0); 581 setUpUser(TEST_USER_ID2, 0); 582 int numerOfUserSwitches = 1; 583 addForegroundUserAndContinueUserSwitch(TEST_USER_ID, UserHandle.USER_SYSTEM, 584 numerOfUserSwitches, false); 585 // running: user 0, USER_ID 586 assertTrue(mUserController.canStartMoreUsers()); 587 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID}), 588 mUserController.getRunningUsersLU()); 589 590 numerOfUserSwitches++; 591 addForegroundUserAndContinueUserSwitch(TEST_USER_ID1, TEST_USER_ID, 592 numerOfUserSwitches, false); 593 // running: user 0, USER_ID, USER_ID1 594 assertFalse(mUserController.canStartMoreUsers()); 595 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID, TEST_USER_ID1}), 596 mUserController.getRunningUsersLU()); 597 598 numerOfUserSwitches++; 599 addForegroundUserAndContinueUserSwitch(TEST_USER_ID2, TEST_USER_ID1, 600 numerOfUserSwitches, false); 601 UserState ussUser2 = mUserStates.get(TEST_USER_ID2); 602 // skip middle step and call this directly. 603 mUserController.finishUserSwitch(ussUser2); 604 waitForHandlerToComplete(mInjector.mHandler, HANDLER_WAIT_TIME_MS); 605 // running: user 0, USER_ID1, USER_ID2 606 // USER_ID should be stopped as it is least recently used non user0. 607 assertFalse(mUserController.canStartMoreUsers()); 608 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID1, TEST_USER_ID2}), 609 mUserController.getRunningUsersLU()); 610 verifySystemUserVisibilityChangesNeverNotified(); 611 } 612 613 /** 614 * This test tests delayed locking mode using 4 users. As core logic of delayed locking is 615 * happening in finishUserStopped call, the test also calls finishUserStopped while skipping 616 * all middle steps which takes too much work to mock. 617 */ 618 @Test testUserLockingFromUserSwitchingForMultipleUsersDelayedLockingMode()619 public void testUserLockingFromUserSwitchingForMultipleUsersDelayedLockingMode() 620 throws Exception { 621 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 622 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ true); 623 624 setUpUser(TEST_USER_ID1, 0); 625 setUpUser(TEST_USER_ID2, 0); 626 int numerOfUserSwitches = 1; 627 addForegroundUserAndContinueUserSwitch(TEST_USER_ID, UserHandle.USER_SYSTEM, 628 numerOfUserSwitches, false); 629 // running: user 0, USER_ID 630 assertTrue(mUserController.canStartMoreUsers()); 631 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID}), 632 mUserController.getRunningUsersLU()); 633 numerOfUserSwitches++; 634 635 addForegroundUserAndContinueUserSwitch(TEST_USER_ID1, TEST_USER_ID, 636 numerOfUserSwitches, true); 637 // running: user 0, USER_ID1 638 // stopped + unlocked: USER_ID 639 numerOfUserSwitches++; 640 assertTrue(mUserController.canStartMoreUsers()); 641 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID1}), 642 mUserController.getRunningUsersLU()); 643 // Skip all other steps and test unlock delaying only 644 UserState uss = mUserStates.get(TEST_USER_ID); 645 uss.setState(UserState.STATE_SHUTDOWN); // necessary state change from skipped part 646 mUserController.finishUserStopped(uss, /* allowDelayedLocking= */ true); 647 // Cannot mock FgThread handler, so confirm that there is no posted message left before 648 // checking. 649 waitForHandlerToComplete(FgThread.getHandler(), HANDLER_WAIT_TIME_MS); 650 verify(mInjector.mStorageManagerMock, times(0)) 651 .lockUserKey(anyInt()); 652 653 addForegroundUserAndContinueUserSwitch(TEST_USER_ID2, TEST_USER_ID1, 654 numerOfUserSwitches, true); 655 // running: user 0, USER_ID2 656 // stopped + unlocked: USER_ID1 657 // stopped + locked: USER_ID 658 assertTrue(mUserController.canStartMoreUsers()); 659 assertEquals(Arrays.asList(new Integer[] {0, TEST_USER_ID2}), 660 mUserController.getRunningUsersLU()); 661 UserState ussUser1 = mUserStates.get(TEST_USER_ID1); 662 ussUser1.setState(UserState.STATE_SHUTDOWN); 663 mUserController.finishUserStopped(ussUser1, /* allowDelayedLocking= */ true); 664 waitForHandlerToComplete(FgThread.getHandler(), HANDLER_WAIT_TIME_MS); 665 verify(mInjector.mStorageManagerMock, times(1)) 666 .lockUserKey(TEST_USER_ID); 667 } 668 669 /** 670 * Test locking user with mDelayUserDataLocking false. 671 */ 672 @Test testUserLockingWithStopUserForNonDelayedLockingMode()673 public void testUserLockingWithStopUserForNonDelayedLockingMode() throws Exception { 674 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 675 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 676 677 setUpAndStartUserInBackground(TEST_USER_ID); 678 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* delayedLocking= */ true, 679 /* keyEvictedCallback= */ null, /* expectLocking= */ true); 680 681 setUpAndStartUserInBackground(TEST_USER_ID1); 682 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true, 683 /* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true); 684 685 setUpAndStartUserInBackground(TEST_USER_ID2); 686 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* delayedLocking= */ false, 687 /* keyEvictedCallback= */ null, /* expectLocking= */ true); 688 689 setUpAndStartUserInBackground(TEST_USER_ID3); 690 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* delayedLocking= */ false, 691 /* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true); 692 } 693 694 @Test testStopUser_invalidUser()695 public void testStopUser_invalidUser() { 696 int userId = -1; 697 698 assertThrows(IllegalArgumentException.class, 699 () -> mUserController.stopUser(userId, /* force= */ true, 700 /* allowDelayedLocking= */ true, /* stopUserCallback= */ null, 701 /* keyEvictedCallback= */ null)); 702 } 703 704 @Test testStopUser_systemUser()705 public void testStopUser_systemUser() { 706 int userId = UserHandle.USER_SYSTEM; 707 708 int r = mUserController.stopUser(userId, /* force= */ true, 709 /* allowDelayedLocking= */ true, /* stopUserCallback= */ null, 710 /* keyEvictedCallback= */ null); 711 712 assertThat(r).isEqualTo(ActivityManager.USER_OP_ERROR_IS_SYSTEM); 713 } 714 715 @Test testStopUser_currentUser()716 public void testStopUser_currentUser() { 717 setUpUser(TEST_USER_ID1, /* flags= */ 0); 718 mUserController.startUser(TEST_USER_ID1, USER_START_MODE_FOREGROUND); 719 720 int r = mUserController.stopUser(TEST_USER_ID1, /* force= */ true, 721 /* allowDelayedLocking= */ true, /* stopUserCallback= */ null, 722 /* keyEvictedCallback= */ null); 723 724 assertThat(r).isEqualTo(ActivityManager.USER_OP_IS_CURRENT); 725 } 726 727 /** 728 * Test conditional delayed locking with mDelayUserDataLocking true. 729 */ 730 @Test testUserLockingForDelayedLockingMode()731 public void testUserLockingForDelayedLockingMode() throws Exception { 732 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 733 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ true); 734 735 // delayedLocking set and no KeyEvictedCallback, so it should not lock. 736 setUpAndStartUserInBackground(TEST_USER_ID); 737 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID, /* delayedLocking= */ true, 738 /* keyEvictedCallback= */ null, /* expectLocking= */ false); 739 740 setUpAndStartUserInBackground(TEST_USER_ID1); 741 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* delayedLocking= */ true, 742 /* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true); 743 744 setUpAndStartUserInBackground(TEST_USER_ID2); 745 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID2, /* delayedLocking= */ false, 746 /* keyEvictedCallback= */ null, /* expectLocking= */ true); 747 748 setUpAndStartUserInBackground(TEST_USER_ID3); 749 assertUserLockedOrUnlockedAfterStopping(TEST_USER_ID3, /* delayedLocking= */ false, 750 /* keyEvictedCallback= */ mKeyEvictedCallback, /* expectLocking= */ true); 751 } 752 753 @Test testUserNotUnlockedBeforeAllowed()754 public void testUserNotUnlockedBeforeAllowed() throws Exception { 755 mUserController.setAllowUserUnlocking(false); 756 757 mUserController.startUser(TEST_USER_ID, USER_START_MODE_BACKGROUND); 758 759 verify(mInjector.mStorageManagerMock, never()) 760 .unlockUserKey(eq(TEST_USER_ID), anyInt(), any()); 761 } 762 763 @Test testStartProfile_fullUserFails()764 public void testStartProfile_fullUserFails() { 765 setUpUser(TEST_USER_ID1, 0); 766 assertThrows(IllegalArgumentException.class, 767 () -> mUserController.startProfile(TEST_USER_ID1, /* evenWhenDisabled= */ false, 768 /* unlockListener= */ null)); 769 770 verifyUserNeverAssignedToDisplay(); 771 } 772 773 @Test testStopProfile_fullUserFails()774 public void testStopProfile_fullUserFails() throws Exception { 775 setUpAndStartUserInBackground(TEST_USER_ID1); 776 assertThrows(IllegalArgumentException.class, 777 () -> mUserController.stopProfile(TEST_USER_ID1)); 778 verifyUserUnassignedFromDisplayNeverCalled(TEST_USER_ID); 779 } 780 781 @Test testStartProfile_disabledProfileFails()782 public void testStartProfile_disabledProfileFails() { 783 setUpUser(TEST_USER_ID1, UserInfo.FLAG_PROFILE | UserInfo.FLAG_DISABLED, /* preCreated= */ 784 false, UserManager.USER_TYPE_PROFILE_MANAGED); 785 assertThat(mUserController.startProfile(TEST_USER_ID1, /* evenWhenDisabled=*/ false, 786 /* unlockListener= */ null)).isFalse(); 787 788 verifyUserNeverAssignedToDisplay(); 789 } 790 791 @Test testStartProfile()792 public void testStartProfile() throws Exception { 793 setUpAndStartProfileInBackground(TEST_USER_ID1); 794 795 startBackgroundUserAssertions(); 796 verifyUserAssignedToDisplay(TEST_USER_ID1, Display.DEFAULT_DISPLAY); 797 } 798 799 @Test testStartProfile_whenUsersOnSecondaryDisplaysIsEnabled()800 public void testStartProfile_whenUsersOnSecondaryDisplaysIsEnabled() throws Exception { 801 mockIsUsersOnSecondaryDisplaysEnabled(true); 802 803 setUpAndStartProfileInBackground(TEST_USER_ID1); 804 805 startBackgroundUserAssertions(); 806 verifyUserAssignedToDisplay(TEST_USER_ID1, Display.DEFAULT_DISPLAY); 807 } 808 809 @Test testStopProfile()810 public void testStopProfile() throws Exception { 811 setUpAndStartProfileInBackground(TEST_USER_ID1); 812 assertProfileLockedOrUnlockedAfterStopping(TEST_USER_ID1, /* expectLocking= */ true); 813 verifyUserUnassignedFromDisplay(TEST_USER_ID1); 814 } 815 816 /** Tests handleIncomingUser() for a variety of permissions and situations. */ 817 @Test testHandleIncomingUser()818 public void testHandleIncomingUser() throws Exception { 819 final UserInfo user1a = new UserInfo(111, "user1a", 0); 820 final UserInfo user1b = new UserInfo(112, "user1b", 0); 821 final UserInfo user2 = new UserInfo(113, "user2", 0); 822 // user1a and user2b are in the same profile group; user2 is in a different one. 823 user1a.profileGroupId = 5; 824 user1b.profileGroupId = 5; 825 user2.profileGroupId = 6; 826 827 final List<UserInfo> users = Arrays.asList(user1a, user1b, user2); 828 when(mInjector.mUserManagerMock.getUsers(false)).thenReturn(users); 829 mUserController.onSystemReady(); // To set the profileGroupIds in UserController. 830 831 832 // Has INTERACT_ACROSS_USERS_FULL. 833 when(mInjector.checkComponentPermission( 834 eq(INTERACT_ACROSS_USERS_FULL), anyInt(), anyInt(), anyInt(), anyBoolean())) 835 .thenReturn(PackageManager.PERMISSION_GRANTED); 836 when(mInjector.checkComponentPermission( 837 eq(INTERACT_ACROSS_USERS), anyInt(), anyInt(), anyInt(), anyBoolean())) 838 .thenReturn(PackageManager.PERMISSION_DENIED); 839 when(mInjector.checkPermissionForPreflight( 840 eq(INTERACT_ACROSS_PROFILES), anyInt(), anyInt(), any())).thenReturn(false); 841 842 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL, true); 843 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL_IN_PROFILE, true); 844 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_FULL_ONLY, true); 845 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_PROFILES_OR_NON_FULL, true); 846 847 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL, true); 848 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL_IN_PROFILE, true); 849 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_FULL_ONLY, true); 850 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_PROFILES_OR_NON_FULL, true); 851 852 853 // Has INTERACT_ACROSS_USERS. 854 when(mInjector.checkComponentPermission( 855 eq(INTERACT_ACROSS_USERS_FULL), anyInt(), anyInt(), anyInt(), anyBoolean())) 856 .thenReturn(PackageManager.PERMISSION_DENIED); 857 when(mInjector.checkComponentPermission( 858 eq(INTERACT_ACROSS_USERS), anyInt(), anyInt(), anyInt(), anyBoolean())) 859 .thenReturn(PackageManager.PERMISSION_GRANTED); 860 when(mInjector.checkPermissionForPreflight( 861 eq(INTERACT_ACROSS_PROFILES), anyInt(), anyInt(), any())).thenReturn(false); 862 863 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL, true); 864 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL_IN_PROFILE, false); 865 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_FULL_ONLY, false); 866 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_PROFILES_OR_NON_FULL, true); 867 868 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL, true); 869 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL_IN_PROFILE, true); 870 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_FULL_ONLY, false); 871 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_PROFILES_OR_NON_FULL, true); 872 873 874 // Has INTERACT_ACROSS_PROFILES. 875 when(mInjector.checkComponentPermission( 876 eq(INTERACT_ACROSS_USERS_FULL), anyInt(), anyInt(), anyInt(), anyBoolean())) 877 .thenReturn(PackageManager.PERMISSION_DENIED); 878 when(mInjector.checkComponentPermission( 879 eq(INTERACT_ACROSS_USERS), anyInt(), anyInt(), anyInt(), anyBoolean())) 880 .thenReturn(PackageManager.PERMISSION_DENIED); 881 when(mInjector.checkPermissionForPreflight( 882 eq(INTERACT_ACROSS_PROFILES), anyInt(), anyInt(), any())).thenReturn(true); 883 884 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL, false); 885 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_NON_FULL_IN_PROFILE, false); 886 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_FULL_ONLY, false); 887 checkHandleIncomingUser(user1a.id, user2.id, ALLOW_PROFILES_OR_NON_FULL, false); 888 889 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL, false); 890 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_NON_FULL_IN_PROFILE, false); 891 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_FULL_ONLY, false); 892 checkHandleIncomingUser(user1a.id, user1b.id, ALLOW_PROFILES_OR_NON_FULL, true); 893 } 894 checkHandleIncomingUser(int fromUser, int toUser, int allowMode, boolean pass)895 private void checkHandleIncomingUser(int fromUser, int toUser, int allowMode, boolean pass) { 896 final int pid = 100; 897 final int uid = fromUser * UserHandle.PER_USER_RANGE + 34567 + fromUser; 898 final String name = "whatever"; 899 final String pkg = "some.package"; 900 final boolean allowAll = false; 901 902 if (pass) { 903 mUserController.handleIncomingUser(pid, uid, toUser, allowAll, allowMode, name, pkg); 904 } else { 905 assertThrows(SecurityException.class, () -> mUserController.handleIncomingUser( 906 pid, uid, toUser, allowAll, allowMode, name, pkg)); 907 } 908 } 909 910 @Test testScheduleOnUserCompletedEvent()911 public void testScheduleOnUserCompletedEvent() throws Exception { 912 // user1 is starting, switching, and unlocked, but not scheduled unlocked yet 913 // user2 is starting and had unlocked but isn't unlocked anymore for whatever reason 914 915 final int user1 = 101; 916 final int user2 = 102; 917 setUpUser(user1, 0); 918 setUpUser(user2, 0); 919 920 mUserController.startUser(user1, USER_START_MODE_FOREGROUND); 921 mUserController.getStartedUserState(user1).setState(UserState.STATE_RUNNING_UNLOCKED); 922 923 mUserController.startUser(user2, USER_START_MODE_BACKGROUND); 924 mUserController.getStartedUserState(user2).setState(UserState.STATE_RUNNING_LOCKED); 925 926 final int event1a = SystemService.UserCompletedEventType.EVENT_TYPE_USER_STARTING; 927 final int event1b = SystemService.UserCompletedEventType.EVENT_TYPE_USER_SWITCHING; 928 929 final int event2a = SystemService.UserCompletedEventType.EVENT_TYPE_USER_STARTING; 930 final int event2b = SystemService.UserCompletedEventType.EVENT_TYPE_USER_UNLOCKED; 931 932 933 mUserController.scheduleOnUserCompletedEvent(user1, event1a, 2000); 934 assertNotNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user1)); 935 assertNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user2)); 936 937 mUserController.scheduleOnUserCompletedEvent(user2, event2a, 2000); 938 assertNotNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user1)); 939 assertNotNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user2)); 940 941 mUserController.scheduleOnUserCompletedEvent(user2, event2b, 2000); 942 mUserController.scheduleOnUserCompletedEvent(user1, event1b, 2000); 943 mUserController.scheduleOnUserCompletedEvent(user1, 0, 2000); 944 945 assertNotNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user1)); 946 assertNotNull(mInjector.mHandler.getMessageForCode(USER_COMPLETED_EVENT_MSG, user2)); 947 948 mUserController.reportOnUserCompletedEvent(user1); 949 verify(mInjector, times(1)) 950 .systemServiceManagerOnUserCompletedEvent(eq(user1), eq(event1a | event1b)); 951 verify(mInjector, never()).systemServiceManagerOnUserCompletedEvent(eq(user2), anyInt()); 952 953 mUserController.reportOnUserCompletedEvent(user2); 954 verify(mInjector, times(1)) 955 .systemServiceManagerOnUserCompletedEvent(eq(user2), eq(event2a)); 956 } 957 958 @Test testStallUserSwitchUntilTheKeyguardIsShown()959 public void testStallUserSwitchUntilTheKeyguardIsShown() throws Exception { 960 // enable user switch ui, because keyguard is only shown then 961 mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, 962 /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); 963 964 // mock the device to be secure in order to expect the keyguard to be shown 965 when(mInjector.mKeyguardManagerMock.isDeviceSecure(anyInt())).thenReturn(true); 966 967 // call real lockDeviceNowAndWaitForKeyguardShown method for this test 968 doCallRealMethod().when(mInjector).lockDeviceNowAndWaitForKeyguardShown(); 969 970 // call startUser on a thread because we're expecting it to be blocked 971 Thread threadStartUser = new Thread(()-> { 972 mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); 973 }); 974 threadStartUser.start(); 975 976 // make sure the switch is stalled... 977 Thread.sleep(2000); 978 // by checking REPORT_USER_SWITCH_MSG is not sent yet 979 assertNull(mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG)); 980 // and the thread is still alive 981 assertTrue(threadStartUser.isAlive()); 982 983 // mock send the keyguard shown event 984 ArgumentCaptor<ActivityTaskManagerInternal.ScreenObserver> captor = ArgumentCaptor.forClass( 985 ActivityTaskManagerInternal.ScreenObserver.class); 986 verify(mInjector.mActivityTaskManagerInternal).registerScreenObserver(captor.capture()); 987 captor.getValue().onKeyguardStateChanged(true); 988 989 // verify the switch now moves on... 990 Thread.sleep(1000); 991 // by checking REPORT_USER_SWITCH_MSG is sent 992 assertNotNull(mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG)); 993 // and the thread is finished 994 assertFalse(threadStartUser.isAlive()); 995 } 996 setUpAndStartUserInBackground(int userId)997 private void setUpAndStartUserInBackground(int userId) throws Exception { 998 setUpUser(userId, 0); 999 mUserController.startUser(userId, USER_START_MODE_BACKGROUND); 1000 verify(mInjector.mLockPatternUtilsMock, times(1)).unlockUserKeyIfUnsecured(userId); 1001 mUserStates.put(userId, mUserController.getStartedUserState(userId)); 1002 } 1003 setUpAndStartProfileInBackground(int userId)1004 private void setUpAndStartProfileInBackground(int userId) throws Exception { 1005 setUpUser(userId, UserInfo.FLAG_PROFILE, false, UserManager.USER_TYPE_PROFILE_MANAGED); 1006 assertThat(mUserController.startProfile(userId, /* evenWhenDisabled=*/ false, 1007 /* unlockListener= */ null)).isTrue(); 1008 1009 verify(mInjector.mLockPatternUtilsMock, times(1)).unlockUserKeyIfUnsecured(userId); 1010 mUserStates.put(userId, mUserController.getStartedUserState(userId)); 1011 } 1012 assertUserLockedOrUnlockedAfterStopping(int userId, boolean delayedLocking, KeyEvictedCallback keyEvictedCallback, boolean expectLocking)1013 private void assertUserLockedOrUnlockedAfterStopping(int userId, boolean delayedLocking, 1014 KeyEvictedCallback keyEvictedCallback, boolean expectLocking) throws Exception { 1015 int r = mUserController.stopUser(userId, /* force= */ true, /* delayedLocking= */ 1016 delayedLocking, null, keyEvictedCallback); 1017 assertThat(r).isEqualTo(ActivityManager.USER_OP_SUCCESS); 1018 assertUserLockedOrUnlockedState(userId, delayedLocking, expectLocking); 1019 } 1020 assertProfileLockedOrUnlockedAfterStopping(int userId, boolean expectLocking)1021 private void assertProfileLockedOrUnlockedAfterStopping(int userId, boolean expectLocking) 1022 throws Exception { 1023 boolean profileStopped = mUserController.stopProfile(userId); 1024 assertThat(profileStopped).isTrue(); 1025 assertUserLockedOrUnlockedState(userId, /* delayedLocking= */ false, expectLocking); 1026 } 1027 assertUserLockedOrUnlockedState(int userId, boolean delayedLocking, boolean expectLocking)1028 private void assertUserLockedOrUnlockedState(int userId, boolean delayedLocking, 1029 boolean expectLocking) throws InterruptedException, RemoteException { 1030 // fake all interim steps 1031 UserState ussUser = mUserStates.get(userId); 1032 ussUser.setState(UserState.STATE_SHUTDOWN); 1033 // Passing delayedLocking invalidates incorrect internal data passing but currently there is 1034 // no easy way to get that information passed through lambda. 1035 mUserController.finishUserStopped(ussUser, delayedLocking); 1036 waitForHandlerToComplete(FgThread.getHandler(), HANDLER_WAIT_TIME_MS); 1037 verify(mInjector.mStorageManagerMock, times(expectLocking ? 1 : 0)) 1038 .lockUserKey(userId); 1039 } 1040 addForegroundUserAndContinueUserSwitch(int newUserId, int expectedOldUserId, int expectedNumberOfCalls, boolean expectOldUserStopping)1041 private void addForegroundUserAndContinueUserSwitch(int newUserId, int expectedOldUserId, 1042 int expectedNumberOfCalls, boolean expectOldUserStopping) { 1043 // Start user -- this will update state of mUserController 1044 mUserController.startUser(newUserId, USER_START_MODE_FOREGROUND); 1045 Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); 1046 assertNotNull(reportMsg); 1047 UserState userState = (UserState) reportMsg.obj; 1048 int oldUserId = reportMsg.arg1; 1049 assertEquals(expectedOldUserId, oldUserId); 1050 assertEquals(newUserId, reportMsg.arg2); 1051 mUserStates.put(newUserId, userState); 1052 mInjector.mHandler.clearAllRecordedMessages(); 1053 // Verify that continueUserSwitch worked as expected 1054 continueAndCompleteUserSwitch(userState, oldUserId, newUserId); 1055 verify(mInjector, times(expectedNumberOfCalls)).dismissUserSwitchingDialog(any()); 1056 continueUserSwitchAssertions(oldUserId, newUserId, expectOldUserStopping); 1057 } 1058 setUpUser(@serIdInt int userId, @UserInfoFlag int flags)1059 private void setUpUser(@UserIdInt int userId, @UserInfoFlag int flags) { 1060 setUpUser(userId, flags, /* preCreated= */ false, /* userType */ null); 1061 } 1062 setUpUser(@serIdInt int userId, @UserInfoFlag int flags, boolean preCreated, @Nullable String userType)1063 private void setUpUser(@UserIdInt int userId, @UserInfoFlag int flags, boolean preCreated, 1064 @Nullable String userType) { 1065 if (userType == null) { 1066 userType = UserInfo.getDefaultUserType(flags); 1067 } 1068 UserInfo userInfo = new UserInfo(userId, "User" + userId, /* iconPath= */ null, flags, 1069 userType); 1070 userInfo.preCreated = preCreated; 1071 when(mInjector.mUserManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo); 1072 when(mInjector.mUserManagerMock.isPreCreated(userId)).thenReturn(preCreated); 1073 } 1074 getActions(List<Intent> intents)1075 private static List<String> getActions(List<Intent> intents) { 1076 List<String> result = new ArrayList<>(); 1077 for (Intent intent : intents) { 1078 result.add(intent.getAction()); 1079 } 1080 return result; 1081 } 1082 waitForHandlerToComplete(Handler handler, long waitTimeMs)1083 private void waitForHandlerToComplete(Handler handler, long waitTimeMs) 1084 throws InterruptedException { 1085 final Object lock = new Object(); 1086 synchronized (lock) { 1087 handler.post(() -> { 1088 synchronized (lock) { 1089 lock.notify(); 1090 } 1091 }); 1092 lock.wait(waitTimeMs); 1093 } 1094 } 1095 mockIsHeadlessSystemUserMode(boolean value)1096 private void mockIsHeadlessSystemUserMode(boolean value) { 1097 when(mInjector.isHeadlessSystemUserMode()).thenReturn(value); 1098 } 1099 mockIsUsersOnSecondaryDisplaysEnabled(boolean value)1100 private void mockIsUsersOnSecondaryDisplaysEnabled(boolean value) { 1101 when(mInjector.isUsersOnSecondaryDisplaysEnabled()).thenReturn(value); 1102 } 1103 verifyUserAssignedToDisplay(@serIdInt int userId, int displayId)1104 private void verifyUserAssignedToDisplay(@UserIdInt int userId, int displayId) { 1105 verify(mInjector.getUserManagerInternal()).assignUserToDisplayOnStart(eq(userId), anyInt(), 1106 anyInt(), eq(displayId)); 1107 } 1108 verifyUserNeverAssignedToDisplay()1109 private void verifyUserNeverAssignedToDisplay() { 1110 verify(mInjector.getUserManagerInternal(), never()).assignUserToDisplayOnStart(anyInt(), 1111 anyInt(), anyInt(), anyInt()); 1112 } 1113 verifyUserUnassignedFromDisplay(@serIdInt int userId)1114 private void verifyUserUnassignedFromDisplay(@UserIdInt int userId) { 1115 verify(mInjector.getUserManagerInternal()).unassignUserFromDisplayOnStop(userId); 1116 } 1117 verifyUserUnassignedFromDisplayNeverCalled(@serIdInt int userId)1118 private void verifyUserUnassignedFromDisplayNeverCalled(@UserIdInt int userId) { 1119 verify(mInjector.getUserManagerInternal(), never()).unassignUserFromDisplayOnStop(userId); 1120 } 1121 verifySystemUserVisibilityChangesNeverNotified()1122 private void verifySystemUserVisibilityChangesNeverNotified() { 1123 verify(mInjector, never()).onSystemUserVisibilityChanged(anyBoolean()); 1124 } 1125 1126 // Should be public to allow mocking 1127 private static class TestInjector extends UserController.Injector { 1128 public final TestHandler mHandler; 1129 public final HandlerThread mHandlerThread; 1130 public final UserManagerService mUserManagerMock; 1131 public final List<Intent> mSentIntents = new ArrayList<>(); 1132 1133 private final TestHandler mUiHandler; 1134 1135 private final IStorageManager mStorageManagerMock; 1136 private final UserManagerInternal mUserManagerInternalMock; 1137 private final WindowManagerService mWindowManagerMock; 1138 private final ActivityTaskManagerInternal mActivityTaskManagerInternal; 1139 private final KeyguardManager mKeyguardManagerMock; 1140 private final LockPatternUtils mLockPatternUtilsMock; 1141 1142 private final UserJourneyLogger mUserJourneyLoggerMock; 1143 1144 private final Context mCtx; 1145 1146 private Integer mRelevantUser; 1147 TestInjector(Context ctx)1148 TestInjector(Context ctx) { 1149 super(null); 1150 mCtx = ctx; 1151 mHandlerThread = new HandlerThread(TAG); 1152 mHandlerThread.start(); 1153 mHandler = new TestHandler(mHandlerThread.getLooper()); 1154 mUiHandler = new TestHandler(mHandlerThread.getLooper()); 1155 mUserManagerMock = mock(UserManagerService.class); 1156 mUserManagerInternalMock = mock(UserManagerInternal.class); 1157 mWindowManagerMock = mock(WindowManagerService.class); 1158 mActivityTaskManagerInternal = mock(ActivityTaskManagerInternal.class); 1159 mStorageManagerMock = mock(IStorageManager.class); 1160 mKeyguardManagerMock = mock(KeyguardManager.class); 1161 when(mKeyguardManagerMock.isDeviceSecure(anyInt())).thenReturn(true); 1162 mLockPatternUtilsMock = mock(LockPatternUtils.class); 1163 mUserJourneyLoggerMock = mock(UserJourneyLogger.class); 1164 } 1165 1166 @Override getHandler(Handler.Callback callback)1167 protected Handler getHandler(Handler.Callback callback) { 1168 return mHandler; 1169 } 1170 1171 @Override getUiHandler(Handler.Callback callback)1172 protected Handler getUiHandler(Handler.Callback callback) { 1173 return mUiHandler; 1174 } 1175 1176 @Override getUserManager()1177 protected UserManagerService getUserManager() { 1178 return mUserManagerMock; 1179 } 1180 1181 @Override getUserManagerInternal()1182 UserManagerInternal getUserManagerInternal() { 1183 return mUserManagerInternalMock; 1184 } 1185 1186 @Override getContext()1187 protected Context getContext() { 1188 return mCtx; 1189 } 1190 1191 @Override checkCallingPermission(String permission)1192 int checkCallingPermission(String permission) { 1193 Log.i(TAG, "checkCallingPermission " + permission); 1194 return PERMISSION_GRANTED; 1195 } 1196 1197 @Override checkComponentPermission(String permission, int pid, int uid, int owner, boolean exp)1198 int checkComponentPermission(String permission, int pid, int uid, int owner, boolean exp) { 1199 Log.i(TAG, "checkComponentPermission " + permission); 1200 return PERMISSION_GRANTED; 1201 } 1202 1203 @Override checkPermissionForPreflight(String permission, int pid, int uid, String pkg)1204 boolean checkPermissionForPreflight(String permission, int pid, int uid, String pkg) { 1205 Log.i(TAG, "checkPermissionForPreflight " + permission); 1206 return true; 1207 } 1208 1209 @Override isCallerRecents(int uid)1210 boolean isCallerRecents(int uid) { 1211 return false; 1212 } 1213 1214 @Override getWindowManager()1215 WindowManagerService getWindowManager() { 1216 return mWindowManagerMock; 1217 } 1218 1219 @Override getActivityTaskManagerInternal()1220 ActivityTaskManagerInternal getActivityTaskManagerInternal() { 1221 return mActivityTaskManagerInternal; 1222 } 1223 1224 @Override getKeyguardManager()1225 KeyguardManager getKeyguardManager() { 1226 return mKeyguardManagerMock; 1227 } 1228 1229 @Override updateUserConfiguration()1230 void updateUserConfiguration() { 1231 Log.i(TAG, "updateUserConfiguration"); 1232 } 1233 1234 @Override broadcastIntent(Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)1235 protected int broadcastIntent(Intent intent, String resolvedType, 1236 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, 1237 String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, 1238 boolean sticky, int callingPid, int callingUid, int realCallingUid, 1239 int realCallingPid, int userId) { 1240 Log.i(TAG, "broadcastIntentLocked " + intent); 1241 if (mRelevantUser == null || mRelevantUser == userId || userId == UserHandle.USER_ALL) { 1242 mSentIntents.add(intent); 1243 } 1244 return 0; 1245 } 1246 1247 @Override reportGlobalUsageEvent(int event)1248 void reportGlobalUsageEvent(int event) { 1249 } 1250 1251 @Override reportCurWakefulnessUsageEvent()1252 void reportCurWakefulnessUsageEvent() { 1253 } 1254 1255 @Override isRuntimeRestarted()1256 boolean isRuntimeRestarted() { 1257 // to pass all metrics related calls 1258 return true; 1259 } 1260 1261 @Override getStorageManager()1262 protected IStorageManager getStorageManager() { 1263 return mStorageManagerMock; 1264 } 1265 1266 @Override dismissKeyguard(Runnable runnable)1267 protected void dismissKeyguard(Runnable runnable) { 1268 runnable.run(); 1269 } 1270 1271 @Override showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser, String switchingFromSystemUserMessage, String switchingToSystemUserMessage, Runnable onShown)1272 void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser, 1273 String switchingFromSystemUserMessage, String switchingToSystemUserMessage, 1274 Runnable onShown) { 1275 if (onShown != null) { 1276 onShown.run(); 1277 } 1278 } 1279 1280 @Override dismissUserSwitchingDialog(Runnable onDismissed)1281 void dismissUserSwitchingDialog(Runnable onDismissed) { 1282 if (onDismissed != null) { 1283 onDismissed.run(); 1284 } 1285 } 1286 1287 @Override getLockPatternUtils()1288 protected LockPatternUtils getLockPatternUtils() { 1289 return mLockPatternUtilsMock; 1290 } 1291 1292 @Override onUserStarting(@serIdInt int userId)1293 void onUserStarting(@UserIdInt int userId) { 1294 Log.i(TAG, "onUserStarting(" + userId + ")"); 1295 } 1296 1297 @Override onSystemUserVisibilityChanged(boolean visible)1298 void onSystemUserVisibilityChanged(boolean visible) { 1299 Log.i(TAG, "onSystemUserVisibilityChanged(" + visible + ")"); 1300 } 1301 1302 @Override getUserJourneyLogger()1303 protected UserJourneyLogger getUserJourneyLogger() { 1304 return mUserJourneyLoggerMock; 1305 } 1306 } 1307 1308 private static class TestHandler extends Handler { 1309 private final List<Message> mMessages = new ArrayList<>(); 1310 TestHandler(Looper looper)1311 TestHandler(Looper looper) { 1312 super(looper); 1313 } 1314 getMessageCodes()1315 Set<Integer> getMessageCodes() { 1316 Set<Integer> result = new LinkedHashSet<>(); 1317 for (Message msg : mMessages) { 1318 result.add(msg.what); 1319 } 1320 return result; 1321 } 1322 getMessageForCode(int what)1323 Message getMessageForCode(int what) { 1324 return getMessageForCode(what, null); 1325 } 1326 getMessageForCode(int what, Object obj)1327 Message getMessageForCode(int what, Object obj) { 1328 for (Message msg : mMessages) { 1329 if (msg.what == what && (obj == null || obj.equals(msg.obj))) { 1330 return msg; 1331 } 1332 } 1333 return null; 1334 } 1335 clearAllRecordedMessages()1336 void clearAllRecordedMessages() { 1337 mMessages.clear(); 1338 } 1339 1340 @Override sendMessageAtTime(Message msg, long uptimeMillis)1341 public boolean sendMessageAtTime(Message msg, long uptimeMillis) { 1342 Message copy = new Message(); 1343 copy.copyFrom(msg); 1344 mMessages.add(copy); 1345 if (msg.getCallback() != null) { 1346 msg.getCallback().run(); 1347 msg.setCallback(null); 1348 } 1349 return super.sendMessageAtTime(msg, uptimeMillis); 1350 } 1351 } 1352 } 1353