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