DevicePolicyManagerTest.java revision 1970f97e4758224132329a3e0dbe9c3946c4499b
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 843 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner 844 // and once for clearing it. 845 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 846 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 847 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 848 // TODO Check other calls. 849 } 850 851 public void testClearDeviceOwner_fromDifferentUser() throws Exception { 852 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 853 mContext.callerPermissions.add(permission.MANAGE_USERS); 854 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 855 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 856 857 // Set admin1 as a DA to the secondary user. 858 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 859 860 dpm.setActiveAdmin(admin1, /* replace =*/ false); 861 862 // Set admin 1 as the DO to the system user. 863 864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 865 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 866 dpm.setActiveAdmin(admin1, /* replace =*/ false); 867 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 868 869 // Verify internal calls. 870 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 871 eq(admin1.getPackageName())); 872 873 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 874 875 // Now call clear from the secondary user, which should throw. 876 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 877 878 // Now call clear. 879 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( 880 eq(admin1.getPackageName()), 881 anyInt()); 882 try { 883 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 884 fail("Didn't throw"); 885 } catch (SecurityException e) { 886 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage()); 887 } 888 889 // DO shouldn't be removed. 890 assertTrue(dpm.isDeviceManaged()); 891 } 892 893 public void testSetProfileOwner() throws Exception { 894 setAsProfileOwner(admin1); 895 896 // PO admin can't be deactivated. 897 dpm.removeActiveAdmin(admin1); 898 assertTrue(dpm.isAdminActive(admin1)); 899 900 // Try setting DO on the same user, which should fail. 901 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 902 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); 903 try { 904 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); 905 fail("IllegalStateException not thrown"); 906 } catch (IllegalStateException expected) { 907 assertTrue("Message was: " + expected.getMessage(), 908 expected.getMessage().contains("already has a profile owner")); 909 } 910 } 911 912 public void testClearProfileOwner() throws Exception { 913 setAsProfileOwner(admin1); 914 915 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 916 917 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); 918 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 919 920 // First try when the user is locked, which should fail. 921 when(mContext.userManager.isUserUnlocked(anyInt())) 922 .thenReturn(false); 923 try { 924 dpm.clearProfileOwner(admin1); 925 fail("Didn't throw IllegalStateException"); 926 } catch (IllegalStateException expected) { 927 MoreAsserts.assertContainsRegex( 928 "User must be running and unlocked", expected.getMessage()); 929 } 930 // Clear, really. 931 when(mContext.userManager.isUserUnlocked(anyInt())) 932 .thenReturn(true); 933 dpm.clearProfileOwner(admin1); 934 935 // Check 936 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); 937 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 938 } 939 940 public void testSetProfileOwner_failures() throws Exception { 941 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). 942 } 943 944 public void testGetDeviceOwnerAdminLocked() throws Exception { 945 checkDeviceOwnerWithMultipleDeviceAdmins(); 946 } 947 948 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception { 949 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them, 950 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to 951 // make sure it gets the right component from the right user. 952 953 final int ANOTHER_USER_ID = 100; 954 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); 955 956 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 957 958 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 959 mContext.callerPermissions.add(permission.MANAGE_USERS); 960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 962 963 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 964 965 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 966 967 // Make sure the admin packge is installed to each user. 968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 969 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID); 970 971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 972 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 973 974 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 975 976 977 // Set active admins to the users. 978 dpm.setActiveAdmin(admin1, /* replace =*/ false); 979 dpm.setActiveAdmin(admin3, /* replace =*/ false); 980 981 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 982 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 983 984 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); 985 986 // Set DO on the first non-system user. 987 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); 988 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 989 990 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 991 992 // Then check getDeviceOwnerAdminLocked(). 993 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent()); 994 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid()); 995 } 996 997 /** 998 * This essentially tests 999 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is 1000 * private.) 1001 * 1002 * We didn't use to persist the DO component class name, but now we do, and the above method 1003 * finds the right component from a package name upon migration. 1004 */ 1005 public void testDeviceOwnerMigration() throws Exception { 1006 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1007 checkDeviceOwnerWithMultipleDeviceAdmins(); 1008 1009 // Overwrite the device owner setting and clears the clas name. 1010 dpms.mOwners.setDeviceOwner( 1011 new ComponentName(admin2.getPackageName(), ""), 1012 "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1013 dpms.mOwners.writeDeviceOwner(); 1014 1015 // Make sure the DO component name doesn't have a class name. 1016 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); 1017 1018 // Then create a new DPMS to have it load the settings from files. 1019 when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) 1020 .thenReturn(new Bundle()); 1021 initializeDpms(); 1022 1023 // Now the DO component name is a full name. 1024 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the 1025 // DO. 1026 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1027 } 1028 1029 public void testSetGetApplicationRestriction() { 1030 setAsProfileOwner(admin1); 1031 1032 { 1033 Bundle rest = new Bundle(); 1034 rest.putString("KEY_STRING", "Foo1"); 1035 dpm.setApplicationRestrictions(admin1, "pkg1", rest); 1036 } 1037 1038 { 1039 Bundle rest = new Bundle(); 1040 rest.putString("KEY_STRING", "Foo2"); 1041 dpm.setApplicationRestrictions(admin1, "pkg2", rest); 1042 } 1043 1044 { 1045 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); 1046 assertNotNull(returned); 1047 assertEquals(returned.size(), 1); 1048 assertEquals(returned.get("KEY_STRING"), "Foo1"); 1049 } 1050 1051 { 1052 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); 1053 assertNotNull(returned); 1054 assertEquals(returned.size(), 1); 1055 assertEquals(returned.get("KEY_STRING"), "Foo2"); 1056 } 1057 1058 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); 1059 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); 1060 } 1061 1062 public void testApplicationRestrictionsManagingApp() throws Exception { 1063 setAsProfileOwner(admin1); 1064 1065 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2"; 1066 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager"; 1067 final int appRestrictionsManagerAppId = 20987; 1068 final int appRestrictionsManagerUid = UserHandle.getUid( 1069 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId); 1070 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser( 1071 eq(appRestrictionsManagerPackage), 1072 eq(DpmMockContext.CALLER_USER_HANDLE)); 1073 mContext.binder.callingUid = appRestrictionsManagerUid; 1074 1075 final PackageInfo pi = new PackageInfo(); 1076 pi.applicationInfo = new ApplicationInfo(); 1077 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE; 1078 doReturn(pi).when(mContext.ipackageManager).getPackageInfo( 1079 eq(appRestrictionsManagerPackage), 1080 anyInt(), 1081 eq(DpmMockContext.CALLER_USER_HANDLE)); 1082 1083 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't 1084 // delegated that permission yet. 1085 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1086 Bundle rest = new Bundle(); 1087 rest.putString("KEY_STRING", "Foo1"); 1088 try { 1089 dpm.setApplicationRestrictions(null, "pkg1", rest); 1090 fail("Didn't throw expected SecurityException"); 1091 } catch (SecurityException expected) { 1092 MoreAsserts.assertContainsRegex( 1093 "caller cannot manage application restrictions", expected.getMessage()); 1094 } 1095 try { 1096 dpm.getApplicationRestrictions(null, "pkg1"); 1097 fail("Didn't throw expected SecurityException"); 1098 } catch (SecurityException expected) { 1099 MoreAsserts.assertContainsRegex( 1100 "caller cannot manage application restrictions", expected.getMessage()); 1101 } 1102 1103 // Check via the profile owner that no restrictions were set. 1104 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1105 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1106 1107 // Check the API does not allow setting a non-existent package 1108 try { 1109 dpm.setApplicationRestrictionsManagingPackage(admin1, 1110 nonExistAppRestrictionsManagerPackage); 1111 fail("Non-existent app set as app restriction manager."); 1112 } catch (PackageManager.NameNotFoundException expected) { 1113 MoreAsserts.assertContainsRegex( 1114 nonExistAppRestrictionsManagerPackage, expected.getMessage()); 1115 } 1116 1117 // Let appRestrictionsManagerPackage manage app restrictions 1118 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); 1119 assertEquals(appRestrictionsManagerPackage, 1120 dpm.getApplicationRestrictionsManagingPackage(admin1)); 1121 1122 // Now that package should be able to set and retrieve app restrictions. 1123 mContext.binder.callingUid = appRestrictionsManagerUid; 1124 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); 1125 dpm.setApplicationRestrictions(null, "pkg1", rest); 1126 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); 1127 assertEquals(1, returned.size(), 1); 1128 assertEquals("Foo1", returned.get("KEY_STRING")); 1129 1130 // The same app running on a separate user shouldn't be able to manage app restrictions. 1131 mContext.binder.callingUid = UserHandle.getUid( 1132 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); 1133 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1134 try { 1135 dpm.setApplicationRestrictions(null, "pkg1", rest); 1136 fail("Didn't throw expected SecurityException"); 1137 } catch (SecurityException expected) { 1138 MoreAsserts.assertContainsRegex( 1139 "caller cannot manage application restrictions", expected.getMessage()); 1140 } 1141 1142 // The DPM is still able to manage app restrictions, even if it allowed another app to do it 1143 // too. 1144 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1145 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); 1146 dpm.setApplicationRestrictions(admin1, "pkg1", null); 1147 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1148 1149 // Removing the ability for the package to manage app restrictions. 1150 dpm.setApplicationRestrictionsManagingPackage(admin1, null); 1151 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); 1152 mContext.binder.callingUid = appRestrictionsManagerUid; 1153 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1154 try { 1155 dpm.setApplicationRestrictions(null, "pkg1", null); 1156 fail("Didn't throw expected SecurityException"); 1157 } catch (SecurityException expected) { 1158 MoreAsserts.assertContainsRegex( 1159 "caller cannot manage application restrictions", expected.getMessage()); 1160 } 1161 } 1162 1163 public void testSetUserRestriction_asDo() throws Exception { 1164 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1165 mContext.callerPermissions.add(permission.MANAGE_USERS); 1166 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1167 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1168 1169 // First, set DO. 1170 1171 // Call from a process on the system user. 1172 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1173 1174 // Make sure admin1 is installed on system user. 1175 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1176 1177 // Call. 1178 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1179 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1180 UserHandle.USER_SYSTEM)); 1181 1182 DpmTestUtils.assertRestrictions( 1183 DpmTestUtils.newRestrictions(), 1184 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1185 ); 1186 DpmTestUtils.assertRestrictions( 1187 DpmTestUtils.newRestrictions(), 1188 dpm.getUserRestrictions(admin1) 1189 ); 1190 1191 reset(mContext.userManagerInternal); 1192 1193 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1194 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1195 eq(UserHandle.USER_SYSTEM), 1196 MockUtils.checkUserRestrictions(), 1197 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1198 ); 1199 reset(mContext.userManagerInternal); 1200 1201 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1202 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1203 eq(UserHandle.USER_SYSTEM), 1204 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1205 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1206 ); 1207 reset(mContext.userManagerInternal); 1208 1209 DpmTestUtils.assertRestrictions( 1210 DpmTestUtils.newRestrictions( 1211 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1212 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1213 ); 1214 DpmTestUtils.assertRestrictions( 1215 DpmTestUtils.newRestrictions( 1216 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1217 dpm.getUserRestrictions(admin1) 1218 ); 1219 1220 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1221 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1222 eq(UserHandle.USER_SYSTEM), 1223 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1224 MockUtils.checkUserRestrictions() 1225 ); 1226 reset(mContext.userManagerInternal); 1227 1228 DpmTestUtils.assertRestrictions( 1229 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1230 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1231 ); 1232 DpmTestUtils.assertRestrictions( 1233 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1234 dpm.getUserRestrictions(admin1) 1235 ); 1236 1237 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1238 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1239 eq(UserHandle.USER_SYSTEM), 1240 MockUtils.checkUserRestrictions(), 1241 MockUtils.checkUserRestrictions() 1242 ); 1243 reset(mContext.userManagerInternal); 1244 1245 DpmTestUtils.assertRestrictions( 1246 DpmTestUtils.newRestrictions(), 1247 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1248 ); 1249 DpmTestUtils.assertRestrictions( 1250 DpmTestUtils.newRestrictions(), 1251 dpm.getUserRestrictions(admin1) 1252 ); 1253 1254 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when 1255 // DO sets them, the scope is global. 1256 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1257 reset(mContext.userManagerInternal); 1258 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1259 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1260 eq(UserHandle.USER_SYSTEM), 1261 MockUtils.checkUserRestrictions(), 1262 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1263 UserManager.DISALLOW_UNMUTE_MICROPHONE) 1264 ); 1265 reset(mContext.userManagerInternal); 1266 1267 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1268 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1269 1270 1271 // More tests. 1272 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1273 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1274 eq(UserHandle.USER_SYSTEM), 1275 MockUtils.checkUserRestrictions(), 1276 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1277 ); 1278 reset(mContext.userManagerInternal); 1279 1280 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); 1281 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1282 eq(UserHandle.USER_SYSTEM), 1283 MockUtils.checkUserRestrictions(), 1284 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1285 UserManager.DISALLOW_ADD_USER) 1286 ); 1287 reset(mContext.userManagerInternal); 1288 1289 dpm.setCameraDisabled(admin1, true); 1290 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1291 eq(UserHandle.USER_SYSTEM), 1292 // DISALLOW_CAMERA will be applied to both local and global. 1293 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1294 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1295 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER) 1296 ); 1297 reset(mContext.userManagerInternal); 1298 1299 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied 1300 // locally. 1301 dpm.setCameraDisabled(admin1, false); 1302 reset(mContext.userManagerInternal); 1303 1304 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 1305 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); 1306 dpm.setCameraDisabled(admin2, true); 1307 1308 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1309 eq(UserHandle.USER_SYSTEM), 1310 // DISALLOW_CAMERA will be applied to both local and global. 1311 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1313 UserManager.DISALLOW_ADD_USER) 1314 ); 1315 reset(mContext.userManagerInternal); 1316 // TODO Make sure restrictions are written to the file. 1317 } 1318 1319 public void testSetUserRestriction_asPo() { 1320 setAsProfileOwner(admin1); 1321 1322 DpmTestUtils.assertRestrictions( 1323 DpmTestUtils.newRestrictions(), 1324 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1325 .ensureUserRestrictions() 1326 ); 1327 1328 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1329 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1330 eq(DpmMockContext.CALLER_USER_HANDLE), 1331 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), 1332 isNull(Bundle.class) 1333 ); 1334 reset(mContext.userManagerInternal); 1335 1336 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1337 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1338 eq(DpmMockContext.CALLER_USER_HANDLE), 1339 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1340 UserManager.DISALLOW_OUTGOING_CALLS), 1341 isNull(Bundle.class) 1342 ); 1343 reset(mContext.userManagerInternal); 1344 1345 DpmTestUtils.assertRestrictions( 1346 DpmTestUtils.newRestrictions( 1347 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1348 UserManager.DISALLOW_OUTGOING_CALLS 1349 ), 1350 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1351 .ensureUserRestrictions() 1352 ); 1353 DpmTestUtils.assertRestrictions( 1354 DpmTestUtils.newRestrictions( 1355 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1356 UserManager.DISALLOW_OUTGOING_CALLS 1357 ), 1358 dpm.getUserRestrictions(admin1) 1359 ); 1360 1361 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1362 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1363 eq(DpmMockContext.CALLER_USER_HANDLE), 1364 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1365 isNull(Bundle.class) 1366 ); 1367 reset(mContext.userManagerInternal); 1368 1369 DpmTestUtils.assertRestrictions( 1370 DpmTestUtils.newRestrictions( 1371 UserManager.DISALLOW_OUTGOING_CALLS 1372 ), 1373 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1374 .ensureUserRestrictions() 1375 ); 1376 DpmTestUtils.assertRestrictions( 1377 DpmTestUtils.newRestrictions( 1378 UserManager.DISALLOW_OUTGOING_CALLS 1379 ), 1380 dpm.getUserRestrictions(admin1) 1381 ); 1382 1383 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1384 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1385 eq(DpmMockContext.CALLER_USER_HANDLE), 1386 MockUtils.checkUserRestrictions(), 1387 isNull(Bundle.class) 1388 ); 1389 reset(mContext.userManagerInternal); 1390 1391 DpmTestUtils.assertRestrictions( 1392 DpmTestUtils.newRestrictions(), 1393 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1394 .ensureUserRestrictions() 1395 ); 1396 DpmTestUtils.assertRestrictions( 1397 DpmTestUtils.newRestrictions(), 1398 dpm.getUserRestrictions(admin1) 1399 ); 1400 1401 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even 1402 // though when DO sets them they'll be applied globally. 1403 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1404 reset(mContext.userManagerInternal); 1405 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1406 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1407 eq(DpmMockContext.CALLER_USER_HANDLE), 1408 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1409 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1410 isNull(Bundle.class) 1411 ); 1412 reset(mContext.userManagerInternal); 1413 1414 dpm.setCameraDisabled(admin1, true); 1415 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1416 eq(DpmMockContext.CALLER_USER_HANDLE), 1417 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA, 1418 UserManager.DISALLOW_ADJUST_VOLUME, 1419 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1420 isNull(Bundle.class) 1421 ); 1422 reset(mContext.userManagerInternal); 1423 1424 // TODO Make sure restrictions are written to the file. 1425 } 1426 1427 public void testGetMacAddress() throws Exception { 1428 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1429 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1430 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1431 1432 // In this test, change the caller user to "system". 1433 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1434 1435 // Make sure admin1 is installed on system user. 1436 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1437 1438 // Test 1. Caller doesn't have DO or DA. 1439 try { 1440 dpm.getWifiMacAddress(admin1); 1441 fail(); 1442 } catch (SecurityException e) { 1443 MoreAsserts.assertContainsRegex("No active admin", e.getMessage()); 1444 } 1445 1446 // DO needs to be an DA. 1447 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1448 assertTrue(dpm.isAdminActive(admin1)); 1449 1450 // Test 2. Caller has DA, but not DO. 1451 try { 1452 dpm.getWifiMacAddress(admin1); 1453 fail(); 1454 } catch (SecurityException e) { 1455 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1456 } 1457 1458 // Test 3. Caller has PO, but not DO. 1459 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1460 try { 1461 dpm.getWifiMacAddress(admin1); 1462 fail(); 1463 } catch (SecurityException e) { 1464 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1465 } 1466 1467 // Remove PO. 1468 dpm.clearProfileOwner(admin1); 1469 dpm.setActiveAdmin(admin1, false); 1470 // Test 4, Caller is DO now. 1471 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1472 1473 // 4-1. But no WifiInfo. 1474 assertNull(dpm.getWifiMacAddress(admin1)); 1475 1476 // 4-2. Returns WifiInfo, but with the default MAC. 1477 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); 1478 assertNull(dpm.getWifiMacAddress(admin1)); 1479 1480 // 4-3. With a real MAC address. 1481 final WifiInfo wi = new WifiInfo(); 1482 wi.setMacAddress("11:22:33:44:55:66"); 1483 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); 1484 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); 1485 } 1486 1487 public void testReboot() throws Exception { 1488 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1489 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1490 1491 // In this test, change the caller user to "system". 1492 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1493 1494 // Make sure admin1 is installed on system user. 1495 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1496 1497 // Set admin1 as DA. 1498 dpm.setActiveAdmin(admin1, false); 1499 assertTrue(dpm.isAdminActive(admin1)); 1500 try { 1501 dpm.reboot(admin1); 1502 fail("DA calls DPM.reboot(), did not throw expected SecurityException"); 1503 } catch (SecurityException expected) { 1504 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1505 } 1506 1507 // Set admin1 as PO. 1508 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1509 try { 1510 dpm.reboot(admin1); 1511 fail("PO calls DPM.reboot(), did not throw expected SecurityException"); 1512 } catch (SecurityException expected) { 1513 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1514 } 1515 1516 // Remove PO and add DO. 1517 dpm.clearProfileOwner(admin1); 1518 dpm.setActiveAdmin(admin1, false); 1519 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1520 1521 // admin1 is DO. 1522 // Set current call state of device to ringing. 1523 when(mContext.telephonyManager.getCallState()) 1524 .thenReturn(TelephonyManager.CALL_STATE_RINGING); 1525 try { 1526 dpm.reboot(admin1); 1527 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException"); 1528 } catch (IllegalStateException expected) { 1529 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1530 } 1531 1532 // Set current call state of device to dialing/active. 1533 when(mContext.telephonyManager.getCallState()) 1534 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); 1535 try { 1536 dpm.reboot(admin1); 1537 fail("DPM.reboot() called when dialing, 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 idle. 1543 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); 1544 dpm.reboot(admin1); 1545 } 1546 1547 public void testSetGetSupportText() { 1548 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1549 dpm.setActiveAdmin(admin1, true); 1550 dpm.setActiveAdmin(admin2, true); 1551 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); 1552 1553 // Null default support messages. 1554 { 1555 assertNull(dpm.getLongSupportMessage(admin1)); 1556 assertNull(dpm.getShortSupportMessage(admin1)); 1557 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1558 assertNull(dpm.getShortSupportMessageForUser(admin1, 1559 DpmMockContext.CALLER_USER_HANDLE)); 1560 assertNull(dpm.getLongSupportMessageForUser(admin1, 1561 DpmMockContext.CALLER_USER_HANDLE)); 1562 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1563 } 1564 1565 // Only system can call the per user versions. 1566 { 1567 try { 1568 dpm.getShortSupportMessageForUser(admin1, 1569 DpmMockContext.CALLER_USER_HANDLE); 1570 fail("Only system should be able to call getXXXForUser versions"); 1571 } catch (SecurityException expected) { 1572 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1573 } 1574 try { 1575 dpm.getLongSupportMessageForUser(admin1, 1576 DpmMockContext.CALLER_USER_HANDLE); 1577 fail("Only system should be able to call getXXXForUser versions"); 1578 } catch (SecurityException expected) { 1579 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1580 } 1581 } 1582 1583 // Can't set message for admin in another uid. 1584 { 1585 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1; 1586 try { 1587 dpm.setShortSupportMessage(admin1, "Some text"); 1588 fail("Admins should only be able to change their own support text."); 1589 } catch (SecurityException expected) { 1590 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage()); 1591 } 1592 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1593 } 1594 1595 // Set/Get short returns what it sets and other admins text isn't changed. 1596 { 1597 final String supportText = "Some text to test with."; 1598 dpm.setShortSupportMessage(admin1, supportText); 1599 assertEquals(supportText, dpm.getShortSupportMessage(admin1)); 1600 assertNull(dpm.getLongSupportMessage(admin1)); 1601 assertNull(dpm.getShortSupportMessage(admin2)); 1602 1603 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1604 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, 1605 DpmMockContext.CALLER_USER_HANDLE)); 1606 assertNull(dpm.getShortSupportMessageForUser(admin2, 1607 DpmMockContext.CALLER_USER_HANDLE)); 1608 assertNull(dpm.getLongSupportMessageForUser(admin1, 1609 DpmMockContext.CALLER_USER_HANDLE)); 1610 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1611 1612 dpm.setShortSupportMessage(admin1, null); 1613 assertNull(dpm.getShortSupportMessage(admin1)); 1614 } 1615 1616 // Set/Get long returns what it sets and other admins text isn't changed. 1617 { 1618 final String supportText = "Some text to test with.\nWith more text."; 1619 dpm.setLongSupportMessage(admin1, supportText); 1620 assertEquals(supportText, dpm.getLongSupportMessage(admin1)); 1621 assertNull(dpm.getShortSupportMessage(admin1)); 1622 assertNull(dpm.getLongSupportMessage(admin2)); 1623 1624 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1625 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, 1626 DpmMockContext.CALLER_USER_HANDLE)); 1627 assertNull(dpm.getLongSupportMessageForUser(admin2, 1628 DpmMockContext.CALLER_USER_HANDLE)); 1629 assertNull(dpm.getShortSupportMessageForUser(admin1, 1630 DpmMockContext.CALLER_USER_HANDLE)); 1631 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1632 1633 dpm.setLongSupportMessage(admin1, null); 1634 assertNull(dpm.getLongSupportMessage(admin1)); 1635 } 1636 } 1637 1638 /** 1639 * Test for: 1640 * {@link DevicePolicyManager#setAffiliationIds} 1641 * {@link DevicePolicyManager#isAffiliatedUser} 1642 */ 1643 public void testUserAffiliation() throws Exception { 1644 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1645 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1646 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1647 1648 // Check that the system user is unaffiliated. 1649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1650 assertFalse(dpm.isAffiliatedUser()); 1651 1652 // Set a device owner on the system user. Check that the system user becomes affiliated. 1653 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1654 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1655 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 1656 assertTrue(dpm.isAffiliatedUser()); 1657 1658 // Install a profile owner whose package name matches the device owner on a test user. Check 1659 // that the test user is unaffiliated. 1660 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1661 setAsProfileOwner(admin2); 1662 assertFalse(dpm.isAffiliatedUser()); 1663 1664 // Have the profile owner specify a set of affiliation ids. Check that the test user remains 1665 // unaffiliated. 1666 final Set<String> userAffiliationIds = new ArraySet<>(); 1667 userAffiliationIds.add("red"); 1668 userAffiliationIds.add("green"); 1669 userAffiliationIds.add("blue"); 1670 dpm.setAffiliationIds(admin2, userAffiliationIds); 1671 assertFalse(dpm.isAffiliatedUser()); 1672 1673 // Have the device owner specify a set of affiliation ids that do not intersect with those 1674 // specified by the profile owner. Check that the test user remains unaffiliated. 1675 final Set<String> deviceAffiliationIds = new ArraySet<>(); 1676 deviceAffiliationIds.add("cyan"); 1677 deviceAffiliationIds.add("yellow"); 1678 deviceAffiliationIds.add("magenta"); 1679 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1680 dpm.setAffiliationIds(admin1, deviceAffiliationIds); 1681 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1682 assertFalse(dpm.isAffiliatedUser()); 1683 1684 // Have the profile owner specify a set of affiliation ids that intersect with those 1685 // specified by the device owner. Check that the test user becomes affiliated. 1686 userAffiliationIds.add("yellow"); 1687 dpm.setAffiliationIds(admin2, userAffiliationIds); 1688 assertTrue(dpm.isAffiliatedUser()); 1689 1690 // Change the profile owner to one whose package name does not match the device owner. Check 1691 // that the test user is not affiliated anymore. 1692 dpm.clearProfileOwner(admin2); 1693 final ComponentName admin = new ComponentName("test", "test"); 1694 1695 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID, 1696 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 1697 /* appTargetSdk = */ null, admin2); 1698 1699 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE); 1700 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1701 assertFalse(dpm.isAffiliatedUser()); 1702 1703 // Check that the system user remains affiliated. 1704 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1705 assertTrue(dpm.isAffiliatedUser()); 1706 } 1707 1708 public void testGetUserProvisioningState_defaultResult() { 1709 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1710 } 1711 1712 public void testSetUserProvisioningState_permission() throws Exception { 1713 setupProfileOwner(); 1714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1715 1716 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1717 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1718 } 1719 1720 public void testSetUserProvisioningState_unprivileged() throws Exception { 1721 setupProfileOwner(); 1722 try { 1723 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1724 DpmMockContext.CALLER_USER_HANDLE); 1725 fail("Expected SecurityException"); 1726 } catch (SecurityException expected) { 1727 } 1728 } 1729 1730 public void testSetUserProvisioningState_noManagement() { 1731 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1732 try { 1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1734 DpmMockContext.CALLER_USER_HANDLE); 1735 fail("IllegalStateException expected"); 1736 } catch (IllegalStateException e) { 1737 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set", 1738 e.getMessage()); 1739 } 1740 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1741 } 1742 1743 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception { 1744 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1745 setupDeviceOwner(); 1746 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1747 1748 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1749 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 1750 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1751 } 1752 1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative() 1754 throws Exception { 1755 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1756 setupDeviceOwner(); 1757 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1758 1759 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 1760 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 1761 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1762 } 1763 1764 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() 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_FINALIZED); 1771 } 1772 1773 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser() 1774 throws Exception { 1775 setupProfileOwner(); 1776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1777 1778 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1779 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE, 1780 DevicePolicyManager.STATE_USER_UNMANAGED); 1781 } 1782 1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile() 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_SETUP_COMPLETE, 1790 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1791 } 1792 1793 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception { 1794 setupProfileOwner(); 1795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1796 1797 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1798 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 1799 } 1800 1801 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception { 1802 setupProfileOwner(); 1803 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1804 1805 try { 1806 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1807 DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 1808 DevicePolicyManager.STATE_USER_UNMANAGED); 1809 fail("Expected IllegalStateException"); 1810 } catch (IllegalStateException e) { 1811 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 1812 e.getMessage()); 1813 } 1814 } 1815 1816 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState() 1817 throws Exception { 1818 setupProfileOwner(); 1819 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1820 1821 try { 1822 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 1823 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 1824 DevicePolicyManager.STATE_USER_SETUP_COMPLETE); 1825 fail("Expected IllegalStateException"); 1826 } catch (IllegalStateException e) { 1827 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 1828 e.getMessage()); 1829 } 1830 } 1831 1832 private void exerciseUserProvisioningTransitions(int userId, int... states) { 1833 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 1834 for (int state : states) { 1835 dpm.setUserProvisioningState(state, userId); 1836 assertEquals(state, dpm.getUserProvisioningState()); 1837 } 1838 } 1839 1840 private void setupProfileOwner() throws Exception { 1841 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 1842 1843 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 1844 dpm.setActiveAdmin(admin1, false); 1845 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE)); 1846 1847 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 1848 } 1849 1850 private void setupDeviceOwner() throws Exception { 1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 1852 1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1854 dpm.setActiveAdmin(admin1, false); 1855 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1856 1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 1858 } 1859 1860 public void testSetMaximumTimeToLock() { 1861 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 1862 1863 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1864 dpm.setActiveAdmin(admin2, /* replace =*/ false); 1865 1866 reset(mMockContext.powerManagerInternal); 1867 reset(mMockContext.settings); 1868 1869 dpm.setMaximumTimeToLock(admin1, 0); 1870 verifyScreenTimeoutCall(null, false); 1871 reset(mMockContext.powerManagerInternal); 1872 reset(mMockContext.settings); 1873 1874 dpm.setMaximumTimeToLock(admin1, 1); 1875 verifyScreenTimeoutCall(1, true); 1876 reset(mMockContext.powerManagerInternal); 1877 reset(mMockContext.settings); 1878 1879 dpm.setMaximumTimeToLock(admin2, 10); 1880 verifyScreenTimeoutCall(null, false); 1881 reset(mMockContext.powerManagerInternal); 1882 reset(mMockContext.settings); 1883 1884 dpm.setMaximumTimeToLock(admin1, 5); 1885 verifyScreenTimeoutCall(5, true); 1886 reset(mMockContext.powerManagerInternal); 1887 reset(mMockContext.settings); 1888 1889 dpm.setMaximumTimeToLock(admin2, 4); 1890 verifyScreenTimeoutCall(4, true); 1891 reset(mMockContext.powerManagerInternal); 1892 reset(mMockContext.settings); 1893 1894 dpm.setMaximumTimeToLock(admin1, 0); 1895 reset(mMockContext.powerManagerInternal); 1896 reset(mMockContext.settings); 1897 1898 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE); 1899 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 1900 reset(mMockContext.powerManagerInternal); 1901 reset(mMockContext.settings); 1902 1903 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1); 1904 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 1905 reset(mMockContext.powerManagerInternal); 1906 reset(mMockContext.settings); 1907 1908 dpm.setMaximumTimeToLock(admin2, 10); 1909 verifyScreenTimeoutCall(10, true); 1910 reset(mMockContext.powerManagerInternal); 1911 reset(mMockContext.settings); 1912 1913 // There's no restriction; shold be set to MAX. 1914 dpm.setMaximumTimeToLock(admin2, 0); 1915 verifyScreenTimeoutCall(Integer.MAX_VALUE, false); 1916 } 1917 1918 private void verifyScreenTimeoutCall(Integer expectedTimeout, 1919 boolean shouldStayOnWhilePluggedInBeCleared) { 1920 if (expectedTimeout == null) { 1921 verify(mMockContext.powerManagerInternal, times(0)) 1922 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt()); 1923 } else { 1924 verify(mMockContext.powerManagerInternal, times(1)) 1925 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout)); 1926 } 1927 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw 1928 // UnfinishedVerificationException. 1929 } 1930 1931 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception { 1932 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) 1933 .thenReturn(false); 1934 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1935 .thenReturn(false); 1936 initializeDpms(); 1937 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1938 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1939 .thenReturn(true); 1940 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1941 1942 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1943 1944 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 1945 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1946 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1947 false); 1948 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1949 } 1950 1951 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { 1952 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1953 .thenReturn(false); 1954 initializeDpms(); 1955 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1956 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1957 .thenReturn(true); 1958 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1959 1960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1961 1962 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1963 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1964 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1965 false); 1966 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1967 1968 // Test again when split user is on 1969 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1970 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1971 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 1972 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1973 true); 1974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 1975 } 1976 1977 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { 1978 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1979 .thenReturn(true); 1980 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 1981 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 1982 .thenReturn(true); 1983 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 1984 1985 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1986 1987 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 1988 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 1989 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 1990 false /* because of non-split user */); 1991 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 1992 false /* because of non-split user */); 1993 } 1994 1995 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() 1996 throws Exception { 1997 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 1998 .thenReturn(true); 1999 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2000 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2001 .thenReturn(true); 2002 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2003 2004 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2005 2006 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2007 false/* because of completed device setup */); 2008 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2009 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2010 false/* because of non-split user */); 2011 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2012 false/* because of non-split user */); 2013 } 2014 2015 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { 2016 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2017 .thenReturn(true); 2018 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2019 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2020 .thenReturn(false); 2021 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2022 2023 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2024 2025 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2027 false /* because canAddMoreManagedProfiles returns false */); 2028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2029 true); 2030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2031 false/* because calling uid is system user */); 2032 2033 } 2034 2035 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { 2036 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2037 .thenReturn(true); 2038 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2039 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2040 .thenReturn(false); 2041 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2042 2043 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2044 2045 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2046 true/* it's undefined behavior. Can be changed into false in the future */); 2047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2048 false /* because canAddMoreManagedProfiles returns false */); 2049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2050 true/* it's undefined behavior. Can be changed into false in the future */); 2051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2052 false/* because calling uid is system user */); 2053 } 2054 2055 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { 2056 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2057 .thenReturn(true); 2058 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2059 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2060 true)).thenReturn(true); 2061 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2062 2063 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2064 2065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2067 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2068 true); 2069 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); 2070 2071 } 2072 2073 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() 2074 throws Exception { 2075 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2076 .thenReturn(true); 2077 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2078 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2079 true)).thenReturn(true); 2080 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); 2081 2082 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2083 2084 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2085 true/* it's undefined behavior. Can be changed into false in the future */); 2086 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2087 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2088 true/* it's undefined behavior. Can be changed into false in the future */); 2089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2090 false/* because user setup completed */); 2091 } 2092 2093 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() 2094 throws Exception { 2095 setDeviceOwner(); 2096 2097 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2098 .thenReturn(true); 2099 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2100 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2101 .thenReturn(false); 2102 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2103 2104 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2105 2106 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2107 false /* can't provision managed profile on system user */); 2108 } 2109 2110 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() 2111 throws Exception { 2112 setDeviceOwner(); 2113 2114 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2115 .thenReturn(true); 2116 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2117 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2118 true)).thenReturn(true); 2119 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2120 2121 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2122 2123 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2124 } 2125 2126 public void testForceUpdateUserSetupComplete_permission() { 2127 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2128 try { 2129 dpm.forceUpdateUserSetupComplete(); 2130 fail("Didn't throw SecurityException"); 2131 } catch (SecurityException expected) { 2132 } 2133 } 2134 2135 public void testForceUpdateUserSetupComplete_systemUser() { 2136 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2137 // GIVEN calling from user 20 2138 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2139 try { 2140 dpm.forceUpdateUserSetupComplete(); 2141 fail("Didn't throw SecurityException"); 2142 } catch (SecurityException expected) { 2143 } 2144 } 2145 2146 public void testForceUpdateUserSetupComplete_userbuild() { 2147 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2148 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2149 2150 final int userId = UserHandle.USER_SYSTEM; 2151 // GIVEN userComplete is false in SettingsProvider 2152 setUserSetupCompleteForUser(false, userId); 2153 2154 // GIVEN userComplete is true in DPM 2155 DevicePolicyManagerService.DevicePolicyData userData = 2156 new DevicePolicyManagerService.DevicePolicyData(userId); 2157 userData.mUserSetupComplete = true; 2158 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2159 2160 // GIVEN it's user build 2161 mContext.buildMock.isDebuggable = false; 2162 2163 assertTrue(dpms.hasUserSetupCompleted()); 2164 2165 dpm.forceUpdateUserSetupComplete(); 2166 2167 // THEN the state in dpms is not changed 2168 assertTrue(dpms.hasUserSetupCompleted()); 2169 } 2170 2171 public void testForceUpdateUserSetupComplete_userDebugbuild() { 2172 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2173 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2174 2175 final int userId = UserHandle.USER_SYSTEM; 2176 // GIVEN userComplete is false in SettingsProvider 2177 setUserSetupCompleteForUser(false, userId); 2178 2179 // GIVEN userComplete is true in DPM 2180 DevicePolicyManagerService.DevicePolicyData userData = 2181 new DevicePolicyManagerService.DevicePolicyData(userId); 2182 userData.mUserSetupComplete = true; 2183 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2184 2185 // GIVEN it's userdebug build 2186 mContext.buildMock.isDebuggable = true; 2187 2188 assertTrue(dpms.hasUserSetupCompleted()); 2189 2190 dpm.forceUpdateUserSetupComplete(); 2191 2192 // THEN the state in dpms is not changed 2193 assertFalse(dpms.hasUserSetupCompleted()); 2194 } 2195 2196 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 2197 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 2198 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 2199 dpms.notifyChangeToContentObserver( 2200 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 2201 } 2202 2203 private void assertProvisioningAllowed(String action, boolean expected) { 2204 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 2205 dpm.isProvisioningAllowed(action)); 2206 } 2207} 2208