DevicePolicyManagerTest.java revision dd7f8dafd862fa1a6132b37b47f1b160a4065a9e
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 testIsProvisioningAllowed_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 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 2010 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2011 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2012 false); 2013 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2014 } 2015 2016 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { 2017 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2018 .thenReturn(false); 2019 initializeDpms(); 2020 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2021 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2022 .thenReturn(true); 2023 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2024 2025 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2026 2027 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2030 false); 2031 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2032 2033 // Test again when split user is on 2034 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2037 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2038 true); 2039 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2040 } 2041 2042 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { 2043 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2044 .thenReturn(true); 2045 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2046 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2047 .thenReturn(true); 2048 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2049 2050 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2051 2052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2055 false /* because of non-split user */); 2056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2057 false /* because of non-split user */); 2058 } 2059 2060 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() 2061 throws Exception { 2062 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2063 .thenReturn(true); 2064 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2065 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2066 .thenReturn(true); 2067 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2068 2069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2070 2071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2072 false/* because of completed device setup */); 2073 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2074 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2075 false/* because of non-split user */); 2076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2077 false/* because of non-split user */); 2078 } 2079 2080 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { 2081 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2082 .thenReturn(true); 2083 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2084 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2085 .thenReturn(false); 2086 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2087 2088 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2089 2090 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2092 false /* because canAddMoreManagedProfiles returns false */); 2093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2094 true); 2095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2096 false/* because calling uid is system user */); 2097 2098 } 2099 2100 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { 2101 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2102 .thenReturn(true); 2103 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2104 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2105 .thenReturn(false); 2106 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2107 2108 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2109 2110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2111 true/* it's undefined behavior. Can be changed into false in the future */); 2112 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2113 false /* because canAddMoreManagedProfiles returns false */); 2114 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2115 true/* it's undefined behavior. Can be changed into false in the future */); 2116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2117 false/* because calling uid is system user */); 2118 } 2119 2120 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { 2121 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2122 .thenReturn(true); 2123 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2124 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2125 true)).thenReturn(true); 2126 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2127 2128 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2129 2130 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2133 true); 2134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); 2135 2136 } 2137 2138 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() 2139 throws Exception { 2140 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2141 .thenReturn(true); 2142 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2143 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2144 true)).thenReturn(true); 2145 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); 2146 2147 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2148 2149 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2150 true/* it's undefined behavior. Can be changed into false in the future */); 2151 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2152 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2153 true/* it's undefined behavior. Can be changed into false in the future */); 2154 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2155 false/* because user setup completed */); 2156 } 2157 2158 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() 2159 throws Exception { 2160 setDeviceOwner(); 2161 2162 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2163 .thenReturn(true); 2164 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2165 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2166 .thenReturn(false); 2167 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2168 2169 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2170 2171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2172 false /* can't provision managed profile on system user */); 2173 } 2174 2175 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() 2176 throws Exception { 2177 setDeviceOwner(); 2178 2179 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2180 .thenReturn(true); 2181 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2182 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2183 true)).thenReturn(true); 2184 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2185 2186 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2187 2188 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2189 } 2190 2191 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser() 2192 throws Exception { 2193 setDeviceOwner(); 2194 2195 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2196 .thenReturn(true); 2197 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2198 when(mContext.userManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER)) 2199 .thenReturn(true); 2200 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2201 false /* we can't remove a managed profile*/)).thenReturn(false); 2202 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2203 true)).thenReturn(true); 2204 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2205 2206 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2207 2208 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2209 } 2210 2211 public void testForceUpdateUserSetupComplete_permission() { 2212 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2213 try { 2214 dpm.forceUpdateUserSetupComplete(); 2215 fail("Didn't throw SecurityException"); 2216 } catch (SecurityException expected) { 2217 } 2218 } 2219 2220 public void testForceUpdateUserSetupComplete_systemUser() { 2221 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2222 // GIVEN calling from user 20 2223 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2224 try { 2225 dpm.forceUpdateUserSetupComplete(); 2226 fail("Didn't throw SecurityException"); 2227 } catch (SecurityException expected) { 2228 } 2229 } 2230 2231 public void testForceUpdateUserSetupComplete_userbuild() { 2232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2234 2235 final int userId = UserHandle.USER_SYSTEM; 2236 // GIVEN userComplete is false in SettingsProvider 2237 setUserSetupCompleteForUser(false, userId); 2238 2239 // GIVEN userComplete is true in DPM 2240 DevicePolicyManagerService.DevicePolicyData userData = 2241 new DevicePolicyManagerService.DevicePolicyData(userId); 2242 userData.mUserSetupComplete = true; 2243 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2244 2245 // GIVEN it's user build 2246 mContext.buildMock.isDebuggable = false; 2247 2248 assertTrue(dpms.hasUserSetupCompleted()); 2249 2250 dpm.forceUpdateUserSetupComplete(); 2251 2252 // THEN the state in dpms is not changed 2253 assertTrue(dpms.hasUserSetupCompleted()); 2254 } 2255 2256 public void testForceUpdateUserSetupComplete_userDebugbuild() { 2257 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2258 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2259 2260 final int userId = UserHandle.USER_SYSTEM; 2261 // GIVEN userComplete is false in SettingsProvider 2262 setUserSetupCompleteForUser(false, userId); 2263 2264 // GIVEN userComplete is true in DPM 2265 DevicePolicyManagerService.DevicePolicyData userData = 2266 new DevicePolicyManagerService.DevicePolicyData(userId); 2267 userData.mUserSetupComplete = true; 2268 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2269 2270 // GIVEN it's userdebug build 2271 mContext.buildMock.isDebuggable = true; 2272 2273 assertTrue(dpms.hasUserSetupCompleted()); 2274 2275 dpm.forceUpdateUserSetupComplete(); 2276 2277 // THEN the state in dpms is not changed 2278 assertFalse(dpms.hasUserSetupCompleted()); 2279 } 2280 2281 private void clearDeviceOwner() throws Exception { 2282 final long ident = mContext.binder.clearCallingIdentity(); 2283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2284 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager) 2285 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt()); 2286 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 2287 mContext.binder.restoreCallingIdentity(ident); 2288 } 2289 2290 public void testGetLastSecurityLogRetrievalTime() throws Exception { 2291 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2292 setupDeviceOwner(); 2293 when(mContext.userManager.getUserCount()).thenReturn(1); 2294 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs)) 2295 .thenReturn(true); 2296 2297 // No logs were retrieved so far. 2298 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2299 2300 // Enabling logging should not change the timestamp. 2301 dpm.setSecurityLoggingEnabled(admin1, true); 2302 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2303 2304 // Retrieving the logs should update the timestamp. 2305 final long beforeRetrieval = System.currentTimeMillis(); 2306 dpm.retrieveSecurityLogs(admin1); 2307 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2308 final long afterRetrieval = System.currentTimeMillis(); 2309 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval); 2310 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval); 2311 2312 // Retrieving the pre-boot logs should update the timestamp. 2313 Thread.sleep(2); 2314 dpm.retrievePreRebootSecurityLogs(admin1); 2315 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2316 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime); 2317 2318 // Checking the timestamp again should not change it. 2319 Thread.sleep(2); 2320 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2321 2322 // Retrieving the logs again should update the timestamp. 2323 dpm.retrieveSecurityLogs(admin1); 2324 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 2325 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime); 2326 2327 // Disabling logging should not change the timestamp. 2328 Thread.sleep(2); 2329 dpm.setSecurityLoggingEnabled(admin1, false); 2330 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2331 2332 // Restarting the DPMS should not lose the timestamp. 2333 initializeDpms(); 2334 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2335 2336 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2337 mContext.binder.callingUid = 1234567; 2338 mContext.callerPermissions.add(permission.MANAGE_USERS); 2339 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2340 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2341 2342 // System can retrieve the timestamp. 2343 mContext.binder.clearCallingIdentity(); 2344 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 2345 2346 // Removing the device owner should clear the timestamp. 2347 clearDeviceOwner(); 2348 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2349 } 2350 2351 public void testGetLastBugReportRequestTime() throws Exception { 2352 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2353 setupDeviceOwner(); 2354 when(mContext.userManager.getUserCount()).thenReturn(1); 2355 mContext.packageName = admin1.getPackageName(); 2356 mContext.applicationInfo = new ApplicationInfo(); 2357 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject())) 2358 .thenReturn(Color.WHITE); 2359 when(mContext.resources.getColor(eq(R.color.notification_material_background_color), 2360 anyObject())).thenReturn(Color.WHITE); 2361 2362 // No bug reports were requested so far. 2363 assertEquals(-1, dpm.getLastBugReportRequestTime()); 2364 2365 // Requesting a bug report should update the timestamp. 2366 final long beforeRequest = System.currentTimeMillis(); 2367 dpm.requestBugreport(admin1); 2368 final long bugReportRequestTime = dpm.getLastBugReportRequestTime(); 2369 final long afterRequest = System.currentTimeMillis(); 2370 assertTrue(bugReportRequestTime >= beforeRequest); 2371 assertTrue(bugReportRequestTime <= afterRequest); 2372 2373 // Checking the timestamp again should not change it. 2374 Thread.sleep(2); 2375 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2376 2377 // Restarting the DPMS should not lose the timestamp. 2378 initializeDpms(); 2379 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2380 2381 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2382 mContext.binder.callingUid = 1234567; 2383 mContext.callerPermissions.add(permission.MANAGE_USERS); 2384 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2385 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2386 2387 // System can retrieve the timestamp. 2388 mContext.binder.clearCallingIdentity(); 2389 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 2390 2391 // Removing the device owner should clear the timestamp. 2392 clearDeviceOwner(); 2393 assertEquals(-1, dpm.getLastBugReportRequestTime()); 2394 } 2395 2396 public void testGetLastNetworkLogRetrievalTime() throws Exception { 2397 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2398 setupDeviceOwner(); 2399 when(mContext.userManager.getUserCount()).thenReturn(1); 2400 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject())) 2401 .thenReturn(true); 2402 2403 // No logs were retrieved so far. 2404 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2405 2406 // Attempting to retrieve logs without enabling logging should not change the timestamp. 2407 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2408 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2409 2410 // Enabling logging should not change the timestamp. 2411 dpm.setNetworkLoggingEnabled(admin1, true); 2412 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2413 2414 // Retrieving the logs should update the timestamp. 2415 final long beforeRetrieval = System.currentTimeMillis(); 2416 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2417 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 2418 final long afterRetrieval = System.currentTimeMillis(); 2419 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval); 2420 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval); 2421 2422 // Checking the timestamp again should not change it. 2423 Thread.sleep(2); 2424 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2425 2426 // Retrieving the logs again should update the timestamp. 2427 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 2428 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 2429 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime); 2430 2431 // Disabling logging should not change the timestamp. 2432 Thread.sleep(2); 2433 dpm.setNetworkLoggingEnabled(admin1, false); 2434 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2435 2436 // Restarting the DPMS should not lose the timestamp. 2437 initializeDpms(); 2438 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2439 2440 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 2441 mContext.binder.callingUid = 1234567; 2442 mContext.callerPermissions.add(permission.MANAGE_USERS); 2443 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2444 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2445 2446 // System can retrieve the timestamp. 2447 mContext.binder.clearCallingIdentity(); 2448 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 2449 2450 // Removing the device owner should clear the timestamp. 2451 clearDeviceOwner(); 2452 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 2453 } 2454 2455 public void testGetBindDeviceAdminTargetUsers() throws Exception { 2456 // Setup device owner. 2457 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2458 setupDeviceOwner(); 2459 2460 // Only device owner is setup, the result list should be empty. 2461 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2462 MoreAsserts.assertEmpty(targetUsers); 2463 2464 // Setup a managed profile managed by the same admin. 2465 final int MANAGED_PROFILE_USER_ID = 15; 2466 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 2467 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 2468 2469 // Add a secondary user, it should never talk with. 2470 final int ANOTHER_USER_ID = 36; 2471 mContext.addUser(ANOTHER_USER_ID, 0); 2472 2473 // Calling from device owner admin, the result list should just contain the managed 2474 // profile user id. 2475 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2476 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID)); 2477 2478 // Calling from managed profile admin, the result list should just contain the system 2479 // user id. 2480 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 2481 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2482 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM); 2483 } 2484 2485 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception { 2486 // Setup a device owner. 2487 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2488 setupDeviceOwner(); 2489 2490 // Set up a managed profile managed by different package. 2491 final int MANAGED_PROFILE_USER_ID = 15; 2492 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 2493 final ComponentName adminDifferentPackage = 2494 new ComponentName("another.package", "whatever.class"); 2495 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2); 2496 2497 // Calling from device owner admin, we should get zero bind device admin target users as 2498 // their packages are different. 2499 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 2500 MoreAsserts.assertEmpty(targetUsers); 2501 2502 // Calling from managed profile admin, we should still get zero target users for the same 2503 // reason. 2504 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 2505 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage); 2506 MoreAsserts.assertEmpty(targetUsers); 2507 } 2508 2509 public void testIsDeviceManaged() throws Exception { 2510 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2511 setupDeviceOwner(); 2512 2513 // The device owner itself, any uid holding MANAGE_USERS permission and the system can 2514 // find out that the device has a device owner. 2515 assertTrue(dpm.isDeviceManaged()); 2516 mContext.binder.callingUid = 1234567; 2517 mContext.callerPermissions.add(permission.MANAGE_USERS); 2518 assertTrue(dpm.isDeviceManaged()); 2519 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2520 mContext.binder.clearCallingIdentity(); 2521 assertTrue(dpm.isDeviceManaged()); 2522 2523 clearDeviceOwner(); 2524 2525 // Any uid holding MANAGE_USERS permission and the system can find out that the device does 2526 // not have a device owner. 2527 mContext.binder.callingUid = 1234567; 2528 mContext.callerPermissions.add(permission.MANAGE_USERS); 2529 assertFalse(dpm.isDeviceManaged()); 2530 mContext.callerPermissions.remove(permission.MANAGE_USERS); 2531 mContext.binder.clearCallingIdentity(); 2532 assertFalse(dpm.isDeviceManaged()); 2533 } 2534 2535 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 2536 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 2537 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 2538 dpms.notifyChangeToContentObserver( 2539 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 2540 } 2541 2542 private void assertProvisioningAllowed(String action, boolean expected) { 2543 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 2544 dpm.isProvisioningAllowed(action)); 2545 } 2546 2547 /** 2548 * Setup a managed profile with the specified admin and its uid. 2549 * @param admin ComponentName that's visible to the test code, which doesn't have to exist. 2550 * @param adminUid uid of the admin package. 2551 * @param copyFromAdmin package information for {@code admin} will be built based on this 2552 * component's information. 2553 */ 2554 private void addManagedProfile( 2555 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception { 2556 final int userId = UserHandle.getUserId(adminUid); 2557 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); 2558 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2559 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); 2560 dpm.setActiveAdmin(admin, false, userId); 2561 assertTrue(dpm.setProfileOwner(admin, null, userId)); 2562 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2563 } 2564} 2565