DevicePolicyManagerTest.java revision f994677626a6babc5121647646f17a7de85065a7
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 static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY; 20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED; 21 22import android.Manifest.permission; 23import android.app.Activity; 24import android.app.admin.DeviceAdminReceiver; 25import android.app.admin.DevicePolicyManager; 26import android.app.admin.DevicePolicyManagerInternal; 27import android.content.BroadcastReceiver; 28import android.content.ComponentName; 29import android.content.Context; 30import android.content.Intent; 31import android.content.ServiceConnection; 32import android.content.pm.ApplicationInfo; 33import android.content.pm.PackageInfo; 34import android.content.pm.PackageManager; 35import android.content.res.Resources; 36import android.graphics.Color; 37import android.net.IIpConnectivityMetrics; 38import android.content.pm.UserInfo; 39import android.net.wifi.WifiInfo; 40import android.os.Build.VERSION_CODES; 41import android.os.Bundle; 42import android.os.IBinder; 43import android.os.Process; 44import android.os.UserHandle; 45import android.os.UserManager; 46import android.os.UserManagerInternal; 47import android.provider.Settings; 48import android.telephony.TelephonyManager; 49import android.test.MoreAsserts; 50import android.test.suitebuilder.annotation.SmallTest; 51import android.util.ArraySet; 52import android.util.Pair; 53 54import com.android.internal.R; 55import com.android.server.LocalServices; 56import com.android.server.SystemService; 57import com.android.server.pm.UserRestrictionsUtils; 58 59import org.mockito.invocation.InvocationOnMock; 60import org.mockito.stubbing.Answer; 61 62import java.util.ArrayList; 63import java.util.Arrays; 64import java.util.Collections; 65import java.util.HashMap; 66import java.util.List; 67import java.util.Map; 68import java.util.Set; 69import java.util.concurrent.TimeUnit; 70 71import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 72import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 73 74import static org.mockito.Matchers.any; 75import static org.mockito.Matchers.anyInt; 76import static org.mockito.Matchers.anyLong; 77import static org.mockito.Matchers.anyObject; 78import static org.mockito.Matchers.anyString; 79import static org.mockito.Matchers.eq; 80import static org.mockito.Matchers.isNull; 81import static org.mockito.Mockito.atLeast; 82import static org.mockito.Mockito.doAnswer; 83import static org.mockito.Mockito.doReturn; 84import static org.mockito.Mockito.never; 85import static org.mockito.Mockito.reset; 86import static org.mockito.Mockito.times; 87import static org.mockito.Mockito.verify; 88import static org.mockito.Mockito.when; 89 90/** 91 * Tests for DevicePolicyManager( and DevicePolicyManagerService). 92 * You can run them via: 93 m FrameworksServicesTests && 94 adb install \ 95 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && 96 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \ 97 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner 98 99 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) 100 * 101 * , or: 102 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services 103 */ 104@SmallTest 105public class DevicePolicyManagerTest extends DpmTestBase { 106 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList( 107 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, 108 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL); 109 110 private DpmMockContext mContext; 111 public DevicePolicyManager dpm; 112 public DevicePolicyManagerServiceTestable dpms; 113 114 @Override 115 protected void setUp() throws Exception { 116 super.setUp(); 117 118 mContext = getContext(); 119 120 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 121 .thenReturn(true); 122 123 // By default, pretend all users are running and unlocked. 124 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 125 126 initializeDpms(); 127 128 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 129 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 130 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID); 131 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID); 132 133 setUpUserManager(); 134 } 135 136 private void initializeDpms() { 137 // Need clearCallingIdentity() to pass permission checks. 138 final long ident = mContext.binder.clearCallingIdentity(); 139 try { 140 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 141 142 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); 143 144 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); 145 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); 146 147 dpm = new DevicePolicyManagerTestable(mContext, dpms); 148 } finally { 149 mContext.binder.restoreCallingIdentity(ident); 150 } 151 } 152 153 private void setUpUserManager() { 154 // Emulate UserManager.set/getApplicationRestriction(). 155 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>(); 156 157 // UM.setApplicationRestrictions() will save to appRestrictions. 158 doAnswer(new Answer<Void>() { 159 @Override 160 public Void answer(InvocationOnMock invocation) throws Throwable { 161 String pkg = (String) invocation.getArguments()[0]; 162 Bundle bundle = (Bundle) invocation.getArguments()[1]; 163 UserHandle user = (UserHandle) invocation.getArguments()[2]; 164 165 appRestrictions.put(Pair.create(pkg, user), bundle); 166 167 return null; 168 } 169 }).when(mContext.userManager).setApplicationRestrictions( 170 anyString(), any(Bundle.class), any(UserHandle.class)); 171 172 // UM.getApplicationRestrictions() will read from appRestrictions. 173 doAnswer(new Answer<Bundle>() { 174 @Override 175 public Bundle answer(InvocationOnMock invocation) throws Throwable { 176 String pkg = (String) invocation.getArguments()[0]; 177 UserHandle user = (UserHandle) invocation.getArguments()[1]; 178 179 return appRestrictions.get(Pair.create(pkg, user)); 180 } 181 }).when(mContext.userManager).getApplicationRestrictions( 182 anyString(), any(UserHandle.class)); 183 184 // Add the first secondary user. 185 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0); 186 } 187 188 private void setAsProfileOwner(ComponentName admin) { 189 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 190 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 191 192 // PO needs to be an DA. 193 dpm.setActiveAdmin(admin, /* replace =*/ false); 194 195 // Fire! 196 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 197 198 // Check 199 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); 200 } 201 202 public void testHasNoFeature() throws Exception { 203 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) 204 .thenReturn(false); 205 206 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 207 new DevicePolicyManagerServiceTestable(mContext, dataDir); 208 209 // If the device has no DPMS feature, it shouldn't register the local service. 210 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); 211 } 212 213 /** 214 * Caller doesn't have proper permissions. 215 */ 216 public void testSetActiveAdmin_SecurityException() { 217 // 1. Failure cases. 218 219 // Caller doesn't have MANAGE_DEVICE_ADMINS. 220 try { 221 dpm.setActiveAdmin(admin1, false); 222 fail("Didn't throw SecurityException"); 223 } catch (SecurityException expected) { 224 } 225 226 // Caller has MANAGE_DEVICE_ADMINS, but for different user. 227 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 228 try { 229 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1); 230 fail("Didn't throw SecurityException"); 231 } catch (SecurityException expected) { 232 } 233 } 234 235 /** 236 * Test for: 237 * {@link DevicePolicyManager#setActiveAdmin} 238 * with replace=false and replace=true 239 * {@link DevicePolicyManager#isAdminActive} 240 * {@link DevicePolicyManager#isAdminActiveAsUser} 241 * {@link DevicePolicyManager#getActiveAdmins} 242 * {@link DevicePolicyManager#getActiveAdminsAsUser} 243 */ 244 public void testSetActiveAdmin() throws Exception { 245 // 1. Make sure the caller has proper permissions. 246 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 247 248 // 2. Call the API. 249 dpm.setActiveAdmin(admin1, /* replace =*/ false); 250 251 // 3. Verify internal calls. 252 253 // Check if the boradcast is sent. 254 verify(mContext.spiedContext).sendBroadcastAsUser( 255 MockUtils.checkIntentAction( 256 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 257 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 258 verify(mContext.spiedContext).sendBroadcastAsUser( 259 MockUtils.checkIntentAction( 260 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED), 261 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 262 263 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 264 eq(admin1.getPackageName()), 265 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 266 eq(PackageManager.DONT_KILL_APP), 267 eq(DpmMockContext.CALLER_USER_HANDLE), 268 anyString()); 269 270 // TODO Verify other calls too. 271 272 // Make sure it's active admin1. 273 assertTrue(dpm.isAdminActive(admin1)); 274 assertFalse(dpm.isAdminActive(admin2)); 275 assertFalse(dpm.isAdminActive(admin3)); 276 277 // But not admin1 for a different user. 278 279 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL. 280 // (Because we're checking a different user's status from CALLER_USER_HANDLE.) 281 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 282 283 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1)); 284 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1)); 285 286 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 287 288 // Next, add one more admin. 289 // Before doing so, update the application info, now it's enabled. 290 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID, 291 PackageManager.COMPONENT_ENABLED_STATE_ENABLED); 292 293 dpm.setActiveAdmin(admin2, /* replace =*/ false); 294 295 // Now we have two admins. 296 assertTrue(dpm.isAdminActive(admin1)); 297 assertTrue(dpm.isAdminActive(admin2)); 298 assertFalse(dpm.isAdminActive(admin3)); 299 300 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called 301 // again. (times(1) because it was previously called for admin1) 302 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( 303 eq(admin1.getPackageName()), 304 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), 305 eq(PackageManager.DONT_KILL_APP), 306 eq(DpmMockContext.CALLER_USER_HANDLE), 307 anyString()); 308 309 // 4. Add the same admin1 again without replace, which should throw. 310 try { 311 dpm.setActiveAdmin(admin1, /* replace =*/ false); 312 fail("Didn't throw"); 313 } catch (IllegalArgumentException expected) { 314 } 315 316 // 5. Add the same admin1 again with replace, which should succeed. 317 dpm.setActiveAdmin(admin1, /* replace =*/ true); 318 319 // TODO make sure it's replaced. 320 321 // 6. Test getActiveAdmins() 322 List<ComponentName> admins = dpm.getActiveAdmins(); 323 assertEquals(2, admins.size()); 324 assertEquals(admin1, admins.get(0)); 325 assertEquals(admin2, admins.get(1)); 326 327 // Another user has no admins. 328 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); 329 330 assertEquals(0, DpmTestUtils.getListSizeAllowingNull( 331 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1))); 332 333 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); 334 } 335 336 public void testSetActiveAdmin_multiUsers() throws Exception { 337 338 final int ANOTHER_USER_ID = 100; 339 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456); 340 341 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 342 343 // Set up pacakge manager for the other user. 344 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 345 346 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 347 348 dpm.setActiveAdmin(admin1, /* replace =*/ false); 349 350 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 351 dpm.setActiveAdmin(admin2, /* replace =*/ false); 352 353 354 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 355 assertTrue(dpm.isAdminActive(admin1)); 356 assertFalse(dpm.isAdminActive(admin2)); 357 358 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; 359 assertFalse(dpm.isAdminActive(admin1)); 360 assertTrue(dpm.isAdminActive(admin2)); 361 } 362 363 /** 364 * Test for: 365 * {@link DevicePolicyManager#setActiveAdmin} 366 * with replace=false 367 */ 368 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception { 369 // 1. Make sure the caller has proper permissions. 370 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 371 372 dpm.setActiveAdmin(admin1, /* replace =*/ false); 373 assertTrue(dpm.isAdminActive(admin1)); 374 375 // Add the same admin1 again without replace, which should throw. 376 try { 377 dpm.setActiveAdmin(admin1, /* replace =*/ false); 378 fail("Didn't throw"); 379 } catch (IllegalArgumentException expected) { 380 } 381 } 382 383 /** 384 * Test for: 385 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with 386 * BIND_DEVICE_ADMIN. 387 */ 388 public void testSetActiveAdmin_permissionCheck() throws Exception { 389 // 1. Make sure the caller has proper permissions. 390 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 391 392 try { 393 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 394 fail(); 395 } catch (IllegalArgumentException expected) { 396 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN)); 397 } 398 assertFalse(dpm.isAdminActive(adminNoPerm)); 399 400 // Change the target API level to MNC. Now it can be set as DA. 401 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null, 402 VERSION_CODES.M); 403 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); 404 assertTrue(dpm.isAdminActive(adminNoPerm)); 405 406 // TODO Test the "load from the file" case where DA will still be loaded even without 407 // BIND_DEVICE_ADMIN and target API is N. 408 } 409 410 /** 411 * Test for: 412 * {@link DevicePolicyManager#removeActiveAdmin} 413 */ 414 public void testRemoveActiveAdmin_SecurityException() { 415 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 416 417 // Add admin. 418 419 dpm.setActiveAdmin(admin1, /* replace =*/ false); 420 421 assertTrue(dpm.isAdminActive(admin1)); 422 423 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 424 425 // Directly call the DPMS method with a different userid, which should fail. 426 try { 427 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1); 428 fail("Didn't throw SecurityException"); 429 } catch (SecurityException expected) { 430 } 431 432 // Try to remove active admin with a different caller userid should fail too, without 433 // having MANAGE_DEVICE_ADMINS. 434 mContext.callerPermissions.clear(); 435 436 // Change the caller, and call into DPMS directly with a different user-id. 437 438 mContext.binder.callingUid = 1234567; 439 try { 440 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 441 fail("Didn't throw SecurityException"); 442 } catch (SecurityException expected) { 443 } 444 } 445 446 /** 447 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked 448 * (because we can't send the remove broadcast). 449 */ 450 public void testRemoveActiveAdmin_userNotRunningOrLocked() { 451 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 452 453 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 454 455 // Add admin. 456 457 dpm.setActiveAdmin(admin1, /* replace =*/ false); 458 459 assertTrue(dpm.isAdminActive(admin1)); 460 461 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 462 463 // 1. User not unlocked. 464 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 465 .thenReturn(false); 466 try { 467 dpm.removeActiveAdmin(admin1); 468 fail("Didn't throw IllegalStateException"); 469 } catch (IllegalStateException expected) { 470 MoreAsserts.assertContainsRegex( 471 "User must be running and unlocked", expected.getMessage()); 472 } 473 474 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 475 476 // 2. User unlocked. 477 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) 478 .thenReturn(true); 479 480 dpm.removeActiveAdmin(admin1); 481 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 482 } 483 484 /** 485 * Test for: 486 * {@link DevicePolicyManager#removeActiveAdmin} 487 */ 488 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() { 489 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 490 491 // Add admin1. 492 493 dpm.setActiveAdmin(admin1, /* replace =*/ false); 494 495 assertTrue(dpm.isAdminActive(admin1)); 496 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 497 498 // Different user, but should work, because caller has proper permissions. 499 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 500 501 // Change the caller, and call into DPMS directly with a different user-id. 502 mContext.binder.callingUid = 1234567; 503 504 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE); 505 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 506 507 // TODO DO Still can't be removed in this case. 508 } 509 510 /** 511 * Test for: 512 * {@link DevicePolicyManager#removeActiveAdmin} 513 */ 514 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() { 515 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. 516 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 517 518 // Add admin1. 519 520 dpm.setActiveAdmin(admin1, /* replace =*/ false); 521 522 assertTrue(dpm.isAdminActive(admin1)); 523 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 524 525 // Broadcast from saveSettingsLocked(). 526 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 527 MockUtils.checkIntentAction( 528 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 529 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 530 531 // Remove. No permissions, but same user, so it'll work. 532 mContext.callerPermissions.clear(); 533 dpm.removeActiveAdmin(admin1); 534 535 verify(mContext.spiedContext).sendOrderedBroadcastAsUser( 536 MockUtils.checkIntentAction( 537 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED), 538 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE), 539 isNull(String.class), 540 any(BroadcastReceiver.class), 541 eq(dpms.mHandler), 542 eq(Activity.RESULT_OK), 543 isNull(String.class), 544 isNull(Bundle.class)); 545 546 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 547 548 // Again broadcast from saveSettingsLocked(). 549 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 550 MockUtils.checkIntentAction( 551 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 552 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); 553 554 // TODO Check other internal calls. 555 } 556 557 /** 558 * Test for: @{link DevicePolicyManager#setActivePasswordState} 559 * 560 * Validates that when the password for a user changes, the notification broadcast intent 561 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in 562 * addition to ones in the original user. 563 */ 564 public void testSetActivePasswordState_sendToProfiles() throws Exception { 565 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); 566 567 final int MANAGED_PROFILE_USER_ID = 78; 568 final int MANAGED_PROFILE_ADMIN_UID = 569 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID); 570 571 // Setup device owner. 572 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 573 mContext.packageName = admin1.getPackageName(); 574 setupDeviceOwner(); 575 576 // Add a managed profile belonging to the system user. 577 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 578 579 // Change the parent user's password. 580 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM); 581 582 // Both the device owner and the managed profile owner should receive this broadcast. 583 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); 584 intent.setComponent(admin1); 585 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM)); 586 587 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 588 MockUtils.checkIntent(intent), 589 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 590 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 591 MockUtils.checkIntent(intent), 592 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID)); 593 } 594 595 /** 596 * Test for: @{link DevicePolicyManager#setActivePasswordState} 597 * 598 * Validates that when the password for a managed profile changes, the notification broadcast 599 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not 600 * its parent. 601 */ 602 public void testSetActivePasswordState_notSentToParent() throws Exception { 603 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); 604 605 final int MANAGED_PROFILE_USER_ID = 78; 606 final int MANAGED_PROFILE_ADMIN_UID = 607 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID); 608 609 // Setup device owner. 610 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 611 mContext.packageName = admin1.getPackageName(); 612 doReturn(true).when(mContext.lockPatternUtils) 613 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID); 614 setupDeviceOwner(); 615 616 // Add a managed profile belonging to the system user. 617 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 618 619 // Change the profile's password. 620 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID); 621 622 // Both the device owner and the managed profile owner should receive this broadcast. 623 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); 624 intent.setComponent(admin1); 625 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID)); 626 627 verify(mContext.spiedContext, never()).sendBroadcastAsUser( 628 MockUtils.checkIntent(intent), 629 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 630 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 631 MockUtils.checkIntent(intent), 632 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID)); 633 } 634 /** 635 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully. 636 */ 637 public void testSetDeviceOwner() throws Exception { 638 setDeviceOwner(); 639 640 // Try to set a profile owner on the same user, which should fail. 641 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 642 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM); 643 try { 644 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM); 645 fail("IllegalStateException not thrown"); 646 } catch (IllegalStateException expected) { 647 assertTrue("Message was: " + expected.getMessage(), 648 expected.getMessage().contains("already has a device owner")); 649 } 650 651 // DO admin can't be deactivated. 652 dpm.removeActiveAdmin(admin1); 653 assertTrue(dpm.isAdminActive(admin1)); 654 655 // TODO Test getDeviceOwnerName() too. To do so, we need to change 656 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 657 } 658 659 private void setDeviceOwner() throws Exception { 660 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 661 mContext.callerPermissions.add(permission.MANAGE_USERS); 662 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 663 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 664 665 // In this test, change the caller user to "system". 666 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 667 668 // Make sure admin1 is installed on system user. 669 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 670 671 // Check various get APIs. 672 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false); 673 674 // DO needs to be an DA. 675 dpm.setActiveAdmin(admin1, /* replace =*/ false); 676 677 // Fire! 678 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 679 680 // getDeviceOwnerComponent should return the admin1 component. 681 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 682 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 683 684 // Check various get APIs. 685 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true); 686 687 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users. 688 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 689 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 691 692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 693 694 // Verify internal calls. 695 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 696 eq(admin1.getPackageName())); 697 698 // TODO We should check if the caller has called clearCallerIdentity(). 699 verify(mContext.ibackupManager, times(1)).setBackupServiceActive( 700 eq(UserHandle.USER_SYSTEM), eq(false)); 701 702 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( 703 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 704 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 705 706 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 707 } 708 709 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) { 710 final int origCallingUser = mContext.binder.callingUid; 711 final List origPermissions = new ArrayList(mContext.callerPermissions); 712 mContext.callerPermissions.clear(); 713 714 mContext.callerPermissions.add(permission.MANAGE_USERS); 715 716 mContext.binder.callingUid = Process.SYSTEM_UID; 717 718 // TODO Test getDeviceOwnerName() too. To do so, we need to change 719 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. 720 if (hasDeviceOwner) { 721 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 722 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 723 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 724 725 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 726 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 727 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 728 } else { 729 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 730 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 731 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 732 733 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 734 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 735 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 736 } 737 738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 739 if (hasDeviceOwner) { 740 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 741 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 742 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 743 744 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 745 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 746 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 747 } else { 748 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 749 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 750 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 751 752 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 753 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 754 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 755 } 756 757 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 758 // Still with MANAGE_USERS. 759 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 760 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 761 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 762 763 if (hasDeviceOwner) { 764 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 765 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 766 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 767 } else { 768 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 769 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 770 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 771 } 772 773 mContext.binder.callingUid = Process.SYSTEM_UID; 774 mContext.callerPermissions.remove(permission.MANAGE_USERS); 775 // System can still call "OnAnyUser" without MANAGE_USERS. 776 if (hasDeviceOwner) { 777 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 778 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 779 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 780 781 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 782 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 783 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); 784 } else { 785 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 786 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 787 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 788 789 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); 790 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); 791 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); 792 } 793 794 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 795 // Still no MANAGE_USERS. 796 if (hasDeviceOwner) { 797 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 798 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 799 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); 800 } else { 801 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 802 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 803 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 804 } 805 806 try { 807 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 808 fail(); 809 } catch (SecurityException expected) { 810 } 811 try { 812 dpm.getDeviceOwnerComponentOnAnyUser(); 813 fail(); 814 } catch (SecurityException expected) { 815 } 816 try { 817 dpm.getDeviceOwnerUserId(); 818 fail(); 819 } catch (SecurityException expected) { 820 } 821 try { 822 dpm.getDeviceOwnerNameOnAnyUser(); 823 fail(); 824 } catch (SecurityException expected) { 825 } 826 827 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 828 // Still no MANAGE_USERS. 829 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); 830 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); 831 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); 832 833 try { 834 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()); 835 fail(); 836 } catch (SecurityException expected) { 837 } 838 try { 839 dpm.getDeviceOwnerComponentOnAnyUser(); 840 fail(); 841 } catch (SecurityException expected) { 842 } 843 try { 844 dpm.getDeviceOwnerUserId(); 845 fail(); 846 } catch (SecurityException expected) { 847 } 848 try { 849 dpm.getDeviceOwnerNameOnAnyUser(); 850 fail(); 851 } catch (SecurityException expected) { 852 } 853 854 // Restore. 855 mContext.binder.callingUid = origCallingUser; 856 mContext.callerPermissions.addAll(origPermissions); 857 } 858 859 860 /** 861 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist. 862 */ 863 public void testSetDeviceOwner_noSuchPackage() { 864 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 865 mContext.callerPermissions.add(permission.MANAGE_USERS); 866 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 867 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 868 869 // Call from a process on the system user. 870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 871 872 try { 873 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")); 874 fail("Didn't throw IllegalArgumentException"); 875 } catch (IllegalArgumentException expected) { 876 assertTrue("Message was: " + expected.getMessage(), 877 expected.getMessage().contains("Invalid component")); 878 } 879 } 880 881 public void testSetDeviceOwner_failures() throws Exception { 882 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner(). 883 } 884 885 public void testClearDeviceOwner() throws Exception { 886 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 887 mContext.callerPermissions.add(permission.MANAGE_USERS); 888 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 889 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 890 891 // Set admin1 as a DA to the secondary user. 892 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 893 894 dpm.setActiveAdmin(admin1, /* replace =*/ false); 895 896 // Set admin 1 as the DO to the system user. 897 898 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 899 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 900 dpm.setActiveAdmin(admin1, /* replace =*/ false); 901 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 902 903 // Verify internal calls. 904 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 905 eq(admin1.getPackageName())); 906 907 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 908 909 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 910 911 assertTrue(dpm.isAdminActive(admin1)); 912 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); 913 914 // Set up other mocks. 915 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle()); 916 917 // Now call clear. 918 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser( 919 eq(admin1.getPackageName()), 920 anyInt()); 921 922 // But first pretend the user is locked. Then it should fail. 923 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false); 924 try { 925 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 926 fail("Didn't throw IllegalStateException"); 927 } catch (IllegalStateException expected) { 928 MoreAsserts.assertContainsRegex( 929 "User must be running and unlocked", expected.getMessage()); 930 } 931 932 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); 933 reset(mContext.userManagerInternal); 934 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 935 936 // Now DO shouldn't be set. 937 assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); 938 939 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 940 eq(UserHandle.USER_SYSTEM), 941 eq(null), 942 eq(true), eq(CAMERA_NOT_DISABLED)); 943 944 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)); 945 946 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner 947 // and once for clearing it. 948 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( 949 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); 951 // TODO Check other calls. 952 } 953 954 public void testClearDeviceOwner_fromDifferentUser() throws Exception { 955 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 956 mContext.callerPermissions.add(permission.MANAGE_USERS); 957 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 958 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 959 960 // Set admin1 as a DA to the secondary user. 961 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 962 963 dpm.setActiveAdmin(admin1, /* replace =*/ false); 964 965 // Set admin 1 as the DO to the system user. 966 967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 969 dpm.setActiveAdmin(admin1, /* replace =*/ false); 970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 971 972 // Verify internal calls. 973 verify(mContext.iactivityManager, times(1)).updateDeviceOwner( 974 eq(admin1.getPackageName())); 975 976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); 977 978 // Now call clear from the secondary user, which should throw. 979 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 980 981 // Now call clear. 982 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( 983 eq(admin1.getPackageName()), 984 anyInt()); 985 try { 986 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 987 fail("Didn't throw"); 988 } catch (SecurityException e) { 989 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage()); 990 } 991 992 // DO shouldn't be removed. 993 assertTrue(dpm.isDeviceManaged()); 994 } 995 996 public void testSetProfileOwner() throws Exception { 997 setAsProfileOwner(admin1); 998 999 // PO admin can't be deactivated. 1000 dpm.removeActiveAdmin(admin1); 1001 assertTrue(dpm.isAdminActive(admin1)); 1002 1003 // Try setting DO on the same user, which should fail. 1004 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 1005 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); 1006 try { 1007 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1008 fail("IllegalStateException not thrown"); 1009 } catch (IllegalStateException expected) { 1010 assertTrue("Message was: " + expected.getMessage(), 1011 expected.getMessage().contains("already has a profile owner")); 1012 } 1013 } 1014 1015 public void testClearProfileOwner() throws Exception { 1016 setAsProfileOwner(admin1); 1017 1018 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1019 1020 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); 1021 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); 1022 1023 // First try when the user is locked, which should fail. 1024 when(mContext.userManager.isUserUnlocked(anyInt())) 1025 .thenReturn(false); 1026 try { 1027 dpm.clearProfileOwner(admin1); 1028 fail("Didn't throw IllegalStateException"); 1029 } catch (IllegalStateException expected) { 1030 MoreAsserts.assertContainsRegex( 1031 "User must be running and unlocked", expected.getMessage()); 1032 } 1033 // Clear, really. 1034 when(mContext.userManager.isUserUnlocked(anyInt())) 1035 .thenReturn(true); 1036 dpm.clearProfileOwner(admin1); 1037 1038 // Check 1039 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); 1040 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE)); 1041 } 1042 1043 public void testSetProfileOwner_failures() throws Exception { 1044 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). 1045 } 1046 1047 public void testGetDeviceOwnerAdminLocked() throws Exception { 1048 checkDeviceOwnerWithMultipleDeviceAdmins(); 1049 } 1050 1051 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception { 1052 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them, 1053 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to 1054 // make sure it gets the right component from the right user. 1055 1056 final int ANOTHER_USER_ID = 100; 1057 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); 1058 1059 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. 1060 1061 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1062 mContext.callerPermissions.add(permission.MANAGE_USERS); 1063 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1064 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1065 1066 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1067 1068 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1069 1070 // Make sure the admin packge is installed to each user. 1071 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1072 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID); 1073 1074 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 1075 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); 1076 1077 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); 1078 1079 1080 // Set active admins to the users. 1081 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1082 dpm.setActiveAdmin(admin3, /* replace =*/ false); 1083 1084 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 1085 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE); 1086 1087 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); 1088 1089 // Set DO on the first non-system user. 1090 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); 1091 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); 1092 1093 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1094 1095 // Then check getDeviceOwnerAdminLocked(). 1096 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent()); 1097 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid()); 1098 } 1099 1100 /** 1101 * This essentially tests 1102 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is 1103 * private.) 1104 * 1105 * We didn't use to persist the DO component class name, but now we do, and the above method 1106 * finds the right component from a package name upon migration. 1107 */ 1108 public void testDeviceOwnerMigration() throws Exception { 1109 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 1110 checkDeviceOwnerWithMultipleDeviceAdmins(); 1111 1112 // Overwrite the device owner setting and clears the clas name. 1113 dpms.mOwners.setDeviceOwner( 1114 new ComponentName(admin2.getPackageName(), ""), 1115 "owner-name", DpmMockContext.CALLER_USER_HANDLE); 1116 dpms.mOwners.writeDeviceOwner(); 1117 1118 // Make sure the DO component name doesn't have a class name. 1119 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); 1120 1121 // Then create a new DPMS to have it load the settings from files. 1122 when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) 1123 .thenReturn(new Bundle()); 1124 initializeDpms(); 1125 1126 // Now the DO component name is a full name. 1127 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the 1128 // DO. 1129 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); 1130 } 1131 1132 public void testSetGetApplicationRestriction() { 1133 setAsProfileOwner(admin1); 1134 mContext.packageName = admin1.getPackageName(); 1135 1136 { 1137 Bundle rest = new Bundle(); 1138 rest.putString("KEY_STRING", "Foo1"); 1139 dpm.setApplicationRestrictions(admin1, "pkg1", rest); 1140 } 1141 1142 { 1143 Bundle rest = new Bundle(); 1144 rest.putString("KEY_STRING", "Foo2"); 1145 dpm.setApplicationRestrictions(admin1, "pkg2", rest); 1146 } 1147 1148 { 1149 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); 1150 assertNotNull(returned); 1151 assertEquals(returned.size(), 1); 1152 assertEquals(returned.get("KEY_STRING"), "Foo1"); 1153 } 1154 1155 { 1156 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); 1157 assertNotNull(returned); 1158 assertEquals(returned.size(), 1); 1159 assertEquals(returned.get("KEY_STRING"), "Foo2"); 1160 } 1161 1162 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); 1163 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); 1164 } 1165 1166 /** 1167 * Setup a package in the package manager mock. Useful for faking installed applications. 1168 * 1169 * @param packageName the name of the package to be setup 1170 * @param appId the application ID to be given to the package 1171 * @return the UID of the package as known by the mock package manager 1172 */ 1173 private int setupPackageInPackageManager(final String packageName, final int appId) 1174 throws Exception { 1175 // Make the PackageManager return the package instead of throwing a NameNotFoundException 1176 final PackageInfo pi = new PackageInfo(); 1177 pi.applicationInfo = new ApplicationInfo(); 1178 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE; 1179 doReturn(pi).when(mContext.ipackageManager).getPackageInfo( 1180 eq(packageName), 1181 anyInt(), 1182 eq(DpmMockContext.CALLER_USER_HANDLE)); 1183 // Setup application UID with the PackageManager 1184 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId); 1185 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser( 1186 eq(packageName), 1187 eq(DpmMockContext.CALLER_USER_HANDLE)); 1188 // Associate packageName to uid 1189 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid)); 1190 doReturn(new String[]{packageName}) 1191 .when(mContext.ipackageManager).getPackagesForUid(eq(uid)); 1192 return uid; 1193 } 1194 1195 /** 1196 * Simple test for delegate set/get and general delegation. Tests verifying that delegated 1197 * privileges can acually be exercised by a delegate are not covered here. 1198 */ 1199 public void testDelegation() throws Exception { 1200 setAsProfileOwner(admin1); 1201 1202 final int userHandle = DpmMockContext.CALLER_USER_HANDLE; 1203 1204 // Given two packages 1205 final String CERT_DELEGATE = "com.delegate.certs"; 1206 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions"; 1207 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988); 1208 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE, 1209 20989); 1210 1211 // On delegation 1212 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1213 mContext.packageName = admin1.getPackageName(); 1214 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE); 1215 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE); 1216 1217 // DPMS correctly stores and retrieves the delegates 1218 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle); 1219 assertEquals(2, policy.mDelegationMap.size()); 1220 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE), 1221 DELEGATION_CERT_INSTALL); 1222 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE), 1223 DELEGATION_CERT_INSTALL); 1224 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1)); 1225 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE), 1226 DELEGATION_APP_RESTRICTIONS); 1227 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE), 1228 DELEGATION_APP_RESTRICTIONS); 1229 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1)); 1230 1231 // On calling install certificate APIs from an unauthorized process 1232 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID; 1233 mContext.packageName = RESTRICTIONS_DELEGATE; 1234 1235 // DPMS throws a SecurityException 1236 try { 1237 dpm.installCaCert(null, null); 1238 fail("Didn't throw SecurityException on unauthorized access"); 1239 } catch (SecurityException expected) { 1240 } 1241 1242 // On calling install certificate APIs from an authorized process 1243 mContext.binder.callingUid = CERT_DELEGATE_UID; 1244 mContext.packageName = CERT_DELEGATE; 1245 1246 // DPMS executes without a SecurityException 1247 try { 1248 dpm.installCaCert(null, null); 1249 } catch (SecurityException unexpected) { 1250 fail("Threw SecurityException on authorized access"); 1251 } catch (NullPointerException expected) { 1252 } 1253 1254 // On removing a delegate 1255 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1256 mContext.packageName = admin1.getPackageName(); 1257 dpm.setCertInstallerPackage(admin1, null); 1258 1259 // DPMS does not allow access to ex-delegate 1260 mContext.binder.callingUid = CERT_DELEGATE_UID; 1261 mContext.packageName = CERT_DELEGATE; 1262 try { 1263 dpm.installCaCert(null, null); 1264 fail("Didn't throw SecurityException on unauthorized access"); 1265 } catch (SecurityException expected) { 1266 } 1267 1268 // But still allows access to other existing delegates 1269 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID; 1270 mContext.packageName = RESTRICTIONS_DELEGATE; 1271 try { 1272 dpm.getApplicationRestrictions(null, "pkg"); 1273 } catch (SecurityException expected) { 1274 fail("Threw SecurityException on authorized access"); 1275 } 1276 } 1277 1278 public void testApplicationRestrictionsManagingApp() throws Exception { 1279 setAsProfileOwner(admin1); 1280 1281 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2"; 1282 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager"; 1283 final int appRestrictionsManagerAppId = 20987; 1284 final int appRestrictionsManagerUid = setupPackageInPackageManager( 1285 appRestrictionsManagerPackage, appRestrictionsManagerAppId); 1286 1287 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't 1288 // delegated that permission yet. 1289 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1290 mContext.packageName = admin1.getPackageName(); 1291 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1292 Bundle rest = new Bundle(); 1293 rest.putString("KEY_STRING", "Foo1"); 1294 try { 1295 dpm.setApplicationRestrictions(null, "pkg1", rest); 1296 fail("Didn't throw expected SecurityException"); 1297 } catch (SecurityException expected) { 1298 MoreAsserts.assertContainsRegex( 1299 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.", 1300 expected.getMessage()); 1301 } 1302 try { 1303 dpm.getApplicationRestrictions(null, "pkg1"); 1304 fail("Didn't throw expected SecurityException"); 1305 } catch (SecurityException expected) { 1306 MoreAsserts.assertContainsRegex( 1307 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.", 1308 expected.getMessage()); 1309 } 1310 1311 // Check via the profile owner that no restrictions were set. 1312 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1313 mContext.packageName = admin1.getPackageName(); 1314 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1315 1316 // Check the API does not allow setting a non-existent package 1317 try { 1318 dpm.setApplicationRestrictionsManagingPackage(admin1, 1319 nonExistAppRestrictionsManagerPackage); 1320 fail("Non-existent app set as app restriction manager."); 1321 } catch (PackageManager.NameNotFoundException expected) { 1322 MoreAsserts.assertContainsRegex( 1323 nonExistAppRestrictionsManagerPackage, expected.getMessage()); 1324 } 1325 1326 // Let appRestrictionsManagerPackage manage app restrictions 1327 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); 1328 assertEquals(appRestrictionsManagerPackage, 1329 dpm.getApplicationRestrictionsManagingPackage(admin1)); 1330 1331 // Now that package should be able to set and retrieve app restrictions. 1332 mContext.binder.callingUid = appRestrictionsManagerUid; 1333 mContext.packageName = appRestrictionsManagerPackage; 1334 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); 1335 dpm.setApplicationRestrictions(null, "pkg1", rest); 1336 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); 1337 assertEquals(1, returned.size(), 1); 1338 assertEquals("Foo1", returned.get("KEY_STRING")); 1339 1340 // The same app running on a separate user shouldn't be able to manage app restrictions. 1341 mContext.binder.callingUid = UserHandle.getUid( 1342 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); 1343 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1344 try { 1345 dpm.setApplicationRestrictions(null, "pkg1", rest); 1346 fail("Didn't throw expected SecurityException"); 1347 } catch (SecurityException expected) { 1348 MoreAsserts.assertContainsRegex( 1349 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.", 1350 expected.getMessage()); 1351 } 1352 1353 // The DPM is still able to manage app restrictions, even if it allowed another app to do it 1354 // too. 1355 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1356 mContext.packageName = admin1.getPackageName(); 1357 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); 1358 dpm.setApplicationRestrictions(admin1, "pkg1", null); 1359 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); 1360 1361 // Removing the ability for the package to manage app restrictions. 1362 dpm.setApplicationRestrictionsManagingPackage(admin1, null); 1363 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); 1364 mContext.binder.callingUid = appRestrictionsManagerUid; 1365 mContext.packageName = appRestrictionsManagerPackage; 1366 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); 1367 try { 1368 dpm.setApplicationRestrictions(null, "pkg1", null); 1369 fail("Didn't throw expected SecurityException"); 1370 } catch (SecurityException expected) { 1371 MoreAsserts.assertContainsRegex( 1372 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.", 1373 expected.getMessage()); 1374 } 1375 } 1376 1377 public void testSetUserRestriction_asDo() throws Exception { 1378 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1379 mContext.callerPermissions.add(permission.MANAGE_USERS); 1380 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1381 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1382 1383 // First, set DO. 1384 1385 // Call from a process on the system user. 1386 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1387 1388 // Make sure admin1 is installed on system user. 1389 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1390 1391 // Call. 1392 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1393 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1394 UserHandle.USER_SYSTEM)); 1395 1396 // Check that the user restrictions that are enabled by default are set. Then unset them. 1397 String[] defaultRestrictions = UserRestrictionsUtils 1398 .getDefaultEnabledForDeviceOwner().toArray(new String[0]); 1399 DpmTestUtils.assertRestrictions( 1400 DpmTestUtils.newRestrictions(defaultRestrictions), 1401 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1402 ); 1403 DpmTestUtils.assertRestrictions( 1404 DpmTestUtils.newRestrictions(defaultRestrictions), 1405 dpm.getUserRestrictions(admin1) 1406 ); 1407 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1408 eq(UserHandle.USER_SYSTEM), 1409 MockUtils.checkUserRestrictions(defaultRestrictions), 1410 eq(true) /* isDeviceOwner */, 1411 eq(CAMERA_NOT_DISABLED) 1412 ); 1413 reset(mContext.userManagerInternal); 1414 1415 for (String restriction : defaultRestrictions) { 1416 dpm.clearUserRestriction(admin1, restriction); 1417 } 1418 1419 assertNoDeviceOwnerRestrictions(); 1420 reset(mContext.userManagerInternal); 1421 1422 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1423 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1424 eq(UserHandle.USER_SYSTEM), 1425 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER), 1426 eq(true), eq(CAMERA_NOT_DISABLED)); 1427 reset(mContext.userManagerInternal); 1428 1429 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1430 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1431 eq(UserHandle.USER_SYSTEM), 1432 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS, 1433 UserManager.DISALLOW_ADD_USER), 1434 eq(true), eq(CAMERA_NOT_DISABLED)); 1435 reset(mContext.userManagerInternal); 1436 1437 DpmTestUtils.assertRestrictions( 1438 DpmTestUtils.newRestrictions( 1439 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1440 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1441 ); 1442 DpmTestUtils.assertRestrictions( 1443 DpmTestUtils.newRestrictions( 1444 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS), 1445 dpm.getUserRestrictions(admin1) 1446 ); 1447 1448 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1449 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1450 eq(UserHandle.USER_SYSTEM), 1451 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1452 eq(true), eq(CAMERA_NOT_DISABLED)); 1453 reset(mContext.userManagerInternal); 1454 1455 DpmTestUtils.assertRestrictions( 1456 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1457 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1458 ); 1459 DpmTestUtils.assertRestrictions( 1460 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1461 dpm.getUserRestrictions(admin1) 1462 ); 1463 1464 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1465 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1466 eq(UserHandle.USER_SYSTEM), 1467 MockUtils.checkUserRestrictions(), 1468 eq(true), eq(CAMERA_NOT_DISABLED)); 1469 reset(mContext.userManagerInternal); 1470 1471 assertNoDeviceOwnerRestrictions(); 1472 1473 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when 1474 // DO sets them, the scope is global. 1475 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1476 reset(mContext.userManagerInternal); 1477 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1478 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1479 eq(UserHandle.USER_SYSTEM), 1480 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1481 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1482 eq(true), eq(CAMERA_NOT_DISABLED)); 1483 reset(mContext.userManagerInternal); 1484 1485 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1486 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1487 reset(mContext.userManagerInternal); 1488 1489 // More tests. 1490 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); 1491 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1492 eq(UserHandle.USER_SYSTEM), 1493 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER), 1494 eq(true), eq(CAMERA_NOT_DISABLED)); 1495 reset(mContext.userManagerInternal); 1496 1497 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); 1498 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1499 eq(UserHandle.USER_SYSTEM), 1500 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1501 UserManager.DISALLOW_ADD_USER), 1502 eq(true), eq(CAMERA_NOT_DISABLED)); 1503 reset(mContext.userManagerInternal); 1504 1505 dpm.setCameraDisabled(admin1, true); 1506 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1507 eq(UserHandle.USER_SYSTEM), 1508 // DISALLOW_CAMERA will be applied to both local and global. 1509 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1510 UserManager.DISALLOW_ADD_USER), 1511 eq(true), eq(CAMERA_DISABLED_GLOBALLY)); 1512 reset(mContext.userManagerInternal); 1513 1514 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied 1515 // locally. 1516 dpm.setCameraDisabled(admin1, false); 1517 reset(mContext.userManagerInternal); 1518 1519 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); 1520 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); 1521 dpm.setCameraDisabled(admin2, true); 1522 1523 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1524 eq(UserHandle.USER_SYSTEM), 1525 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this 1526 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, 1527 UserManager.DISALLOW_ADD_USER), 1528 eq(true), eq(CAMERA_DISABLED_LOCALLY)); 1529 reset(mContext.userManagerInternal); 1530 // TODO Make sure restrictions are written to the file. 1531 } 1532 1533 public void testSetUserRestriction_asPo() { 1534 setAsProfileOwner(admin1); 1535 1536 DpmTestUtils.assertRestrictions( 1537 DpmTestUtils.newRestrictions(), 1538 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1539 .ensureUserRestrictions() 1540 ); 1541 1542 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1543 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1544 eq(DpmMockContext.CALLER_USER_HANDLE), 1545 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), 1546 eq(false), eq(CAMERA_NOT_DISABLED)); 1547 reset(mContext.userManagerInternal); 1548 1549 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1550 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1551 eq(DpmMockContext.CALLER_USER_HANDLE), 1552 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1553 UserManager.DISALLOW_OUTGOING_CALLS), 1554 eq(false), eq(CAMERA_NOT_DISABLED)); 1555 reset(mContext.userManagerInternal); 1556 1557 DpmTestUtils.assertRestrictions( 1558 DpmTestUtils.newRestrictions( 1559 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1560 UserManager.DISALLOW_OUTGOING_CALLS 1561 ), 1562 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1563 .ensureUserRestrictions() 1564 ); 1565 DpmTestUtils.assertRestrictions( 1566 DpmTestUtils.newRestrictions( 1567 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 1568 UserManager.DISALLOW_OUTGOING_CALLS 1569 ), 1570 dpm.getUserRestrictions(admin1) 1571 ); 1572 1573 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); 1574 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1575 eq(DpmMockContext.CALLER_USER_HANDLE), 1576 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), 1577 eq(false), eq(CAMERA_NOT_DISABLED)); 1578 reset(mContext.userManagerInternal); 1579 1580 DpmTestUtils.assertRestrictions( 1581 DpmTestUtils.newRestrictions( 1582 UserManager.DISALLOW_OUTGOING_CALLS 1583 ), 1584 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1585 .ensureUserRestrictions() 1586 ); 1587 DpmTestUtils.assertRestrictions( 1588 DpmTestUtils.newRestrictions( 1589 UserManager.DISALLOW_OUTGOING_CALLS 1590 ), 1591 dpm.getUserRestrictions(admin1) 1592 ); 1593 1594 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); 1595 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1596 eq(DpmMockContext.CALLER_USER_HANDLE), 1597 MockUtils.checkUserRestrictions(), 1598 eq(false), eq(CAMERA_NOT_DISABLED)); 1599 reset(mContext.userManagerInternal); 1600 1601 DpmTestUtils.assertRestrictions( 1602 DpmTestUtils.newRestrictions(), 1603 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE) 1604 .ensureUserRestrictions() 1605 ); 1606 DpmTestUtils.assertRestrictions( 1607 DpmTestUtils.newRestrictions(), 1608 dpm.getUserRestrictions(admin1) 1609 ); 1610 1611 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even 1612 // though when DO sets them they'll be applied globally. 1613 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); 1614 reset(mContext.userManagerInternal); 1615 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); 1616 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1617 eq(DpmMockContext.CALLER_USER_HANDLE), 1618 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1619 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1620 eq(false), eq(CAMERA_NOT_DISABLED)); 1621 reset(mContext.userManagerInternal); 1622 1623 dpm.setCameraDisabled(admin1, true); 1624 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1625 eq(DpmMockContext.CALLER_USER_HANDLE), 1626 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, 1627 UserManager.DISALLOW_UNMUTE_MICROPHONE), 1628 eq(false), eq(CAMERA_DISABLED_LOCALLY)); 1629 reset(mContext.userManagerInternal); 1630 1631 // TODO Make sure restrictions are written to the file. 1632 } 1633 1634 1635 public void testDefaultEnabledUserRestrictions() throws Exception { 1636 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1637 mContext.callerPermissions.add(permission.MANAGE_USERS); 1638 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1639 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1640 1641 // First, set DO. 1642 1643 // Call from a process on the system user. 1644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1645 1646 // Make sure admin1 is installed on system user. 1647 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1648 1649 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); 1650 assertTrue(dpm.setDeviceOwner(admin1, "owner-name", 1651 UserHandle.USER_SYSTEM)); 1652 1653 // Check that the user restrictions that are enabled by default are set. Then unset them. 1654 String[] defaultRestrictions = UserRestrictionsUtils 1655 .getDefaultEnabledForDeviceOwner().toArray(new String[0]); 1656 assertTrue(defaultRestrictions.length > 0); 1657 DpmTestUtils.assertRestrictions( 1658 DpmTestUtils.newRestrictions(defaultRestrictions), 1659 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1660 ); 1661 DpmTestUtils.assertRestrictions( 1662 DpmTestUtils.newRestrictions(defaultRestrictions), 1663 dpm.getUserRestrictions(admin1) 1664 ); 1665 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( 1666 eq(UserHandle.USER_SYSTEM), 1667 MockUtils.checkUserRestrictions(defaultRestrictions), 1668 eq(true) /* isDeviceOwner */, 1669 eq(CAMERA_NOT_DISABLED) 1670 ); 1671 reset(mContext.userManagerInternal); 1672 1673 for (String restriction : defaultRestrictions) { 1674 dpm.clearUserRestriction(admin1, restriction); 1675 } 1676 1677 assertNoDeviceOwnerRestrictions(); 1678 1679 // Initialize DPMS again and check that the user restriction wasn't enabled again. 1680 reset(mContext.userManagerInternal); 1681 initializeDpms(); 1682 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1683 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1684 1685 assertNoDeviceOwnerRestrictions(); 1686 1687 // Add a new restriction to the default set, initialize DPMS, and check that the restriction 1688 // is set as it wasn't enabled during setDeviceOwner. 1689 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 1690 assertFalse(UserRestrictionsUtils 1691 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction)); 1692 UserRestrictionsUtils 1693 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction); 1694 try { 1695 reset(mContext.userManagerInternal); 1696 initializeDpms(); 1697 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1698 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1699 1700 DpmTestUtils.assertRestrictions( 1701 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction), 1702 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1703 ); 1704 DpmTestUtils.assertRestrictions( 1705 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction), 1706 dpm.getUserRestrictions(admin1) 1707 ); 1708 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions( 1709 eq(UserHandle.USER_SYSTEM), 1710 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction), 1711 eq(true) /* isDeviceOwner */, 1712 eq(CAMERA_NOT_DISABLED) 1713 ); 1714 reset(mContext.userManagerInternal); 1715 1716 // Remove the restriction. 1717 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction); 1718 1719 // Initialize DPMS again. The restriction shouldn't be enabled for a second time. 1720 initializeDpms(); 1721 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); 1722 assertNotNull(dpms.getDeviceOwnerAdminLocked()); 1723 assertNoDeviceOwnerRestrictions(); 1724 } finally { 1725 UserRestrictionsUtils 1726 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction); 1727 } 1728 } 1729 1730 private void assertNoDeviceOwnerRestrictions() { 1731 DpmTestUtils.assertRestrictions( 1732 DpmTestUtils.newRestrictions(), 1733 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions() 1734 ); 1735 DpmTestUtils.assertRestrictions( 1736 DpmTestUtils.newRestrictions(), 1737 dpm.getUserRestrictions(admin1) 1738 ); 1739 } 1740 1741 public void testGetMacAddress() throws Exception { 1742 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1743 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1744 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1745 1746 // In this test, change the caller user to "system". 1747 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1748 1749 // Make sure admin1 is installed on system user. 1750 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1751 1752 // Test 1. Caller doesn't have DO or DA. 1753 try { 1754 dpm.getWifiMacAddress(admin1); 1755 fail(); 1756 } catch (SecurityException e) { 1757 MoreAsserts.assertContainsRegex("No active admin", e.getMessage()); 1758 } 1759 1760 // DO needs to be an DA. 1761 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1762 assertTrue(dpm.isAdminActive(admin1)); 1763 1764 // Test 2. Caller has DA, but not DO. 1765 try { 1766 dpm.getWifiMacAddress(admin1); 1767 fail(); 1768 } catch (SecurityException e) { 1769 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1770 } 1771 1772 // Test 3. Caller has PO, but not DO. 1773 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1774 try { 1775 dpm.getWifiMacAddress(admin1); 1776 fail(); 1777 } catch (SecurityException e) { 1778 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage()); 1779 } 1780 1781 // Remove PO. 1782 dpm.clearProfileOwner(admin1); 1783 dpm.setActiveAdmin(admin1, false); 1784 // Test 4, Caller is DO now. 1785 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1786 1787 // 4-1. But no WifiInfo. 1788 assertNull(dpm.getWifiMacAddress(admin1)); 1789 1790 // 4-2. Returns WifiInfo, but with the default MAC. 1791 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); 1792 assertNull(dpm.getWifiMacAddress(admin1)); 1793 1794 // 4-3. With a real MAC address. 1795 final WifiInfo wi = new WifiInfo(); 1796 wi.setMacAddress("11:22:33:44:55:66"); 1797 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); 1798 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); 1799 } 1800 1801 public void testReboot() throws Exception { 1802 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1803 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1804 1805 // In this test, change the caller user to "system". 1806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1807 1808 // Make sure admin1 is installed on system user. 1809 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1810 1811 // Set admin1 as DA. 1812 dpm.setActiveAdmin(admin1, false); 1813 assertTrue(dpm.isAdminActive(admin1)); 1814 try { 1815 dpm.reboot(admin1); 1816 fail("DA calls DPM.reboot(), did not throw expected SecurityException"); 1817 } catch (SecurityException expected) { 1818 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1819 } 1820 1821 // Set admin1 as PO. 1822 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); 1823 try { 1824 dpm.reboot(admin1); 1825 fail("PO calls DPM.reboot(), did not throw expected SecurityException"); 1826 } catch (SecurityException expected) { 1827 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage()); 1828 } 1829 1830 // Remove PO and add DO. 1831 dpm.clearProfileOwner(admin1); 1832 dpm.setActiveAdmin(admin1, false); 1833 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 1834 1835 // admin1 is DO. 1836 // Set current call state of device to ringing. 1837 when(mContext.telephonyManager.getCallState()) 1838 .thenReturn(TelephonyManager.CALL_STATE_RINGING); 1839 try { 1840 dpm.reboot(admin1); 1841 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException"); 1842 } catch (IllegalStateException expected) { 1843 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1844 } 1845 1846 // Set current call state of device to dialing/active. 1847 when(mContext.telephonyManager.getCallState()) 1848 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); 1849 try { 1850 dpm.reboot(admin1); 1851 fail("DPM.reboot() called when dialing, should thrown IllegalStateException"); 1852 } catch (IllegalStateException expected) { 1853 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage()); 1854 } 1855 1856 // Set current call state of device to idle. 1857 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); 1858 dpm.reboot(admin1); 1859 } 1860 1861 public void testSetGetSupportText() { 1862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1863 dpm.setActiveAdmin(admin1, true); 1864 dpm.setActiveAdmin(admin2, true); 1865 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); 1866 1867 // Null default support messages. 1868 { 1869 assertNull(dpm.getLongSupportMessage(admin1)); 1870 assertNull(dpm.getShortSupportMessage(admin1)); 1871 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1872 assertNull(dpm.getShortSupportMessageForUser(admin1, 1873 DpmMockContext.CALLER_USER_HANDLE)); 1874 assertNull(dpm.getLongSupportMessageForUser(admin1, 1875 DpmMockContext.CALLER_USER_HANDLE)); 1876 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1877 } 1878 1879 // Only system can call the per user versions. 1880 { 1881 try { 1882 dpm.getShortSupportMessageForUser(admin1, 1883 DpmMockContext.CALLER_USER_HANDLE); 1884 fail("Only system should be able to call getXXXForUser versions"); 1885 } catch (SecurityException expected) { 1886 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1887 } 1888 try { 1889 dpm.getLongSupportMessageForUser(admin1, 1890 DpmMockContext.CALLER_USER_HANDLE); 1891 fail("Only system should be able to call getXXXForUser versions"); 1892 } catch (SecurityException expected) { 1893 MoreAsserts.assertContainsRegex("message for user", expected.getMessage()); 1894 } 1895 } 1896 1897 // Can't set message for admin in another uid. 1898 { 1899 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1; 1900 try { 1901 dpm.setShortSupportMessage(admin1, "Some text"); 1902 fail("Admins should only be able to change their own support text."); 1903 } catch (SecurityException expected) { 1904 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage()); 1905 } 1906 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1907 } 1908 1909 // Set/Get short returns what it sets and other admins text isn't changed. 1910 { 1911 final String supportText = "Some text to test with."; 1912 dpm.setShortSupportMessage(admin1, supportText); 1913 assertEquals(supportText, dpm.getShortSupportMessage(admin1)); 1914 assertNull(dpm.getLongSupportMessage(admin1)); 1915 assertNull(dpm.getShortSupportMessage(admin2)); 1916 1917 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1918 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, 1919 DpmMockContext.CALLER_USER_HANDLE)); 1920 assertNull(dpm.getShortSupportMessageForUser(admin2, 1921 DpmMockContext.CALLER_USER_HANDLE)); 1922 assertNull(dpm.getLongSupportMessageForUser(admin1, 1923 DpmMockContext.CALLER_USER_HANDLE)); 1924 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1925 1926 dpm.setShortSupportMessage(admin1, null); 1927 assertNull(dpm.getShortSupportMessage(admin1)); 1928 } 1929 1930 // Set/Get long returns what it sets and other admins text isn't changed. 1931 { 1932 final String supportText = "Some text to test with.\nWith more text."; 1933 dpm.setLongSupportMessage(admin1, supportText); 1934 assertEquals(supportText, dpm.getLongSupportMessage(admin1)); 1935 assertNull(dpm.getShortSupportMessage(admin1)); 1936 assertNull(dpm.getLongSupportMessage(admin2)); 1937 1938 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 1939 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, 1940 DpmMockContext.CALLER_USER_HANDLE)); 1941 assertNull(dpm.getLongSupportMessageForUser(admin2, 1942 DpmMockContext.CALLER_USER_HANDLE)); 1943 assertNull(dpm.getShortSupportMessageForUser(admin1, 1944 DpmMockContext.CALLER_USER_HANDLE)); 1945 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 1946 1947 dpm.setLongSupportMessage(admin1, null); 1948 assertNull(dpm.getLongSupportMessage(admin1)); 1949 } 1950 } 1951 1952 /** 1953 * Test for: 1954 * {@link DevicePolicyManager#setAffiliationIds} 1955 * {@link DevicePolicyManager#getAffiliationIds} 1956 * {@link DevicePolicyManager#isAffiliatedUser} 1957 */ 1958 public void testUserAffiliation() throws Exception { 1959 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); 1960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 1961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); 1962 1963 // Check that the system user is unaffiliated. 1964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1965 assertFalse(dpm.isAffiliatedUser()); 1966 1967 // Set a device owner on the system user. Check that the system user becomes affiliated. 1968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 1969 dpm.setActiveAdmin(admin1, /* replace =*/ false); 1970 assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); 1971 assertTrue(dpm.isAffiliatedUser()); 1972 assertTrue(dpm.getAffiliationIds(admin1).isEmpty()); 1973 1974 // Install a profile owner. Check that the test user is unaffiliated. 1975 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 1976 setAsProfileOwner(admin2); 1977 assertFalse(dpm.isAffiliatedUser()); 1978 assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); 1979 1980 // Have the profile owner specify a set of affiliation ids. Check that the test user remains 1981 // unaffiliated. 1982 final List<String> userAffiliationIds = new ArrayList<>(); 1983 userAffiliationIds.add("red"); 1984 userAffiliationIds.add("green"); 1985 userAffiliationIds.add("blue"); 1986 dpm.setAffiliationIds(admin2, userAffiliationIds); 1987 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue"); 1988 assertFalse(dpm.isAffiliatedUser()); 1989 1990 // Have the device owner specify a set of affiliation ids that do not intersect with those 1991 // specified by the profile owner. Check that the test user remains unaffiliated. 1992 final List<String> deviceAffiliationIds = new ArrayList<>(); 1993 deviceAffiliationIds.add("cyan"); 1994 deviceAffiliationIds.add("yellow"); 1995 deviceAffiliationIds.add("magenta"); 1996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 1997 dpm.setAffiliationIds(admin1, deviceAffiliationIds); 1998 MoreAsserts.assertContentsInAnyOrder( 1999 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta"); 2000 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2001 assertFalse(dpm.isAffiliatedUser()); 2002 2003 // Have the profile owner specify a set of affiliation ids that intersect with those 2004 // specified by the device owner. Check that the test user becomes affiliated. 2005 userAffiliationIds.add("yellow"); 2006 dpm.setAffiliationIds(admin2, userAffiliationIds); 2007 MoreAsserts.assertContentsInAnyOrder( 2008 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow"); 2009 assertTrue(dpm.isAffiliatedUser()); 2010 2011 // Clear affiliation ids for the profile owner. The user becomes unaffiliated. 2012 dpm.setAffiliationIds(admin2, Collections.emptyList()); 2013 assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); 2014 assertFalse(dpm.isAffiliatedUser()); 2015 2016 // Check that the system user remains affiliated. 2017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2018 assertTrue(dpm.isAffiliatedUser()); 2019 } 2020 2021 public void testGetUserProvisioningState_defaultResult() { 2022 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 2023 } 2024 2025 public void testSetUserProvisioningState_permission() throws Exception { 2026 setupProfileOwner(); 2027 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2028 2029 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2030 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2031 } 2032 2033 public void testSetUserProvisioningState_unprivileged() throws Exception { 2034 setupProfileOwner(); 2035 try { 2036 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 2037 DpmMockContext.CALLER_USER_HANDLE); 2038 fail("Expected SecurityException"); 2039 } catch (SecurityException expected) { 2040 } 2041 } 2042 2043 public void testSetUserProvisioningState_noManagement() { 2044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2045 try { 2046 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 2047 DpmMockContext.CALLER_USER_HANDLE); 2048 fail("IllegalStateException expected"); 2049 } catch (IllegalStateException e) { 2050 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set", 2051 e.getMessage()); 2052 } 2053 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 2054 } 2055 2056 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception { 2057 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2058 setupDeviceOwner(); 2059 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2060 2061 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 2062 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 2063 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2064 } 2065 2066 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative() 2067 throws Exception { 2068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2069 setupDeviceOwner(); 2070 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2071 2072 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 2073 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 2074 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2075 } 2076 2077 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception { 2078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2079 setupDeviceOwner(); 2080 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2081 2082 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM, 2083 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2084 } 2085 2086 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser() 2087 throws Exception { 2088 setupProfileOwner(); 2089 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2090 2091 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2092 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE, 2093 DevicePolicyManager.STATE_USER_UNMANAGED); 2094 } 2095 2096 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile() 2097 throws Exception { 2098 setupProfileOwner(); 2099 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2100 2101 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2102 DevicePolicyManager.STATE_USER_SETUP_COMPLETE, 2103 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2104 } 2105 2106 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception { 2107 setupProfileOwner(); 2108 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2109 2110 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2111 DevicePolicyManager.STATE_USER_SETUP_FINALIZED); 2112 } 2113 2114 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception { 2115 setupProfileOwner(); 2116 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2117 2118 try { 2119 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2120 DevicePolicyManager.STATE_USER_SETUP_FINALIZED, 2121 DevicePolicyManager.STATE_USER_UNMANAGED); 2122 fail("Expected IllegalStateException"); 2123 } catch (IllegalStateException e) { 2124 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 2125 e.getMessage()); 2126 } 2127 } 2128 2129 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState() 2130 throws Exception { 2131 setupProfileOwner(); 2132 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2133 2134 try { 2135 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE, 2136 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE, 2137 DevicePolicyManager.STATE_USER_SETUP_COMPLETE); 2138 fail("Expected IllegalStateException"); 2139 } catch (IllegalStateException e) { 2140 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state", 2141 e.getMessage()); 2142 } 2143 } 2144 2145 private void exerciseUserProvisioningTransitions(int userId, int... states) { 2146 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); 2147 for (int state : states) { 2148 dpm.setUserProvisioningState(state, userId); 2149 assertEquals(state, dpm.getUserProvisioningState()); 2150 } 2151 } 2152 2153 private void setupProfileOwner() throws Exception { 2154 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2155 2156 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); 2157 dpm.setActiveAdmin(admin1, false); 2158 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE)); 2159 2160 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2161 } 2162 2163 private void setupDeviceOwner() throws Exception { 2164 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 2165 2166 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); 2167 dpm.setActiveAdmin(admin1, false); 2168 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); 2169 2170 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 2171 } 2172 2173 public void testSetMaximumTimeToLock() { 2174 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); 2175 2176 dpm.setActiveAdmin(admin1, /* replace =*/ false); 2177 dpm.setActiveAdmin(admin2, /* replace =*/ false); 2178 2179 reset(mMockContext.powerManagerInternal); 2180 reset(mMockContext.settings); 2181 2182 dpm.setMaximumTimeToLock(admin1, 0); 2183 verifyScreenTimeoutCall(null, false); 2184 reset(mMockContext.powerManagerInternal); 2185 reset(mMockContext.settings); 2186 2187 dpm.setMaximumTimeToLock(admin1, 1); 2188 verifyScreenTimeoutCall(1, true); 2189 reset(mMockContext.powerManagerInternal); 2190 reset(mMockContext.settings); 2191 2192 dpm.setMaximumTimeToLock(admin2, 10); 2193 verifyScreenTimeoutCall(null, false); 2194 reset(mMockContext.powerManagerInternal); 2195 reset(mMockContext.settings); 2196 2197 dpm.setMaximumTimeToLock(admin1, 5); 2198 verifyScreenTimeoutCall(5, true); 2199 reset(mMockContext.powerManagerInternal); 2200 reset(mMockContext.settings); 2201 2202 dpm.setMaximumTimeToLock(admin2, 4); 2203 verifyScreenTimeoutCall(4, true); 2204 reset(mMockContext.powerManagerInternal); 2205 reset(mMockContext.settings); 2206 2207 dpm.setMaximumTimeToLock(admin1, 0); 2208 reset(mMockContext.powerManagerInternal); 2209 reset(mMockContext.settings); 2210 2211 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE); 2212 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 2213 reset(mMockContext.powerManagerInternal); 2214 reset(mMockContext.settings); 2215 2216 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1); 2217 verifyScreenTimeoutCall(Integer.MAX_VALUE, true); 2218 reset(mMockContext.powerManagerInternal); 2219 reset(mMockContext.settings); 2220 2221 dpm.setMaximumTimeToLock(admin2, 10); 2222 verifyScreenTimeoutCall(10, true); 2223 reset(mMockContext.powerManagerInternal); 2224 reset(mMockContext.settings); 2225 2226 // There's no restriction; shold be set to MAX. 2227 dpm.setMaximumTimeToLock(admin2, 0); 2228 verifyScreenTimeoutCall(Integer.MAX_VALUE, false); 2229 } 2230 2231 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception { 2232 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2233 setupDeviceOwner(); 2234 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2235 2236 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 2237 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1); 2238 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE; 2239 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS 2240 - ONE_MINUTE; 2241 2242 // verify that the minimum timeout cannot be modified on user builds (system property is 2243 // not being read) 2244 mContext.buildMock.isDebuggable = false; 2245 2246 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE); 2247 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE); 2248 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE); 2249 2250 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong()); 2251 2252 // restore to the debuggable build state 2253 mContext.buildMock.isDebuggable = true; 2254 2255 // Always return the default (second arg) when getting system property for long type 2256 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer( 2257 new Answer<Long>() { 2258 @Override 2259 public Long answer(InvocationOnMock invocation) throws Throwable { 2260 return (Long) invocation.getArguments()[1]; 2261 } 2262 } 2263 ); 2264 2265 // reset to default (0 means the admin is not participating, so default should be returned) 2266 dpm.setRequiredStrongAuthTimeout(admin1, 0); 2267 2268 // aggregation should be the default if unset by any admin 2269 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2270 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2271 2272 // admin not participating by default 2273 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2274 2275 //clamping from the top 2276 dpm.setRequiredStrongAuthTimeout(admin1, 2277 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE); 2278 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 2279 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2280 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2281 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2282 2283 // 0 means the admin is not participating, so default should be returned 2284 dpm.setRequiredStrongAuthTimeout(admin1, 0); 2285 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2286 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2287 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2288 2289 // clamping from the bottom 2290 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE); 2291 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS); 2292 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS); 2293 2294 // values within range 2295 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE); 2296 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE); 2297 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE); 2298 2299 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE); 2300 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE); 2301 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE); 2302 2303 // reset to default 2304 dpm.setRequiredStrongAuthTimeout(admin1, 0); 2305 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); 2306 assertEquals(dpm.getRequiredStrongAuthTimeout(null), 2307 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); 2308 2309 // negative value 2310 try { 2311 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE); 2312 fail("Didn't throw IllegalArgumentException"); 2313 } catch (IllegalArgumentException iae) { 2314 } 2315 } 2316 2317 private void verifyScreenTimeoutCall(Integer expectedTimeout, 2318 boolean shouldStayOnWhilePluggedInBeCleared) { 2319 if (expectedTimeout == null) { 2320 verify(mMockContext.powerManagerInternal, times(0)) 2321 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt()); 2322 } else { 2323 verify(mMockContext.powerManagerInternal, times(1)) 2324 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout)); 2325 } 2326 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw 2327 // UnfinishedVerificationException. 2328 } 2329 2330 private void setup_DeviceAdminFeatureOff() throws Exception { 2331 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) 2332 .thenReturn(false); 2333 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2334 .thenReturn(false); 2335 initializeDpms(); 2336 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2337 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2338 .thenReturn(true); 2339 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2340 2341 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2342 } 2343 2344 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception { 2345 setup_DeviceAdminFeatureOff(); 2346 mContext.packageName = admin1.getPackageName(); 2347 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2348 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 2349 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2350 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2351 false); 2352 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2353 } 2354 2355 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception { 2356 setup_DeviceAdminFeatureOff(); 2357 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2358 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2359 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2360 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2361 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2362 assertCheckProvisioningPreCondition( 2363 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2364 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2365 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2366 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED); 2367 } 2368 2369 private void setup_ManagedProfileFeatureOff() throws Exception { 2370 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2371 .thenReturn(false); 2372 initializeDpms(); 2373 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2374 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2375 .thenReturn(true); 2376 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2377 2378 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2379 } 2380 2381 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { 2382 setup_ManagedProfileFeatureOff(); 2383 mContext.packageName = admin1.getPackageName(); 2384 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2388 false); 2389 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2390 2391 // Test again when split user is on 2392 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2393 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2394 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2396 true); 2397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); 2398 } 2399 2400 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception { 2401 setup_ManagedProfileFeatureOff(); 2402 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2403 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2404 DevicePolicyManager.CODE_OK); 2405 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2406 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2407 assertCheckProvisioningPreCondition( 2408 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2409 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2410 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2411 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2412 2413 // Test again when split user is on 2414 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2415 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2416 DevicePolicyManager.CODE_OK); 2417 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2418 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2419 assertCheckProvisioningPreCondition( 2420 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2421 DevicePolicyManager.CODE_OK); 2422 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2423 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); 2424 } 2425 2426 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception { 2427 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2428 .thenReturn(true); 2429 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2430 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2431 .thenReturn(true); 2432 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2433 2434 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2435 } 2436 2437 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { 2438 setup_nonSplitUser_firstBoot_primaryUser(); 2439 mContext.packageName = admin1.getPackageName(); 2440 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2441 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2444 false /* because of non-split user */); 2445 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2446 false /* because of non-split user */); 2447 } 2448 2449 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser() 2450 throws Exception { 2451 setup_nonSplitUser_firstBoot_primaryUser(); 2452 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2453 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2454 DevicePolicyManager.CODE_OK); 2455 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2456 DevicePolicyManager.CODE_OK); 2457 assertCheckProvisioningPreCondition( 2458 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2459 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2460 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2461 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2462 } 2463 2464 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { 2465 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2466 .thenReturn(true); 2467 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); 2468 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2469 .thenReturn(true); 2470 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2471 2472 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2473 } 2474 2475 private void setup_nonSplitUser_withDo_primaryUser() throws Exception { 2476 setDeviceOwner(); 2477 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2478 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2); 2479 } 2480 2481 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception { 2482 setup_nonSplitUser_withDo_primaryUser(); 2483 final int MANAGED_PROFILE_USER_ID = 18; 2484 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308); 2485 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 2486 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, 2487 false /* we can't remove a managed profile */)).thenReturn(false); 2488 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, 2489 true)).thenReturn(true); 2490 } 2491 2492 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() 2493 throws Exception { 2494 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2495 mContext.packageName = admin1.getPackageName(); 2496 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2497 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2498 false/* because of completed device setup */); 2499 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2500 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2501 false/* because of non-split user */); 2502 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2503 false/* because of non-split user */); 2504 } 2505 2506 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser() 2507 throws Exception { 2508 setup_nonSplitUser_afterDeviceSetup_primaryUser(); 2509 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2510 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2511 DevicePolicyManager.CODE_USER_SETUP_COMPLETED); 2512 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2513 DevicePolicyManager.CODE_OK); 2514 assertCheckProvisioningPreCondition( 2515 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2516 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2517 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2518 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); 2519 } 2520 2521 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception { 2522 setup_nonSplitUser_withDo_primaryUser(); 2523 mContext.packageName = admin1.getPackageName(); 2524 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2525 2526 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2527 DevicePolicyManager.CODE_HAS_DEVICE_OWNER); 2528 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false); 2529 2530 // COMP mode is allowed. 2531 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2532 DevicePolicyManager.CODE_OK); 2533 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2534 2535 // And other DPCs can also provision a managed profile (DO + BYOD case). 2536 assertCheckProvisioningPreCondition( 2537 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2538 DpmMockContext.ANOTHER_PACKAGE_NAME, 2539 DevicePolicyManager.CODE_OK); 2540 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true, 2541 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); 2542 } 2543 2544 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception { 2545 setup_nonSplitUser_withDo_primaryUser(); 2546 mContext.packageName = admin1.getPackageName(); 2547 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2548 // The DO should be allowed to initiate provisioning if it set the restriction itself, but 2549 // other packages should be forbidden. 2550 when(mContext.userManager.hasUserRestriction( 2551 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2552 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2553 .thenReturn(true); 2554 when(mContext.userManager.getUserRestrictionSource( 2555 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2556 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2557 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); 2558 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2559 DevicePolicyManager.CODE_OK); 2560 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2561 assertCheckProvisioningPreCondition( 2562 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2563 DpmMockContext.ANOTHER_PACKAGE_NAME, 2564 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2565 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false, 2566 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); 2567 } 2568 2569 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem() 2570 throws Exception { 2571 setup_nonSplitUser_withDo_primaryUser(); 2572 mContext.packageName = admin1.getPackageName(); 2573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2574 // The DO should not be allowed to initiate provisioning if the restriction is set by 2575 // another entity. 2576 when(mContext.userManager.hasUserRestriction( 2577 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2578 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2579 .thenReturn(true); 2580 when(mContext.userManager.getUserRestrictionSource( 2581 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), 2582 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) 2583 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); 2584 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2585 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2587 2588 assertCheckProvisioningPreCondition( 2589 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2590 DpmMockContext.ANOTHER_PACKAGE_NAME, 2591 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED); 2592 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false, 2593 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); 2594 } 2595 2596 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception { 2597 setup_nonSplitUser_withDo_primaryUser_ManagedProfile(); 2598 mContext.packageName = admin1.getPackageName(); 2599 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2600 2601 // We can delete the managed profile to create a new one, so provisioning is allowed. 2602 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2603 DevicePolicyManager.CODE_OK); 2604 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2605 assertCheckProvisioningPreCondition( 2606 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2607 DpmMockContext.ANOTHER_PACKAGE_NAME, 2608 DevicePolicyManager.CODE_OK); 2609 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true, 2610 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); 2611 } 2612 2613 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile() 2614 throws Exception { 2615 setup_nonSplitUser_withDo_primaryUser_ManagedProfile(); 2616 mContext.packageName = admin1.getPackageName(); 2617 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2618 when(mContext.userManager.hasUserRestriction( 2619 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), 2620 eq(UserHandle.SYSTEM))) 2621 .thenReturn(true); 2622 when(mContext.userManager.getUserRestrictionSource( 2623 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), 2624 eq(UserHandle.SYSTEM))) 2625 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); 2626 2627 // We can't remove the profile to create a new one. 2628 assertCheckProvisioningPreCondition( 2629 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2630 DpmMockContext.ANOTHER_PACKAGE_NAME, 2631 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE); 2632 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false, 2633 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); 2634 2635 // But the device owner can still do it because it has set the restriction itself. 2636 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2637 DevicePolicyManager.CODE_OK); 2638 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2639 } 2640 2641 private void setup_splitUser_firstBoot_systemUser() throws Exception { 2642 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2643 .thenReturn(true); 2644 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2645 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2646 .thenReturn(false); 2647 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); 2648 2649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2650 } 2651 2652 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { 2653 setup_splitUser_firstBoot_systemUser(); 2654 mContext.packageName = admin1.getPackageName(); 2655 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2656 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2658 false /* because canAddMoreManagedProfiles returns false */); 2659 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2660 true); 2661 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2662 false/* because calling uid is system user */); 2663 } 2664 2665 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser() 2666 throws Exception { 2667 setup_splitUser_firstBoot_systemUser(); 2668 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2669 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2670 DevicePolicyManager.CODE_OK); 2671 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2672 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2673 assertCheckProvisioningPreCondition( 2674 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2675 DevicePolicyManager.CODE_OK); 2676 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2677 DevicePolicyManager.CODE_SYSTEM_USER); 2678 } 2679 2680 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception { 2681 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2682 .thenReturn(true); 2683 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2684 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2685 .thenReturn(false); 2686 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2687 2688 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2689 } 2690 2691 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { 2692 setup_splitUser_afterDeviceSetup_systemUser(); 2693 mContext.packageName = admin1.getPackageName(); 2694 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2695 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2696 true/* it's undefined behavior. Can be changed into false in the future */); 2697 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2698 false /* because canAddMoreManagedProfiles returns false */); 2699 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2700 true/* it's undefined behavior. Can be changed into false in the future */); 2701 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2702 false/* because calling uid is system user */); 2703 } 2704 2705 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser() 2706 throws Exception { 2707 setup_splitUser_afterDeviceSetup_systemUser(); 2708 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2709 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2710 DevicePolicyManager.CODE_OK); 2711 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2712 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2713 assertCheckProvisioningPreCondition( 2714 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2715 DevicePolicyManager.CODE_OK); 2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2717 DevicePolicyManager.CODE_SYSTEM_USER); 2718 } 2719 2720 private void setup_splitUser_firstBoot_primaryUser() throws Exception { 2721 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2722 .thenReturn(true); 2723 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2724 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2725 true)).thenReturn(true); 2726 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2727 2728 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2729 } 2730 2731 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { 2732 setup_splitUser_firstBoot_primaryUser(); 2733 mContext.packageName = admin1.getPackageName(); 2734 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2735 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); 2736 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2738 true); 2739 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); 2740 } 2741 2742 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser() 2743 throws Exception { 2744 setup_splitUser_firstBoot_primaryUser(); 2745 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2746 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2747 DevicePolicyManager.CODE_OK); 2748 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2749 DevicePolicyManager.CODE_OK); 2750 assertCheckProvisioningPreCondition( 2751 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2752 DevicePolicyManager.CODE_OK); 2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2754 DevicePolicyManager.CODE_OK); 2755 } 2756 2757 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception { 2758 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2759 .thenReturn(true); 2760 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2761 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2762 true)).thenReturn(true); 2763 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); 2764 2765 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2766 } 2767 2768 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() 2769 throws Exception { 2770 setup_splitUser_afterDeviceSetup_primaryUser(); 2771 mContext.packageName = admin1.getPackageName(); 2772 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2773 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2774 true/* it's undefined behavior. Can be changed into false in the future */); 2775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2777 true/* it's undefined behavior. Can be changed into false in the future */); 2778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2779 false/* because user setup completed */); 2780 } 2781 2782 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser() 2783 throws Exception { 2784 setup_splitUser_afterDeviceSetup_primaryUser(); 2785 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2786 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, 2787 DevicePolicyManager.CODE_OK); 2788 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2789 DevicePolicyManager.CODE_OK); 2790 assertCheckProvisioningPreCondition( 2791 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, 2792 DevicePolicyManager.CODE_OK); 2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, 2794 DevicePolicyManager.CODE_USER_SETUP_COMPLETED); 2795 } 2796 2797 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { 2798 setDeviceOwner(); 2799 2800 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2801 .thenReturn(true); 2802 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2803 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) 2804 .thenReturn(false); 2805 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); 2806 2807 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2808 } 2809 2810 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() 2811 throws Exception { 2812 setup_provisionManagedProfileWithDeviceOwner_systemUser(); 2813 mContext.packageName = admin1.getPackageName(); 2814 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2815 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2816 false /* can't provision managed profile on system user */); 2817 } 2818 2819 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser() 2820 throws Exception { 2821 setup_provisionManagedProfileWithDeviceOwner_systemUser(); 2822 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2823 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2824 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER); 2825 } 2826 2827 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { 2828 setDeviceOwner(); 2829 2830 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2831 .thenReturn(true); 2832 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2833 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2834 true)).thenReturn(true); 2835 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2836 2837 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2838 } 2839 2840 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() 2841 throws Exception { 2842 setup_provisionManagedProfileWithDeviceOwner_primaryUser(); 2843 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2844 mContext.packageName = admin1.getPackageName(); 2845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true); 2846 } 2847 2848 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser() 2849 throws Exception { 2850 setup_provisionManagedProfileWithDeviceOwner_primaryUser(); 2851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2852 2853 // COMP mode is allowed. 2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2855 DevicePolicyManager.CODE_OK); 2856 } 2857 2858 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { 2859 setDeviceOwner(); 2860 2861 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) 2862 .thenReturn(true); 2863 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); 2864 when(mContext.userManager.hasUserRestriction( 2865 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), 2866 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))) 2867 .thenReturn(true); 2868 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2869 false /* we can't remove a managed profile */)).thenReturn(false); 2870 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, 2871 true)).thenReturn(true); 2872 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); 2873 2874 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2875 } 2876 2877 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser() 2878 throws Exception { 2879 setup_provisionManagedProfileCantRemoveUser_primaryUser(); 2880 mContext.packageName = admin1.getPackageName(); 2881 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid); 2882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); 2883 } 2884 2885 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser() 2886 throws Exception { 2887 setup_provisionManagedProfileCantRemoveUser_primaryUser(); 2888 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2889 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, 2890 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE); 2891 } 2892 2893 public void testCheckProvisioningPreCondition_permission() { 2894 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2895 try { 2896 dpm.checkProvisioningPreCondition( 2897 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"); 2898 fail("Didn't throw SecurityException"); 2899 } catch (SecurityException expected) { 2900 } 2901 } 2902 2903 public void testForceUpdateUserSetupComplete_permission() { 2904 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted 2905 try { 2906 dpm.forceUpdateUserSetupComplete(); 2907 fail("Didn't throw SecurityException"); 2908 } catch (SecurityException expected) { 2909 } 2910 } 2911 2912 public void testForceUpdateUserSetupComplete_systemUser() { 2913 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2914 // GIVEN calling from user 20 2915 mContext.binder.callingUid = DpmMockContext.CALLER_UID; 2916 try { 2917 dpm.forceUpdateUserSetupComplete(); 2918 fail("Didn't throw SecurityException"); 2919 } catch (SecurityException expected) { 2920 } 2921 } 2922 2923 public void testForceUpdateUserSetupComplete_userbuild() { 2924 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2925 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2926 2927 final int userId = UserHandle.USER_SYSTEM; 2928 // GIVEN userComplete is false in SettingsProvider 2929 setUserSetupCompleteForUser(false, userId); 2930 2931 // GIVEN userComplete is true in DPM 2932 DevicePolicyManagerService.DevicePolicyData userData = 2933 new DevicePolicyManagerService.DevicePolicyData(userId); 2934 userData.mUserSetupComplete = true; 2935 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2936 2937 // GIVEN it's user build 2938 mContext.buildMock.isDebuggable = false; 2939 2940 assertTrue(dpms.hasUserSetupCompleted()); 2941 2942 dpm.forceUpdateUserSetupComplete(); 2943 2944 // THEN the state in dpms is not changed 2945 assertTrue(dpms.hasUserSetupCompleted()); 2946 } 2947 2948 public void testForceUpdateUserSetupComplete_userDebugbuild() { 2949 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); 2950 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2951 2952 final int userId = UserHandle.USER_SYSTEM; 2953 // GIVEN userComplete is false in SettingsProvider 2954 setUserSetupCompleteForUser(false, userId); 2955 2956 // GIVEN userComplete is true in DPM 2957 DevicePolicyManagerService.DevicePolicyData userData = 2958 new DevicePolicyManagerService.DevicePolicyData(userId); 2959 userData.mUserSetupComplete = true; 2960 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); 2961 2962 // GIVEN it's userdebug build 2963 mContext.buildMock.isDebuggable = true; 2964 2965 assertTrue(dpms.hasUserSetupCompleted()); 2966 2967 dpm.forceUpdateUserSetupComplete(); 2968 2969 // THEN the state in dpms is not changed 2970 assertFalse(dpms.hasUserSetupCompleted()); 2971 } 2972 2973 private void clearDeviceOwner() throws Exception { 2974 final long ident = mContext.binder.clearCallingIdentity(); 2975 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2976 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager) 2977 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt()); 2978 dpm.clearDeviceOwnerApp(admin1.getPackageName()); 2979 mContext.binder.restoreCallingIdentity(ident); 2980 } 2981 2982 public void testGetLastSecurityLogRetrievalTime() throws Exception { 2983 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 2984 setupDeviceOwner(); 2985 2986 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the 2987 // feature is disabled because there are non-affiliated secondary users. 2988 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); 2989 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs)) 2990 .thenReturn(true); 2991 2992 // No logs were retrieved so far. 2993 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 2994 2995 // Enabling logging should not change the timestamp. 2996 dpm.setSecurityLoggingEnabled(admin1, true); 2997 verify(mContext.settings) 2998 .securityLogSetLoggingEnabledProperty(true); 2999 when(mContext.settings.securityLogGetLoggingEnabledProperty()) 3000 .thenReturn(true); 3001 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 3002 3003 // Retrieving the logs should update the timestamp. 3004 final long beforeRetrieval = System.currentTimeMillis(); 3005 dpm.retrieveSecurityLogs(admin1); 3006 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 3007 final long afterRetrieval = System.currentTimeMillis(); 3008 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval); 3009 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval); 3010 3011 // Retrieving the pre-boot logs should update the timestamp. 3012 Thread.sleep(2); 3013 dpm.retrievePreRebootSecurityLogs(admin1); 3014 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 3015 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime); 3016 3017 // Checking the timestamp again should not change it. 3018 Thread.sleep(2); 3019 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 3020 3021 // Retrieving the logs again should update the timestamp. 3022 dpm.retrieveSecurityLogs(admin1); 3023 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); 3024 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime); 3025 3026 // Disabling logging should not change the timestamp. 3027 Thread.sleep(2); 3028 dpm.setSecurityLoggingEnabled(admin1, false); 3029 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 3030 3031 // Restarting the DPMS should not lose the timestamp. 3032 initializeDpms(); 3033 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 3034 3035 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 3036 mContext.binder.callingUid = 1234567; 3037 mContext.callerPermissions.add(permission.MANAGE_USERS); 3038 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 3039 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3040 3041 // System can retrieve the timestamp. 3042 mContext.binder.clearCallingIdentity(); 3043 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); 3044 3045 // Removing the device owner should clear the timestamp. 3046 clearDeviceOwner(); 3047 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); 3048 } 3049 3050 public void testGetLastBugReportRequestTime() throws Exception { 3051 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3052 setupDeviceOwner(); 3053 3054 mContext.packageName = admin1.getPackageName(); 3055 mContext.applicationInfo = new ApplicationInfo(); 3056 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject())) 3057 .thenReturn(Color.WHITE); 3058 when(mContext.resources.getColor(eq(R.color.notification_material_background_color), 3059 anyObject())).thenReturn(Color.WHITE); 3060 3061 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the 3062 // feature is disabled because there are non-affiliated secondary users. 3063 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); 3064 3065 // No bug reports were requested so far. 3066 assertEquals(-1, dpm.getLastBugReportRequestTime()); 3067 3068 // Requesting a bug report should update the timestamp. 3069 final long beforeRequest = System.currentTimeMillis(); 3070 dpm.requestBugreport(admin1); 3071 final long bugReportRequestTime = dpm.getLastBugReportRequestTime(); 3072 final long afterRequest = System.currentTimeMillis(); 3073 assertTrue(bugReportRequestTime >= beforeRequest); 3074 assertTrue(bugReportRequestTime <= afterRequest); 3075 3076 // Checking the timestamp again should not change it. 3077 Thread.sleep(2); 3078 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 3079 3080 // Restarting the DPMS should not lose the timestamp. 3081 initializeDpms(); 3082 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 3083 3084 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 3085 mContext.binder.callingUid = 1234567; 3086 mContext.callerPermissions.add(permission.MANAGE_USERS); 3087 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 3088 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3089 3090 // System can retrieve the timestamp. 3091 mContext.binder.clearCallingIdentity(); 3092 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); 3093 3094 // Removing the device owner should clear the timestamp. 3095 clearDeviceOwner(); 3096 assertEquals(-1, dpm.getLastBugReportRequestTime()); 3097 } 3098 3099 public void testGetLastNetworkLogRetrievalTime() throws Exception { 3100 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3101 setupDeviceOwner(); 3102 mContext.packageName = admin1.getPackageName(); 3103 mContext.applicationInfo = new ApplicationInfo(); 3104 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject())) 3105 .thenReturn(Color.WHITE); 3106 when(mContext.resources.getColor(eq(R.color.notification_material_background_color), 3107 anyObject())).thenReturn(Color.WHITE); 3108 3109 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the 3110 // feature is disabled because there are non-affiliated secondary users. 3111 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); 3112 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject())) 3113 .thenReturn(true); 3114 3115 // No logs were retrieved so far. 3116 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 3117 3118 // Attempting to retrieve logs without enabling logging should not change the timestamp. 3119 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 3120 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 3121 3122 // Enabling logging should not change the timestamp. 3123 dpm.setNetworkLoggingEnabled(admin1, true); 3124 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 3125 3126 // Retrieving the logs should update the timestamp. 3127 final long beforeRetrieval = System.currentTimeMillis(); 3128 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 3129 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 3130 final long afterRetrieval = System.currentTimeMillis(); 3131 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval); 3132 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval); 3133 3134 // Checking the timestamp again should not change it. 3135 Thread.sleep(2); 3136 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 3137 3138 // Retrieving the logs again should update the timestamp. 3139 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); 3140 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); 3141 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime); 3142 3143 // Disabling logging should not change the timestamp. 3144 Thread.sleep(2); 3145 dpm.setNetworkLoggingEnabled(admin1, false); 3146 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 3147 3148 // Restarting the DPMS should not lose the timestamp. 3149 initializeDpms(); 3150 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 3151 3152 // Any uid holding MANAGE_USERS permission can retrieve the timestamp. 3153 mContext.binder.callingUid = 1234567; 3154 mContext.callerPermissions.add(permission.MANAGE_USERS); 3155 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 3156 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3157 3158 // System can retrieve the timestamp. 3159 mContext.binder.clearCallingIdentity(); 3160 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); 3161 3162 // Removing the device owner should clear the timestamp. 3163 clearDeviceOwner(); 3164 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); 3165 } 3166 3167 public void testGetBindDeviceAdminTargetUsers() throws Exception { 3168 // Setup device owner. 3169 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3170 setupDeviceOwner(); 3171 3172 // Only device owner is setup, the result list should be empty. 3173 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3174 MoreAsserts.assertEmpty(targetUsers); 3175 3176 // Setup a managed profile managed by the same admin. 3177 final int MANAGED_PROFILE_USER_ID = 15; 3178 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 3179 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 3180 3181 // Add a secondary user, it should never talk with. 3182 final int ANOTHER_USER_ID = 36; 3183 mContext.addUser(ANOTHER_USER_ID, 0); 3184 3185 // Since the managed profile is not affiliated, they should not be allowed to talk to each 3186 // other. 3187 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3188 MoreAsserts.assertEmpty(targetUsers); 3189 3190 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3191 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3192 MoreAsserts.assertEmpty(targetUsers); 3193 3194 // Setting affiliation ids 3195 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id"); 3196 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3197 dpm.setAffiliationIds(admin1, userAffiliationIds); 3198 3199 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3200 dpm.setAffiliationIds(admin1, userAffiliationIds); 3201 3202 // Calling from device owner admin, the result list should just contain the managed 3203 // profile user id. 3204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3205 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3206 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID)); 3207 3208 // Calling from managed profile admin, the result list should just contain the system 3209 // user id. 3210 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3211 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3212 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM); 3213 3214 // Changing affiliation ids in one 3215 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id")); 3216 3217 // Since the managed profile is not affiliated any more, they should not be allowed to talk 3218 // to each other. 3219 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3220 MoreAsserts.assertEmpty(targetUsers); 3221 3222 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3223 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3224 MoreAsserts.assertEmpty(targetUsers); 3225 } 3226 3227 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception { 3228 // Setup a device owner. 3229 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3230 setupDeviceOwner(); 3231 3232 // Set up a managed profile managed by different package. 3233 final int MANAGED_PROFILE_USER_ID = 15; 3234 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456); 3235 final ComponentName adminDifferentPackage = 3236 new ComponentName("another.package", "whatever.class"); 3237 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2); 3238 3239 // Setting affiliation ids 3240 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id"); 3241 dpm.setAffiliationIds(admin1, userAffiliationIds); 3242 3243 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3244 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds); 3245 3246 // Calling from device owner admin, we should get zero bind device admin target users as 3247 // their packages are different. 3248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3249 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1); 3250 MoreAsserts.assertEmpty(targetUsers); 3251 3252 // Calling from managed profile admin, we should still get zero target users for the same 3253 // reason. 3254 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3255 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage); 3256 MoreAsserts.assertEmpty(targetUsers); 3257 } 3258 3259 public void testIsDeviceManaged() throws Exception { 3260 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3261 setupDeviceOwner(); 3262 3263 // The device owner itself, any uid holding MANAGE_USERS permission and the system can 3264 // find out that the device has a device owner. 3265 assertTrue(dpm.isDeviceManaged()); 3266 mContext.binder.callingUid = 1234567; 3267 mContext.callerPermissions.add(permission.MANAGE_USERS); 3268 assertTrue(dpm.isDeviceManaged()); 3269 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3270 mContext.binder.clearCallingIdentity(); 3271 assertTrue(dpm.isDeviceManaged()); 3272 3273 clearDeviceOwner(); 3274 3275 // Any uid holding MANAGE_USERS permission and the system can find out that the device does 3276 // not have a device owner. 3277 mContext.binder.callingUid = 1234567; 3278 mContext.callerPermissions.add(permission.MANAGE_USERS); 3279 assertFalse(dpm.isDeviceManaged()); 3280 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3281 mContext.binder.clearCallingIdentity(); 3282 assertFalse(dpm.isDeviceManaged()); 3283 } 3284 3285 public void testDeviceOwnerOrganizationName() throws Exception { 3286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; 3287 setupDeviceOwner(); 3288 3289 dpm.setOrganizationName(admin1, "organization"); 3290 3291 // Device owner can retrieve organization managing the device. 3292 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3293 3294 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device. 3295 mContext.binder.callingUid = 1234567; 3296 mContext.callerPermissions.add(permission.MANAGE_USERS); 3297 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3298 mContext.callerPermissions.remove(permission.MANAGE_USERS); 3299 3300 // System can retrieve organization managing the device. 3301 mContext.binder.clearCallingIdentity(); 3302 assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); 3303 3304 // Removing the device owner clears the organization managing the device. 3305 clearDeviceOwner(); 3306 assertNull(dpm.getDeviceOwnerOrganizationName()); 3307 } 3308 3309 public void testWipeDataManagedProfile() throws Exception { 3310 final int MANAGED_PROFILE_USER_ID = 15; 3311 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436); 3312 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 3313 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3314 3315 // Even if the caller is the managed profile, the current user is the user 0 3316 when(mContext.iactivityManager.getCurrentUser()) 3317 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); 3318 3319 dpm.wipeData(0); 3320 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed( 3321 MANAGED_PROFILE_USER_ID); 3322 } 3323 3324 public void testWipeDataManagedProfileDisallowed() throws Exception { 3325 final int MANAGED_PROFILE_USER_ID = 15; 3326 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436); 3327 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); 3328 3329 // Even if the caller is the managed profile, the current user is the user 0 3330 when(mContext.iactivityManager.getCurrentUser()) 3331 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); 3332 3333 when(mContext.userManager.getUserRestrictionSource( 3334 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 3335 UserHandle.of(MANAGED_PROFILE_USER_ID))) 3336 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); 3337 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; 3338 try { 3339 // The PO is not allowed to remove the profile if the user restriction was set on the 3340 // profile by the system 3341 dpm.wipeData(0); 3342 fail("SecurityException not thrown"); 3343 } catch (SecurityException expected) { 3344 } 3345 } 3346 3347 public void testGetPermissionGrantState() throws Exception { 3348 final String permission = "some.permission"; 3349 final String app1 = "com.example.app1"; 3350 final String app2 = "com.example.app2"; 3351 3352 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt())) 3353 .thenReturn(PackageManager.PERMISSION_GRANTED); 3354 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager) 3355 .getPermissionFlags(permission, app1, UserHandle.SYSTEM); 3356 when(mContext.packageManager.getPermissionFlags(permission, app1, 3357 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))) 3358 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED); 3359 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt())) 3360 .thenReturn(PackageManager.PERMISSION_DENIED); 3361 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2, 3362 UserHandle.SYSTEM); 3363 when(mContext.packageManager.getPermissionFlags(permission, app2, 3364 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0); 3365 3366 // System can retrieve permission grant state. 3367 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; 3368 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED, 3369 dpm.getPermissionGrantState(null, app1, permission)); 3370 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT, 3371 dpm.getPermissionGrantState(null, app2, permission)); 3372 3373 // A regular app cannot retrieve permission grant state. 3374 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; 3375 try { 3376 dpm.getPermissionGrantState(null, app1, permission); 3377 fail("Didn't throw IllegalStateException"); 3378 } catch (IllegalStateException expected) { 3379 } 3380 3381 // Profile owner can retrieve permission grant state. 3382 setAsProfileOwner(admin1); 3383 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED, 3384 dpm.getPermissionGrantState(admin1, app1, permission)); 3385 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT, 3386 dpm.getPermissionGrantState(admin1, app2, permission)); 3387 } 3388 3389 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { 3390 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 3391 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); 3392 dpms.notifyChangeToContentObserver( 3393 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); 3394 } 3395 3396 private void assertProvisioningAllowed(String action, boolean expected) { 3397 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, 3398 dpm.isProvisioningAllowed(action)); 3399 } 3400 3401 private void assertProvisioningAllowed(String action, boolean expected, String packageName, 3402 int uid) { 3403 String previousPackageName = mContext.packageName; 3404 int previousUid = mMockContext.binder.callingUid; 3405 3406 // Call assertProvisioningAllowed with the packageName / uid passed as arguments. 3407 mContext.packageName = packageName; 3408 mMockContext.binder.callingUid = uid; 3409 assertProvisioningAllowed(action, expected); 3410 3411 // Set the previous package name / calling uid to go back to the initial state. 3412 mContext.packageName = previousPackageName; 3413 mMockContext.binder.callingUid = previousUid; 3414 } 3415 3416 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) { 3417 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition); 3418 } 3419 3420 private void assertCheckProvisioningPreCondition( 3421 String action, String packageName, int provisioningCondition) { 3422 assertEquals("checkProvisioningPreCondition(" 3423 + action + ", " + packageName + ") returning unexpected result", 3424 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName)); 3425 } 3426 3427 /** 3428 * Setup a managed profile with the specified admin and its uid. 3429 * @param admin ComponentName that's visible to the test code, which doesn't have to exist. 3430 * @param adminUid uid of the admin package. 3431 * @param copyFromAdmin package information for {@code admin} will be built based on this 3432 * component's information. 3433 */ 3434 private void addManagedProfile( 3435 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception { 3436 final int userId = UserHandle.getUserId(adminUid); 3437 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); 3438 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); 3439 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); 3440 dpm.setActiveAdmin(admin, false, userId); 3441 assertTrue(dpm.setProfileOwner(admin, null, userId)); 3442 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); 3443 } 3444} 3445