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