DevicePolicyManagerTest.java revision d2a73ed21152517097a603e03c08eafbce926c3d
1/* 2 * Copyright (C) 2015 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 */ 16package com.android.server.devicepolicy; 17 18import android.Manifest.permission; 19import android.app.Activity; 20import android.app.admin.DeviceAdminReceiver; 21import android.app.admin.DevicePolicyManager; 22import android.app.admin.DevicePolicyManagerInternal; 23import android.content.BroadcastReceiver; 24import android.content.ComponentName; 25import android.content.Context; 26import android.content.Intent; 27import android.content.ServiceConnection; 28import android.content.pm.ApplicationInfo; 29import android.content.pm.PackageInfo; 30import android.content.pm.PackageManager; 31import android.content.res.Resources; 32import android.graphics.Color; 33import android.net.IIpConnectivityMetrics; 34import android.content.pm.UserInfo; 35import android.net.wifi.WifiInfo; 36import android.os.Build.VERSION_CODES; 37import android.os.Bundle; 38import android.os.IBinder; 39import android.os.Process; 40import android.os.UserHandle; 41import android.os.UserManager; 42import android.provider.Settings; 43import android.telephony.TelephonyManager; 44import android.test.MoreAsserts; 45import android.test.suitebuilder.annotation.SmallTest; 46import android.util.ArraySet; 47import android.util.Pair; 48 49import com.android.internal.R; 50import com.android.server.LocalServices; 51import com.android.server.SystemService; 52import com.android.server.pm.UserRestrictionsUtils; 53 54import org.mockito.invocation.InvocationOnMock; 55import org.mockito.stubbing.Answer; 56 57import java.util.ArrayList; 58import java.util.Arrays; 59import java.util.Collections; 60import java.util.HashMap; 61import java.util.List; 62import java.util.Map; 63import java.util.Set; 64 65import static org.mockito.Matchers.any; 66import static org.mockito.Matchers.anyInt; 67import static org.mockito.Matchers.anyObject; 68import static org.mockito.Matchers.anyString; 69import static org.mockito.Matchers.eq; 70import static org.mockito.Matchers.isNull; 71import static org.mockito.Mockito.atLeast; 72import static org.mockito.Mockito.doAnswer; 73import static org.mockito.Mockito.doReturn; 74import static org.mockito.Mockito.never; 75import static org.mockito.Mockito.reset; 76import static org.mockito.Mockito.times; 77import static org.mockito.Mockito.verify; 78import static org.mockito.Mockito.when; 79 80/** 81 * Tests for DevicePolicyManager( and DevicePolicyManagerService). 82 * You can run them via: 83 m FrameworksServicesTests && 84 adb install \ 85 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && 86 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \ 87 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner 88 89 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) 90 * 91 * , or: 92 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services 93 */ 94@SmallTest 95public class DevicePolicyManagerTest extends DpmTestBase { 96 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList( 97 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, 98 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL); 99 100 private DpmMockContext mContext; 101 public DevicePolicyManager dpm; 102 public DevicePolicyManagerServiceTestable dpms; 103 104 @Override 105 protected void setUp() throws Exception { 106 super.setUp(); 107 108 mContext = getContext(); 109 110 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 111 .thenReturn(true); 112 113 // By default, pretend all users are running and unlocked. 114 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 115 116 initializeDpms(); 117 118 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 119 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 120 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID); 121 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID); 122 123 setUpUserManager(); 124 } 125 126 private void initializeDpms() { 127 // Need clearCallingIdentity() to pass permission checks. 128 final long ident = mContext.binder.clearCallingIdentity(); 129 try { 130 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 131 132 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); 133 134 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); 135 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); 136 137 dpm = new DevicePolicyManagerTestable(mContext, dpms); 138 } finally { 139 mContext.binder.restoreCallingIdentity(ident); 140 } 141 } 142 143 private void setUpUserManager() { 144 // Emulate UserManager.set/getApplicationRestriction(). 145 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>(); 146 147 // UM.setApplicationRestrictions() will save to appRestrictions. 148 doAnswer(new Answer<Void>() { 149 @Override 150 public Void answer(InvocationOnMock invocation) throws Throwable { 151 String pkg = (String) invocation.getArguments()[0]; 152 Bundle bundle = (Bundle) invocation.getArguments()[1]; 153 UserHandle user = (UserHandle) invocation.getArguments()[2]; 154 155 appRestrictions.put(Pair.create(pkg, user), bundle); 156 157 return null; 158 } 159 }).when(mContext.userManager).setApplicationRestrictions( 160 anyString(), any(Bundle.class), any(UserHandle.class)); 161 162 // UM.getApplicationRestrictions() will read from appRestrictions. 163 doAnswer(new Answer<Bundle>() { 164 @Override 165 public Bundle answer(InvocationOnMock invocation) throws Throwable { 166 String pkg = (String) invocation.getArguments()[0]; 167 UserHandle user = (UserHandle) invocation.getArguments()[1]; 168 169 return appRestrictions.get(Pair.create(pkg, user)); 170 } 171 }).when(mContext.userManager).getApplicationRestrictions( 172 anyString(), any(UserHandle.class)); 173 174 // Add the first secondary user. 175 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0); 176 } 177 178 private void setAsProfileOwner(ComponentName admin) { 179 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 180 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 181 182 // PO needs to be an DA. 183 dpm.setActiveAdmin(admin, /* replace =*/ false); 184 185 // Fire! 186 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 187 188 // Check 189 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); 190 } 191 192 public void testHasNoFeature() throws Exception { 193 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 194 .thenReturn(false); 195 196 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 197 new DevicePolicyManagerServiceTestable(mContext, dataDir); 198 199 // If the device has no DPMS feature, it shouldn't register the local service. 200 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); 201 } 202 203 /** 204 * Caller doesn't have proper permissions. 205 */ 206 public void testSetActiveAdmin_SecurityException() { 207 // 1. Failure cases. 208 209 // Caller doesn't have MANAGE_DEVICE_ADMINS. 210 try { 211 dpm.setActiveAdmin(admin1, false); 212 fail("Didn't throw SecurityException"); 213 } catch (SecurityException expected) { 214 } 215 216 // Caller has MANAGE_DEVICE_ADMINS, but for different user. 217 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 218 try { 219 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1); 220 fail("Didn't throw SecurityException"); 221 } catch (SecurityException expected) { 222 } 223 } 224 225 /** 226 * Test for: 227 * {@link DevicePolicyManager#setActiveAdmin} 228 * with replace=false and replace=true 229 * {@link DevicePolicyManager#isAdminActive} 230 * {@link DevicePolicyManager#isAdminActiveAsUser} 231 * {@link DevicePolicyManager#getActiveAdmins} 232 * {@link DevicePolicyManager#getActiveAdminsAsUser} 233 */ 234 public void testSetActiveAdmin() throws Exception { 235 // 1. Make sure the caller has proper permissions. 236 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 237 238 // 2. Call the API. 239 dpm.setActiveAdmin(admin1, /* replace =*/ false); 240 241 // 3. Verify internal calls. 242 243 // Check if the boradcast is sent. 244 verify(mContext.spiedContext).sendBroadcastAsUser( 245 MockUtils.checkIntentAction( 246 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 247 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 248 verify(mContext.spiedContext).sendBroadcastAsUser( 249 MockUtils.checkIntentAction( 250 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED), 251 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 252 253 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 254 eq(admin1.getPackageName()), 255 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 256 eq(PackageManager.DONT_KILL_APP), 257 eq(DpmMockContext.CALLER_USER_HANDLE), 258 anyString()); 259 260 // TODO Verify other calls too. 261 262 // Make sure it's active admin1. 263 assertTrue(dpm.isAdminActive(admin1)); 264 assertFalse(dpm.isAdminActive(admin2)); 265 assertFalse(dpm.isAdminActive(admin3)); 266 267 // But not admin1 for a different user. 268 269 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL. 270 // (Because we're checking a different user's status from CALLER_USER_HANDLE.) 271 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 272 273 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1)); 274 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1)); 275 276 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 277 278 // Next, add one more admin. 279 // Before doing so, update the application info, now it's enabled. 280 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID, 281 PackageManager.COMPONENT_ENABLED_STATE_ENABLED); 282 283 dpm.setActiveAdmin(admin2, /* replace =*/ false); 284 285 // Now we have two admins. 286 assertTrue(dpm.isAdminActive(admin1)); 287 assertTrue(dpm.isAdminActive(admin2)); 288 assertFalse(dpm.isAdminActive(admin3)); 289 290 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called 291 // again. (times(1) because it was previously called for admin1) 292 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 293 eq(admin1.getPackageName()), 294 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 295 eq(PackageManager.DONT_KILL_APP), 296 eq(DpmMockContext.CALLER_USER_HANDLE), 297 anyString()); 298 299 // 4. Add the same admin1 again without replace, which should throw. 300 try { 301 dpm.setActiveAdmin(admin1, /* replace =*/ false); 302 fail("Didn't throw"); 303 } catch (IllegalArgumentException expected) { 304 } 305 306 // 5. Add the same admin1 again with replace, which should succeed. 307 dpm.setActiveAdmin(admin1, /* replace =*/ true); 308 309 // TODO make sure it's replaced. 310 311 // 6. Test getActiveAdmins() 312 List<ComponentName> admins = dpm.getActiveAdmins(); 313 assertEquals(2, admins.size()); 314 assertEquals(admin1, admins.get(0)); 315 assertEquals(admin2, admins.get(1)); 316 317 // Another user has no admins. 318 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 319 320 assertEquals(0, DpmTestUtils.getListSizeAllowingNull( 321 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1))); 322 323 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 324 } 325 326 public void testSetActiveAdmin_multiUsers() throws Exception { 327 328 final int ANOTHER_USER_ID = 100; 329 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456); 330 331 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 332 333 // Set up pacakge manager for the other user. 334 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 335 336 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 337 338 dpm.setActiveAdmin(admin1, /* replace =*/ false); 339 340 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 341 dpm.setActiveAdmin(admin2, /* replace =*/ false); 342 343 344 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 345 assertTrue(dpm.isAdminActive(admin1)); 346 assertFalse(dpm.isAdminActive(admin2)); 347 348 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 349 assertFalse(dpm.isAdminActive(admin1)); 350 assertTrue(dpm.isAdminActive(admin2)); 351 } 352 353 /** 354 * Test for: 355 * {@link DevicePolicyManager#setActiveAdmin} 356 * with replace=false 357 */ 358 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception { 359 // 1. Make sure the caller has proper permissions. 360 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 361 362 dpm.setActiveAdmin(admin1, /* replace =*/ false); 363 assertTrue(dpm.isAdminActive(admin1)); 364 365 // Add the same admin1 again without replace, which should throw. 366 try { 367 dpm.setActiveAdmin(admin1, /* replace =*/ false); 368 fail("Didn't throw"); 369 } catch (IllegalArgumentException expected) { 370 } 371 } 372 373 /** 374 * Test for: 375 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with 376 * BIND_DEVICE_ADMIN. 377 */ 378 public void testSetActiveAdmin_permissionCheck() throws Exception { 379 // 1. Make sure the caller has proper permissions. 380 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 381 382 try { 383 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 384 fail(); 385 } catch (IllegalArgumentException expected) { 386 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN)); 387 } 388 assertFalse(dpm.isAdminActive(adminNoPerm)); 389 390 // Change the target API level to MNC. Now it can be set as DA. 391 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null, 392 VERSION_CODES.M); 393 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 394 assertTrue(dpm.isAdminActive(adminNoPerm)); 395 396 // TODO Test the "load from the file" case where DA will still be loaded even without 397 // BIND_DEVICE_ADMIN and target API is N. 398 } 399 400 /** 401 * Test for: 402 * {@link DevicePolicyManager#removeActiveAdmin} 403 */ 404 public void testRemoveActiveAdmin_SecurityException() { 405 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 406 407 // Add admin. 408 409 dpm.setActiveAdmin(admin1, /* replace =*/ false); 410 411 assertTrue(dpm.isAdminActive(admin1)); 412 413 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 414 415 // Directly call the DPMS method with a different userid, which should fail. 416 try { 417 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1); 418 fail("Didn't throw SecurityException"); 419 } catch (SecurityException expected) { 420 } 421 422 // Try to remove active admin with a different caller userid should fail too, without 423 // having MANAGE_DEVICE_ADMINS. 424 mContext.callerPermissions.clear(); 425 426 // Change the caller, and call into DPMS directly with a different user-id. 427 428 mContext.binder.callingUid = 1234567; 429 try { 430 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 431 fail("Didn't throw SecurityException"); 432 } catch (SecurityException expected) { 433 } 434 } 435 436 /** 437 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked 438 * (because we can't send the remove broadcast). 439 */ 440 public void testRemoveActiveAdmin_userNotRunningOrLocked() { 441 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 442 443 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 444 445 // Add admin. 446 447 dpm.setActiveAdmin(admin1, /* replace =*/ false); 448 449 assertTrue(dpm.isAdminActive(admin1)); 450 451 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 452 453 // 1. User not unlocked. 454 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 455 .thenReturn(false); 456 try { 457 dpm.removeActiveAdmin(admin1); 458 fail("Didn't throw IllegalStateException"); 459 } catch (IllegalStateException expected) { 460 MoreAsserts.assertContainsRegex( 461 "User must be running and unlocked", expected.getMessage()); 462 } 463 464 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 465 466 // 2. User unlocked. 467 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 468 .thenReturn(true); 469 470 dpm.removeActiveAdmin(admin1); 471 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 472 } 473 474 /** 475 * Test for: 476 * {@link DevicePolicyManager#removeActiveAdmin} 477 */ 478 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() { 479 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 480 481 // Add admin1. 482 483 dpm.setActiveAdmin(admin1, /* replace =*/ false); 484 485 assertTrue(dpm.isAdminActive(admin1)); 486 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 487 488 // Different user, but should work, because caller has proper permissions. 489 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 490 491 // Change the caller, and call into DPMS directly with a different user-id. 492 mContext.binder.callingUid = 1234567; 493 494 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 495 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 496 497 // TODO DO Still can't be removed in this case. 498 } 499 500 /** 501 * Test for: 502 * {@link DevicePolicyManager#removeActiveAdmin} 503 */ 504 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() { 505 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. 506 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 507 508 // Add admin1. 509 510 dpm.setActiveAdmin(admin1, /* replace =*/ false); 511 512 assertTrue(dpm.isAdminActive(admin1)); 513 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 514 515 // Broadcast from saveSettingsLocked(). 516 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 517 MockUtils.checkIntentAction( 518 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 519 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 520 521 // Remove. No permissions, but same user, so it'll work. 522 mContext.callerPermissions.clear(); 523 dpm.removeActiveAdmin(admin1); 524 525 verify(mContext.spiedContext).sendOrderedBroadcastAsUser( 526 MockUtils.checkIntentAction( 527 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED), 528 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE), 529 isNull(String.class), 530 any(BroadcastReceiver.class), 531 eq(dpms.mHandler), 532 eq(Activity.RESULT_OK), 533 isNull(String.class), 534 isNull(Bundle.class)); 535 536 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 537 538 // Again broadcast from saveSettingsLocked(). 539 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 540 MockUtils.checkIntentAction( 541 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 542 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 543 544 // TODO Check other internal calls. 545 } 546 547 /** 548 * Test for: @{link DevicePolicyManager#setActivePasswordState} 549 * 550 * Validates that when the password for a user changes, the notification broadcast intent 551 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in 552 * addition to ones in the original user. 553 */ 554 public void testSetActivePasswordState_sendToProfiles() throws Exception { 555 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); 556 557 final int MANAGED_PROFILE_USER_ID = 78; 558 final int MANAGED_PROFILE_ADMIN_UID = 559 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID); 560 561 // Setup device owner. 562 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 563 mContext.packageName = admin1.getPackageName(); 564 setupDeviceOwner(); 565 566 // Add a managed profile belonging to the system user. 567 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 568 569 // Change the parent user's password. 570 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM); 571 572 // Both the device owner and the managed profile owner should receive this broadcast. 573 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); 574 intent.setComponent(admin1); 575 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM)); 576 577 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 578 MockUtils.checkIntent(intent), 579 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 580 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 581 MockUtils.checkIntent(intent), 582 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID)); 583 } 584 585 /** 586 * Test for: @{link DevicePolicyManager#setActivePasswordState} 587 * 588 * Validates that when the password for a managed profile changes, the notification broadcast 589 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not 590 * its parent. 591 */ 592 public void testSetActivePasswordState_notSentToParent() throws Exception { 593 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); 594 595 final int MANAGED_PROFILE_USER_ID = 78; 596 final int MANAGED_PROFILE_ADMIN_UID = 597 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID); 598 599 // Setup device owner. 600 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 601 mContext.packageName = admin1.getPackageName(); 602 doReturn(true).when(mContext.lockPatternUtils) 603 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID); 604 setupDeviceOwner(); 605 606 // Add a managed profile belonging to the system user. 607 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 608 609 // Change the profile's password. 610 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID); 611 612 // Both the device owner and the managed profile owner should receive this broadcast. 613 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); 614 intent.setComponent(admin1); 615 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID)); 616 617 verify(mContext.spiedContext, never()).sendBroadcastAsUser( 618 MockUtils.checkIntent(intent), 619 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 620 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 621 MockUtils.checkIntent(intent), 622 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID)); 623 } 624 /** 625 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully. 626 */ 627 public void testSetDeviceOwner() throws Exception { 628 setDeviceOwner(); 629 630 // Try to set a profile owner on the same user, which should fail. 631 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 632 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM); 633 try { 634 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM); 635 fail("IllegalStateException not thrown"); 636 } catch (IllegalStateException expected) { 637 assertTrue("Message was: " + expected.getMessage(), 638 expected.getMessage().contains("already has a device owner")); 639 } 640 641 // DO admin can't be deactivated. 642 dpm.removeActiveAdmin(admin1); 643 assertTrue(dpm.isAdminActive(admin1)); 644 645 // TODO Test getDeviceOwnerName() too. To do so, we need to change 646 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 647 } 648 649 private void setDeviceOwner() throws Exception { 650 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 651 mContext.callerPermissions.add(permission.MANAGE_USERS); 652 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 653 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 654 655 // In this test, change the caller user to "system". 656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 657 658 // Make sure admin1 is installed on system user. 659 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 660 661 // Check various get APIs. 662 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false); 663 664 // DO needs to be an DA. 665 dpm.setActiveAdmin(admin1, /* replace =*/ false); 666 667 // Fire! 668 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 669 670 // getDeviceOwnerComponent should return the admin1 component. 671 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 672 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 673 674 // Check various get APIs. 675 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true); 676 677 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users. 678 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 679 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 680 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 681 682 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 683 684 // Verify internal calls. 685 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 686 eq(admin1.getPackageName())); 687 688 // TODO We should check if the caller has called clearCallerIdentity(). 689 verify(mContext.ibackupManager, times(1)).setBackupServiceActive( 690 eq(UserHandle.USER_SYSTEM), eq(false)); 691 692 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 693 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 694 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 695 696 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 697 } 698 699 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) { 700 final int origCallingUser = mContext.binder.callingUid; 701 final List origPermissions = new ArrayList(mContext.callerPermissions); 702 mContext.callerPermissions.clear(); 703 704 mContext.callerPermissions.add(permission.MANAGE_USERS); 705 706 mContext.binder.callingUid = Process.SYSTEM_UID; 707 708 // TODO Test getDeviceOwnerName() too. To do so, we need to change 709 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 710 if (hasDeviceOwner) { 711 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 712 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 713 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 714 715 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 716 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 717 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 718 } else { 719 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 720 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 721 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 722 723 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 724 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 725 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 726 } 727 728 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 729 if (hasDeviceOwner) { 730 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 731 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 732 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 733 734 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 735 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 736 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 737 } else { 738 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 739 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 740 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 741 742 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 743 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 744 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 745 } 746 747 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 748 // Still with MANAGE_USERS. 749 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 750 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 751 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 752 753 if (hasDeviceOwner) { 754 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 755 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 756 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 757 } else { 758 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 759 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 760 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 761 } 762 763 mContext.binder.callingUid = Process.SYSTEM_UID; 764 mContext.callerPermissions.remove(permission.MANAGE_USERS); 765 // System can still call "OnAnyUser" without MANAGE_USERS. 766 if (hasDeviceOwner) { 767 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 768 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 769 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 770 771 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 772 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 773 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 774 } else { 775 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 776 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 777 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 778 779 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 780 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 781 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 782 } 783 784 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 785 // Still no MANAGE_USERS. 786 if (hasDeviceOwner) { 787 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 788 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 789 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 790 } else { 791 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 792 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 793 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 794 } 795 796 try { 797 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 798 fail(); 799 } catch (SecurityException expected) { 800 } 801 try { 802 dpm.getDeviceOwnerComponentOnAnyUser(); 803 fail(); 804 } catch (SecurityException expected) { 805 } 806 try { 807 dpm.getDeviceOwnerUserId(); 808 fail(); 809 } catch (SecurityException expected) { 810 } 811 try { 812 dpm.getDeviceOwnerNameOnAnyUser(); 813 fail(); 814 } catch (SecurityException expected) { 815 } 816 817 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 818 // Still no MANAGE_USERS. 819 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 820 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 821 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 822 823 try { 824 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 825 fail(); 826 } catch (SecurityException expected) { 827 } 828 try { 829 dpm.getDeviceOwnerComponentOnAnyUser(); 830 fail(); 831 } catch (SecurityException expected) { 832 } 833 try { 834 dpm.getDeviceOwnerUserId(); 835 fail(); 836 } catch (SecurityException expected) { 837 } 838 try { 839 dpm.getDeviceOwnerNameOnAnyUser(); 840 fail(); 841 } catch (SecurityException expected) { 842 } 843 844 // Restore. 845 mContext.binder.callingUid = origCallingUser; 846 mContext.callerPermissions.addAll(origPermissions); 847 } 848 849 850 /** 851 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist. 852 */ 853 public void testSetDeviceOwner_noSuchPackage() { 854 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 855 mContext.callerPermissions.add(permission.MANAGE_USERS); 856 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 857 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 858 859 // Call from a process on the system user. 860 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 861 862 try { 863 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")); 864 fail("Didn't throw IllegalArgumentException"); 865 } catch (IllegalArgumentException expected) { 866 assertTrue("Message was: " + expected.getMessage(), 867 expected.getMessage().contains("Invalid component")); 868 } 869 } 870 871 public void testSetDeviceOwner_failures() throws Exception { 872 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner(). 873 } 874 875 public void testClearDeviceOwner() throws Exception { 876 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 877 mContext.callerPermissions.add(permission.MANAGE_USERS); 878 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 879 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 880 881 // Set admin1 as a DA to the secondary user. 882 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 883 884 dpm.setActiveAdmin(admin1, /* replace =*/ false); 885 886 // Set admin 1 as the DO to the system user. 887 888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 889 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 890 dpm.setActiveAdmin(admin1, /* replace =*/ false); 891 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 892 893 // Verify internal calls. 894 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 895 eq(admin1.getPackageName())); 896 897 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 898 899 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 900 901 assertTrue(dpm.isAdminActive(admin1)); 902 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); 903 904 // Set up other mocks. 905 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle()); 906 907 // Now call clear. 908 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser( 909 eq(admin1.getPackageName()), 910 anyInt()); 911 912 // But first pretend the user is locked. Then it should fail. 913 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false); 914 try { 915 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 916 fail("Didn't throw IllegalStateException"); 917 } catch (IllegalStateException expected) { 918 MoreAsserts.assertContainsRegex( 919 "User must be running and unlocked", expected.getMessage()); 920 } 921 922 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 923 reset(mContext.userManagerInternal); 924 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 925 926 // Now DO shouldn't be set. 927 assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); 928 929 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 930 eq(UserHandle.USER_SYSTEM), 931 MockUtils.checkUserRestrictions(), 932 MockUtils.checkUserRestrictions() 933 ); 934 935 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)); 936 937 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner 938 // and once for clearing it. 939 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 940 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 941 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 942 // TODO Check other calls. 943 } 944 945 public void testClearDeviceOwner_fromDifferentUser() throws Exception { 946 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 947 mContext.callerPermissions.add(permission.MANAGE_USERS); 948 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 949 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 950 951 // Set admin1 as a DA to the secondary user. 952 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 953 954 dpm.setActiveAdmin(admin1, /* replace =*/ false); 955 956 // Set admin 1 as the DO to the system user. 957 958 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 959 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 960 dpm.setActiveAdmin(admin1, /* replace =*/ false); 961 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 962 963 // Verify internal calls. 964 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 965 eq(admin1.getPackageName())); 966 967 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 968 969 // Now call clear from the secondary user, which should throw. 970 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 971 972 // Now call clear. 973 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( 974 eq(admin1.getPackageName()), 975 anyInt()); 976 try { 977 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 978 fail("Didn't throw"); 979 } catch (SecurityException e) { 980 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage()); 981 } 982 983 // DO shouldn't be removed. 984 assertTrue(dpm.isDeviceManaged()); 985 } 986 987 public void testSetProfileOwner() throws Exception { 988 setAsProfileOwner(admin1); 989 990 // PO admin can't be deactivated. 991 dpm.removeActiveAdmin(admin1); 992 assertTrue(dpm.isAdminActive(admin1)); 993 994 // Try setting DO on the same user, which should fail. 995 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 996 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); 997 try { 998 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); 999 fail("IllegalStateException not thrown"); 1000 } catch (IllegalStateException expected) { 1001 assertTrue("Message was: " + expected.getMessage(), 1002 expected.getMessage().contains("already has a profile owner")); 1003 } 1004 } 1005 1006 public void testClearProfileOwner() throws Exception { 1007 setAsProfileOwner(admin1); 1008 1009 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1010 1011 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); 1012 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 1013 1014 // First try when the user is locked, which should fail. 1015 when(mContext.userManager.isUserUnlocked(anyInt())) 1016 .thenReturn(false); 1017 try { 1018 dpm.clearProfileOwner(admin1); 1019 fail("Didn't throw IllegalStateException"); 1020 } catch (IllegalStateException expected) { 1021 MoreAsserts.assertContainsRegex( 1022 "User must be running and unlocked", expected.getMessage()); 1023 } 1024 // Clear, really. 1025 when(mContext.userManager.isUserUnlocked(anyInt())) 1026 .thenReturn(true); 1027 dpm.clearProfileOwner(admin1); 1028 1029 // Check 1030 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); 1031 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 1032 } 1033 1034 public void testSetProfileOwner_failures() throws Exception { 1035 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). 1036 } 1037 1038 public void testGetDeviceOwnerAdminLocked() throws Exception { 1039 checkDeviceOwnerWithMultipleDeviceAdmins(); 1040 } 1041 1042 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception { 1043 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them, 1044 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to 1045 // make sure it gets the right component from the right user. 1046 1047 final int ANOTHER_USER_ID = 100; 1048 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); 1049 1050 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 1051 1052 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1053 mContext.callerPermissions.add(permission.MANAGE_USERS); 1054 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1055 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1056 1057 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1058 1059 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1060 1061 // Make sure the admin packge is installed to each user. 1062 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1063 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID); 1064 1065 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 1066 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 1067 1068 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 1069 1070 1071 // Set active admins to the users. 1072 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1073 dpm.setActiveAdmin(admin3, /* replace =*/ false); 1074 1075 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 1076 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 1077 1078 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); 1079 1080 // Set DO on the first non-system user. 1081 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); 1082 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1083 1084 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1085 1086 // Then check getDeviceOwnerAdminLocked(). 1087 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent()); 1088 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid()); 1089 } 1090 1091 /** 1092 * This essentially tests 1093 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is 1094 * private.) 1095 * 1096 * We didn't use to persist the DO component class name, but now we do, and the above method 1097 * finds the right component from a package name upon migration. 1098 */ 1099 public void testDeviceOwnerMigration() throws Exception { 1100 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1101 checkDeviceOwnerWithMultipleDeviceAdmins(); 1102 1103 // Overwrite the device owner setting and clears the clas name. 1104 dpms.mOwners.setDeviceOwner( 1105 new ComponentName(admin2.getPackageName(), ""), 1106 "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1107 dpms.mOwners.writeDeviceOwner(); 1108 1109 // Make sure the DO component name doesn't have a class name. 1110 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); 1111 1112 // Then create a new DPMS to have it load the settings from files. 1113 when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) 1114 .thenReturn(new Bundle()); 1115 initializeDpms(); 1116 1117 // Now the DO component name is a full name. 1118 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the 1119 // DO. 1120 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1121 } 1122 1123 public void testSetGetApplicationRestriction() { 1124 setAsProfileOwner(admin1); 1125 1126 { 1127 Bundle rest = new Bundle(); 1128 rest.putString("KEY_STRING", "Foo1"); 1129 dpm.setApplicationRestrictions(admin1, "pkg1", rest); 1130 } 1131 1132 { 1133 Bundle rest = new Bundle(); 1134 rest.putString("KEY_STRING", "Foo2"); 1135 dpm.setApplicationRestrictions(admin1, "pkg2", rest); 1136 } 1137 1138 { 1139 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); 1140 assertNotNull(returned); 1141 assertEquals(returned.size(), 1); 1142 assertEquals(returned.get("KEY_STRING"), "Foo1"); 1143 } 1144 1145 { 1146 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); 1147 assertNotNull(returned); 1148 assertEquals(returned.size(), 1); 1149 assertEquals(returned.get("KEY_STRING"), "Foo2"); 1150 } 1151 1152 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); 1153 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); 1154 } 1155 1156 public void testApplicationRestrictionsManagingApp() throws Exception { 1157 setAsProfileOwner(admin1); 1158 1159 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2"; 1160 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager"; 1161 final int appRestrictionsManagerAppId = 20987; 1162 final int appRestrictionsManagerUid = UserHandle.getUid( 1163 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId); 1164 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser( 1165 eq(appRestrictionsManagerPackage), 1166 eq(DpmMockContext.CALLER_USER_HANDLE)); 1167 mContext.binder.callingUid = appRestrictionsManagerUid; 1168 1169 final PackageInfo pi = new PackageInfo(); 1170 pi.applicationInfo = new ApplicationInfo(); 1171 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE; 1172 doReturn(pi).when(mContext.ipackageManager).getPackageInfo( 1173 eq(appRestrictionsManagerPackage), 1174 anyInt(), 1175 eq(DpmMockContext.CALLER_USER_HANDLE)); 1176 1177 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't 1178 // delegated that permission yet. 1179 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1180 Bundle rest = new Bundle(); 1181 rest.putString("KEY_STRING", "Foo1"); 1182 try { 1183 dpm.setApplicationRestrictions(null, "pkg1", rest); 1184 fail("Didn't throw expected SecurityException"); 1185 } catch (SecurityException expected) { 1186 MoreAsserts.assertContainsRegex( 1187 "caller cannot manage application restrictions", expected.getMessage()); 1188 } 1189 try { 1190 dpm.getApplicationRestrictions(null, "pkg1"); 1191 fail("Didn't throw expected SecurityException"); 1192 } catch (SecurityException expected) { 1193 MoreAsserts.assertContainsRegex( 1194 "caller cannot manage application restrictions", expected.getMessage()); 1195 } 1196 1197 // Check via the profile owner that no restrictions were set. 1198 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1199 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1200 1201 // Check the API does not allow setting a non-existent package 1202 try { 1203 dpm.setApplicationRestrictionsManagingPackage(admin1, 1204 nonExistAppRestrictionsManagerPackage); 1205 fail("Non-existent app set as app restriction manager."); 1206 } catch (PackageManager.NameNotFoundException expected) { 1207 MoreAsserts.assertContainsRegex( 1208 nonExistAppRestrictionsManagerPackage, expected.getMessage()); 1209 } 1210 1211 // Let appRestrictionsManagerPackage manage app restrictions 1212 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); 1213 assertEquals(appRestrictionsManagerPackage, 1214 dpm.getApplicationRestrictionsManagingPackage(admin1)); 1215 1216 // Now that package should be able to set and retrieve app restrictions. 1217 mContext.binder.callingUid = appRestrictionsManagerUid; 1218 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); 1219 dpm.setApplicationRestrictions(null, "pkg1", rest); 1220 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); 1221 assertEquals(1, returned.size(), 1); 1222 assertEquals("Foo1", returned.get("KEY_STRING")); 1223 1224 // The same app running on a separate user shouldn't be able to manage app restrictions. 1225 mContext.binder.callingUid = UserHandle.getUid( 1226 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); 1227 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1228 try { 1229 dpm.setApplicationRestrictions(null, "pkg1", rest); 1230 fail("Didn't throw expected SecurityException"); 1231 } catch (SecurityException expected) { 1232 MoreAsserts.assertContainsRegex( 1233 "caller cannot manage application restrictions", expected.getMessage()); 1234 } 1235 1236 // The DPM is still able to manage app restrictions, even if it allowed another app to do it 1237 // too. 1238 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1239 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); 1240 dpm.setApplicationRestrictions(admin1, "pkg1", null); 1241 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1242 1243 // Removing the ability for the package to manage app restrictions. 1244 dpm.setApplicationRestrictionsManagingPackage(admin1, null); 1245 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); 1246 mContext.binder.callingUid = appRestrictionsManagerUid; 1247 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1248 try { 1249 dpm.setApplicationRestrictions(null, "pkg1", null); 1250 fail("Didn't throw expected SecurityException"); 1251 } catch (SecurityException expected) { 1252 MoreAsserts.assertContainsRegex( 1253 "caller cannot manage application restrictions", expected.getMessage()); 1254 } 1255 } 1256 1257 public void testSetUserRestriction_asDo() throws Exception { 1258 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1259 mContext.callerPermissions.add(permission.MANAGE_USERS); 1260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1261 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1262 1263 // First, set DO. 1264 1265 // Call from a process on the system user. 1266 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1267 1268 // Make sure admin1 is installed on system user. 1269 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1270 1271 // Call. 1272 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1273 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1274 UserHandle.USER_SYSTEM)); 1275 1276 // Check that the user restrictions that are enabled by default are set. Then unset them. 1277 String[] defaultRestrictions = UserRestrictionsUtils 1278 .getDefaultEnabledForDeviceOwner().toArray(new String[0]); 1279 DpmTestUtils.assertRestrictions( 1280 DpmTestUtils.newRestrictions(defaultRestrictions), 1281 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1282 ); 1283 DpmTestUtils.assertRestrictions( 1284 DpmTestUtils.newRestrictions(defaultRestrictions), 1285 dpm.getUserRestrictions(admin1) 1286 ); 1287 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1288 eq(UserHandle.USER_SYSTEM), 1289 MockUtils.checkUserRestrictions(defaultRestrictions), 1290 MockUtils.checkUserRestrictions() 1291 ); 1292 reset(mContext.userManagerInternal); 1293 1294 for (String restriction : defaultRestrictions) { 1295 dpm.clearUserRestriction(admin1, restriction); 1296 } 1297 1298 assertNoDeviceOwnerRestrictions(); 1299 1300 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1302 eq(UserHandle.USER_SYSTEM), 1303 MockUtils.checkUserRestrictions(), 1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1305 ); 1306 reset(mContext.userManagerInternal); 1307 1308 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1309 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1310 eq(UserHandle.USER_SYSTEM), 1311 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1313 ); 1314 reset(mContext.userManagerInternal); 1315 1316 DpmTestUtils.assertRestrictions( 1317 DpmTestUtils.newRestrictions( 1318 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1319 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1320 ); 1321 DpmTestUtils.assertRestrictions( 1322 DpmTestUtils.newRestrictions( 1323 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1324 dpm.getUserRestrictions(admin1) 1325 ); 1326 1327 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1328 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1329 eq(UserHandle.USER_SYSTEM), 1330 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1331 MockUtils.checkUserRestrictions() 1332 ); 1333 reset(mContext.userManagerInternal); 1334 1335 DpmTestUtils.assertRestrictions( 1336 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1337 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1338 ); 1339 DpmTestUtils.assertRestrictions( 1340 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1341 dpm.getUserRestrictions(admin1) 1342 ); 1343 1344 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1345 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1346 eq(UserHandle.USER_SYSTEM), 1347 MockUtils.checkUserRestrictions(), 1348 MockUtils.checkUserRestrictions() 1349 ); 1350 reset(mContext.userManagerInternal); 1351 1352 assertNoDeviceOwnerRestrictions(); 1353 1354 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when 1355 // DO sets them, the scope is global. 1356 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1357 reset(mContext.userManagerInternal); 1358 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1359 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1360 eq(UserHandle.USER_SYSTEM), 1361 MockUtils.checkUserRestrictions(), 1362 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1363 UserManager.DISALLOW_UNMUTE_MICROPHONE) 1364 ); 1365 reset(mContext.userManagerInternal); 1366 1367 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1368 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1369 1370 1371 // More tests. 1372 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1373 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1374 eq(UserHandle.USER_SYSTEM), 1375 MockUtils.checkUserRestrictions(), 1376 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1377 ); 1378 reset(mContext.userManagerInternal); 1379 1380 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); 1381 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1382 eq(UserHandle.USER_SYSTEM), 1383 MockUtils.checkUserRestrictions(), 1384 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1385 UserManager.DISALLOW_ADD_USER) 1386 ); 1387 reset(mContext.userManagerInternal); 1388 1389 dpm.setCameraDisabled(admin1, true); 1390 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1391 eq(UserHandle.USER_SYSTEM), 1392 // DISALLOW_CAMERA will be applied to both local and global. 1393 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1394 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1395 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER) 1396 ); 1397 reset(mContext.userManagerInternal); 1398 1399 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied 1400 // locally. 1401 dpm.setCameraDisabled(admin1, false); 1402 reset(mContext.userManagerInternal); 1403 1404 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 1405 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); 1406 dpm.setCameraDisabled(admin2, true); 1407 1408 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1409 eq(UserHandle.USER_SYSTEM), 1410 // DISALLOW_CAMERA will be applied to both local and global. 1411 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1412 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1413 UserManager.DISALLOW_ADD_USER) 1414 ); 1415 reset(mContext.userManagerInternal); 1416 // TODO Make sure restrictions are written to the file. 1417 } 1418 1419 public void testSetUserRestriction_asPo() { 1420 setAsProfileOwner(admin1); 1421 1422 DpmTestUtils.assertRestrictions( 1423 DpmTestUtils.newRestrictions(), 1424 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1425 .ensureUserRestrictions() 1426 ); 1427 1428 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1429 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1430 eq(DpmMockContext.CALLER_USER_HANDLE), 1431 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), 1432 isNull(Bundle.class) 1433 ); 1434 reset(mContext.userManagerInternal); 1435 1436 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1437 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1438 eq(DpmMockContext.CALLER_USER_HANDLE), 1439 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1440 UserManager.DISALLOW_OUTGOING_CALLS), 1441 isNull(Bundle.class) 1442 ); 1443 reset(mContext.userManagerInternal); 1444 1445 DpmTestUtils.assertRestrictions( 1446 DpmTestUtils.newRestrictions( 1447 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1448 UserManager.DISALLOW_OUTGOING_CALLS 1449 ), 1450 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1451 .ensureUserRestrictions() 1452 ); 1453 DpmTestUtils.assertRestrictions( 1454 DpmTestUtils.newRestrictions( 1455 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1456 UserManager.DISALLOW_OUTGOING_CALLS 1457 ), 1458 dpm.getUserRestrictions(admin1) 1459 ); 1460 1461 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1462 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1463 eq(DpmMockContext.CALLER_USER_HANDLE), 1464 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1465 isNull(Bundle.class) 1466 ); 1467 reset(mContext.userManagerInternal); 1468 1469 DpmTestUtils.assertRestrictions( 1470 DpmTestUtils.newRestrictions( 1471 UserManager.DISALLOW_OUTGOING_CALLS 1472 ), 1473 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1474 .ensureUserRestrictions() 1475 ); 1476 DpmTestUtils.assertRestrictions( 1477 DpmTestUtils.newRestrictions( 1478 UserManager.DISALLOW_OUTGOING_CALLS 1479 ), 1480 dpm.getUserRestrictions(admin1) 1481 ); 1482 1483 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1484 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1485 eq(DpmMockContext.CALLER_USER_HANDLE), 1486 MockUtils.checkUserRestrictions(), 1487 isNull(Bundle.class) 1488 ); 1489 reset(mContext.userManagerInternal); 1490 1491 DpmTestUtils.assertRestrictions( 1492 DpmTestUtils.newRestrictions(), 1493 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1494 .ensureUserRestrictions() 1495 ); 1496 DpmTestUtils.assertRestrictions( 1497 DpmTestUtils.newRestrictions(), 1498 dpm.getUserRestrictions(admin1) 1499 ); 1500 1501 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even 1502 // though when DO sets them they'll be applied globally. 1503 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1504 reset(mContext.userManagerInternal); 1505 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1506 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1507 eq(DpmMockContext.CALLER_USER_HANDLE), 1508 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1509 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1510 isNull(Bundle.class) 1511 ); 1512 reset(mContext.userManagerInternal); 1513 1514 dpm.setCameraDisabled(admin1, true); 1515 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1516 eq(DpmMockContext.CALLER_USER_HANDLE), 1517 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA, 1518 UserManager.DISALLOW_ADJUST_VOLUME, 1519 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1520 isNull(Bundle.class) 1521 ); 1522 reset(mContext.userManagerInternal); 1523 1524 // TODO Make sure restrictions are written to the file. 1525 } 1526 1527 1528 public void testDefaultEnabledUserRestrictions() throws Exception { 1529 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1530 mContext.callerPermissions.add(permission.MANAGE_USERS); 1531 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1532 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1533 1534 // First, set DO. 1535 1536 // Call from a process on the system user. 1537 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1538 1539 // Make sure admin1 is installed on system user. 1540 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1541 1542 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1543 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1544 UserHandle.USER_SYSTEM)); 1545 1546 // Check that the user restrictions that are enabled by default are set. Then unset them. 1547 String[] defaultRestrictions = UserRestrictionsUtils 1548 .getDefaultEnabledForDeviceOwner().toArray(new String[0]); 1549 assertTrue(defaultRestrictions.length > 0); 1550 DpmTestUtils.assertRestrictions( 1551 DpmTestUtils.newRestrictions(defaultRestrictions), 1552 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1553 ); 1554 DpmTestUtils.assertRestrictions( 1555 DpmTestUtils.newRestrictions(defaultRestrictions), 1556 dpm.getUserRestrictions(admin1) 1557 ); 1558 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1559 eq(UserHandle.USER_SYSTEM), 1560 MockUtils.checkUserRestrictions(defaultRestrictions), 1561 MockUtils.checkUserRestrictions() 1562 ); 1563 reset(mContext.userManagerInternal); 1564 1565 for (String restriction : defaultRestrictions) { 1566 dpm.clearUserRestriction(admin1, restriction); 1567 } 1568 1569 assertNoDeviceOwnerRestrictions(); 1570 1571 // Initialize DPMS again and check that the user restriction wasn't enabled again. 1572 reset(mContext.userManagerInternal); 1573 initializeDpms(); 1574 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1575 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1576 1577 assertNoDeviceOwnerRestrictions(); 1578 1579 // Add a new restriction to the default set, initialize DPMS, and check that the restriction 1580 // is set as it wasn't enabled during setDeviceOwner. 1581 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 1582 assertFalse(UserRestrictionsUtils 1583 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction)); 1584 UserRestrictionsUtils 1585 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction); 1586 try { 1587 reset(mContext.userManagerInternal); 1588 initializeDpms(); 1589 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1590 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1591 1592 DpmTestUtils.assertRestrictions( 1593 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction), 1594 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1595 ); 1596 DpmTestUtils.assertRestrictions( 1597 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction), 1598 dpm.getUserRestrictions(admin1) 1599 ); 1600 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions( 1601 eq(UserHandle.USER_SYSTEM), 1602 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction), 1603 MockUtils.checkUserRestrictions() 1604 ); 1605 reset(mContext.userManagerInternal); 1606 1607 // Remove the restriction. 1608 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction); 1609 1610 // Initialize DPMS again. The restriction shouldn't be enabled for a second time. 1611 initializeDpms(); 1612 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1613 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1614 assertNoDeviceOwnerRestrictions(); 1615 } finally { 1616 UserRestrictionsUtils 1617 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction); 1618 } 1619 } 1620 1621 private void assertNoDeviceOwnerRestrictions() { 1622 DpmTestUtils.assertRestrictions( 1623 DpmTestUtils.newRestrictions(), 1624 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1625 ); 1626 DpmTestUtils.assertRestrictions( 1627 DpmTestUtils.newRestrictions(), 1628 dpm.getUserRestrictions(admin1) 1629 ); 1630 } 1631 1632 public void testGetMacAddress() throws Exception { 1633 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1634 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1635 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1636 1637 // In this test, change the caller user to "system". 1638 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1639 1640 // Make sure admin1 is installed on system user. 1641 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1642 1643 // Test 1. Caller doesn't have DO or DA. 1644 try { 1645 dpm.getWifiMacAddress(admin1); 1646 fail(); 1647 } catch (SecurityException e) { 1648 MoreAsserts.assertContainsRegex("No active admin", e.getMessage()); 1649 } 1650 1651 // DO needs to be an DA. 1652 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1653 assertTrue(dpm.isAdminActive(admin1)); 1654 1655 // Test 2. Caller has DA, but not DO. 1656 try { 1657 dpm.getWifiMacAddress(admin1); 1658 fail(); 1659 } catch (SecurityException e) { 1660 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1661 } 1662 1663 // Test 3. Caller has PO, but not DO. 1664 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1665 try { 1666 dpm.getWifiMacAddress(admin1); 1667 fail(); 1668 } catch (SecurityException e) { 1669 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1670 } 1671 1672 // Remove PO. 1673 dpm.clearProfileOwner(admin1); 1674 dpm.setActiveAdmin(admin1, false); 1675 // Test 4, Caller is DO now. 1676 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1677 1678 // 4-1. But no WifiInfo. 1679 assertNull(dpm.getWifiMacAddress(admin1)); 1680 1681 // 4-2. Returns WifiInfo, but with the default MAC. 1682 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); 1683 assertNull(dpm.getWifiMacAddress(admin1)); 1684 1685 // 4-3. With a real MAC address. 1686 final WifiInfo wi = new WifiInfo(); 1687 wi.setMacAddress("11:22:33:44:55:66"); 1688 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); 1689 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); 1690 } 1691 1692 public void testReboot() throws Exception { 1693 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1694 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1695 1696 // In this test, change the caller user to "system". 1697 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1698 1699 // Make sure admin1 is installed on system user. 1700 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1701 1702 // Set admin1 as DA. 1703 dpm.setActiveAdmin(admin1, false); 1704 assertTrue(dpm.isAdminActive(admin1)); 1705 try { 1706 dpm.reboot(admin1); 1707 fail("DA calls DPM.reboot(), did not throw expected SecurityException"); 1708 } catch (SecurityException expected) { 1709 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1710 } 1711 1712 // Set admin1 as PO. 1713 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1714 try { 1715 dpm.reboot(admin1); 1716 fail("PO calls DPM.reboot(), did not throw expected SecurityException"); 1717 } catch (SecurityException expected) { 1718 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1719 } 1720 1721 // Remove PO and add DO. 1722 dpm.clearProfileOwner(admin1); 1723 dpm.setActiveAdmin(admin1, false); 1724 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1725 1726 // admin1 is DO. 1727 // Set current call state of device to ringing. 1728 when(mContext.telephonyManager.getCallState()) 1729 .thenReturn(TelephonyManager.CALL_STATE_RINGING); 1730 try { 1731 dpm.reboot(admin1); 1732 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException"); 1733 } catch (IllegalStateException expected) { 1734 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1735 } 1736 1737 // Set current call state of device to dialing/active. 1738 when(mContext.telephonyManager.getCallState()) 1739 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); 1740 try { 1741 dpm.reboot(admin1); 1742 fail("DPM.reboot() called when dialing, should thrown IllegalStateException"); 1743 } catch (IllegalStateException expected) { 1744 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1745 } 1746 1747 // Set current call state of device to idle. 1748 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); 1749 dpm.reboot(admin1); 1750 } 1751 1752 public void testSetGetSupportText() { 1753 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1754 dpm.setActiveAdmin(admin1, true); 1755 dpm.setActiveAdmin(admin2, true); 1756 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); 1757 1758 // Null default support messages. 1759 { 1760 assertNull(dpm.getLongSupportMessage(admin1)); 1761 assertNull(dpm.getShortSupportMessage(admin1)); 1762 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1763 assertNull(dpm.getShortSupportMessageForUser(admin1, 1764 DpmMockContext.CALLER_USER_HANDLE)); 1765 assertNull(dpm.getLongSupportMessageForUser(admin1, 1766 DpmMockContext.CALLER_USER_HANDLE)); 1767 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1768 } 1769 1770 // Only system can call the per user versions. 1771 { 1772 try { 1773 dpm.getShortSupportMessageForUser(admin1, 1774 DpmMockContext.CALLER_USER_HANDLE); 1775 fail("Only system should be able to call getXXXForUser versions"); 1776 } catch (SecurityException expected) { 1777 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1778 } 1779 try { 1780 dpm.getLongSupportMessageForUser(admin1, 1781 DpmMockContext.CALLER_USER_HANDLE); 1782 fail("Only system should be able to call getXXXForUser versions"); 1783 } catch (SecurityException expected) { 1784 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1785 } 1786 } 1787 1788 // Can't set message for admin in another uid. 1789 { 1790 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1; 1791 try { 1792 dpm.setShortSupportMessage(admin1, "Some text"); 1793 fail("Admins should only be able to change their own support text."); 1794 } catch (SecurityException expected) { 1795 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage()); 1796 } 1797 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1798 } 1799 1800 // Set/Get short returns what it sets and other admins text isn't changed. 1801 { 1802 final String supportText = "Some text to test with."; 1803 dpm.setShortSupportMessage(admin1, supportText); 1804 assertEquals(supportText, dpm.getShortSupportMessage(admin1)); 1805 assertNull(dpm.getLongSupportMessage(admin1)); 1806 assertNull(dpm.getShortSupportMessage(admin2)); 1807 1808 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1809 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, 1810 DpmMockContext.CALLER_USER_HANDLE)); 1811 assertNull(dpm.getShortSupportMessageForUser(admin2, 1812 DpmMockContext.CALLER_USER_HANDLE)); 1813 assertNull(dpm.getLongSupportMessageForUser(admin1, 1814 DpmMockContext.CALLER_USER_HANDLE)); 1815 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1816 1817 dpm.setShortSupportMessage(admin1, null); 1818 assertNull(dpm.getShortSupportMessage(admin1)); 1819 } 1820 1821 // Set/Get long returns what it sets and other admins text isn't changed. 1822 { 1823 final String supportText = "Some text to test with.\nWith more text."; 1824 dpm.setLongSupportMessage(admin1, supportText); 1825 assertEquals(supportText, dpm.getLongSupportMessage(admin1)); 1826 assertNull(dpm.getShortSupportMessage(admin1)); 1827 assertNull(dpm.getLongSupportMessage(admin2)); 1828 1829 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1830 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, 1831 DpmMockContext.CALLER_USER_HANDLE)); 1832 assertNull(dpm.getLongSupportMessageForUser(admin2, 1833 DpmMockContext.CALLER_USER_HANDLE)); 1834 assertNull(dpm.getShortSupportMessageForUser(admin1, 1835 DpmMockContext.CALLER_USER_HANDLE)); 1836 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1837 1838 dpm.setLongSupportMessage(admin1, null); 1839 assertNull(dpm.getLongSupportMessage(admin1)); 1840 } 1841 } 1842 1843 /** 1844 * Test for: 1845 * {@link DevicePolicyManager#setAffiliationIds} 1846 * {@link DevicePolicyManager#getAffiliationIds} 1847 * {@link DevicePolicyManager#isAffiliatedUser} 1848 */ 1849 public void testUserAffiliation() throws Exception { 1850 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1852 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1853 1854 // Check that the system user is unaffiliated. 1855 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1856 assertFalse(dpm.isAffiliatedUser()); 1857 1858 // Set a device owner on the system user. Check that the system user becomes affiliated. 1859 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1860 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1861 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 1862 assertTrue(dpm.isAffiliatedUser()); 1863 assertTrue(dpm.getAffiliationIds(admin1).isEmpty()); 1864 1865 // Install a profile owner. Check that the test user is unaffiliated. 1866 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1867 setAsProfileOwner(admin2); 1868 assertFalse(dpm.isAffiliatedUser()); 1869 assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); 1870 1871 // Have the profile owner specify a set of affiliation ids. Check that the test user remains 1872 // unaffiliated. 1873 final List<String> userAffiliationIds = new ArrayList<>(); 1874 userAffiliationIds.add("red"); 1875 userAffiliationIds.add("green"); 1876 userAffiliationIds.add("blue"); 1877 dpm.setAffiliationIds(admin2, userAffiliationIds); 1878 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue"); 1879 assertFalse(dpm.isAffiliatedUser()); 1880 1881 // Have the device owner specify a set of affiliation ids that do not intersect with those 1882 // specified by the profile owner. Check that the test user remains unaffiliated. 1883 final List<String> deviceAffiliationIds = new ArrayList<>(); 1884 deviceAffiliationIds.add("cyan"); 1885 deviceAffiliationIds.add("yellow"); 1886 deviceAffiliationIds.add("magenta"); 1887 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1888 dpm.setAffiliationIds(admin1, deviceAffiliationIds); 1889 MoreAsserts.assertContentsInAnyOrder( 1890 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta"); 1891 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1892 assertFalse(dpm.isAffiliatedUser()); 1893 1894 // Have the profile owner specify a set of affiliation ids that intersect with those 1895 // specified by the device owner. Check that the test user becomes affiliated. 1896 userAffiliationIds.add("yellow"); 1897 dpm.setAffiliationIds(admin2, userAffiliationIds); 1898 MoreAsserts.assertContentsInAnyOrder( 1899 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow"); 1900 assertTrue(dpm.isAffiliatedUser()); 1901 1902 // Clear affiliation ids for the profile owner. The user becomes unaffiliated. 1903 dpm.setAffiliationIds(admin2, Collections.emptyList()); 1904 assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); 1905 assertFalse(dpm.isAffiliatedUser()); 1906 1907 // Check that the system user remains affiliated. 1908 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1909 assertTrue(dpm.isAffiliatedUser()); 1910 } 1911 1912 public void testGetUserProvisioningState_defaultResult() { 1913 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1914 } 1915 1916 public void testSetUserProvisioningState_permission() throws Exception { 1917 setupProfileOwner(); 1918 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1919 1920 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1921 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1922 } 1923 1924 public void testSetUserProvisioningState_unprivileged() throws Exception { 1925 setupProfileOwner(); 1926 try { 1927 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1928 DpmMockContext.CALLER_USER_HANDLE); 1929 fail("Expected SecurityException"); 1930 } catch (SecurityException expected) { 1931 } 1932 } 1933 1934 public void testSetUserProvisioningState_noManagement() { 1935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1936 try { 1937 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1938 DpmMockContext.CALLER_USER_HANDLE); 1939 fail("IllegalStateException expected"); 1940 } catch (IllegalStateException e) { 1941 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set", 1942 e.getMessage()); 1943 } 1944 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1945 } 1946 1947 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception { 1948 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1949 setupDeviceOwner(); 1950 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1951 1952 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1953 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 1954 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1955 } 1956 1957 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative() 1958 throws Exception { 1959 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1960 setupDeviceOwner(); 1961 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1962 1963 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1964 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 1965 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1966 } 1967 1968 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception { 1969 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1970 setupDeviceOwner(); 1971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1972 1973 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1974 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1975 } 1976 1977 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser() 1978 throws Exception { 1979 setupProfileOwner(); 1980 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1981 1982 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1983 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE, 1984 DevicePolicyManager.STATE_USER_UNMANAGED); 1985 } 1986 1987 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile() 1988 throws Exception { 1989 setupProfileOwner(); 1990 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1991 1992 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1993 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 1994 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1995 } 1996 1997 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception { 1998 setupProfileOwner(); 1999 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2000 2001 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2002 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2003 } 2004 2005 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception { 2006 setupProfileOwner(); 2007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2008 2009 try { 2010 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2011 DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 2012 DevicePolicyManager.STATE_USER_UNMANAGED); 2013 fail("Expected IllegalStateException"); 2014 } catch (IllegalStateException e) { 2015 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 2016 e.getMessage()); 2017 } 2018 } 2019 2020 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState() 2021 throws Exception { 2022 setupProfileOwner(); 2023 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2024 2025 try { 2026 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2027 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 2028 DevicePolicyManager.STATE_USER_SETUP_COMPLETE); 2029 fail("Expected IllegalStateException"); 2030 } catch (IllegalStateException e) { 2031 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 2032 e.getMessage()); 2033 } 2034 } 2035 2036 private void exerciseUserProvisioningTransitions(int userId, int... states) { 2037 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 2038 for (int state : states) { 2039 dpm.setUserProvisioningState(state, userId); 2040 assertEquals(state, dpm.getUserProvisioningState()); 2041 } 2042 } 2043 2044 private void setupProfileOwner() throws Exception { 2045 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2046 2047 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 2048 dpm.setActiveAdmin(admin1, false); 2049 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE)); 2050 2051 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2052 } 2053 2054 private void setupDeviceOwner() throws Exception { 2055 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2056 2057 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 2058 dpm.setActiveAdmin(admin1, false); 2059 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 2060 2061 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2062 } 2063 2064 public void testSetMaximumTimeToLock() { 2065 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 2066 2067 dpm.setActiveAdmin(admin1, /* replace =*/ false); 2068 dpm.setActiveAdmin(admin2, /* replace =*/ false); 2069 2070 reset(mMockContext.powerManagerInternal); 2071 reset(mMockContext.settings); 2072 2073 dpm.setMaximumTimeToLock(admin1, 0); 2074 verifyScreenTimeoutCall(null, false); 2075 reset(mMockContext.powerManagerInternal); 2076 reset(mMockContext.settings); 2077 2078 dpm.setMaximumTimeToLock(admin1, 1); 2079 verifyScreenTimeoutCall(1, true); 2080 reset(mMockContext.powerManagerInternal); 2081 reset(mMockContext.settings); 2082 2083 dpm.setMaximumTimeToLock(admin2, 10); 2084 verifyScreenTimeoutCall(null, false); 2085 reset(mMockContext.powerManagerInternal); 2086 reset(mMockContext.settings); 2087 2088 dpm.setMaximumTimeToLock(admin1, 5); 2089 verifyScreenTimeoutCall(5, true); 2090 reset(mMockContext.powerManagerInternal); 2091 reset(mMockContext.settings); 2092 2093 dpm.setMaximumTimeToLock(admin2, 4); 2094 verifyScreenTimeoutCall(4, true); 2095 reset(mMockContext.powerManagerInternal); 2096 reset(mMockContext.settings); 2097 2098 dpm.setMaximumTimeToLock(admin1, 0); 2099 reset(mMockContext.powerManagerInternal); 2100 reset(mMockContext.settings); 2101 2102 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE); 2103 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 2104 reset(mMockContext.powerManagerInternal); 2105 reset(mMockContext.settings); 2106 2107 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1); 2108 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 2109 reset(mMockContext.powerManagerInternal); 2110 reset(mMockContext.settings); 2111 2112 dpm.setMaximumTimeToLock(admin2, 10); 2113 verifyScreenTimeoutCall(10, true); 2114 reset(mMockContext.powerManagerInternal); 2115 reset(mMockContext.settings); 2116 2117 // There's no restriction; shold be set to MAX. 2118 dpm.setMaximumTimeToLock(admin2, 0); 2119 verifyScreenTimeoutCall(Integer.MAX_VALUE, false); 2120 } 2121 2122 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception { 2123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2124 setupDeviceOwner(); 2125 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2126 2127 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h 2128 final long ONE_MINUTE = 60 * 1000; 2129 2130 // aggregation should be the default if unset by any admin 2131 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2132 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2133 2134 // admin not participating by default 2135 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2136 2137 //clamping from the top 2138 dpm.setRequiredStrongAuthTimeout(admin1, 2139 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE); 2140 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 2141 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2142 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2143 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2144 2145 // 0 means default 2146 dpm.setRequiredStrongAuthTimeout(admin1, 0); 2147 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2148 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2149 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2150 2151 // clamping from the bottom 2152 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE); 2153 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS); 2154 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS); 2155 2156 // value within range 2157 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE); 2158 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS 2159 + ONE_MINUTE); 2160 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS 2161 + ONE_MINUTE); 2162 2163 // reset to default 2164 dpm.setRequiredStrongAuthTimeout(admin1, 0); 2165 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2166 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2167 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2168 2169 // negative value 2170 try { 2171 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE); 2172 fail("Didn't throw IllegalArgumentException"); 2173 } catch (IllegalArgumentException iae) { 2174 } 2175 } 2176 2177 private void verifyScreenTimeoutCall(Integer expectedTimeout, 2178 boolean shouldStayOnWhilePluggedInBeCleared) { 2179 if (expectedTimeout == null) { 2180 verify(mMockContext.powerManagerInternal, times(0)) 2181 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt()); 2182 } else { 2183 verify(mMockContext.powerManagerInternal, times(1)) 2184 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout)); 2185 } 2186 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw 2187 // UnfinishedVerificationException. 2188 } 2189 2190 private void setup_DeviceAdminFeatureOff() throws Exception { 2191 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) 2192 .thenReturn(false); 2193 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2194 .thenReturn(false); 2195 initializeDpms(); 2196 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2197 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2198 .thenReturn(true); 2199 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2200 2201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2202 } 2203 2204 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception { 2205 setup_DeviceAdminFeatureOff(); 2206 mContext.packageName = admin1.getPackageName(); 2207 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2208 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 2209 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2210 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2211 false); 2212 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2213 } 2214 2215 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception { 2216 setup_DeviceAdminFeatureOff(); 2217 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2218 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2219 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2220 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2221 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2222 assertCheckProvisioningPreCondition( 2223 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2224 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2225 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2226 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2227 } 2228 2229 private void setup_ManagedProfileFeatureOff() throws Exception { 2230 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2231 .thenReturn(false); 2232 initializeDpms(); 2233 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2234 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2235 .thenReturn(true); 2236 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2237 2238 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2239 } 2240 2241 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { 2242 setup_ManagedProfileFeatureOff(); 2243 mContext.packageName = admin1.getPackageName(); 2244 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2245 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2246 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2247 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2248 false); 2249 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2250 2251 // Test again when split user is on 2252 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2253 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2255 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2256 true); 2257 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2258 } 2259 2260 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception { 2261 setup_ManagedProfileFeatureOff(); 2262 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2264 DevicePolicyManager.CODE_OK); 2265 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2266 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2267 assertCheckProvisioningPreCondition( 2268 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2269 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2270 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2271 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2272 2273 // Test again when split user is on 2274 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2275 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2276 DevicePolicyManager.CODE_OK); 2277 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2278 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2279 assertCheckProvisioningPreCondition( 2280 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2281 DevicePolicyManager.CODE_OK); 2282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2283 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2284 } 2285 2286 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception { 2287 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2288 .thenReturn(true); 2289 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2290 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2291 .thenReturn(true); 2292 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2293 2294 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2295 } 2296 2297 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { 2298 setup_nonSplitUser_firstBoot_primaryUser(); 2299 mContext.packageName = admin1.getPackageName(); 2300 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2301 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2302 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2303 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2304 false /* because of non-split user */); 2305 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2306 false /* because of non-split user */); 2307 } 2308 2309 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser() 2310 throws Exception { 2311 setup_nonSplitUser_firstBoot_primaryUser(); 2312 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2313 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2314 DevicePolicyManager.CODE_OK); 2315 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2316 DevicePolicyManager.CODE_OK); 2317 assertCheckProvisioningPreCondition( 2318 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2319 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2320 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2321 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2322 } 2323 2324 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { 2325 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2326 .thenReturn(true); 2327 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2328 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2329 .thenReturn(true); 2330 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2331 2332 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2333 } 2334 2335 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() 2336 throws Exception { 2337 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2338 mContext.packageName = admin1.getPackageName(); 2339 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2340 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2341 false/* because of completed device setup */); 2342 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2343 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2344 false/* because of non-split user */); 2345 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2346 false/* because of non-split user */); 2347 } 2348 2349 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser() 2350 throws Exception { 2351 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2352 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2353 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2354 DevicePolicyManager.CODE_USER_SETUP_COMPLETED); 2355 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2356 DevicePolicyManager.CODE_OK); 2357 assertCheckProvisioningPreCondition( 2358 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2359 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2360 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2361 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2362 } 2363 2364 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception { 2365 setDeviceOwner(); 2366 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2367 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2368 mContext.packageName = admin1.getPackageName(); 2369 2370 // COMP mode is allowed. 2371 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2372 2373 when(mContext.userManager.hasUserRestriction( 2374 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2375 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2376 .thenReturn(true); 2377 2378 // The DO should be allowed to initiate provisioning if it set the restriction itself. 2379 when(mContext.userManager.getUserRestrictionSource( 2380 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2381 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2382 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); 2383 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2384 2385 // The DO should not be allowed to initiate provisioning if the restriction is set by 2386 // another entity. 2387 when(mContext.userManager.getUserRestrictionSource( 2388 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2389 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2390 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); 2391 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2392 } 2393 2394 public void 2395 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception { 2396 setDeviceOwner(); 2397 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2398 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2399 2400 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2401 DevicePolicyManager.CODE_HAS_DEVICE_OWNER); 2402 2403 // COMP mode is allowed. 2404 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2405 DevicePolicyManager.CODE_OK); 2406 2407 // And other DPCs can also provisioning a managed profile (DO + BYOD case). 2408 assertCheckProvisioningPreCondition( 2409 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2410 "some.other.dpc.package.name", 2411 DevicePolicyManager.CODE_OK); 2412 2413 when(mContext.userManager.hasUserRestriction( 2414 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2415 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2416 .thenReturn(true); 2417 2418 // The DO should be allowed to initiate provisioning if it set the restriction itself, but 2419 // other packages should be forbidden. 2420 when(mContext.userManager.getUserRestrictionSource( 2421 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2422 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2423 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); 2424 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2425 DevicePolicyManager.CODE_OK); 2426 assertCheckProvisioningPreCondition( 2427 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2428 "some.other.dpc.package.name", 2429 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2430 2431 // The DO should not be allowed to initiate provisioning if the restriction is set by 2432 // another entity. 2433 when(mContext.userManager.getUserRestrictionSource( 2434 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2435 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2436 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); 2437 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2438 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2439 assertCheckProvisioningPreCondition( 2440 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2441 "some.other.dpc.package.name", 2442 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2443 } 2444 2445 private void setup_splitUser_firstBoot_systemUser() throws Exception { 2446 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2447 .thenReturn(true); 2448 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2449 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2450 .thenReturn(false); 2451 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2452 2453 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2454 } 2455 2456 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { 2457 setup_splitUser_firstBoot_systemUser(); 2458 mContext.packageName = admin1.getPackageName(); 2459 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2460 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2461 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2462 false /* because canAddMoreManagedProfiles returns false */); 2463 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2464 true); 2465 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2466 false/* because calling uid is system user */); 2467 } 2468 2469 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser() 2470 throws Exception { 2471 setup_splitUser_firstBoot_systemUser(); 2472 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2473 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2474 DevicePolicyManager.CODE_OK); 2475 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2476 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2477 assertCheckProvisioningPreCondition( 2478 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2479 DevicePolicyManager.CODE_OK); 2480 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2481 DevicePolicyManager.CODE_SYSTEM_USER); 2482 } 2483 2484 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception { 2485 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2486 .thenReturn(true); 2487 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2488 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2489 .thenReturn(false); 2490 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2491 2492 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2493 } 2494 2495 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { 2496 setup_splitUser_afterDeviceSetup_systemUser(); 2497 mContext.packageName = admin1.getPackageName(); 2498 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2499 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2500 true/* it's undefined behavior. Can be changed into false in the future */); 2501 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2502 false /* because canAddMoreManagedProfiles returns false */); 2503 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2504 true/* it's undefined behavior. Can be changed into false in the future */); 2505 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2506 false/* because calling uid is system user */); 2507 } 2508 2509 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser() 2510 throws Exception { 2511 setup_splitUser_afterDeviceSetup_systemUser(); 2512 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2513 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2514 DevicePolicyManager.CODE_OK); 2515 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2516 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2517 assertCheckProvisioningPreCondition( 2518 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2519 DevicePolicyManager.CODE_OK); 2520 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2521 DevicePolicyManager.CODE_SYSTEM_USER); 2522 } 2523 2524 private void setup_splitUser_firstBoot_primaryUser() throws Exception { 2525 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2526 .thenReturn(true); 2527 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2528 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2529 true)).thenReturn(true); 2530 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2531 2532 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2533 } 2534 2535 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { 2536 setup_splitUser_firstBoot_primaryUser(); 2537 mContext.packageName = admin1.getPackageName(); 2538 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2539 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2540 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2541 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2542 true); 2543 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); 2544 } 2545 2546 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser() 2547 throws Exception { 2548 setup_splitUser_firstBoot_primaryUser(); 2549 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2550 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2551 DevicePolicyManager.CODE_OK); 2552 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2553 DevicePolicyManager.CODE_OK); 2554 assertCheckProvisioningPreCondition( 2555 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2556 DevicePolicyManager.CODE_OK); 2557 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2558 DevicePolicyManager.CODE_OK); 2559 } 2560 2561 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception { 2562 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2563 .thenReturn(true); 2564 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2565 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2566 true)).thenReturn(true); 2567 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); 2568 2569 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2570 } 2571 2572 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() 2573 throws Exception { 2574 setup_splitUser_afterDeviceSetup_primaryUser(); 2575 mContext.packageName = admin1.getPackageName(); 2576 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2577 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2578 true/* it's undefined behavior. Can be changed into false in the future */); 2579 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2580 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2581 true/* it's undefined behavior. Can be changed into false in the future */); 2582 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2583 false/* because user setup completed */); 2584 } 2585 2586 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser() 2587 throws Exception { 2588 setup_splitUser_afterDeviceSetup_primaryUser(); 2589 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2590 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2591 DevicePolicyManager.CODE_OK); 2592 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2593 DevicePolicyManager.CODE_OK); 2594 assertCheckProvisioningPreCondition( 2595 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2596 DevicePolicyManager.CODE_OK); 2597 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2598 DevicePolicyManager.CODE_USER_SETUP_COMPLETED); 2599 } 2600 2601 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { 2602 setDeviceOwner(); 2603 2604 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2605 .thenReturn(true); 2606 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2607 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2608 .thenReturn(false); 2609 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2610 2611 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2612 } 2613 2614 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() 2615 throws Exception { 2616 setup_provisionManagedProfileWithDeviceOwner_systemUser(); 2617 mContext.packageName = admin1.getPackageName(); 2618 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2619 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2620 false /* can't provision managed profile on system user */); 2621 } 2622 2623 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser() 2624 throws Exception { 2625 setup_provisionManagedProfileWithDeviceOwner_systemUser(); 2626 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2627 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2628 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2629 } 2630 2631 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { 2632 setDeviceOwner(); 2633 2634 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2635 .thenReturn(true); 2636 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2637 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2638 true)).thenReturn(true); 2639 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2640 2641 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2642 } 2643 2644 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() 2645 throws Exception { 2646 setup_provisionManagedProfileWithDeviceOwner_primaryUser(); 2647 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2648 mContext.packageName = admin1.getPackageName(); 2649 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2650 } 2651 2652 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser() 2653 throws Exception { 2654 setup_provisionManagedProfileWithDeviceOwner_primaryUser(); 2655 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2656 2657 // COMP mode is allowed. 2658 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2659 DevicePolicyManager.CODE_OK); 2660 } 2661 2662 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { 2663 setDeviceOwner(); 2664 2665 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2666 .thenReturn(true); 2667 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2668 when(mContext.userManager.hasUserRestriction( 2669 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), 2670 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))) 2671 .thenReturn(true); 2672 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2673 false /* we can't remove a managed profile */)).thenReturn(false); 2674 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2675 true)).thenReturn(true); 2676 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2677 2678 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2679 } 2680 2681 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser() 2682 throws Exception { 2683 setup_provisionManagedProfileCantRemoveUser_primaryUser(); 2684 mContext.packageName = admin1.getPackageName(); 2685 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2686 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2687 } 2688 2689 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser() 2690 throws Exception { 2691 setup_provisionManagedProfileCantRemoveUser_primaryUser(); 2692 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2693 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2694 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE); 2695 } 2696 2697 public void testCheckProvisioningPreCondition_permission() { 2698 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2699 try { 2700 dpm.checkProvisioningPreCondition( 2701 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"); 2702 fail("Didn't throw SecurityException"); 2703 } catch (SecurityException expected) { 2704 } 2705 } 2706 2707 public void testForceUpdateUserSetupComplete_permission() { 2708 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2709 try { 2710 dpm.forceUpdateUserSetupComplete(); 2711 fail("Didn't throw SecurityException"); 2712 } catch (SecurityException expected) { 2713 } 2714 } 2715 2716 public void testForceUpdateUserSetupComplete_systemUser() { 2717 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2718 // GIVEN calling from user 20 2719 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2720 try { 2721 dpm.forceUpdateUserSetupComplete(); 2722 fail("Didn't throw SecurityException"); 2723 } catch (SecurityException expected) { 2724 } 2725 } 2726 2727 public void testForceUpdateUserSetupComplete_userbuild() { 2728 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2729 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2730 2731 final int userId = UserHandle.USER_SYSTEM; 2732 // GIVEN userComplete is false in SettingsProvider 2733 setUserSetupCompleteForUser(false, userId); 2734 2735 // GIVEN userComplete is true in DPM 2736 DevicePolicyManagerService.DevicePolicyData userData = 2737 new DevicePolicyManagerService.DevicePolicyData(userId); 2738 userData.mUserSetupComplete = true; 2739 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2740 2741 // GIVEN it's user build 2742 mContext.buildMock.isDebuggable = false; 2743 2744 assertTrue(dpms.hasUserSetupCompleted()); 2745 2746 dpm.forceUpdateUserSetupComplete(); 2747 2748 // THEN the state in dpms is not changed 2749 assertTrue(dpms.hasUserSetupCompleted()); 2750 } 2751 2752 public void testForceUpdateUserSetupComplete_userDebugbuild() { 2753 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2754 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2755 2756 final int userId = UserHandle.USER_SYSTEM; 2757 // GIVEN userComplete is false in SettingsProvider 2758 setUserSetupCompleteForUser(false, userId); 2759 2760 // GIVEN userComplete is true in DPM 2761 DevicePolicyManagerService.DevicePolicyData userData = 2762 new DevicePolicyManagerService.DevicePolicyData(userId); 2763 userData.mUserSetupComplete = true; 2764 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2765 2766 // GIVEN it's userdebug build 2767 mContext.buildMock.isDebuggable = true; 2768 2769 assertTrue(dpms.hasUserSetupCompleted()); 2770 2771 dpm.forceUpdateUserSetupComplete(); 2772 2773 // THEN the state in dpms is not changed 2774 assertFalse(dpms.hasUserSetupCompleted()); 2775 } 2776 2777 private void clearDeviceOwner() throws Exception { 2778 final long ident = mContext.binder.clearCallingIdentity(); 2779 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2780 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager) 2781 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt()); 2782 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 2783 mContext.binder.restoreCallingIdentity(ident); 2784 } 2785 2786 public void testGetLastSecurityLogRetrievalTime() throws Exception { 2787 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2788 setupDeviceOwner(); 2789 when(mContext.userManager.getUserCount()).thenReturn(1); 2790 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs)) 2791 .thenReturn(true); 2792 2793 // No logs were retrieved so far. 2794 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2795 2796 // Enabling logging should not change the timestamp. 2797 dpm.setSecurityLoggingEnabled(admin1, true); 2798 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2799 2800 // Retrieving the logs should update the timestamp. 2801 final long beforeRetrieval = System.currentTimeMillis(); 2802 dpm.retrieveSecurityLogs(admin1); 2803 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2804 final long afterRetrieval = System.currentTimeMillis(); 2805 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval); 2806 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval); 2807 2808 // Retrieving the pre-boot logs should update the timestamp. 2809 Thread.sleep(2); 2810 dpm.retrievePreRebootSecurityLogs(admin1); 2811 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2812 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime); 2813 2814 // Checking the timestamp again should not change it. 2815 Thread.sleep(2); 2816 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2817 2818 // Retrieving the logs again should update the timestamp. 2819 dpm.retrieveSecurityLogs(admin1); 2820 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2821 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime); 2822 2823 // Disabling logging should not change the timestamp. 2824 Thread.sleep(2); 2825 dpm.setSecurityLoggingEnabled(admin1, false); 2826 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2827 2828 // Restarting the DPMS should not lose the timestamp. 2829 initializeDpms(); 2830 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2831 2832 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2833 mContext.binder.callingUid = 1234567; 2834 mContext.callerPermissions.add(permission.MANAGE_USERS); 2835 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2836 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2837 2838 // System can retrieve the timestamp. 2839 mContext.binder.clearCallingIdentity(); 2840 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2841 2842 // Removing the device owner should clear the timestamp. 2843 clearDeviceOwner(); 2844 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2845 } 2846 2847 public void testGetLastBugReportRequestTime() throws Exception { 2848 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2849 setupDeviceOwner(); 2850 when(mContext.userManager.getUserCount()).thenReturn(1); 2851 mContext.packageName = admin1.getPackageName(); 2852 mContext.applicationInfo = new ApplicationInfo(); 2853 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject())) 2854 .thenReturn(Color.WHITE); 2855 when(mContext.resources.getColor(eq(R.color.notification_material_background_color), 2856 anyObject())).thenReturn(Color.WHITE); 2857 2858 // No bug reports were requested so far. 2859 assertEquals(-1, dpm.getLastBugReportRequestTime()); 2860 2861 // Requesting a bug report should update the timestamp. 2862 final long beforeRequest = System.currentTimeMillis(); 2863 dpm.requestBugreport(admin1); 2864 final long bugReportRequestTime = dpm.getLastBugReportRequestTime(); 2865 final long afterRequest = System.currentTimeMillis(); 2866 assertTrue(bugReportRequestTime >= beforeRequest); 2867 assertTrue(bugReportRequestTime <= afterRequest); 2868 2869 // Checking the timestamp again should not change it. 2870 Thread.sleep(2); 2871 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2872 2873 // Restarting the DPMS should not lose the timestamp. 2874 initializeDpms(); 2875 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2876 2877 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2878 mContext.binder.callingUid = 1234567; 2879 mContext.callerPermissions.add(permission.MANAGE_USERS); 2880 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2881 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2882 2883 // System can retrieve the timestamp. 2884 mContext.binder.clearCallingIdentity(); 2885 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2886 2887 // Removing the device owner should clear the timestamp. 2888 clearDeviceOwner(); 2889 assertEquals(-1, dpm.getLastBugReportRequestTime()); 2890 } 2891 2892 public void testGetLastNetworkLogRetrievalTime() throws Exception { 2893 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2894 setupDeviceOwner(); 2895 when(mContext.userManager.getUserCount()).thenReturn(1); 2896 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject())) 2897 .thenReturn(true); 2898 2899 // No logs were retrieved so far. 2900 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2901 2902 // Attempting to retrieve logs without enabling logging should not change the timestamp. 2903 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2904 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2905 2906 // Enabling logging should not change the timestamp. 2907 dpm.setNetworkLoggingEnabled(admin1, true); 2908 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2909 2910 // Retrieving the logs should update the timestamp. 2911 final long beforeRetrieval = System.currentTimeMillis(); 2912 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2913 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 2914 final long afterRetrieval = System.currentTimeMillis(); 2915 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval); 2916 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval); 2917 2918 // Checking the timestamp again should not change it. 2919 Thread.sleep(2); 2920 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2921 2922 // Retrieving the logs again should update the timestamp. 2923 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2924 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 2925 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime); 2926 2927 // Disabling logging should not change the timestamp. 2928 Thread.sleep(2); 2929 dpm.setNetworkLoggingEnabled(admin1, false); 2930 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2931 2932 // Restarting the DPMS should not lose the timestamp. 2933 initializeDpms(); 2934 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2935 2936 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2937 mContext.binder.callingUid = 1234567; 2938 mContext.callerPermissions.add(permission.MANAGE_USERS); 2939 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2940 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2941 2942 // System can retrieve the timestamp. 2943 mContext.binder.clearCallingIdentity(); 2944 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2945 2946 // Removing the device owner should clear the timestamp. 2947 clearDeviceOwner(); 2948 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2949 } 2950 2951 public void testGetBindDeviceAdminTargetUsers() throws Exception { 2952 // Setup device owner. 2953 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2954 setupDeviceOwner(); 2955 2956 // Only device owner is setup, the result list should be empty. 2957 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2958 MoreAsserts.assertEmpty(targetUsers); 2959 2960 // Setup a managed profile managed by the same admin. 2961 final int MANAGED_PROFILE_USER_ID = 15; 2962 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 2963 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 2964 2965 // Add a secondary user, it should never talk with. 2966 final int ANOTHER_USER_ID = 36; 2967 mContext.addUser(ANOTHER_USER_ID, 0); 2968 2969 // Since the managed profile is not affiliated, they should not be allowed to talk to each 2970 // other. 2971 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2972 MoreAsserts.assertEmpty(targetUsers); 2973 2974 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 2975 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2976 MoreAsserts.assertEmpty(targetUsers); 2977 2978 // Setting affiliation ids 2979 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id"); 2980 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2981 dpm.setAffiliationIds(admin1, userAffiliationIds); 2982 2983 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 2984 dpm.setAffiliationIds(admin1, userAffiliationIds); 2985 2986 // Calling from device owner admin, the result list should just contain the managed 2987 // profile user id. 2988 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2989 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2990 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID)); 2991 2992 // Calling from managed profile admin, the result list should just contain the system 2993 // user id. 2994 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 2995 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2996 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM); 2997 2998 // Changing affiliation ids in one 2999 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id")); 3000 3001 // Since the managed profile is not affiliated any more, they should not be allowed to talk 3002 // to each other. 3003 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3004 MoreAsserts.assertEmpty(targetUsers); 3005 3006 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3007 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3008 MoreAsserts.assertEmpty(targetUsers); 3009 } 3010 3011 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception { 3012 // Setup a device owner. 3013 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3014 setupDeviceOwner(); 3015 3016 // Set up a managed profile managed by different package. 3017 final int MANAGED_PROFILE_USER_ID = 15; 3018 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 3019 final ComponentName adminDifferentPackage = 3020 new ComponentName("another.package", "whatever.class"); 3021 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2); 3022 3023 // Setting affiliation ids 3024 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id"); 3025 dpm.setAffiliationIds(admin1, userAffiliationIds); 3026 3027 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3028 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds); 3029 3030 // Calling from device owner admin, we should get zero bind device admin target users as 3031 // their packages are different. 3032 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3033 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3034 MoreAsserts.assertEmpty(targetUsers); 3035 3036 // Calling from managed profile admin, we should still get zero target users for the same 3037 // reason. 3038 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3039 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage); 3040 MoreAsserts.assertEmpty(targetUsers); 3041 } 3042 3043 public void testIsDeviceManaged() throws Exception { 3044 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3045 setupDeviceOwner(); 3046 3047 // The device owner itself, any uid holding MANAGE_USERS permission and the system can 3048 // find out that the device has a device owner. 3049 assertTrue(dpm.isDeviceManaged()); 3050 mContext.binder.callingUid = 1234567; 3051 mContext.callerPermissions.add(permission.MANAGE_USERS); 3052 assertTrue(dpm.isDeviceManaged()); 3053 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3054 mContext.binder.clearCallingIdentity(); 3055 assertTrue(dpm.isDeviceManaged()); 3056 3057 clearDeviceOwner(); 3058 3059 // Any uid holding MANAGE_USERS permission and the system can find out that the device does 3060 // not have a device owner. 3061 mContext.binder.callingUid = 1234567; 3062 mContext.callerPermissions.add(permission.MANAGE_USERS); 3063 assertFalse(dpm.isDeviceManaged()); 3064 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3065 mContext.binder.clearCallingIdentity(); 3066 assertFalse(dpm.isDeviceManaged()); 3067 } 3068 3069 public void testDeviceOwnerOrganizationName() throws Exception { 3070 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3071 setupDeviceOwner(); 3072 3073 dpm.setOrganizationName(admin1, "organization"); 3074 3075 // Device owner can retrieve organization managing the device. 3076 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3077 3078 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device. 3079 mContext.binder.callingUid = 1234567; 3080 mContext.callerPermissions.add(permission.MANAGE_USERS); 3081 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3082 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3083 3084 // System can retrieve organization managing the device. 3085 mContext.binder.clearCallingIdentity(); 3086 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3087 3088 // Removing the device owner clears the organization managing the device. 3089 clearDeviceOwner(); 3090 assertNull(dpm.getDeviceOwnerOrganizationName()); 3091 } 3092 3093 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 3094 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 3095 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 3096 dpms.notifyChangeToContentObserver( 3097 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 3098 } 3099 3100 private void assertProvisioningAllowed(String action, boolean expected) { 3101 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 3102 dpm.isProvisioningAllowed(action)); 3103 } 3104 3105 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) { 3106 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition); 3107 } 3108 3109 private void assertCheckProvisioningPreCondition( 3110 String action, String packageName, int provisioningCondition) { 3111 assertEquals("checkProvisioningPreCondition(" 3112 + action + ", " + packageName + ") returning unexpected result", 3113 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName)); 3114 } 3115 3116 /** 3117 * Setup a managed profile with the specified admin and its uid. 3118 * @param admin ComponentName that's visible to the test code, which doesn't have to exist. 3119 * @param adminUid uid of the admin package. 3120 * @param copyFromAdmin package information for {@code admin} will be built based on this 3121 * component's information. 3122 */ 3123 private void addManagedProfile( 3124 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception { 3125 final int userId = UserHandle.getUserId(adminUid); 3126 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); 3127 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 3128 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); 3129 dpm.setActiveAdmin(admin, false, userId); 3130 assertTrue(dpm.setProfileOwner(admin, null, userId)); 3131 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 3132 } 3133} 3134