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