DevicePolicyManagerTest.java revision 2f26b79eea905f88c872804be01431020e4efb2e
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.HashMap; 59import java.util.List; 60import java.util.Map; 61import java.util.Set; 62 63import static org.mockito.Matchers.any; 64import static org.mockito.Matchers.anyInt; 65import static org.mockito.Matchers.anyObject; 66import static org.mockito.Matchers.anyString; 67import static org.mockito.Matchers.eq; 68import static org.mockito.Matchers.isNull; 69import static org.mockito.Mockito.doAnswer; 70import static org.mockito.Mockito.doReturn; 71import static org.mockito.Mockito.reset; 72import static org.mockito.Mockito.times; 73import static org.mockito.Mockito.verify; 74import static org.mockito.Mockito.when; 75 76/** 77 * Tests for DevicePolicyManager( and DevicePolicyManagerService). 78 * 79 m FrameworksServicesTests && 80 adb install \ 81 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && 82 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \ 83 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner 84 85 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) 86 */ 87@SmallTest 88public class DevicePolicyManagerTest extends DpmTestBase { 89 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList( 90 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, 91 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL); 92 93 private DpmMockContext mContext; 94 public DevicePolicyManager dpm; 95 public DevicePolicyManagerServiceTestable dpms; 96 97 @Override 98 protected void setUp() throws Exception { 99 super.setUp(); 100 101 mContext = getContext(); 102 103 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 104 .thenReturn(true); 105 106 // By default, pretend all users are running and unlocked. 107 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 108 109 initializeDpms(); 110 111 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 112 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 113 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID); 114 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID); 115 116 setUpUserManager(); 117 } 118 119 private void initializeDpms() { 120 // Need clearCallingIdentity() to pass permission checks. 121 final long ident = mContext.binder.clearCallingIdentity(); 122 try { 123 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 124 125 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); 126 127 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); 128 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); 129 130 dpm = new DevicePolicyManagerTestable(mContext, dpms); 131 } finally { 132 mContext.binder.restoreCallingIdentity(ident); 133 } 134 } 135 136 private void setUpUserManager() { 137 // Emulate UserManager.set/getApplicationRestriction(). 138 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>(); 139 140 // UM.setApplicationRestrictions() will save to appRestrictions. 141 doAnswer(new Answer<Void>() { 142 @Override 143 public Void answer(InvocationOnMock invocation) throws Throwable { 144 String pkg = (String) invocation.getArguments()[0]; 145 Bundle bundle = (Bundle) invocation.getArguments()[1]; 146 UserHandle user = (UserHandle) invocation.getArguments()[2]; 147 148 appRestrictions.put(Pair.create(pkg, user), bundle); 149 150 return null; 151 } 152 }).when(mContext.userManager).setApplicationRestrictions( 153 anyString(), any(Bundle.class), any(UserHandle.class)); 154 155 // UM.getApplicationRestrictions() will read from appRestrictions. 156 doAnswer(new Answer<Bundle>() { 157 @Override 158 public Bundle answer(InvocationOnMock invocation) throws Throwable { 159 String pkg = (String) invocation.getArguments()[0]; 160 UserHandle user = (UserHandle) invocation.getArguments()[1]; 161 162 return appRestrictions.get(Pair.create(pkg, user)); 163 } 164 }).when(mContext.userManager).getApplicationRestrictions( 165 anyString(), any(UserHandle.class)); 166 167 // Add the first secondary user. 168 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0); 169 } 170 171 private void setAsProfileOwner(ComponentName admin) { 172 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 173 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 174 175 // PO needs to be an DA. 176 dpm.setActiveAdmin(admin, /* replace =*/ false); 177 178 // Fire! 179 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 180 181 // Check 182 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); 183 } 184 185 public void testHasNoFeature() throws Exception { 186 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 187 .thenReturn(false); 188 189 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 190 new DevicePolicyManagerServiceTestable(mContext, dataDir); 191 192 // If the device has no DPMS feature, it shouldn't register the local service. 193 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); 194 } 195 196 /** 197 * Caller doesn't have proper permissions. 198 */ 199 public void testSetActiveAdmin_SecurityException() { 200 // 1. Failure cases. 201 202 // Caller doesn't have MANAGE_DEVICE_ADMINS. 203 try { 204 dpm.setActiveAdmin(admin1, false); 205 fail("Didn't throw SecurityException"); 206 } catch (SecurityException expected) { 207 } 208 209 // Caller has MANAGE_DEVICE_ADMINS, but for different user. 210 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 211 try { 212 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1); 213 fail("Didn't throw SecurityException"); 214 } catch (SecurityException expected) { 215 } 216 } 217 218 /** 219 * Test for: 220 * {@link DevicePolicyManager#setActiveAdmin} 221 * with replace=false and replace=true 222 * {@link DevicePolicyManager#isAdminActive} 223 * {@link DevicePolicyManager#isAdminActiveAsUser} 224 * {@link DevicePolicyManager#getActiveAdmins} 225 * {@link DevicePolicyManager#getActiveAdminsAsUser} 226 */ 227 public void testSetActiveAdmin() throws Exception { 228 // 1. Make sure the caller has proper permissions. 229 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 230 231 // 2. Call the API. 232 dpm.setActiveAdmin(admin1, /* replace =*/ false); 233 234 // 3. Verify internal calls. 235 236 // Check if the boradcast is sent. 237 verify(mContext.spiedContext).sendBroadcastAsUser( 238 MockUtils.checkIntentAction( 239 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 240 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 241 verify(mContext.spiedContext).sendBroadcastAsUser( 242 MockUtils.checkIntentAction( 243 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED), 244 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 245 246 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 247 eq(admin1.getPackageName()), 248 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 249 eq(PackageManager.DONT_KILL_APP), 250 eq(DpmMockContext.CALLER_USER_HANDLE), 251 anyString()); 252 253 // TODO Verify other calls too. 254 255 // Make sure it's active admin1. 256 assertTrue(dpm.isAdminActive(admin1)); 257 assertFalse(dpm.isAdminActive(admin2)); 258 assertFalse(dpm.isAdminActive(admin3)); 259 260 // But not admin1 for a different user. 261 262 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL. 263 // (Because we're checking a different user's status from CALLER_USER_HANDLE.) 264 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 265 266 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1)); 267 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1)); 268 269 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 270 271 // Next, add one more admin. 272 // Before doing so, update the application info, now it's enabled. 273 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID, 274 PackageManager.COMPONENT_ENABLED_STATE_ENABLED); 275 276 dpm.setActiveAdmin(admin2, /* replace =*/ false); 277 278 // Now we have two admins. 279 assertTrue(dpm.isAdminActive(admin1)); 280 assertTrue(dpm.isAdminActive(admin2)); 281 assertFalse(dpm.isAdminActive(admin3)); 282 283 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called 284 // again. (times(1) because it was previously called for admin1) 285 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 286 eq(admin1.getPackageName()), 287 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 288 eq(PackageManager.DONT_KILL_APP), 289 eq(DpmMockContext.CALLER_USER_HANDLE), 290 anyString()); 291 292 // 4. Add the same admin1 again without replace, which should throw. 293 try { 294 dpm.setActiveAdmin(admin1, /* replace =*/ false); 295 fail("Didn't throw"); 296 } catch (IllegalArgumentException expected) { 297 } 298 299 // 5. Add the same admin1 again with replace, which should succeed. 300 dpm.setActiveAdmin(admin1, /* replace =*/ true); 301 302 // TODO make sure it's replaced. 303 304 // 6. Test getActiveAdmins() 305 List<ComponentName> admins = dpm.getActiveAdmins(); 306 assertEquals(2, admins.size()); 307 assertEquals(admin1, admins.get(0)); 308 assertEquals(admin2, admins.get(1)); 309 310 // Another user has no admins. 311 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 312 313 assertEquals(0, DpmTestUtils.getListSizeAllowingNull( 314 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1))); 315 316 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 317 } 318 319 public void testSetActiveAdmin_multiUsers() throws Exception { 320 321 final int ANOTHER_USER_ID = 100; 322 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456); 323 324 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 325 326 // Set up pacakge manager for the other user. 327 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 328 329 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 330 331 dpm.setActiveAdmin(admin1, /* replace =*/ false); 332 333 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 334 dpm.setActiveAdmin(admin2, /* replace =*/ false); 335 336 337 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 338 assertTrue(dpm.isAdminActive(admin1)); 339 assertFalse(dpm.isAdminActive(admin2)); 340 341 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 342 assertFalse(dpm.isAdminActive(admin1)); 343 assertTrue(dpm.isAdminActive(admin2)); 344 } 345 346 /** 347 * Test for: 348 * {@link DevicePolicyManager#setActiveAdmin} 349 * with replace=false 350 */ 351 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception { 352 // 1. Make sure the caller has proper permissions. 353 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 354 355 dpm.setActiveAdmin(admin1, /* replace =*/ false); 356 assertTrue(dpm.isAdminActive(admin1)); 357 358 // Add the same admin1 again without replace, which should throw. 359 try { 360 dpm.setActiveAdmin(admin1, /* replace =*/ false); 361 fail("Didn't throw"); 362 } catch (IllegalArgumentException expected) { 363 } 364 } 365 366 /** 367 * Test for: 368 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with 369 * BIND_DEVICE_ADMIN. 370 */ 371 public void testSetActiveAdmin_permissionCheck() throws Exception { 372 // 1. Make sure the caller has proper permissions. 373 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 374 375 try { 376 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 377 fail(); 378 } catch (IllegalArgumentException expected) { 379 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN)); 380 } 381 assertFalse(dpm.isAdminActive(adminNoPerm)); 382 383 // Change the target API level to MNC. Now it can be set as DA. 384 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null, 385 VERSION_CODES.M); 386 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 387 assertTrue(dpm.isAdminActive(adminNoPerm)); 388 389 // TODO Test the "load from the file" case where DA will still be loaded even without 390 // BIND_DEVICE_ADMIN and target API is N. 391 } 392 393 /** 394 * Test for: 395 * {@link DevicePolicyManager#removeActiveAdmin} 396 */ 397 public void testRemoveActiveAdmin_SecurityException() { 398 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 399 400 // Add admin. 401 402 dpm.setActiveAdmin(admin1, /* replace =*/ false); 403 404 assertTrue(dpm.isAdminActive(admin1)); 405 406 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 407 408 // Directly call the DPMS method with a different userid, which should fail. 409 try { 410 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1); 411 fail("Didn't throw SecurityException"); 412 } catch (SecurityException expected) { 413 } 414 415 // Try to remove active admin with a different caller userid should fail too, without 416 // having MANAGE_DEVICE_ADMINS. 417 mContext.callerPermissions.clear(); 418 419 // Change the caller, and call into DPMS directly with a different user-id. 420 421 mContext.binder.callingUid = 1234567; 422 try { 423 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 424 fail("Didn't throw SecurityException"); 425 } catch (SecurityException expected) { 426 } 427 } 428 429 /** 430 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked 431 * (because we can't send the remove broadcast). 432 */ 433 public void testRemoveActiveAdmin_userNotRunningOrLocked() { 434 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 435 436 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 437 438 // Add admin. 439 440 dpm.setActiveAdmin(admin1, /* replace =*/ false); 441 442 assertTrue(dpm.isAdminActive(admin1)); 443 444 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 445 446 // 1. User not unlocked. 447 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 448 .thenReturn(false); 449 try { 450 dpm.removeActiveAdmin(admin1); 451 fail("Didn't throw IllegalStateException"); 452 } catch (IllegalStateException expected) { 453 MoreAsserts.assertContainsRegex( 454 "User must be running and unlocked", expected.getMessage()); 455 } 456 457 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 458 459 // 2. User unlocked. 460 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 461 .thenReturn(true); 462 463 dpm.removeActiveAdmin(admin1); 464 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 465 } 466 467 /** 468 * Test for: 469 * {@link DevicePolicyManager#removeActiveAdmin} 470 */ 471 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() { 472 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 473 474 // Add admin1. 475 476 dpm.setActiveAdmin(admin1, /* replace =*/ false); 477 478 assertTrue(dpm.isAdminActive(admin1)); 479 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 480 481 // Different user, but should work, because caller has proper permissions. 482 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 483 484 // Change the caller, and call into DPMS directly with a different user-id. 485 mContext.binder.callingUid = 1234567; 486 487 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 488 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 489 490 // TODO DO Still can't be removed in this case. 491 } 492 493 /** 494 * Test for: 495 * {@link DevicePolicyManager#removeActiveAdmin} 496 */ 497 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() { 498 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. 499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 500 501 // Add admin1. 502 503 dpm.setActiveAdmin(admin1, /* replace =*/ false); 504 505 assertTrue(dpm.isAdminActive(admin1)); 506 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 507 508 // Broadcast from saveSettingsLocked(). 509 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 510 MockUtils.checkIntentAction( 511 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 512 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 513 514 // Remove. No permissions, but same user, so it'll work. 515 mContext.callerPermissions.clear(); 516 dpm.removeActiveAdmin(admin1); 517 518 verify(mContext.spiedContext).sendOrderedBroadcastAsUser( 519 MockUtils.checkIntentAction( 520 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED), 521 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE), 522 isNull(String.class), 523 any(BroadcastReceiver.class), 524 eq(dpms.mHandler), 525 eq(Activity.RESULT_OK), 526 isNull(String.class), 527 isNull(Bundle.class)); 528 529 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 530 531 // Again broadcast from saveSettingsLocked(). 532 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 533 MockUtils.checkIntentAction( 534 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 535 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 536 537 // TODO Check other internal calls. 538 } 539 540 /** 541 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully. 542 */ 543 public void testSetDeviceOwner() throws Exception { 544 setDeviceOwner(); 545 546 // Try to set a profile owner on the same user, which should fail. 547 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 548 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM); 549 try { 550 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM); 551 fail("IllegalStateException not thrown"); 552 } catch (IllegalStateException expected) { 553 assertTrue("Message was: " + expected.getMessage(), 554 expected.getMessage().contains("already has a device owner")); 555 } 556 557 // DO admin can't be deactivated. 558 dpm.removeActiveAdmin(admin1); 559 assertTrue(dpm.isAdminActive(admin1)); 560 561 // TODO Test getDeviceOwnerName() too. To do so, we need to change 562 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 563 } 564 565 private void setDeviceOwner() throws Exception { 566 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 567 mContext.callerPermissions.add(permission.MANAGE_USERS); 568 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 569 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 570 571 // In this test, change the caller user to "system". 572 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 573 574 // Make sure admin1 is installed on system user. 575 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 576 577 // Check various get APIs. 578 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false); 579 580 // DO needs to be an DA. 581 dpm.setActiveAdmin(admin1, /* replace =*/ false); 582 583 // Fire! 584 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 585 586 // getDeviceOwnerComponent should return the admin1 component. 587 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 588 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 589 590 // Check various get APIs. 591 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true); 592 593 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users. 594 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 595 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 596 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 597 598 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 599 600 // Verify internal calls. 601 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 602 eq(admin1.getPackageName())); 603 604 // TODO We should check if the caller has called clearCallerIdentity(). 605 verify(mContext.ibackupManager, times(1)).setBackupServiceActive( 606 eq(UserHandle.USER_SYSTEM), eq(false)); 607 608 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 609 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 610 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 611 612 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 613 } 614 615 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) { 616 final int origCallingUser = mContext.binder.callingUid; 617 final List origPermissions = new ArrayList(mContext.callerPermissions); 618 mContext.callerPermissions.clear(); 619 620 mContext.callerPermissions.add(permission.MANAGE_USERS); 621 622 mContext.binder.callingUid = Process.SYSTEM_UID; 623 624 // TODO Test getDeviceOwnerName() too. To do so, we need to change 625 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 626 if (hasDeviceOwner) { 627 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 628 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 629 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 630 631 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 632 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 633 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 634 } else { 635 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 636 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 637 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 638 639 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 640 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 641 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 642 } 643 644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 645 if (hasDeviceOwner) { 646 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 647 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 648 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 649 650 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 651 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 652 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 653 } else { 654 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 655 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 656 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 657 658 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 659 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 660 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 661 } 662 663 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 664 // Still with MANAGE_USERS. 665 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 666 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 667 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 668 669 if (hasDeviceOwner) { 670 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 671 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 672 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 673 } else { 674 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 675 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 676 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 677 } 678 679 mContext.binder.callingUid = Process.SYSTEM_UID; 680 mContext.callerPermissions.remove(permission.MANAGE_USERS); 681 // System can still call "OnAnyUser" without MANAGE_USERS. 682 if (hasDeviceOwner) { 683 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 684 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 685 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 686 687 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 688 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 689 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 690 } else { 691 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 692 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 693 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 694 695 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 696 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 697 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 698 } 699 700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 701 // Still no MANAGE_USERS. 702 if (hasDeviceOwner) { 703 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 704 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 705 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 706 } else { 707 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 708 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 709 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 710 } 711 712 try { 713 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 714 fail(); 715 } catch (SecurityException expected) { 716 } 717 try { 718 dpm.getDeviceOwnerComponentOnAnyUser(); 719 fail(); 720 } catch (SecurityException expected) { 721 } 722 try { 723 dpm.getDeviceOwnerUserId(); 724 fail(); 725 } catch (SecurityException expected) { 726 } 727 try { 728 dpm.getDeviceOwnerNameOnAnyUser(); 729 fail(); 730 } catch (SecurityException expected) { 731 } 732 733 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 734 // Still no MANAGE_USERS. 735 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 736 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 737 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 738 739 try { 740 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 741 fail(); 742 } catch (SecurityException expected) { 743 } 744 try { 745 dpm.getDeviceOwnerComponentOnAnyUser(); 746 fail(); 747 } catch (SecurityException expected) { 748 } 749 try { 750 dpm.getDeviceOwnerUserId(); 751 fail(); 752 } catch (SecurityException expected) { 753 } 754 try { 755 dpm.getDeviceOwnerNameOnAnyUser(); 756 fail(); 757 } catch (SecurityException expected) { 758 } 759 760 // Restore. 761 mContext.binder.callingUid = origCallingUser; 762 mContext.callerPermissions.addAll(origPermissions); 763 } 764 765 766 /** 767 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist. 768 */ 769 public void testSetDeviceOwner_noSuchPackage() { 770 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 771 mContext.callerPermissions.add(permission.MANAGE_USERS); 772 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 773 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 774 775 // Call from a process on the system user. 776 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 777 778 try { 779 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")); 780 fail("Didn't throw IllegalArgumentException"); 781 } catch (IllegalArgumentException expected) { 782 assertTrue("Message was: " + expected.getMessage(), 783 expected.getMessage().contains("Invalid component")); 784 } 785 } 786 787 public void testSetDeviceOwner_failures() throws Exception { 788 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner(). 789 } 790 791 public void testClearDeviceOwner() throws Exception { 792 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 793 mContext.callerPermissions.add(permission.MANAGE_USERS); 794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 795 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 796 797 // Set admin1 as a DA to the secondary user. 798 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 799 800 dpm.setActiveAdmin(admin1, /* replace =*/ false); 801 802 // Set admin 1 as the DO to the system user. 803 804 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 805 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 806 dpm.setActiveAdmin(admin1, /* replace =*/ false); 807 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 808 809 // Verify internal calls. 810 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 811 eq(admin1.getPackageName())); 812 813 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 814 815 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 816 817 assertTrue(dpm.isAdminActive(admin1)); 818 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); 819 820 // Set up other mocks. 821 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle()); 822 823 // Now call clear. 824 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser( 825 eq(admin1.getPackageName()), 826 anyInt()); 827 828 // But first pretend the user is locked. Then it should fail. 829 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false); 830 try { 831 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 832 fail("Didn't throw IllegalStateException"); 833 } catch (IllegalStateException expected) { 834 MoreAsserts.assertContainsRegex( 835 "User must be running and unlocked", expected.getMessage()); 836 } 837 838 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 839 reset(mContext.userManagerInternal); 840 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 841 842 // Now DO shouldn't be set. 843 assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); 844 845 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 846 eq(UserHandle.USER_SYSTEM), 847 MockUtils.checkUserRestrictions(), 848 MockUtils.checkUserRestrictions() 849 ); 850 851 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)); 852 853 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner 854 // and once for clearing it. 855 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 856 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 857 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 858 // TODO Check other calls. 859 } 860 861 public void testClearDeviceOwner_fromDifferentUser() throws Exception { 862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 863 mContext.callerPermissions.add(permission.MANAGE_USERS); 864 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 865 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 866 867 // Set admin1 as a DA to the secondary user. 868 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 869 870 dpm.setActiveAdmin(admin1, /* replace =*/ false); 871 872 // Set admin 1 as the DO to the system user. 873 874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 875 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 876 dpm.setActiveAdmin(admin1, /* replace =*/ false); 877 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 878 879 // Verify internal calls. 880 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 881 eq(admin1.getPackageName())); 882 883 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 884 885 // Now call clear from the secondary user, which should throw. 886 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 887 888 // Now call clear. 889 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( 890 eq(admin1.getPackageName()), 891 anyInt()); 892 try { 893 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 894 fail("Didn't throw"); 895 } catch (SecurityException e) { 896 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage()); 897 } 898 899 // DO shouldn't be removed. 900 assertTrue(dpm.isDeviceManaged()); 901 } 902 903 public void testSetProfileOwner() throws Exception { 904 setAsProfileOwner(admin1); 905 906 // PO admin can't be deactivated. 907 dpm.removeActiveAdmin(admin1); 908 assertTrue(dpm.isAdminActive(admin1)); 909 910 // Try setting DO on the same user, which should fail. 911 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 912 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); 913 try { 914 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); 915 fail("IllegalStateException not thrown"); 916 } catch (IllegalStateException expected) { 917 assertTrue("Message was: " + expected.getMessage(), 918 expected.getMessage().contains("already has a profile owner")); 919 } 920 } 921 922 public void testClearProfileOwner() throws Exception { 923 setAsProfileOwner(admin1); 924 925 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 926 927 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); 928 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 929 930 // First try when the user is locked, which should fail. 931 when(mContext.userManager.isUserUnlocked(anyInt())) 932 .thenReturn(false); 933 try { 934 dpm.clearProfileOwner(admin1); 935 fail("Didn't throw IllegalStateException"); 936 } catch (IllegalStateException expected) { 937 MoreAsserts.assertContainsRegex( 938 "User must be running and unlocked", expected.getMessage()); 939 } 940 // Clear, really. 941 when(mContext.userManager.isUserUnlocked(anyInt())) 942 .thenReturn(true); 943 dpm.clearProfileOwner(admin1); 944 945 // Check 946 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); 947 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 948 } 949 950 public void testSetProfileOwner_failures() throws Exception { 951 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). 952 } 953 954 public void testGetDeviceOwnerAdminLocked() throws Exception { 955 checkDeviceOwnerWithMultipleDeviceAdmins(); 956 } 957 958 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception { 959 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them, 960 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to 961 // make sure it gets the right component from the right user. 962 963 final int ANOTHER_USER_ID = 100; 964 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); 965 966 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 967 968 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 969 mContext.callerPermissions.add(permission.MANAGE_USERS); 970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 971 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 972 973 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 974 975 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 976 977 // Make sure the admin packge is installed to each user. 978 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 979 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID); 980 981 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 982 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 983 984 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 985 986 987 // Set active admins to the users. 988 dpm.setActiveAdmin(admin1, /* replace =*/ false); 989 dpm.setActiveAdmin(admin3, /* replace =*/ false); 990 991 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 992 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 993 994 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); 995 996 // Set DO on the first non-system user. 997 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); 998 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 999 1000 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1001 1002 // Then check getDeviceOwnerAdminLocked(). 1003 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent()); 1004 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid()); 1005 } 1006 1007 /** 1008 * This essentially tests 1009 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is 1010 * private.) 1011 * 1012 * We didn't use to persist the DO component class name, but now we do, and the above method 1013 * finds the right component from a package name upon migration. 1014 */ 1015 public void testDeviceOwnerMigration() throws Exception { 1016 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1017 checkDeviceOwnerWithMultipleDeviceAdmins(); 1018 1019 // Overwrite the device owner setting and clears the clas name. 1020 dpms.mOwners.setDeviceOwner( 1021 new ComponentName(admin2.getPackageName(), ""), 1022 "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1023 dpms.mOwners.writeDeviceOwner(); 1024 1025 // Make sure the DO component name doesn't have a class name. 1026 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); 1027 1028 // Then create a new DPMS to have it load the settings from files. 1029 when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) 1030 .thenReturn(new Bundle()); 1031 initializeDpms(); 1032 1033 // Now the DO component name is a full name. 1034 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the 1035 // DO. 1036 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1037 } 1038 1039 public void testSetGetApplicationRestriction() { 1040 setAsProfileOwner(admin1); 1041 1042 { 1043 Bundle rest = new Bundle(); 1044 rest.putString("KEY_STRING", "Foo1"); 1045 dpm.setApplicationRestrictions(admin1, "pkg1", rest); 1046 } 1047 1048 { 1049 Bundle rest = new Bundle(); 1050 rest.putString("KEY_STRING", "Foo2"); 1051 dpm.setApplicationRestrictions(admin1, "pkg2", rest); 1052 } 1053 1054 { 1055 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); 1056 assertNotNull(returned); 1057 assertEquals(returned.size(), 1); 1058 assertEquals(returned.get("KEY_STRING"), "Foo1"); 1059 } 1060 1061 { 1062 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); 1063 assertNotNull(returned); 1064 assertEquals(returned.size(), 1); 1065 assertEquals(returned.get("KEY_STRING"), "Foo2"); 1066 } 1067 1068 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); 1069 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); 1070 } 1071 1072 public void testApplicationRestrictionsManagingApp() throws Exception { 1073 setAsProfileOwner(admin1); 1074 1075 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2"; 1076 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager"; 1077 final int appRestrictionsManagerAppId = 20987; 1078 final int appRestrictionsManagerUid = UserHandle.getUid( 1079 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId); 1080 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser( 1081 eq(appRestrictionsManagerPackage), 1082 eq(DpmMockContext.CALLER_USER_HANDLE)); 1083 mContext.binder.callingUid = appRestrictionsManagerUid; 1084 1085 final PackageInfo pi = new PackageInfo(); 1086 pi.applicationInfo = new ApplicationInfo(); 1087 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE; 1088 doReturn(pi).when(mContext.ipackageManager).getPackageInfo( 1089 eq(appRestrictionsManagerPackage), 1090 anyInt(), 1091 eq(DpmMockContext.CALLER_USER_HANDLE)); 1092 1093 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't 1094 // delegated that permission yet. 1095 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1096 Bundle rest = new Bundle(); 1097 rest.putString("KEY_STRING", "Foo1"); 1098 try { 1099 dpm.setApplicationRestrictions(null, "pkg1", rest); 1100 fail("Didn't throw expected SecurityException"); 1101 } catch (SecurityException expected) { 1102 MoreAsserts.assertContainsRegex( 1103 "caller cannot manage application restrictions", expected.getMessage()); 1104 } 1105 try { 1106 dpm.getApplicationRestrictions(null, "pkg1"); 1107 fail("Didn't throw expected SecurityException"); 1108 } catch (SecurityException expected) { 1109 MoreAsserts.assertContainsRegex( 1110 "caller cannot manage application restrictions", expected.getMessage()); 1111 } 1112 1113 // Check via the profile owner that no restrictions were set. 1114 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1115 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1116 1117 // Check the API does not allow setting a non-existent package 1118 try { 1119 dpm.setApplicationRestrictionsManagingPackage(admin1, 1120 nonExistAppRestrictionsManagerPackage); 1121 fail("Non-existent app set as app restriction manager."); 1122 } catch (PackageManager.NameNotFoundException expected) { 1123 MoreAsserts.assertContainsRegex( 1124 nonExistAppRestrictionsManagerPackage, expected.getMessage()); 1125 } 1126 1127 // Let appRestrictionsManagerPackage manage app restrictions 1128 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); 1129 assertEquals(appRestrictionsManagerPackage, 1130 dpm.getApplicationRestrictionsManagingPackage(admin1)); 1131 1132 // Now that package should be able to set and retrieve app restrictions. 1133 mContext.binder.callingUid = appRestrictionsManagerUid; 1134 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); 1135 dpm.setApplicationRestrictions(null, "pkg1", rest); 1136 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); 1137 assertEquals(1, returned.size(), 1); 1138 assertEquals("Foo1", returned.get("KEY_STRING")); 1139 1140 // The same app running on a separate user shouldn't be able to manage app restrictions. 1141 mContext.binder.callingUid = UserHandle.getUid( 1142 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); 1143 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1144 try { 1145 dpm.setApplicationRestrictions(null, "pkg1", rest); 1146 fail("Didn't throw expected SecurityException"); 1147 } catch (SecurityException expected) { 1148 MoreAsserts.assertContainsRegex( 1149 "caller cannot manage application restrictions", expected.getMessage()); 1150 } 1151 1152 // The DPM is still able to manage app restrictions, even if it allowed another app to do it 1153 // too. 1154 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1155 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); 1156 dpm.setApplicationRestrictions(admin1, "pkg1", null); 1157 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1158 1159 // Removing the ability for the package to manage app restrictions. 1160 dpm.setApplicationRestrictionsManagingPackage(admin1, null); 1161 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); 1162 mContext.binder.callingUid = appRestrictionsManagerUid; 1163 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1164 try { 1165 dpm.setApplicationRestrictions(null, "pkg1", null); 1166 fail("Didn't throw expected SecurityException"); 1167 } catch (SecurityException expected) { 1168 MoreAsserts.assertContainsRegex( 1169 "caller cannot manage application restrictions", expected.getMessage()); 1170 } 1171 } 1172 1173 public void testSetUserRestriction_asDo() throws Exception { 1174 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1175 mContext.callerPermissions.add(permission.MANAGE_USERS); 1176 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1177 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1178 1179 // First, set DO. 1180 1181 // Call from a process on the system user. 1182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1183 1184 // Make sure admin1 is installed on system user. 1185 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1186 1187 // Call. 1188 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1189 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1190 UserHandle.USER_SYSTEM)); 1191 1192 DpmTestUtils.assertRestrictions( 1193 DpmTestUtils.newRestrictions(), 1194 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1195 ); 1196 DpmTestUtils.assertRestrictions( 1197 DpmTestUtils.newRestrictions(), 1198 dpm.getUserRestrictions(admin1) 1199 ); 1200 1201 reset(mContext.userManagerInternal); 1202 1203 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1204 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1205 eq(UserHandle.USER_SYSTEM), 1206 MockUtils.checkUserRestrictions(), 1207 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1208 ); 1209 reset(mContext.userManagerInternal); 1210 1211 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1212 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1213 eq(UserHandle.USER_SYSTEM), 1214 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1215 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1216 ); 1217 reset(mContext.userManagerInternal); 1218 1219 DpmTestUtils.assertRestrictions( 1220 DpmTestUtils.newRestrictions( 1221 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1222 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1223 ); 1224 DpmTestUtils.assertRestrictions( 1225 DpmTestUtils.newRestrictions( 1226 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1227 dpm.getUserRestrictions(admin1) 1228 ); 1229 1230 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1231 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1232 eq(UserHandle.USER_SYSTEM), 1233 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1234 MockUtils.checkUserRestrictions() 1235 ); 1236 reset(mContext.userManagerInternal); 1237 1238 DpmTestUtils.assertRestrictions( 1239 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1240 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1241 ); 1242 DpmTestUtils.assertRestrictions( 1243 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1244 dpm.getUserRestrictions(admin1) 1245 ); 1246 1247 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1248 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1249 eq(UserHandle.USER_SYSTEM), 1250 MockUtils.checkUserRestrictions(), 1251 MockUtils.checkUserRestrictions() 1252 ); 1253 reset(mContext.userManagerInternal); 1254 1255 DpmTestUtils.assertRestrictions( 1256 DpmTestUtils.newRestrictions(), 1257 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1258 ); 1259 DpmTestUtils.assertRestrictions( 1260 DpmTestUtils.newRestrictions(), 1261 dpm.getUserRestrictions(admin1) 1262 ); 1263 1264 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when 1265 // DO sets them, the scope is global. 1266 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1267 reset(mContext.userManagerInternal); 1268 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1269 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1270 eq(UserHandle.USER_SYSTEM), 1271 MockUtils.checkUserRestrictions(), 1272 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1273 UserManager.DISALLOW_UNMUTE_MICROPHONE) 1274 ); 1275 reset(mContext.userManagerInternal); 1276 1277 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1278 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1279 1280 1281 // More tests. 1282 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1283 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1284 eq(UserHandle.USER_SYSTEM), 1285 MockUtils.checkUserRestrictions(), 1286 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER) 1287 ); 1288 reset(mContext.userManagerInternal); 1289 1290 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); 1291 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1292 eq(UserHandle.USER_SYSTEM), 1293 MockUtils.checkUserRestrictions(), 1294 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1295 UserManager.DISALLOW_ADD_USER) 1296 ); 1297 reset(mContext.userManagerInternal); 1298 1299 dpm.setCameraDisabled(admin1, true); 1300 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1301 eq(UserHandle.USER_SYSTEM), 1302 // DISALLOW_CAMERA will be applied to both local and global. 1303 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1305 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER) 1306 ); 1307 reset(mContext.userManagerInternal); 1308 1309 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied 1310 // locally. 1311 dpm.setCameraDisabled(admin1, false); 1312 reset(mContext.userManagerInternal); 1313 1314 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 1315 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); 1316 dpm.setCameraDisabled(admin2, true); 1317 1318 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1319 eq(UserHandle.USER_SYSTEM), 1320 // DISALLOW_CAMERA will be applied to both local and global. 1321 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA), 1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1323 UserManager.DISALLOW_ADD_USER) 1324 ); 1325 reset(mContext.userManagerInternal); 1326 // TODO Make sure restrictions are written to the file. 1327 } 1328 1329 public void testSetUserRestriction_asPo() { 1330 setAsProfileOwner(admin1); 1331 1332 DpmTestUtils.assertRestrictions( 1333 DpmTestUtils.newRestrictions(), 1334 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1335 .ensureUserRestrictions() 1336 ); 1337 1338 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1339 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1340 eq(DpmMockContext.CALLER_USER_HANDLE), 1341 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), 1342 isNull(Bundle.class) 1343 ); 1344 reset(mContext.userManagerInternal); 1345 1346 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1347 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1348 eq(DpmMockContext.CALLER_USER_HANDLE), 1349 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1350 UserManager.DISALLOW_OUTGOING_CALLS), 1351 isNull(Bundle.class) 1352 ); 1353 reset(mContext.userManagerInternal); 1354 1355 DpmTestUtils.assertRestrictions( 1356 DpmTestUtils.newRestrictions( 1357 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1358 UserManager.DISALLOW_OUTGOING_CALLS 1359 ), 1360 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1361 .ensureUserRestrictions() 1362 ); 1363 DpmTestUtils.assertRestrictions( 1364 DpmTestUtils.newRestrictions( 1365 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1366 UserManager.DISALLOW_OUTGOING_CALLS 1367 ), 1368 dpm.getUserRestrictions(admin1) 1369 ); 1370 1371 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1372 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1373 eq(DpmMockContext.CALLER_USER_HANDLE), 1374 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1375 isNull(Bundle.class) 1376 ); 1377 reset(mContext.userManagerInternal); 1378 1379 DpmTestUtils.assertRestrictions( 1380 DpmTestUtils.newRestrictions( 1381 UserManager.DISALLOW_OUTGOING_CALLS 1382 ), 1383 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1384 .ensureUserRestrictions() 1385 ); 1386 DpmTestUtils.assertRestrictions( 1387 DpmTestUtils.newRestrictions( 1388 UserManager.DISALLOW_OUTGOING_CALLS 1389 ), 1390 dpm.getUserRestrictions(admin1) 1391 ); 1392 1393 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1394 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1395 eq(DpmMockContext.CALLER_USER_HANDLE), 1396 MockUtils.checkUserRestrictions(), 1397 isNull(Bundle.class) 1398 ); 1399 reset(mContext.userManagerInternal); 1400 1401 DpmTestUtils.assertRestrictions( 1402 DpmTestUtils.newRestrictions(), 1403 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1404 .ensureUserRestrictions() 1405 ); 1406 DpmTestUtils.assertRestrictions( 1407 DpmTestUtils.newRestrictions(), 1408 dpm.getUserRestrictions(admin1) 1409 ); 1410 1411 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even 1412 // though when DO sets them they'll be applied globally. 1413 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1414 reset(mContext.userManagerInternal); 1415 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1416 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1417 eq(DpmMockContext.CALLER_USER_HANDLE), 1418 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1419 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1420 isNull(Bundle.class) 1421 ); 1422 reset(mContext.userManagerInternal); 1423 1424 dpm.setCameraDisabled(admin1, true); 1425 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1426 eq(DpmMockContext.CALLER_USER_HANDLE), 1427 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA, 1428 UserManager.DISALLOW_ADJUST_VOLUME, 1429 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1430 isNull(Bundle.class) 1431 ); 1432 reset(mContext.userManagerInternal); 1433 1434 // TODO Make sure restrictions are written to the file. 1435 } 1436 1437 public void testGetMacAddress() throws Exception { 1438 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1439 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1440 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1441 1442 // In this test, change the caller user to "system". 1443 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1444 1445 // Make sure admin1 is installed on system user. 1446 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1447 1448 // Test 1. Caller doesn't have DO or DA. 1449 try { 1450 dpm.getWifiMacAddress(admin1); 1451 fail(); 1452 } catch (SecurityException e) { 1453 MoreAsserts.assertContainsRegex("No active admin", e.getMessage()); 1454 } 1455 1456 // DO needs to be an DA. 1457 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1458 assertTrue(dpm.isAdminActive(admin1)); 1459 1460 // Test 2. Caller has DA, but not DO. 1461 try { 1462 dpm.getWifiMacAddress(admin1); 1463 fail(); 1464 } catch (SecurityException e) { 1465 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1466 } 1467 1468 // Test 3. Caller has PO, but not DO. 1469 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1470 try { 1471 dpm.getWifiMacAddress(admin1); 1472 fail(); 1473 } catch (SecurityException e) { 1474 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1475 } 1476 1477 // Remove PO. 1478 dpm.clearProfileOwner(admin1); 1479 dpm.setActiveAdmin(admin1, false); 1480 // Test 4, Caller is DO now. 1481 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1482 1483 // 4-1. But no WifiInfo. 1484 assertNull(dpm.getWifiMacAddress(admin1)); 1485 1486 // 4-2. Returns WifiInfo, but with the default MAC. 1487 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); 1488 assertNull(dpm.getWifiMacAddress(admin1)); 1489 1490 // 4-3. With a real MAC address. 1491 final WifiInfo wi = new WifiInfo(); 1492 wi.setMacAddress("11:22:33:44:55:66"); 1493 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); 1494 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); 1495 } 1496 1497 public void testReboot() throws Exception { 1498 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1499 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1500 1501 // In this test, change the caller user to "system". 1502 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1503 1504 // Make sure admin1 is installed on system user. 1505 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1506 1507 // Set admin1 as DA. 1508 dpm.setActiveAdmin(admin1, false); 1509 assertTrue(dpm.isAdminActive(admin1)); 1510 try { 1511 dpm.reboot(admin1); 1512 fail("DA calls DPM.reboot(), did not throw expected SecurityException"); 1513 } catch (SecurityException expected) { 1514 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1515 } 1516 1517 // Set admin1 as PO. 1518 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1519 try { 1520 dpm.reboot(admin1); 1521 fail("PO calls DPM.reboot(), did not throw expected SecurityException"); 1522 } catch (SecurityException expected) { 1523 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1524 } 1525 1526 // Remove PO and add DO. 1527 dpm.clearProfileOwner(admin1); 1528 dpm.setActiveAdmin(admin1, false); 1529 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1530 1531 // admin1 is DO. 1532 // Set current call state of device to ringing. 1533 when(mContext.telephonyManager.getCallState()) 1534 .thenReturn(TelephonyManager.CALL_STATE_RINGING); 1535 try { 1536 dpm.reboot(admin1); 1537 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException"); 1538 } catch (IllegalStateException expected) { 1539 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1540 } 1541 1542 // Set current call state of device to dialing/active. 1543 when(mContext.telephonyManager.getCallState()) 1544 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); 1545 try { 1546 dpm.reboot(admin1); 1547 fail("DPM.reboot() called when dialing, should thrown IllegalStateException"); 1548 } catch (IllegalStateException expected) { 1549 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1550 } 1551 1552 // Set current call state of device to idle. 1553 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); 1554 dpm.reboot(admin1); 1555 } 1556 1557 public void testSetGetSupportText() { 1558 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1559 dpm.setActiveAdmin(admin1, true); 1560 dpm.setActiveAdmin(admin2, true); 1561 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); 1562 1563 // Null default support messages. 1564 { 1565 assertNull(dpm.getLongSupportMessage(admin1)); 1566 assertNull(dpm.getShortSupportMessage(admin1)); 1567 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1568 assertNull(dpm.getShortSupportMessageForUser(admin1, 1569 DpmMockContext.CALLER_USER_HANDLE)); 1570 assertNull(dpm.getLongSupportMessageForUser(admin1, 1571 DpmMockContext.CALLER_USER_HANDLE)); 1572 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1573 } 1574 1575 // Only system can call the per user versions. 1576 { 1577 try { 1578 dpm.getShortSupportMessageForUser(admin1, 1579 DpmMockContext.CALLER_USER_HANDLE); 1580 fail("Only system should be able to call getXXXForUser versions"); 1581 } catch (SecurityException expected) { 1582 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1583 } 1584 try { 1585 dpm.getLongSupportMessageForUser(admin1, 1586 DpmMockContext.CALLER_USER_HANDLE); 1587 fail("Only system should be able to call getXXXForUser versions"); 1588 } catch (SecurityException expected) { 1589 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1590 } 1591 } 1592 1593 // Can't set message for admin in another uid. 1594 { 1595 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1; 1596 try { 1597 dpm.setShortSupportMessage(admin1, "Some text"); 1598 fail("Admins should only be able to change their own support text."); 1599 } catch (SecurityException expected) { 1600 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage()); 1601 } 1602 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1603 } 1604 1605 // Set/Get short returns what it sets and other admins text isn't changed. 1606 { 1607 final String supportText = "Some text to test with."; 1608 dpm.setShortSupportMessage(admin1, supportText); 1609 assertEquals(supportText, dpm.getShortSupportMessage(admin1)); 1610 assertNull(dpm.getLongSupportMessage(admin1)); 1611 assertNull(dpm.getShortSupportMessage(admin2)); 1612 1613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1614 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, 1615 DpmMockContext.CALLER_USER_HANDLE)); 1616 assertNull(dpm.getShortSupportMessageForUser(admin2, 1617 DpmMockContext.CALLER_USER_HANDLE)); 1618 assertNull(dpm.getLongSupportMessageForUser(admin1, 1619 DpmMockContext.CALLER_USER_HANDLE)); 1620 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1621 1622 dpm.setShortSupportMessage(admin1, null); 1623 assertNull(dpm.getShortSupportMessage(admin1)); 1624 } 1625 1626 // Set/Get long returns what it sets and other admins text isn't changed. 1627 { 1628 final String supportText = "Some text to test with.\nWith more text."; 1629 dpm.setLongSupportMessage(admin1, supportText); 1630 assertEquals(supportText, dpm.getLongSupportMessage(admin1)); 1631 assertNull(dpm.getShortSupportMessage(admin1)); 1632 assertNull(dpm.getLongSupportMessage(admin2)); 1633 1634 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1635 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, 1636 DpmMockContext.CALLER_USER_HANDLE)); 1637 assertNull(dpm.getLongSupportMessageForUser(admin2, 1638 DpmMockContext.CALLER_USER_HANDLE)); 1639 assertNull(dpm.getShortSupportMessageForUser(admin1, 1640 DpmMockContext.CALLER_USER_HANDLE)); 1641 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1642 1643 dpm.setLongSupportMessage(admin1, null); 1644 assertNull(dpm.getLongSupportMessage(admin1)); 1645 } 1646 } 1647 1648 /** 1649 * Test for: 1650 * {@link DevicePolicyManager#setAffiliationIds} 1651 * {@link DevicePolicyManager#isAffiliatedUser} 1652 */ 1653 public void testUserAffiliation() throws Exception { 1654 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1655 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1656 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1657 1658 // Check that the system user is unaffiliated. 1659 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1660 assertFalse(dpm.isAffiliatedUser()); 1661 1662 // Set a device owner on the system user. Check that the system user becomes affiliated. 1663 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1664 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1665 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 1666 assertTrue(dpm.isAffiliatedUser()); 1667 1668 // Install a profile owner whose package name matches the device owner on a test user. Check 1669 // that the test user is unaffiliated. 1670 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1671 setAsProfileOwner(admin2); 1672 assertFalse(dpm.isAffiliatedUser()); 1673 1674 // Have the profile owner specify a set of affiliation ids. Check that the test user remains 1675 // unaffiliated. 1676 final Set<String> userAffiliationIds = new ArraySet<>(); 1677 userAffiliationIds.add("red"); 1678 userAffiliationIds.add("green"); 1679 userAffiliationIds.add("blue"); 1680 dpm.setAffiliationIds(admin2, userAffiliationIds); 1681 assertFalse(dpm.isAffiliatedUser()); 1682 1683 // Have the device owner specify a set of affiliation ids that do not intersect with those 1684 // specified by the profile owner. Check that the test user remains unaffiliated. 1685 final Set<String> deviceAffiliationIds = new ArraySet<>(); 1686 deviceAffiliationIds.add("cyan"); 1687 deviceAffiliationIds.add("yellow"); 1688 deviceAffiliationIds.add("magenta"); 1689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1690 dpm.setAffiliationIds(admin1, deviceAffiliationIds); 1691 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1692 assertFalse(dpm.isAffiliatedUser()); 1693 1694 // Have the profile owner specify a set of affiliation ids that intersect with those 1695 // specified by the device owner. Check that the test user becomes affiliated. 1696 userAffiliationIds.add("yellow"); 1697 dpm.setAffiliationIds(admin2, userAffiliationIds); 1698 assertTrue(dpm.isAffiliatedUser()); 1699 1700 // Change the profile owner to one whose package name does not match the device owner. Check 1701 // that the test user is not affiliated anymore. 1702 dpm.clearProfileOwner(admin2); 1703 final ComponentName admin = new ComponentName("test", "test"); 1704 1705 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID, 1706 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 1707 /* appTargetSdk = */ null, admin2); 1708 1709 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE); 1710 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1711 assertFalse(dpm.isAffiliatedUser()); 1712 1713 // Check that the system user remains affiliated. 1714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1715 assertTrue(dpm.isAffiliatedUser()); 1716 } 1717 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 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 2510 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 2511 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 2512 dpms.notifyChangeToContentObserver( 2513 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 2514 } 2515 2516 private void assertProvisioningAllowed(String action, boolean expected) { 2517 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 2518 dpm.isProvisioningAllowed(action)); 2519 } 2520 2521 /** 2522 * Setup a managed profile with the specified admin and its uid. 2523 * @param admin ComponentName that's visible to the test code, which doesn't have to exist. 2524 * @param adminUid uid of the admin package. 2525 * @param copyFromAdmin package information for {@code admin} will be built based on this 2526 * component's information. 2527 */ 2528 private void addManagedProfile( 2529 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception { 2530 final int userId = UserHandle.getUserId(adminUid); 2531 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); 2532 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2533 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); 2534 dpm.setActiveAdmin(admin, false, userId); 2535 assertTrue(dpm.setProfileOwner(admin, null, userId)); 2536 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2537 } 2538} 2539