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 */ 16 package com.android.server.devicepolicy; 17 18 import android.Manifest.permission; 19 import android.app.Activity; 20 import android.app.admin.DeviceAdminReceiver; 21 import android.app.admin.DevicePolicyManager; 22 import android.app.admin.DevicePolicyManagerInternal; 23 import android.content.BroadcastReceiver; 24 import android.content.ComponentName; 25 import android.content.pm.ApplicationInfo; 26 import android.content.pm.PackageInfo; 27 import android.content.pm.PackageManager; 28 import android.net.wifi.WifiInfo; 29 import android.os.Build.VERSION_CODES; 30 import android.os.Build; 31 import android.os.Bundle; 32 import android.os.Process; 33 import android.os.UserHandle; 34 import android.os.UserManager; 35 import android.provider.Settings; 36 import android.telephony.TelephonyManager; 37 import android.test.MoreAsserts; 38 import android.test.suitebuilder.annotation.SmallTest; 39 import android.util.ArraySet; 40 import android.util.Pair; 41 42 import com.android.server.LocalServices; 43 import com.android.server.SystemService; 44 45 import org.mockito.ArgumentCaptor; 46 import org.mockito.invocation.InvocationOnMock; 47 import org.mockito.stubbing.Answer; 48 49 import java.util.ArrayList; 50 import java.util.Arrays; 51 import java.util.HashMap; 52 import java.util.List; 53 import java.util.Map; 54 import java.util.Set; 55 56 import static org.mockito.Matchers.any; 57 import static org.mockito.Matchers.anyInt; 58 import static org.mockito.Matchers.anyString; 59 import static org.mockito.Matchers.eq; 60 import static org.mockito.Matchers.isNull; 61 import static org.mockito.Mockito.doAnswer; 62 import static org.mockito.Mockito.doReturn; 63 import static org.mockito.Mockito.reset; 64 import static org.mockito.Mockito.times; 65 import static org.mockito.Mockito.validateMockitoUsage; 66 import static org.mockito.Mockito.verify; 67 import static org.mockito.Mockito.when; 68 69 /** 70 * Tests for DevicePolicyManager( and DevicePolicyManagerService). 71 * 72 m FrameworksServicesTests && 73 adb install \ 74 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && 75 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \ 76 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner 77 78 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) 79 */ 80 @SmallTest 81 public class DevicePolicyManagerTest extends DpmTestBase { 82 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList( 83 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, 84 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL); 85 86 private DpmMockContext mContext; 87 public DevicePolicyManager dpm; 88 public DevicePolicyManagerServiceTestable dpms; 89 90 @Override setUp()91 protected void setUp() throws Exception { 92 super.setUp(); 93 94 mContext = getContext(); 95 96 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 97 .thenReturn(true); 98 99 // By default, pretend all users are running and unlocked. 100 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 101 102 initializeDpms(); 103 104 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 105 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 106 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID); 107 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID); 108 109 setUpUserManager(); 110 } 111 initializeDpms()112 private void initializeDpms() { 113 // Need clearCallingIdentity() to pass permission checks. 114 final long ident = mContext.binder.clearCallingIdentity(); 115 try { 116 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 117 118 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); 119 120 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); 121 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); 122 123 dpm = new DevicePolicyManagerTestable(mContext, dpms); 124 } finally { 125 mContext.binder.restoreCallingIdentity(ident); 126 } 127 } 128 setUpUserManager()129 private void setUpUserManager() { 130 // Emulate UserManager.set/getApplicationRestriction(). 131 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>(); 132 133 // UM.setApplicationRestrictions() will save to appRestrictions. 134 doAnswer(new Answer<Void>() { 135 @Override 136 public Void answer(InvocationOnMock invocation) throws Throwable { 137 String pkg = (String) invocation.getArguments()[0]; 138 Bundle bundle = (Bundle) invocation.getArguments()[1]; 139 UserHandle user = (UserHandle) invocation.getArguments()[2]; 140 141 appRestrictions.put(Pair.create(pkg, user), bundle); 142 143 return null; 144 } 145 }).when(mContext.userManager).setApplicationRestrictions( 146 anyString(), any(Bundle.class), any(UserHandle.class)); 147 148 // UM.getApplicationRestrictions() will read from appRestrictions. 149 doAnswer(new Answer<Bundle>() { 150 @Override 151 public Bundle answer(InvocationOnMock invocation) throws Throwable { 152 String pkg = (String) invocation.getArguments()[0]; 153 UserHandle user = (UserHandle) invocation.getArguments()[1]; 154 155 return appRestrictions.get(Pair.create(pkg, user)); 156 } 157 }).when(mContext.userManager).getApplicationRestrictions( 158 anyString(), any(UserHandle.class)); 159 160 // Add the first secondary user. 161 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0); 162 } 163 setAsProfileOwner(ComponentName admin)164 private void setAsProfileOwner(ComponentName admin) { 165 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 166 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 167 168 // PO needs to be an DA. 169 dpm.setActiveAdmin(admin, /* replace =*/ false); 170 171 // Fire! 172 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 173 174 // Check 175 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); 176 } 177 testHasNoFeature()178 public void testHasNoFeature() throws Exception { 179 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 180 .thenReturn(false); 181 182 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 183 new DevicePolicyManagerServiceTestable(mContext, dataDir); 184 185 // If the device has no DPMS feature, it shouldn't register the local service. 186 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); 187 } 188 189 /** 190 * Caller doesn't have proper permissions. 191 */ testSetActiveAdmin_SecurityException()192 public void testSetActiveAdmin_SecurityException() { 193 // 1. Failure cases. 194 195 // Caller doesn't have MANAGE_DEVICE_ADMINS. 196 try { 197 dpm.setActiveAdmin(admin1, false); 198 fail("Didn't throw SecurityException"); 199 } catch (SecurityException expected) { 200 } 201 202 // Caller has MANAGE_DEVICE_ADMINS, but for different user. 203 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 204 try { 205 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1); 206 fail("Didn't throw SecurityException"); 207 } catch (SecurityException expected) { 208 } 209 } 210 211 /** 212 * Test for: 213 * {@link DevicePolicyManager#setActiveAdmin} 214 * with replace=false and replace=true 215 * {@link DevicePolicyManager#isAdminActive} 216 * {@link DevicePolicyManager#isAdminActiveAsUser} 217 * {@link DevicePolicyManager#getActiveAdmins} 218 * {@link DevicePolicyManager#getActiveAdminsAsUser} 219 */ testSetActiveAdmin()220 public void testSetActiveAdmin() throws Exception { 221 // 1. Make sure the caller has proper permissions. 222 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 223 224 // 2. Call the API. 225 dpm.setActiveAdmin(admin1, /* replace =*/ false); 226 227 // 3. Verify internal calls. 228 229 // Check if the boradcast is sent. 230 verify(mContext.spiedContext).sendBroadcastAsUser( 231 MockUtils.checkIntentAction( 232 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 233 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 234 verify(mContext.spiedContext).sendBroadcastAsUser( 235 MockUtils.checkIntentAction( 236 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED), 237 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 238 239 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 240 eq(admin1.getPackageName()), 241 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 242 eq(PackageManager.DONT_KILL_APP), 243 eq(DpmMockContext.CALLER_USER_HANDLE), 244 anyString()); 245 246 // TODO Verify other calls too. 247 248 // Make sure it's active admin1. 249 assertTrue(dpm.isAdminActive(admin1)); 250 assertFalse(dpm.isAdminActive(admin2)); 251 assertFalse(dpm.isAdminActive(admin3)); 252 253 // But not admin1 for a different user. 254 255 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL. 256 // (Because we're checking a different user's status from CALLER_USER_HANDLE.) 257 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 258 259 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1)); 260 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1)); 261 262 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 263 264 // Next, add one more admin. 265 // Before doing so, update the application info, now it's enabled. 266 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID, 267 PackageManager.COMPONENT_ENABLED_STATE_ENABLED); 268 269 dpm.setActiveAdmin(admin2, /* replace =*/ false); 270 271 // Now we have two admins. 272 assertTrue(dpm.isAdminActive(admin1)); 273 assertTrue(dpm.isAdminActive(admin2)); 274 assertFalse(dpm.isAdminActive(admin3)); 275 276 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called 277 // again. (times(1) because it was previously called for admin1) 278 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 279 eq(admin1.getPackageName()), 280 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 281 eq(PackageManager.DONT_KILL_APP), 282 eq(DpmMockContext.CALLER_USER_HANDLE), 283 anyString()); 284 285 // 4. Add the same admin1 again without replace, which should throw. 286 try { 287 dpm.setActiveAdmin(admin1, /* replace =*/ false); 288 fail("Didn't throw"); 289 } catch (IllegalArgumentException expected) { 290 } 291 292 // 5. Add the same admin1 again with replace, which should succeed. 293 dpm.setActiveAdmin(admin1, /* replace =*/ true); 294 295 // TODO make sure it's replaced. 296 297 // 6. Test getActiveAdmins() 298 List<ComponentName> admins = dpm.getActiveAdmins(); 299 assertEquals(2, admins.size()); 300 assertEquals(admin1, admins.get(0)); 301 assertEquals(admin2, admins.get(1)); 302 303 // Another user has no admins. 304 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 305 306 assertEquals(0, DpmTestUtils.getListSizeAllowingNull( 307 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1))); 308 309 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 310 } 311 testSetActiveAdmin_multiUsers()312 public void testSetActiveAdmin_multiUsers() throws Exception { 313 314 final int ANOTHER_USER_ID = 100; 315 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456); 316 317 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 318 319 // Set up pacakge manager for the other user. 320 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 321 322 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 323 324 dpm.setActiveAdmin(admin1, /* replace =*/ false); 325 326 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 327 dpm.setActiveAdmin(admin2, /* replace =*/ false); 328 329 330 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 331 assertTrue(dpm.isAdminActive(admin1)); 332 assertFalse(dpm.isAdminActive(admin2)); 333 334 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 335 assertFalse(dpm.isAdminActive(admin1)); 336 assertTrue(dpm.isAdminActive(admin2)); 337 } 338 339 /** 340 * Test for: 341 * {@link DevicePolicyManager#setActiveAdmin} 342 * with replace=false 343 */ testSetActiveAdmin_twiceWithoutReplace()344 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception { 345 // 1. Make sure the caller has proper permissions. 346 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 347 348 dpm.setActiveAdmin(admin1, /* replace =*/ false); 349 assertTrue(dpm.isAdminActive(admin1)); 350 351 // Add the same admin1 again without replace, which should throw. 352 try { 353 dpm.setActiveAdmin(admin1, /* replace =*/ false); 354 fail("Didn't throw"); 355 } catch (IllegalArgumentException expected) { 356 } 357 } 358 359 /** 360 * Test for: 361 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with 362 * BIND_DEVICE_ADMIN. 363 */ testSetActiveAdmin_permissionCheck()364 public void testSetActiveAdmin_permissionCheck() throws Exception { 365 // 1. Make sure the caller has proper permissions. 366 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 367 368 try { 369 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 370 fail(); 371 } catch (IllegalArgumentException expected) { 372 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN)); 373 } 374 assertFalse(dpm.isAdminActive(adminNoPerm)); 375 376 // Change the target API level to MNC. Now it can be set as DA. 377 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null, 378 VERSION_CODES.M); 379 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 380 assertTrue(dpm.isAdminActive(adminNoPerm)); 381 382 // TODO Test the "load from the file" case where DA will still be loaded even without 383 // BIND_DEVICE_ADMIN and target API is N. 384 } 385 386 /** 387 * Test for: 388 * {@link DevicePolicyManager#removeActiveAdmin} 389 */ testRemoveActiveAdmin_SecurityException()390 public void testRemoveActiveAdmin_SecurityException() { 391 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 392 393 // Add admin. 394 395 dpm.setActiveAdmin(admin1, /* replace =*/ false); 396 397 assertTrue(dpm.isAdminActive(admin1)); 398 399 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 400 401 // Directly call the DPMS method with a different userid, which should fail. 402 try { 403 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1); 404 fail("Didn't throw SecurityException"); 405 } catch (SecurityException expected) { 406 } 407 408 // Try to remove active admin with a different caller userid should fail too, without 409 // having MANAGE_DEVICE_ADMINS. 410 mContext.callerPermissions.clear(); 411 412 // Change the caller, and call into DPMS directly with a different user-id. 413 414 mContext.binder.callingUid = 1234567; 415 try { 416 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 417 fail("Didn't throw SecurityException"); 418 } catch (SecurityException expected) { 419 } 420 } 421 422 /** 423 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked 424 * (because we can't send the remove broadcast). 425 */ testRemoveActiveAdmin_userNotRunningOrLocked()426 public void testRemoveActiveAdmin_userNotRunningOrLocked() { 427 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 428 429 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 430 431 // Add admin. 432 433 dpm.setActiveAdmin(admin1, /* replace =*/ false); 434 435 assertTrue(dpm.isAdminActive(admin1)); 436 437 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 438 439 // 1. User not unlocked. 440 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 441 .thenReturn(false); 442 try { 443 dpm.removeActiveAdmin(admin1); 444 fail("Didn't throw IllegalStateException"); 445 } catch (IllegalStateException expected) { 446 MoreAsserts.assertContainsRegex( 447 "User must be running and unlocked", expected.getMessage()); 448 } 449 450 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 451 452 // 2. User unlocked. 453 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 454 .thenReturn(true); 455 456 dpm.removeActiveAdmin(admin1); 457 458 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 459 } 460 461 /** 462 * Test for: 463 * {@link DevicePolicyManager#removeActiveAdmin} 464 */ testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL()465 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() { 466 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 467 468 // Add admin1. 469 470 dpm.setActiveAdmin(admin1, /* replace =*/ false); 471 472 assertTrue(dpm.isAdminActive(admin1)); 473 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 474 475 // Different user, but should work, because caller has proper permissions. 476 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 477 478 // Change the caller, and call into DPMS directly with a different user-id. 479 mContext.binder.callingUid = 1234567; 480 481 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 482 483 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 484 485 // TODO DO Still can't be removed in this case. 486 } 487 488 /** 489 * Test for: 490 * {@link DevicePolicyManager#removeActiveAdmin} 491 */ testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS()492 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() { 493 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. 494 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 495 496 // Add admin1. 497 498 dpm.setActiveAdmin(admin1, /* replace =*/ false); 499 500 assertTrue(dpm.isAdminActive(admin1)); 501 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 502 503 // Broadcast from saveSettingsLocked(). 504 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 505 MockUtils.checkIntentAction( 506 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 507 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 508 509 // Remove. No permissions, but same user, so it'll work. 510 mContext.callerPermissions.clear(); 511 dpm.removeActiveAdmin(admin1); 512 513 final ArgumentCaptor<BroadcastReceiver> brCap = 514 ArgumentCaptor.forClass(BroadcastReceiver.class); 515 516 // Is removing now, but not removed yet. 517 assertTrue(dpm.isAdminActive(admin1)); 518 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 519 520 verify(mContext.spiedContext).sendOrderedBroadcastAsUser( 521 MockUtils.checkIntentAction( 522 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED), 523 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE), 524 isNull(String.class), 525 brCap.capture(), 526 eq(dpms.mHandler), 527 eq(Activity.RESULT_OK), 528 isNull(String.class), 529 isNull(Bundle.class)); 530 531 brCap.getValue().onReceive(mContext, null); 532 533 assertFalse(dpm.isAdminActive(admin1)); 534 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 535 536 // Again broadcast from saveSettingsLocked(). 537 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 538 MockUtils.checkIntentAction( 539 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 540 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 541 542 // TODO Check other internal calls. 543 } 544 545 /** 546 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully. 547 */ testSetDeviceOwner()548 public void testSetDeviceOwner() throws Exception { 549 setDeviceOwner(); 550 551 // Try to set a profile owner on the same user, which should fail. 552 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 553 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM); 554 try { 555 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM); 556 fail("IllegalStateException not thrown"); 557 } catch (IllegalStateException expected) { 558 assertTrue("Message was: " + expected.getMessage(), 559 expected.getMessage().contains("already has a device owner")); 560 } 561 562 // DO admin can't be deactivated. 563 dpm.removeActiveAdmin(admin1); 564 assertTrue(dpm.isAdminActive(admin1)); 565 566 // TODO Test getDeviceOwnerName() too. To do so, we need to change 567 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 568 } 569 setDeviceOwner()570 private void setDeviceOwner() throws Exception { 571 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 572 mContext.callerPermissions.add(permission.MANAGE_USERS); 573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 574 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 575 576 // In this test, change the caller user to "system". 577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 578 579 // Make sure admin1 is installed on system user. 580 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 581 582 // Check various get APIs. 583 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false); 584 585 // DO needs to be an DA. 586 dpm.setActiveAdmin(admin1, /* replace =*/ false); 587 588 // Fire! 589 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 590 591 // getDeviceOwnerComponent should return the admin1 component. 592 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 593 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 594 595 // Check various get APIs. 596 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true); 597 598 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users. 599 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 600 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 601 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 602 603 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 604 605 // Verify internal calls. 606 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 607 eq(admin1.getPackageName())); 608 609 // TODO We should check if the caller has called clearCallerIdentity(). 610 verify(mContext.ibackupManager, times(1)).setBackupServiceActive( 611 eq(UserHandle.USER_SYSTEM), eq(false)); 612 613 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 614 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 615 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 616 617 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 618 } 619 checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner)620 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) { 621 final int origCallingUser = mContext.binder.callingUid; 622 final List origPermissions = new ArrayList(mContext.callerPermissions); 623 mContext.callerPermissions.clear(); 624 625 mContext.callerPermissions.add(permission.MANAGE_USERS); 626 627 mContext.binder.callingUid = Process.SYSTEM_UID; 628 629 // TODO Test getDeviceOwnerName() too. To do so, we need to change 630 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 631 if (hasDeviceOwner) { 632 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 633 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 634 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 635 636 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 637 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 638 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 639 } else { 640 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 641 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 642 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 643 644 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 645 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 646 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 647 } 648 649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 650 if (hasDeviceOwner) { 651 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 652 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 653 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 654 655 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 656 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 657 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 658 } else { 659 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 660 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 661 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 662 663 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 664 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 665 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 666 } 667 668 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 669 // Still with MANAGE_USERS. 670 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 671 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 672 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 673 674 if (hasDeviceOwner) { 675 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 676 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 677 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 678 } else { 679 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 680 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 681 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 682 } 683 684 mContext.binder.callingUid = Process.SYSTEM_UID; 685 mContext.callerPermissions.remove(permission.MANAGE_USERS); 686 // System can still call "OnAnyUser" without MANAGE_USERS. 687 if (hasDeviceOwner) { 688 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 689 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 691 692 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 693 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 694 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 695 } else { 696 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 697 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 698 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 699 700 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 701 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 702 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 703 } 704 705 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 706 // Still no MANAGE_USERS. 707 if (hasDeviceOwner) { 708 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 709 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 710 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 711 } else { 712 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 713 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 714 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 715 } 716 717 try { 718 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 719 fail(); 720 } catch (SecurityException expected) { 721 } 722 try { 723 dpm.getDeviceOwnerComponentOnAnyUser(); 724 fail(); 725 } catch (SecurityException expected) { 726 } 727 try { 728 dpm.getDeviceOwnerUserId(); 729 fail(); 730 } catch (SecurityException expected) { 731 } 732 try { 733 dpm.getDeviceOwnerNameOnAnyUser(); 734 fail(); 735 } catch (SecurityException expected) { 736 } 737 738 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 739 // Still no MANAGE_USERS. 740 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 741 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 742 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 743 744 try { 745 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 746 fail(); 747 } catch (SecurityException expected) { 748 } 749 try { 750 dpm.getDeviceOwnerComponentOnAnyUser(); 751 fail(); 752 } catch (SecurityException expected) { 753 } 754 try { 755 dpm.getDeviceOwnerUserId(); 756 fail(); 757 } catch (SecurityException expected) { 758 } 759 try { 760 dpm.getDeviceOwnerNameOnAnyUser(); 761 fail(); 762 } catch (SecurityException expected) { 763 } 764 765 // Restore. 766 mContext.binder.callingUid = origCallingUser; 767 mContext.callerPermissions.addAll(origPermissions); 768 } 769 770 771 /** 772 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist. 773 */ testSetDeviceOwner_noSuchPackage()774 public void testSetDeviceOwner_noSuchPackage() { 775 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 776 mContext.callerPermissions.add(permission.MANAGE_USERS); 777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 778 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 779 780 // Call from a process on the system user. 781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 782 783 try { 784 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")); 785 fail("Didn't throw IllegalArgumentException"); 786 } catch (IllegalArgumentException expected) { 787 assertTrue("Message was: " + expected.getMessage(), 788 expected.getMessage().contains("Invalid component")); 789 } 790 } 791 testSetDeviceOwner_failures()792 public void testSetDeviceOwner_failures() throws Exception { 793 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner(). 794 } 795 testClearDeviceOwner()796 public void testClearDeviceOwner() throws Exception { 797 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 798 mContext.callerPermissions.add(permission.MANAGE_USERS); 799 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 800 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 801 802 // Set admin1 as a DA to the secondary user. 803 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 804 805 dpm.setActiveAdmin(admin1, /* replace =*/ false); 806 807 // Set admin 1 as the DO to the system user. 808 809 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 810 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 811 dpm.setActiveAdmin(admin1, /* replace =*/ false); 812 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 813 814 // Verify internal calls. 815 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 816 eq(admin1.getPackageName())); 817 818 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 819 820 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 821 822 assertTrue(dpm.isAdminActive(admin1)); 823 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); 824 825 // Set up other mocks. 826 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle()); 827 828 // Now call clear. 829 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser( 830 eq(admin1.getPackageName()), 831 anyInt()); 832 833 // But first pretend the user is locked. Then it should fail. 834 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false); 835 try { 836 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 837 fail("Didn't throw IllegalStateException"); 838 } catch (IllegalStateException expected) { 839 MoreAsserts.assertContainsRegex( 840 "User must be running and unlocked", expected.getMessage()); 841 } 842 843 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 844 reset(mContext.userManagerInternal); 845 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 846 847 // Now DO shouldn't be set. 848 assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); 849 850 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 851 eq(UserHandle.USER_SYSTEM), 852 MockUtils.checkUserRestrictions(), 853 MockUtils.checkUserRestrictions() 854 ); 855 856 assertTrue(dpm.isAdminActive(admin1)); 857 assertTrue(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); 858 859 // TODO Check other calls. 860 } 861 testClearDeviceOwner_fromDifferentUser()862 public void testClearDeviceOwner_fromDifferentUser() throws Exception { 863 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 864 mContext.callerPermissions.add(permission.MANAGE_USERS); 865 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 866 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 867 868 // Set admin1 as a DA to the secondary user. 869 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 870 871 dpm.setActiveAdmin(admin1, /* replace =*/ false); 872 873 // Set admin 1 as the DO to the system user. 874 875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 876 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 877 dpm.setActiveAdmin(admin1, /* replace =*/ false); 878 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 879 880 // Verify internal calls. 881 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 882 eq(admin1.getPackageName())); 883 884 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 885 886 // Now call clear from the secondary user, which should throw. 887 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 888 889 // Now call clear. 890 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( 891 eq(admin1.getPackageName()), 892 anyInt()); 893 try { 894 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 895 fail("Didn't throw"); 896 } catch (SecurityException e) { 897 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage()); 898 } 899 900 // DO shouldn't be removed. 901 assertTrue(dpm.isDeviceManaged()); 902 } 903 testSetProfileOwner()904 public void testSetProfileOwner() throws Exception { 905 setAsProfileOwner(admin1); 906 907 // PO admin can't be deactivated. 908 dpm.removeActiveAdmin(admin1); 909 assertTrue(dpm.isAdminActive(admin1)); 910 911 // Try setting DO on the same user, which should fail. 912 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 913 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); 914 try { 915 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); 916 fail("IllegalStateException not thrown"); 917 } catch (IllegalStateException expected) { 918 assertTrue("Message was: " + expected.getMessage(), 919 expected.getMessage().contains("already has a profile owner")); 920 } 921 } 922 testClearProfileOwner()923 public void testClearProfileOwner() throws Exception { 924 setAsProfileOwner(admin1); 925 926 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 927 928 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); 929 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 930 931 // First try when the user is locked, which should fail. 932 when(mContext.userManager.isUserUnlocked(anyInt())) 933 .thenReturn(false); 934 try { 935 dpm.clearProfileOwner(admin1); 936 fail("Didn't throw IllegalStateException"); 937 } catch (IllegalStateException expected) { 938 MoreAsserts.assertContainsRegex( 939 "User must be running and unlocked", expected.getMessage()); 940 } 941 // Clear, really. 942 when(mContext.userManager.isUserUnlocked(anyInt())) 943 .thenReturn(true); 944 dpm.clearProfileOwner(admin1); 945 946 // Check 947 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); 948 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 949 } 950 testSetProfileOwner_failures()951 public void testSetProfileOwner_failures() throws Exception { 952 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). 953 } 954 testGetDeviceOwnerAdminLocked()955 public void testGetDeviceOwnerAdminLocked() throws Exception { 956 checkDeviceOwnerWithMultipleDeviceAdmins(); 957 } 958 checkDeviceOwnerWithMultipleDeviceAdmins()959 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception { 960 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them, 961 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to 962 // make sure it gets the right component from the right user. 963 964 final int ANOTHER_USER_ID = 100; 965 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); 966 967 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 968 969 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 970 mContext.callerPermissions.add(permission.MANAGE_USERS); 971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 972 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 973 974 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 975 976 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 977 978 // Make sure the admin packge is installed to each user. 979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 980 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID); 981 982 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 983 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 984 985 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 986 987 988 // Set active admins to the users. 989 dpm.setActiveAdmin(admin1, /* replace =*/ false); 990 dpm.setActiveAdmin(admin3, /* replace =*/ false); 991 992 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 993 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 994 995 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); 996 997 // Set DO on the first non-system user. 998 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); 999 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1000 1001 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1002 1003 // Then check getDeviceOwnerAdminLocked(). 1004 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent()); 1005 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid()); 1006 } 1007 1008 /** 1009 * This essentially tests 1010 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is 1011 * private.) 1012 * 1013 * We didn't use to persist the DO component class name, but now we do, and the above method 1014 * finds the right component from a package name upon migration. 1015 */ testDeviceOwnerMigration()1016 public void testDeviceOwnerMigration() throws Exception { 1017 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1018 checkDeviceOwnerWithMultipleDeviceAdmins(); 1019 1020 // Overwrite the device owner setting and clears the clas name. 1021 dpms.mOwners.setDeviceOwner( 1022 new ComponentName(admin2.getPackageName(), ""), 1023 "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1024 dpms.mOwners.writeDeviceOwner(); 1025 1026 // Make sure the DO component name doesn't have a class name. 1027 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); 1028 1029 // Then create a new DPMS to have it load the settings from files. 1030 when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) 1031 .thenReturn(new Bundle()); 1032 initializeDpms(); 1033 1034 // Now the DO component name is a full name. 1035 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the 1036 // DO. 1037 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1038 } 1039 testSetGetApplicationRestriction()1040 public void testSetGetApplicationRestriction() { 1041 setAsProfileOwner(admin1); 1042 1043 { 1044 Bundle rest = new Bundle(); 1045 rest.putString("KEY_STRING", "Foo1"); 1046 dpm.setApplicationRestrictions(admin1, "pkg1", rest); 1047 } 1048 1049 { 1050 Bundle rest = new Bundle(); 1051 rest.putString("KEY_STRING", "Foo2"); 1052 dpm.setApplicationRestrictions(admin1, "pkg2", rest); 1053 } 1054 1055 { 1056 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); 1057 assertNotNull(returned); 1058 assertEquals(returned.size(), 1); 1059 assertEquals(returned.get("KEY_STRING"), "Foo1"); 1060 } 1061 1062 { 1063 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); 1064 assertNotNull(returned); 1065 assertEquals(returned.size(), 1); 1066 assertEquals(returned.get("KEY_STRING"), "Foo2"); 1067 } 1068 1069 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); 1070 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); 1071 } 1072 testApplicationRestrictionsManagingApp()1073 public void testApplicationRestrictionsManagingApp() throws Exception { 1074 setAsProfileOwner(admin1); 1075 1076 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2"; 1077 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager"; 1078 final int appRestrictionsManagerAppId = 20987; 1079 final int appRestrictionsManagerUid = UserHandle.getUid( 1080 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId); 1081 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser( 1082 eq(appRestrictionsManagerPackage), 1083 eq(DpmMockContext.CALLER_USER_HANDLE)); 1084 mContext.binder.callingUid = appRestrictionsManagerUid; 1085 1086 final PackageInfo pi = new PackageInfo(); 1087 pi.applicationInfo = new ApplicationInfo(); 1088 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE; 1089 doReturn(pi).when(mContext.ipackageManager).getPackageInfo( 1090 eq(appRestrictionsManagerPackage), 1091 anyInt(), 1092 eq(DpmMockContext.CALLER_USER_HANDLE)); 1093 1094 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't 1095 // delegated that permission yet. 1096 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1097 Bundle rest = new Bundle(); 1098 rest.putString("KEY_STRING", "Foo1"); 1099 try { 1100 dpm.setApplicationRestrictions(null, "pkg1", rest); 1101 fail("Didn't throw expected SecurityException"); 1102 } catch (SecurityException expected) { 1103 MoreAsserts.assertContainsRegex( 1104 "caller cannot manage application restrictions", expected.getMessage()); 1105 } 1106 try { 1107 dpm.getApplicationRestrictions(null, "pkg1"); 1108 fail("Didn't throw expected SecurityException"); 1109 } catch (SecurityException expected) { 1110 MoreAsserts.assertContainsRegex( 1111 "caller cannot manage application restrictions", expected.getMessage()); 1112 } 1113 1114 // Check via the profile owner that no restrictions were set. 1115 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1116 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1117 1118 // Check the API does not allow setting a non-existent package 1119 try { 1120 dpm.setApplicationRestrictionsManagingPackage(admin1, 1121 nonExistAppRestrictionsManagerPackage); 1122 fail("Non-existent app set as app restriction manager."); 1123 } catch (PackageManager.NameNotFoundException expected) { 1124 MoreAsserts.assertContainsRegex( 1125 nonExistAppRestrictionsManagerPackage, expected.getMessage()); 1126 } 1127 1128 // Let appRestrictionsManagerPackage manage app restrictions 1129 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); 1130 assertEquals(appRestrictionsManagerPackage, 1131 dpm.getApplicationRestrictionsManagingPackage(admin1)); 1132 1133 // Now that package should be able to set and retrieve app restrictions. 1134 mContext.binder.callingUid = appRestrictionsManagerUid; 1135 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); 1136 dpm.setApplicationRestrictions(null, "pkg1", rest); 1137 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); 1138 assertEquals(1, returned.size(), 1); 1139 assertEquals("Foo1", returned.get("KEY_STRING")); 1140 1141 // The same app running on a separate user shouldn't be able to manage app restrictions. 1142 mContext.binder.callingUid = UserHandle.getUid( 1143 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); 1144 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1145 try { 1146 dpm.setApplicationRestrictions(null, "pkg1", rest); 1147 fail("Didn't throw expected SecurityException"); 1148 } catch (SecurityException expected) { 1149 MoreAsserts.assertContainsRegex( 1150 "caller cannot manage application restrictions", expected.getMessage()); 1151 } 1152 1153 // The DPM is still able to manage app restrictions, even if it allowed another app to do it 1154 // too. 1155 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1156 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); 1157 dpm.setApplicationRestrictions(admin1, "pkg1", null); 1158 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1159 1160 // Removing the ability for the package to manage app restrictions. 1161 dpm.setApplicationRestrictionsManagingPackage(admin1, null); 1162 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); 1163 mContext.binder.callingUid = appRestrictionsManagerUid; 1164 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1165 try { 1166 dpm.setApplicationRestrictions(null, "pkg1", null); 1167 fail("Didn't throw expected SecurityException"); 1168 } catch (SecurityException expected) { 1169 MoreAsserts.assertContainsRegex( 1170 "caller cannot manage application restrictions", expected.getMessage()); 1171 } 1172 } 1173 testSetUserRestriction_asDo()1174 public void testSetUserRestriction_asDo() throws Exception { 1175 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1176 mContext.callerPermissions.add(permission.MANAGE_USERS); 1177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1178 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1179 1180 // First, set DO. 1181 1182 // Call from a process on the system user. 1183 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1184 1185 // Make sure admin1 is installed on system user. 1186 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1187 1188 // Call. 1189 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1190 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1191 UserHandle.USER_SYSTEM)); 1192 1193 DpmTestUtils.assertRestrictions( 1194 DpmTestUtils.newRestrictions(), 1195 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1196 ); 1197 DpmTestUtils.assertRestrictions( 1198 DpmTestUtils.newRestrictions(), 1199 dpm.getUserRestrictions(admin1) 1200 ); 1201 1202 reset(mContext.userManagerInternal); 1203 1204 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1205 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1206 eq(UserHandle.USER_SYSTEM), 1207 MockUtils.checkUserRestrictions(), 1208 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1209 ); 1210 reset(mContext.userManagerInternal); 1211 1212 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1213 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1214 eq(UserHandle.USER_SYSTEM), 1215 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1216 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1217 ); 1218 reset(mContext.userManagerInternal); 1219 1220 DpmTestUtils.assertRestrictions( 1221 DpmTestUtils.newRestrictions( 1222 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1223 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1224 ); 1225 DpmTestUtils.assertRestrictions( 1226 DpmTestUtils.newRestrictions( 1227 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1228 dpm.getUserRestrictions(admin1) 1229 ); 1230 1231 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1232 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1233 eq(UserHandle.USER_SYSTEM), 1234 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1235 MockUtils.checkUserRestrictions() 1236 ); 1237 reset(mContext.userManagerInternal); 1238 1239 DpmTestUtils.assertRestrictions( 1240 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1241 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1242 ); 1243 DpmTestUtils.assertRestrictions( 1244 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1245 dpm.getUserRestrictions(admin1) 1246 ); 1247 1248 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1249 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1250 eq(UserHandle.USER_SYSTEM), 1251 MockUtils.checkUserRestrictions(), 1252 MockUtils.checkUserRestrictions() 1253 ); 1254 reset(mContext.userManagerInternal); 1255 1256 DpmTestUtils.assertRestrictions( 1257 DpmTestUtils.newRestrictions(), 1258 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1259 ); 1260 DpmTestUtils.assertRestrictions( 1261 DpmTestUtils.newRestrictions(), 1262 dpm.getUserRestrictions(admin1) 1263 ); 1264 1265 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when 1266 // DO sets them, the scope is global. 1267 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1268 reset(mContext.userManagerInternal); 1269 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1270 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1271 eq(UserHandle.USER_SYSTEM), 1272 MockUtils.checkUserRestrictions(), 1273 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1274 UserManager.DISALLOW_UNMUTE_MICROPHONE) 1275 ); 1276 reset(mContext.userManagerInternal); 1277 1278 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1279 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1280 1281 1282 // More tests. 1283 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1284 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1285 eq(UserHandle.USER_SYSTEM), 1286 MockUtils.checkUserRestrictions(), 1287 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1288 ); 1289 reset(mContext.userManagerInternal); 1290 1291 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); 1292 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1293 eq(UserHandle.USER_SYSTEM), 1294 MockUtils.checkUserRestrictions(), 1295 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1296 UserManager.DISALLOW_ADD_USER) 1297 ); 1298 reset(mContext.userManagerInternal); 1299 1300 dpm.setCameraDisabled(admin1, true); 1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1302 eq(UserHandle.USER_SYSTEM), 1303 // DISALLOW_CAMERA will be applied to both local and global. 1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1305 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1306 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER) 1307 ); 1308 reset(mContext.userManagerInternal); 1309 1310 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied 1311 // locally. 1312 dpm.setCameraDisabled(admin1, false); 1313 reset(mContext.userManagerInternal); 1314 1315 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 1316 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); 1317 dpm.setCameraDisabled(admin2, true); 1318 1319 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1320 eq(UserHandle.USER_SYSTEM), 1321 // DISALLOW_CAMERA will be applied to both local and global. 1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1323 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1324 UserManager.DISALLOW_ADD_USER) 1325 ); 1326 reset(mContext.userManagerInternal); 1327 // TODO Make sure restrictions are written to the file. 1328 } 1329 testSetUserRestriction_asPo()1330 public void testSetUserRestriction_asPo() { 1331 setAsProfileOwner(admin1); 1332 1333 DpmTestUtils.assertRestrictions( 1334 DpmTestUtils.newRestrictions(), 1335 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1336 .ensureUserRestrictions() 1337 ); 1338 1339 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1340 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1341 eq(DpmMockContext.CALLER_USER_HANDLE), 1342 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), 1343 isNull(Bundle.class) 1344 ); 1345 reset(mContext.userManagerInternal); 1346 1347 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1348 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1349 eq(DpmMockContext.CALLER_USER_HANDLE), 1350 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1351 UserManager.DISALLOW_OUTGOING_CALLS), 1352 isNull(Bundle.class) 1353 ); 1354 reset(mContext.userManagerInternal); 1355 1356 DpmTestUtils.assertRestrictions( 1357 DpmTestUtils.newRestrictions( 1358 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1359 UserManager.DISALLOW_OUTGOING_CALLS 1360 ), 1361 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1362 .ensureUserRestrictions() 1363 ); 1364 DpmTestUtils.assertRestrictions( 1365 DpmTestUtils.newRestrictions( 1366 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1367 UserManager.DISALLOW_OUTGOING_CALLS 1368 ), 1369 dpm.getUserRestrictions(admin1) 1370 ); 1371 1372 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1373 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1374 eq(DpmMockContext.CALLER_USER_HANDLE), 1375 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1376 isNull(Bundle.class) 1377 ); 1378 reset(mContext.userManagerInternal); 1379 1380 DpmTestUtils.assertRestrictions( 1381 DpmTestUtils.newRestrictions( 1382 UserManager.DISALLOW_OUTGOING_CALLS 1383 ), 1384 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1385 .ensureUserRestrictions() 1386 ); 1387 DpmTestUtils.assertRestrictions( 1388 DpmTestUtils.newRestrictions( 1389 UserManager.DISALLOW_OUTGOING_CALLS 1390 ), 1391 dpm.getUserRestrictions(admin1) 1392 ); 1393 1394 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1395 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1396 eq(DpmMockContext.CALLER_USER_HANDLE), 1397 MockUtils.checkUserRestrictions(), 1398 isNull(Bundle.class) 1399 ); 1400 reset(mContext.userManagerInternal); 1401 1402 DpmTestUtils.assertRestrictions( 1403 DpmTestUtils.newRestrictions(), 1404 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1405 .ensureUserRestrictions() 1406 ); 1407 DpmTestUtils.assertRestrictions( 1408 DpmTestUtils.newRestrictions(), 1409 dpm.getUserRestrictions(admin1) 1410 ); 1411 1412 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even 1413 // though when DO sets them they'll be applied globally. 1414 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1415 reset(mContext.userManagerInternal); 1416 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1417 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1418 eq(DpmMockContext.CALLER_USER_HANDLE), 1419 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1420 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1421 isNull(Bundle.class) 1422 ); 1423 reset(mContext.userManagerInternal); 1424 1425 dpm.setCameraDisabled(admin1, true); 1426 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1427 eq(DpmMockContext.CALLER_USER_HANDLE), 1428 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA, 1429 UserManager.DISALLOW_ADJUST_VOLUME, 1430 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1431 isNull(Bundle.class) 1432 ); 1433 reset(mContext.userManagerInternal); 1434 1435 // TODO Make sure restrictions are written to the file. 1436 } 1437 testGetMacAddress()1438 public void testGetMacAddress() throws Exception { 1439 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1440 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1441 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1442 1443 // In this test, change the caller user to "system". 1444 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1445 1446 // Make sure admin1 is installed on system user. 1447 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1448 1449 // Test 1. Caller doesn't have DO or DA. 1450 try { 1451 dpm.getWifiMacAddress(admin1); 1452 fail(); 1453 } catch (SecurityException e) { 1454 MoreAsserts.assertContainsRegex("No active admin", e.getMessage()); 1455 } 1456 1457 // DO needs to be an DA. 1458 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1459 assertTrue(dpm.isAdminActive(admin1)); 1460 1461 // Test 2. Caller has DA, but not DO. 1462 try { 1463 dpm.getWifiMacAddress(admin1); 1464 fail(); 1465 } catch (SecurityException e) { 1466 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1467 } 1468 1469 // Test 3. Caller has PO, but not DO. 1470 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1471 try { 1472 dpm.getWifiMacAddress(admin1); 1473 fail(); 1474 } catch (SecurityException e) { 1475 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1476 } 1477 1478 // Remove PO. 1479 dpm.clearProfileOwner(admin1); 1480 1481 // Test 4, Caller is DO now. 1482 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1483 1484 // 4-1. But no WifiInfo. 1485 assertNull(dpm.getWifiMacAddress(admin1)); 1486 1487 // 4-2. Returns WifiInfo, but with the default MAC. 1488 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); 1489 assertNull(dpm.getWifiMacAddress(admin1)); 1490 1491 // 4-3. With a real MAC address. 1492 final WifiInfo wi = new WifiInfo(); 1493 wi.setMacAddress("11:22:33:44:55:66"); 1494 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); 1495 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); 1496 } 1497 testReboot()1498 public void testReboot() throws Exception { 1499 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1500 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1501 1502 // In this test, change the caller user to "system". 1503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1504 1505 // Make sure admin1 is installed on system user. 1506 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1507 1508 // Set admin1 as DA. 1509 dpm.setActiveAdmin(admin1, false); 1510 assertTrue(dpm.isAdminActive(admin1)); 1511 try { 1512 dpm.reboot(admin1); 1513 fail("DA calls DPM.reboot(), did not throw expected SecurityException"); 1514 } catch (SecurityException expected) { 1515 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1516 } 1517 1518 // Set admin1 as PO. 1519 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1520 try { 1521 dpm.reboot(admin1); 1522 fail("PO calls DPM.reboot(), did not throw expected SecurityException"); 1523 } catch (SecurityException expected) { 1524 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1525 } 1526 1527 // Remove PO and add DO. 1528 dpm.clearProfileOwner(admin1); 1529 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1530 1531 // admin1 is DO. 1532 // Set current call state of device to ringing. 1533 when(mContext.telephonyManager.getCallState()) 1534 .thenReturn(TelephonyManager.CALL_STATE_RINGING); 1535 try { 1536 dpm.reboot(admin1); 1537 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException"); 1538 } catch (IllegalStateException expected) { 1539 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1540 } 1541 1542 // Set current call state of device to dialing/active. 1543 when(mContext.telephonyManager.getCallState()) 1544 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); 1545 try { 1546 dpm.reboot(admin1); 1547 fail("DPM.reboot() called when dialing, should thrown IllegalStateException"); 1548 } catch (IllegalStateException expected) { 1549 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1550 } 1551 1552 // Set current call state of device to idle. 1553 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); 1554 dpm.reboot(admin1); 1555 } 1556 testSetGetSupportText()1557 public void testSetGetSupportText() { 1558 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1559 dpm.setActiveAdmin(admin1, true); 1560 dpm.setActiveAdmin(admin2, true); 1561 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); 1562 1563 // Null default support messages. 1564 { 1565 assertNull(dpm.getLongSupportMessage(admin1)); 1566 assertNull(dpm.getShortSupportMessage(admin1)); 1567 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1568 assertNull(dpm.getShortSupportMessageForUser(admin1, 1569 DpmMockContext.CALLER_USER_HANDLE)); 1570 assertNull(dpm.getLongSupportMessageForUser(admin1, 1571 DpmMockContext.CALLER_USER_HANDLE)); 1572 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1573 } 1574 1575 // Only system can call the per user versions. 1576 { 1577 try { 1578 dpm.getShortSupportMessageForUser(admin1, 1579 DpmMockContext.CALLER_USER_HANDLE); 1580 fail("Only system should be able to call getXXXForUser versions"); 1581 } catch (SecurityException expected) { 1582 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1583 } 1584 try { 1585 dpm.getLongSupportMessageForUser(admin1, 1586 DpmMockContext.CALLER_USER_HANDLE); 1587 fail("Only system should be able to call getXXXForUser versions"); 1588 } catch (SecurityException expected) { 1589 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1590 } 1591 } 1592 1593 // Can't set message for admin in another uid. 1594 { 1595 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1; 1596 try { 1597 dpm.setShortSupportMessage(admin1, "Some text"); 1598 fail("Admins should only be able to change their own support text."); 1599 } catch (SecurityException expected) { 1600 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage()); 1601 } 1602 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1603 } 1604 1605 // Set/Get short returns what it sets and other admins text isn't changed. 1606 { 1607 final String supportText = "Some text to test with."; 1608 dpm.setShortSupportMessage(admin1, supportText); 1609 assertEquals(supportText, dpm.getShortSupportMessage(admin1)); 1610 assertNull(dpm.getLongSupportMessage(admin1)); 1611 assertNull(dpm.getShortSupportMessage(admin2)); 1612 1613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1614 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, 1615 DpmMockContext.CALLER_USER_HANDLE)); 1616 assertNull(dpm.getShortSupportMessageForUser(admin2, 1617 DpmMockContext.CALLER_USER_HANDLE)); 1618 assertNull(dpm.getLongSupportMessageForUser(admin1, 1619 DpmMockContext.CALLER_USER_HANDLE)); 1620 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1621 1622 dpm.setShortSupportMessage(admin1, null); 1623 assertNull(dpm.getShortSupportMessage(admin1)); 1624 } 1625 1626 // Set/Get long returns what it sets and other admins text isn't changed. 1627 { 1628 final String supportText = "Some text to test with.\nWith more text."; 1629 dpm.setLongSupportMessage(admin1, supportText); 1630 assertEquals(supportText, dpm.getLongSupportMessage(admin1)); 1631 assertNull(dpm.getShortSupportMessage(admin1)); 1632 assertNull(dpm.getLongSupportMessage(admin2)); 1633 1634 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1635 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, 1636 DpmMockContext.CALLER_USER_HANDLE)); 1637 assertNull(dpm.getLongSupportMessageForUser(admin2, 1638 DpmMockContext.CALLER_USER_HANDLE)); 1639 assertNull(dpm.getShortSupportMessageForUser(admin1, 1640 DpmMockContext.CALLER_USER_HANDLE)); 1641 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1642 1643 dpm.setLongSupportMessage(admin1, null); 1644 assertNull(dpm.getLongSupportMessage(admin1)); 1645 } 1646 } 1647 1648 /** 1649 * Test for: 1650 * {@link DevicePolicyManager#setAffiliationIds} 1651 * {@link DevicePolicyManager#isAffiliatedUser} 1652 */ testUserAffiliation()1653 public void testUserAffiliation() throws Exception { 1654 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1655 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1656 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1657 1658 // Check that the system user is unaffiliated. 1659 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1660 assertFalse(dpm.isAffiliatedUser()); 1661 1662 // Set a device owner on the system user. Check that the system user becomes affiliated. 1663 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1664 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1665 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 1666 assertTrue(dpm.isAffiliatedUser()); 1667 1668 // Install a profile owner whose package name matches the device owner on a test user. Check 1669 // that the test user is unaffiliated. 1670 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1671 setAsProfileOwner(admin2); 1672 assertFalse(dpm.isAffiliatedUser()); 1673 1674 // Have the profile owner specify a set of affiliation ids. Check that the test user remains 1675 // unaffiliated. 1676 final Set<String> userAffiliationIds = new ArraySet<>(); 1677 userAffiliationIds.add("red"); 1678 userAffiliationIds.add("green"); 1679 userAffiliationIds.add("blue"); 1680 dpm.setAffiliationIds(admin2, userAffiliationIds); 1681 assertFalse(dpm.isAffiliatedUser()); 1682 1683 // Have the device owner specify a set of affiliation ids that do not intersect with those 1684 // specified by the profile owner. Check that the test user remains unaffiliated. 1685 final Set<String> deviceAffiliationIds = new ArraySet<>(); 1686 deviceAffiliationIds.add("cyan"); 1687 deviceAffiliationIds.add("yellow"); 1688 deviceAffiliationIds.add("magenta"); 1689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1690 dpm.setAffiliationIds(admin1, deviceAffiliationIds); 1691 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1692 assertFalse(dpm.isAffiliatedUser()); 1693 1694 // Have the profile owner specify a set of affiliation ids that intersect with those 1695 // specified by the device owner. Check that the test user becomes affiliated. 1696 userAffiliationIds.add("yellow"); 1697 dpm.setAffiliationIds(admin2, userAffiliationIds); 1698 assertTrue(dpm.isAffiliatedUser()); 1699 1700 // Change the profile owner to one whose package name does not match the device owner. Check 1701 // that the test user is not affiliated anymore. 1702 dpm.clearProfileOwner(admin2); 1703 final ComponentName admin = new ComponentName("test", "test"); 1704 1705 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID, 1706 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 1707 /* appTargetSdk = */ null, admin2); 1708 1709 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE); 1710 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1711 assertFalse(dpm.isAffiliatedUser()); 1712 1713 // Check that the system user remains affiliated. 1714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1715 assertTrue(dpm.isAffiliatedUser()); 1716 } 1717 testGetUserProvisioningState_defaultResult()1718 public void testGetUserProvisioningState_defaultResult() { 1719 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1720 } 1721 testSetUserProvisioningState_permission()1722 public void testSetUserProvisioningState_permission() throws Exception { 1723 setupProfileOwner(); 1724 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1725 1726 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1727 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1728 } 1729 testSetUserProvisioningState_unprivileged()1730 public void testSetUserProvisioningState_unprivileged() throws Exception { 1731 setupProfileOwner(); 1732 try { 1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1734 DpmMockContext.CALLER_USER_HANDLE); 1735 fail("Expected SecurityException"); 1736 } catch (SecurityException expected) { 1737 } 1738 } 1739 testSetUserProvisioningState_noManagement()1740 public void testSetUserProvisioningState_noManagement() { 1741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1742 try { 1743 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1744 DpmMockContext.CALLER_USER_HANDLE); 1745 fail("IllegalStateException expected"); 1746 } catch (IllegalStateException e) { 1747 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set", 1748 e.getMessage()); 1749 } 1750 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1751 } 1752 testSetUserProvisioningState_deviceOwnerFromSetupWizard()1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception { 1754 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1755 setupDeviceOwner(); 1756 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1757 1758 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1759 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 1760 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1761 } 1762 testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()1763 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative() 1764 throws Exception { 1765 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1766 setupDeviceOwner(); 1767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1768 1769 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1770 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 1771 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1772 } 1773 testSetUserProvisioningState_deviceOwnerWithoutSetupWizard()1774 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception { 1775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1776 setupDeviceOwner(); 1777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1778 1779 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1780 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1781 } 1782 testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser() 1784 throws Exception { 1785 setupProfileOwner(); 1786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1787 1788 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1789 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE, 1790 DevicePolicyManager.STATE_USER_UNMANAGED); 1791 } 1792 testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()1793 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile() 1794 throws Exception { 1795 setupProfileOwner(); 1796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1797 1798 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1799 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 1800 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1801 } 1802 testSetUserProvisioningState_managedProfileWithoutSetupWizard()1803 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception { 1804 setupProfileOwner(); 1805 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1806 1807 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1808 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1809 } 1810 testSetUserProvisioningState_illegalTransitionOutOfFinalized1()1811 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception { 1812 setupProfileOwner(); 1813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1814 1815 try { 1816 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1817 DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1818 DevicePolicyManager.STATE_USER_UNMANAGED); 1819 fail("Expected IllegalStateException"); 1820 } catch (IllegalStateException e) { 1821 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 1822 e.getMessage()); 1823 } 1824 } 1825 testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()1826 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState() 1827 throws Exception { 1828 setupProfileOwner(); 1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1830 1831 try { 1832 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1833 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 1834 DevicePolicyManager.STATE_USER_SETUP_COMPLETE); 1835 fail("Expected IllegalStateException"); 1836 } catch (IllegalStateException e) { 1837 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 1838 e.getMessage()); 1839 } 1840 } 1841 exerciseUserProvisioningTransitions(int userId, int... states)1842 private void exerciseUserProvisioningTransitions(int userId, int... states) { 1843 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1844 for (int state : states) { 1845 dpm.setUserProvisioningState(state, userId); 1846 assertEquals(state, dpm.getUserProvisioningState()); 1847 } 1848 } 1849 setupProfileOwner()1850 private void setupProfileOwner() throws Exception { 1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 1852 1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 1854 dpm.setActiveAdmin(admin1, false); 1855 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE)); 1856 1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 1858 } 1859 setupDeviceOwner()1860 private void setupDeviceOwner() throws Exception { 1861 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 1862 1863 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1864 dpm.setActiveAdmin(admin1, false); 1865 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1866 1867 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 1868 } 1869 testSetMaximumTimeToLock()1870 public void testSetMaximumTimeToLock() { 1871 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 1872 1873 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1874 dpm.setActiveAdmin(admin2, /* replace =*/ false); 1875 1876 reset(mMockContext.powerManagerInternal); 1877 reset(mMockContext.settings); 1878 1879 dpm.setMaximumTimeToLock(admin1, 0); 1880 verifyScreenTimeoutCall(null, false); 1881 reset(mMockContext.powerManagerInternal); 1882 reset(mMockContext.settings); 1883 1884 dpm.setMaximumTimeToLock(admin1, 1); 1885 verifyScreenTimeoutCall(1, true); 1886 reset(mMockContext.powerManagerInternal); 1887 reset(mMockContext.settings); 1888 1889 dpm.setMaximumTimeToLock(admin2, 10); 1890 verifyScreenTimeoutCall(null, false); 1891 reset(mMockContext.powerManagerInternal); 1892 reset(mMockContext.settings); 1893 1894 dpm.setMaximumTimeToLock(admin1, 5); 1895 verifyScreenTimeoutCall(5, true); 1896 reset(mMockContext.powerManagerInternal); 1897 reset(mMockContext.settings); 1898 1899 dpm.setMaximumTimeToLock(admin2, 4); 1900 verifyScreenTimeoutCall(4, true); 1901 reset(mMockContext.powerManagerInternal); 1902 reset(mMockContext.settings); 1903 1904 dpm.setMaximumTimeToLock(admin1, 0); 1905 reset(mMockContext.powerManagerInternal); 1906 reset(mMockContext.settings); 1907 1908 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE); 1909 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 1910 reset(mMockContext.powerManagerInternal); 1911 reset(mMockContext.settings); 1912 1913 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1); 1914 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 1915 reset(mMockContext.powerManagerInternal); 1916 reset(mMockContext.settings); 1917 1918 dpm.setMaximumTimeToLock(admin2, 10); 1919 verifyScreenTimeoutCall(10, true); 1920 reset(mMockContext.powerManagerInternal); 1921 reset(mMockContext.settings); 1922 1923 // There's no restriction; shold be set to MAX. 1924 dpm.setMaximumTimeToLock(admin2, 0); 1925 verifyScreenTimeoutCall(Integer.MAX_VALUE, false); 1926 } 1927 verifyScreenTimeoutCall(Integer expectedTimeout, boolean shouldStayOnWhilePluggedInBeCleared)1928 private void verifyScreenTimeoutCall(Integer expectedTimeout, 1929 boolean shouldStayOnWhilePluggedInBeCleared) { 1930 if (expectedTimeout == null) { 1931 verify(mMockContext.powerManagerInternal, times(0)) 1932 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt()); 1933 } else { 1934 verify(mMockContext.powerManagerInternal, times(1)) 1935 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout)); 1936 } 1937 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw 1938 // UnfinishedVerificationException. 1939 } 1940 testIsProvisioningAllowed_DeviceAdminFeatureOff()1941 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception { 1942 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) 1943 .thenReturn(false); 1944 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1945 .thenReturn(false); 1946 initializeDpms(); 1947 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1948 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1949 .thenReturn(true); 1950 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1951 1952 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1953 1954 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 1955 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1956 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1957 false); 1958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1959 } 1960 testIsProvisioningAllowed_ManagedProfileFeatureOff()1961 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { 1962 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1963 .thenReturn(false); 1964 initializeDpms(); 1965 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1966 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1967 .thenReturn(true); 1968 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1969 1970 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1971 1972 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1973 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1975 false); 1976 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1977 1978 // Test again when split user is on 1979 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1983 true); 1984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1985 } 1986 testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser()1987 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { 1988 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1989 .thenReturn(true); 1990 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1991 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1992 .thenReturn(true); 1993 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1994 1995 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1996 1997 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 1999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2000 false /* because of non-split user */); 2001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2002 false /* because of non-split user */); 2003 } 2004 testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()2005 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() 2006 throws Exception { 2007 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2008 .thenReturn(true); 2009 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2010 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2011 .thenReturn(true); 2012 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2013 2014 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2015 2016 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2017 false/* because of completed device setup */); 2018 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2019 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2020 false/* because of non-split user */); 2021 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2022 false/* because of non-split user */); 2023 } 2024 testIsProvisioningAllowed_splitUser_firstBoot_systemUser()2025 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { 2026 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2027 .thenReturn(true); 2028 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2029 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2030 .thenReturn(false); 2031 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2032 2033 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2034 2035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2037 false /* because canAddMoreManagedProfiles returns false */); 2038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2039 true); 2040 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2041 false/* because calling uid is system user */); 2042 2043 } 2044 testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser()2045 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { 2046 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2047 .thenReturn(true); 2048 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2049 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2050 .thenReturn(false); 2051 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2052 2053 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2054 2055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2056 true/* it's undefined behavior. Can be changed into false in the future */); 2057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2058 false /* because canAddMoreManagedProfiles returns false */); 2059 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2060 true/* it's undefined behavior. Can be changed into false in the future */); 2061 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2062 false/* because calling uid is system user */); 2063 } 2064 testIsProvisioningAllowed_splitUser_firstBoot_primaryUser()2065 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { 2066 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2067 .thenReturn(true); 2068 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2069 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2070 true)).thenReturn(true); 2071 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2072 2073 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2074 2075 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2077 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2078 true); 2079 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); 2080 2081 } 2082 testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()2083 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() 2084 throws Exception { 2085 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2086 .thenReturn(true); 2087 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2088 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2089 true)).thenReturn(true); 2090 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); 2091 2092 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2093 2094 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2095 true/* it's undefined behavior. Can be changed into false in the future */); 2096 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2098 true/* it's undefined behavior. Can be changed into false in the future */); 2099 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2100 false/* because user setup completed */); 2101 } 2102 testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()2103 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() 2104 throws Exception { 2105 setDeviceOwner(); 2106 2107 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2108 .thenReturn(true); 2109 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2110 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2111 .thenReturn(false); 2112 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2113 2114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2115 2116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2117 false /* can't provision managed profile on system user */); 2118 } 2119 testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()2120 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() 2121 throws Exception { 2122 setDeviceOwner(); 2123 2124 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2125 .thenReturn(true); 2126 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2127 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2128 true)).thenReturn(true); 2129 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2130 2131 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2132 2133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2134 } 2135 setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle)2136 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 2137 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 2138 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 2139 dpms.notifyChangeToContentObserver( 2140 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 2141 } 2142 assertProvisioningAllowed(String action, boolean expected)2143 private void assertProvisioningAllowed(String action, boolean expected) { 2144 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 2145 dpm.isProvisioningAllowed(action)); 2146 } 2147 } 2148