2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package com.android.server.devicepolicy;
18 import android.Manifest.permission;
19 import android.app.Activity;
20 import android.app.admin.DeviceAdminReceiver;
21 import android.app.admin.DevicePolicyManager;
22 import android.app.admin.DevicePolicyManagerInternal;
23 import android.content.BroadcastReceiver;
24 import android.content.ComponentName;
25 import android.content.pm.ApplicationInfo;
26 import android.content.pm.PackageInfo;
27 import android.content.pm.PackageManager;
28 import android.net.wifi.WifiInfo;
29 import android.os.Build.VERSION_CODES;
30 import android.os.Build;
31 import android.os.Bundle;
32 import android.os.Process;
33 import android.os.UserHandle;
34 import android.os.UserManager;
35 import android.provider.Settings;
36 import android.telephony.TelephonyManager;
37 import android.test.MoreAsserts;
38 import android.test.suitebuilder.annotation.SmallTest;
39 import android.util.ArraySet;
40 import android.util.Pair;
42 import com.android.server.LocalServices;
43 import com.android.server.SystemService;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.invocation.InvocationOnMock;
47 import org.mockito.stubbing.Answer;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.HashMap;
52 import java.util.List;
56 import static org.mockito.Matchers.any;
57 import static org.mockito.Matchers.anyInt;
58 import static org.mockito.Matchers.anyString;
59 import static org.mockito.Matchers.eq;
60 import static org.mockito.Matchers.isNull;
61 import static org.mockito.Mockito.doAnswer;
62 import static org.mockito.Mockito.doReturn;
63 import static org.mockito.Mockito.reset;
64 import static org.mockito.Mockito.times;
65 import static org.mockito.Mockito.validateMockitoUsage;
66 import static org.mockito.Mockito.verify;
67 import static org.mockito.Mockito.when;
70 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
72 m FrameworksServicesTests &&
74 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
75 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
76 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
78 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
81 public class DevicePolicyManagerTest extends DpmTestBase {
82 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
83 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
84 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
86 private DpmMockContext mContext;
87 public DevicePolicyManager dpm;
88 public DevicePolicyManagerServiceTestable dpms;
91 protected void setUp() throws Exception {
94 mContext = getContext();
96 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
99 // By default, pretend all users are running and unlocked.
100 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
104 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
105 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
106 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
107 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
112 private void initializeDpms() {
113 // Need clearCallingIdentity() to pass permission checks.
114 final long ident = mContext.binder.clearCallingIdentity();
116 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
118 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
120 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
121 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
123 dpm = new DevicePolicyManagerTestable(mContext, dpms);
125 mContext.binder.restoreCallingIdentity(ident);
129 private void setUpUserManager() {
130 // Emulate UserManager.set/getApplicationRestriction().
131 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
133 // UM.setApplicationRestrictions() will save to appRestrictions.
134 doAnswer(new Answer<Void>() {
136 public Void answer(InvocationOnMock invocation) throws Throwable {
137 String pkg = (String) invocation.getArguments()[0];
138 Bundle bundle = (Bundle) invocation.getArguments()[1];
139 UserHandle user = (UserHandle) invocation.getArguments()[2];
141 appRestrictions.put(Pair.create(pkg, user), bundle);
145 }).when(mContext.userManager).setApplicationRestrictions(
146 anyString(), any(Bundle.class), any(UserHandle.class));
148 // UM.getApplicationRestrictions() will read from appRestrictions.
149 doAnswer(new Answer<Bundle>() {
151 public Bundle answer(InvocationOnMock invocation) throws Throwable {
152 String pkg = (String) invocation.getArguments()[0];
153 UserHandle user = (UserHandle) invocation.getArguments()[1];
155 return appRestrictions.get(Pair.create(pkg, user));
157 }).when(mContext.userManager).getApplicationRestrictions(
158 anyString(), any(UserHandle.class));
160 // Add the first secondary user.
161 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
164 private void setAsProfileOwner(ComponentName admin) {
165 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
166 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
168 // PO needs to be an DA.
169 dpm.setActiveAdmin(admin, /* replace =*/ false);
172 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
175 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
178 public void testHasNoFeature() throws Exception {
179 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
182 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
183 new DevicePolicyManagerServiceTestable(mContext, dataDir);
185 // If the device has no DPMS feature, it shouldn't register the local service.
186 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
190 * Caller doesn't have proper permissions.
192 public void testSetActiveAdmin_SecurityException() {
195 // Caller doesn't have MANAGE_DEVICE_ADMINS.
197 dpm.setActiveAdmin(admin1, false);
198 fail("Didn't throw SecurityException");
199 } catch (SecurityException expected) {
202 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
203 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
205 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
206 fail("Didn't throw SecurityException");
207 } catch (SecurityException expected) {
213 * {@link DevicePolicyManager#setActiveAdmin}
214 * with replace=false and replace=true
215 * {@link DevicePolicyManager#isAdminActive}
216 * {@link DevicePolicyManager#isAdminActiveAsUser}
217 * {@link DevicePolicyManager#getActiveAdmins}
218 * {@link DevicePolicyManager#getActiveAdminsAsUser}
220 public void testSetActiveAdmin() throws Exception {
221 // 1. Make sure the caller has proper permissions.
222 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
225 dpm.setActiveAdmin(admin1, /* replace =*/ false);
227 // 3. Verify internal calls.
229 // Check if the boradcast is sent.
230 verify(mContext.spiedContext).sendBroadcastAsUser(
231 MockUtils.checkIntentAction(
232 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
233 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
234 verify(mContext.spiedContext).sendBroadcastAsUser(
235 MockUtils.checkIntentAction(
236 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
237 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
239 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
240 eq(admin1.getPackageName()),
241 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
242 eq(PackageManager.DONT_KILL_APP),
243 eq(DpmMockContext.CALLER_USER_HANDLE),
246 // TODO Verify other calls too.
248 // Make sure it's active admin1.
249 assertTrue(dpm.isAdminActive(admin1));
250 assertFalse(dpm.isAdminActive(admin2));
251 assertFalse(dpm.isAdminActive(admin3));
253 // But not admin1 for a different user.
255 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
256 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
257 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
259 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
260 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
262 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
264 // Next, add one more admin.
265 // Before doing so, update the application info, now it's enabled.
266 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
267 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
269 dpm.setActiveAdmin(admin2, /* replace =*/ false);
271 // Now we have two admins.
272 assertTrue(dpm.isAdminActive(admin1));
273 assertTrue(dpm.isAdminActive(admin2));
274 assertFalse(dpm.isAdminActive(admin3));
276 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
277 // again. (times(1) because it was previously called for admin1)
278 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
279 eq(admin1.getPackageName()),
280 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
281 eq(PackageManager.DONT_KILL_APP),
282 eq(DpmMockContext.CALLER_USER_HANDLE),
285 // 4. Add the same admin1 again without replace, which should throw.
287 dpm.setActiveAdmin(admin1, /* replace =*/ false);
288 fail("Didn't throw");
289 } catch (IllegalArgumentException expected) {
292 // 5. Add the same admin1 again with replace, which should succeed.
293 dpm.setActiveAdmin(admin1, /* replace =*/ true);
295 // TODO make sure it's replaced.
297 // 6. Test getActiveAdmins()
298 List<ComponentName> admins = dpm.getActiveAdmins();
299 assertEquals(2, admins.size());
300 assertEquals(admin1, admins.get(0));
301 assertEquals(admin2, admins.get(1));
303 // Another user has no admins.
304 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
306 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
307 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
309 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
312 public void testSetActiveAdmin_multiUsers() throws Exception {
314 final int ANOTHER_USER_ID = 100;
315 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
317 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
319 // Set up pacakge manager for the other user.
320 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
322 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
324 dpm.setActiveAdmin(admin1, /* replace =*/ false);
326 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
327 dpm.setActiveAdmin(admin2, /* replace =*/ false);
330 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
331 assertTrue(dpm.isAdminActive(admin1));
332 assertFalse(dpm.isAdminActive(admin2));
334 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
335 assertFalse(dpm.isAdminActive(admin1));
336 assertTrue(dpm.isAdminActive(admin2));
341 * {@link DevicePolicyManager#setActiveAdmin}
344 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
345 // 1. Make sure the caller has proper permissions.
346 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
348 dpm.setActiveAdmin(admin1, /* replace =*/ false);
349 assertTrue(dpm.isAdminActive(admin1));
351 // Add the same admin1 again without replace, which should throw.
353 dpm.setActiveAdmin(admin1, /* replace =*/ false);
354 fail("Didn't throw");
355 } catch (IllegalArgumentException expected) {
361 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
364 public void testSetActiveAdmin_permissionCheck() throws Exception {
365 // 1. Make sure the caller has proper permissions.
366 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
369 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
371 } catch (IllegalArgumentException expected) {
372 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
374 assertFalse(dpm.isAdminActive(adminNoPerm));
376 // Change the target API level to MNC. Now it can be set as DA.
377 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
379 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
380 assertTrue(dpm.isAdminActive(adminNoPerm));
382 // TODO Test the "load from the file" case where DA will still be loaded even without
383 // BIND_DEVICE_ADMIN and target API is N.
388 * {@link DevicePolicyManager#removeActiveAdmin}
390 public void testRemoveActiveAdmin_SecurityException() {
391 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
395 dpm.setActiveAdmin(admin1, /* replace =*/ false);
397 assertTrue(dpm.isAdminActive(admin1));
399 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
401 // Directly call the DPMS method with a different userid, which should fail.
403 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
404 fail("Didn't throw SecurityException");
405 } catch (SecurityException expected) {
408 // Try to remove active admin with a different caller userid should fail too, without
409 // having MANAGE_DEVICE_ADMINS.
410 mContext.callerPermissions.clear();
412 // Change the caller, and call into DPMS directly with a different user-id.
414 mContext.binder.callingUid = 1234567;
416 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
417 fail("Didn't throw SecurityException");
418 } catch (SecurityException expected) {
423 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
424 * (because we can't send the remove broadcast).
426 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
427 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
429 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
433 dpm.setActiveAdmin(admin1, /* replace =*/ false);
435 assertTrue(dpm.isAdminActive(admin1));
437 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
439 // 1. User not unlocked.
440 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
443 dpm.removeActiveAdmin(admin1);
444 fail("Didn't throw IllegalStateException");
445 } catch (IllegalStateException expected) {
446 MoreAsserts.assertContainsRegex(
447 "User must be running and unlocked", expected.getMessage());
450 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
453 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
456 dpm.removeActiveAdmin(admin1);
458 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
463 * {@link DevicePolicyManager#removeActiveAdmin}
465 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
466 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
470 dpm.setActiveAdmin(admin1, /* replace =*/ false);
472 assertTrue(dpm.isAdminActive(admin1));
473 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
475 // Different user, but should work, because caller has proper permissions.
476 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
478 // Change the caller, and call into DPMS directly with a different user-id.
479 mContext.binder.callingUid = 1234567;
481 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
483 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
485 // TODO DO Still can't be removed in this case.
490 * {@link DevicePolicyManager#removeActiveAdmin}
492 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
493 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
494 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
498 dpm.setActiveAdmin(admin1, /* replace =*/ false);
500 assertTrue(dpm.isAdminActive(admin1));
501 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
503 // Broadcast from saveSettingsLocked().
504 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
505 MockUtils.checkIntentAction(
506 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
507 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
509 // Remove. No permissions, but same user, so it'll work.
510 mContext.callerPermissions.clear();
511 dpm.removeActiveAdmin(admin1);
513 final ArgumentCaptor<BroadcastReceiver> brCap =
514 ArgumentCaptor.forClass(BroadcastReceiver.class);
516 // Is removing now, but not removed yet.
517 assertTrue(dpm.isAdminActive(admin1));
518 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
520 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
521 MockUtils.checkIntentAction(
522 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
523 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
524 isNull(String.class),
527 eq(Activity.RESULT_OK),
528 isNull(String.class),
529 isNull(Bundle.class));
531 brCap.getValue().onReceive(mContext, null);
533 assertFalse(dpm.isAdminActive(admin1));
534 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
536 // Again broadcast from saveSettingsLocked().
537 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
538 MockUtils.checkIntentAction(
539 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
540 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
542 // TODO Check other internal calls.
546 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
548 public void testSetDeviceOwner() throws Exception {
551 // Try to set a profile owner on the same user, which should fail.
552 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
553 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
555 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
556 fail("IllegalStateException not thrown");
557 } catch (IllegalStateException expected) {
558 assertTrue("Message was: " + expected.getMessage(),
559 expected.getMessage().contains("already has a device owner"));
562 // DO admin can't be deactivated.
563 dpm.removeActiveAdmin(admin1);
564 assertTrue(dpm.isAdminActive(admin1));
566 // TODO Test getDeviceOwnerName() too. To do so, we need to change
567 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
570 private void setDeviceOwner() throws Exception {
571 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
572 mContext.callerPermissions.add(permission.MANAGE_USERS);
573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
574 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
576 // In this test, change the caller user to "system".
577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
579 // Make sure admin1 is installed on system user.
580 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
582 // Check various get APIs.
583 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
585 // DO needs to be an DA.
586 dpm.setActiveAdmin(admin1, /* replace =*/ false);
589 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
591 // getDeviceOwnerComponent should return the admin1 component.
592 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
593 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
595 // Check various get APIs.
596 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
598 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
599 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
600 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
601 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
603 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
605 // Verify internal calls.
606 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
607 eq(admin1.getPackageName()));
609 // TODO We should check if the caller has called clearCallerIdentity().
610 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
611 eq(UserHandle.USER_SYSTEM), eq(false));
613 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
614 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
615 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
617 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
620 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
621 final int origCallingUser = mContext.binder.callingUid;
622 final List origPermissions = new ArrayList(mContext.callerPermissions);
623 mContext.callerPermissions.clear();
625 mContext.callerPermissions.add(permission.MANAGE_USERS);
627 mContext.binder.callingUid = Process.SYSTEM_UID;
629 // TODO Test getDeviceOwnerName() too. To do so, we need to change
630 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
631 if (hasDeviceOwner) {
632 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
633 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
634 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
636 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
637 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
638 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
640 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
641 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
642 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
644 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
645 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
646 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
650 if (hasDeviceOwner) {
651 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
652 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
653 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
655 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
656 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
657 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
659 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
660 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
661 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
663 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
664 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
665 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
668 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
669 // Still with MANAGE_USERS.
670 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
671 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
672 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
674 if (hasDeviceOwner) {
675 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
676 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
677 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
679 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
680 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
681 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
684 mContext.binder.callingUid = Process.SYSTEM_UID;
685 mContext.callerPermissions.remove(permission.MANAGE_USERS);
686 // System can still call "OnAnyUser" without MANAGE_USERS.
687 if (hasDeviceOwner) {
688 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
689 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
690 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
692 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
693 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
694 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
696 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
697 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
698 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
700 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
701 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
702 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
705 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
706 // Still no MANAGE_USERS.
707 if (hasDeviceOwner) {
708 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
709 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
710 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
712 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
713 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
714 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
718 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
720 } catch (SecurityException expected) {
723 dpm.getDeviceOwnerComponentOnAnyUser();
725 } catch (SecurityException expected) {
728 dpm.getDeviceOwnerUserId();
730 } catch (SecurityException expected) {
733 dpm.getDeviceOwnerNameOnAnyUser();
735 } catch (SecurityException expected) {
738 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
739 // Still no MANAGE_USERS.
740 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
741 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
742 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
745 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
747 } catch (SecurityException expected) {
750 dpm.getDeviceOwnerComponentOnAnyUser();
752 } catch (SecurityException expected) {
755 dpm.getDeviceOwnerUserId();
757 } catch (SecurityException expected) {
760 dpm.getDeviceOwnerNameOnAnyUser();
762 } catch (SecurityException expected) {
766 mContext.binder.callingUid = origCallingUser;
767 mContext.callerPermissions.addAll(origPermissions);
772 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
774 public void testSetDeviceOwner_noSuchPackage() {
775 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
776 mContext.callerPermissions.add(permission.MANAGE_USERS);
777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
778 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
780 // Call from a process on the system user.
781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
784 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
785 fail("Didn't throw IllegalArgumentException");
786 } catch (IllegalArgumentException expected) {
787 assertTrue("Message was: " + expected.getMessage(),
788 expected.getMessage().contains("Invalid component"));
792 public void testSetDeviceOwner_failures() throws Exception {
793 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
796 public void testClearDeviceOwner() throws Exception {
797 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
798 mContext.callerPermissions.add(permission.MANAGE_USERS);
799 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
800 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
802 // Set admin1 as a DA to the secondary user.
803 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
805 dpm.setActiveAdmin(admin1, /* replace =*/ false);
807 // Set admin 1 as the DO to the system user.
809 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
810 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
811 dpm.setActiveAdmin(admin1, /* replace =*/ false);
812 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
814 // Verify internal calls.
815 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
816 eq(admin1.getPackageName()));
818 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
820 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
822 assertTrue(dpm.isAdminActive(admin1));
823 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
825 // Set up other mocks.
826 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
829 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
830 eq(admin1.getPackageName()),
833 // But first pretend the user is locked. Then it should fail.
834 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
836 dpm.clearDeviceOwnerApp(admin1.getPackageName());
837 fail("Didn't throw IllegalStateException");
838 } catch (IllegalStateException expected) {
839 MoreAsserts.assertContainsRegex(
840 "User must be running and unlocked", expected.getMessage());
843 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
844 reset(mContext.userManagerInternal);
845 dpm.clearDeviceOwnerApp(admin1.getPackageName());
847 // Now DO shouldn't be set.
848 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
850 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
851 eq(UserHandle.USER_SYSTEM),
852 MockUtils.checkUserRestrictions(),
853 MockUtils.checkUserRestrictions()
856 assertTrue(dpm.isAdminActive(admin1));
857 assertTrue(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
859 // TODO Check other calls.
862 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
863 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
864 mContext.callerPermissions.add(permission.MANAGE_USERS);
865 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
866 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
868 // Set admin1 as a DA to the secondary user.
869 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
871 dpm.setActiveAdmin(admin1, /* replace =*/ false);
873 // Set admin 1 as the DO to the system user.
875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
876 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
877 dpm.setActiveAdmin(admin1, /* replace =*/ false);
878 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
880 // Verify internal calls.
881 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
882 eq(admin1.getPackageName()));
884 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
886 // Now call clear from the secondary user, which should throw.
887 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
890 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
891 eq(admin1.getPackageName()),
894 dpm.clearDeviceOwnerApp(admin1.getPackageName());
895 fail("Didn't throw");
896 } catch (SecurityException e) {
897 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
900 // DO shouldn't be removed.
901 assertTrue(dpm.isDeviceManaged());
904 public void testSetProfileOwner() throws Exception {
905 setAsProfileOwner(admin1);
907 // PO admin can't be deactivated.
908 dpm.removeActiveAdmin(admin1);
909 assertTrue(dpm.isAdminActive(admin1));
911 // Try setting DO on the same user, which should fail.
912 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
913 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
915 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
916 fail("IllegalStateException not thrown");
917 } catch (IllegalStateException expected) {
918 assertTrue("Message was: " + expected.getMessage(),
919 expected.getMessage().contains("already has a profile owner"));
923 public void testClearProfileOwner() throws Exception {
924 setAsProfileOwner(admin1);
926 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
928 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
929 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
931 // First try when the user is locked, which should fail.
932 when(mContext.userManager.isUserUnlocked(anyInt()))
935 dpm.clearProfileOwner(admin1);
936 fail("Didn't throw IllegalStateException");
937 } catch (IllegalStateException expected) {
938 MoreAsserts.assertContainsRegex(
939 "User must be running and unlocked", expected.getMessage());
942 when(mContext.userManager.isUserUnlocked(anyInt()))
944 dpm.clearProfileOwner(admin1);
947 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
948 assertTrue(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
951 public void testSetProfileOwner_failures() throws Exception {
952 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
955 public void testGetDeviceOwnerAdminLocked() throws Exception {
956 checkDeviceOwnerWithMultipleDeviceAdmins();
959 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
960 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
961 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
962 // make sure it gets the right component from the right user.
964 final int ANOTHER_USER_ID = 100;
965 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
967 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
969 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
970 mContext.callerPermissions.add(permission.MANAGE_USERS);
971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
972 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
974 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
976 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
978 // Make sure the admin packge is installed to each user.
979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
980 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
982 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
983 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
985 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
988 // Set active admins to the users.
989 dpm.setActiveAdmin(admin1, /* replace =*/ false);
990 dpm.setActiveAdmin(admin3, /* replace =*/ false);
992 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
993 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
995 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
997 // Set DO on the first non-system user.
998 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
999 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1001 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1003 // Then check getDeviceOwnerAdminLocked().
1004 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1005 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1009 * This essentially tests
1010 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1013 * We didn't use to persist the DO component class name, but now we do, and the above method
1014 * finds the right component from a package name upon migration.
1016 public void testDeviceOwnerMigration() throws Exception {
1017 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1018 checkDeviceOwnerWithMultipleDeviceAdmins();
1020 // Overwrite the device owner setting and clears the clas name.
1021 dpms.mOwners.setDeviceOwner(
1022 new ComponentName(admin2.getPackageName(), ""),
1023 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1024 dpms.mOwners.writeDeviceOwner();
1026 // Make sure the DO component name doesn't have a class name.
1027 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
1029 // Then create a new DPMS to have it load the settings from files.
1030 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1031 .thenReturn(new Bundle());
1034 // Now the DO component name is a full name.
1035 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1037 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1040 public void testSetGetApplicationRestriction() {
1041 setAsProfileOwner(admin1);
1044 Bundle rest = new Bundle();
1045 rest.putString("KEY_STRING", "Foo1");
1046 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1050 Bundle rest = new Bundle();
1051 rest.putString("KEY_STRING", "Foo2");
1052 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1056 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1057 assertNotNull(returned);
1058 assertEquals(returned.size(), 1);
1059 assertEquals(returned.get("KEY_STRING"), "Foo1");
1063 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1064 assertNotNull(returned);
1065 assertEquals(returned.size(), 1);
1066 assertEquals(returned.get("KEY_STRING"), "Foo2");
1069 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1070 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1073 public void testApplicationRestrictionsManagingApp() throws Exception {
1074 setAsProfileOwner(admin1);
1076 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
1077 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1078 final int appRestrictionsManagerAppId = 20987;
1079 final int appRestrictionsManagerUid = UserHandle.getUid(
1080 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
1081 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
1082 eq(appRestrictionsManagerPackage),
1083 eq(DpmMockContext.CALLER_USER_HANDLE));
1084 mContext.binder.callingUid = appRestrictionsManagerUid;
1086 final PackageInfo pi = new PackageInfo();
1087 pi.applicationInfo = new ApplicationInfo();
1088 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1089 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1090 eq(appRestrictionsManagerPackage),
1092 eq(DpmMockContext.CALLER_USER_HANDLE));
1094 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1095 // delegated that permission yet.
1096 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1097 Bundle rest = new Bundle();
1098 rest.putString("KEY_STRING", "Foo1");
1100 dpm.setApplicationRestrictions(null, "pkg1", rest);
1101 fail("Didn't throw expected SecurityException");
1102 } catch (SecurityException expected) {
1103 MoreAsserts.assertContainsRegex(
1104 "caller cannot manage application restrictions", expected.getMessage());
1107 dpm.getApplicationRestrictions(null, "pkg1");
1108 fail("Didn't throw expected SecurityException");
1109 } catch (SecurityException expected) {
1110 MoreAsserts.assertContainsRegex(
1111 "caller cannot manage application restrictions", expected.getMessage());
1114 // Check via the profile owner that no restrictions were set.
1115 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1116 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1118 // Check the API does not allow setting a non-existent package
1120 dpm.setApplicationRestrictionsManagingPackage(admin1,
1121 nonExistAppRestrictionsManagerPackage);
1122 fail("Non-existent app set as app restriction manager.");
1123 } catch (PackageManager.NameNotFoundException expected) {
1124 MoreAsserts.assertContainsRegex(
1125 nonExistAppRestrictionsManagerPackage, expected.getMessage());
1128 // Let appRestrictionsManagerPackage manage app restrictions
1129 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1130 assertEquals(appRestrictionsManagerPackage,
1131 dpm.getApplicationRestrictionsManagingPackage(admin1));
1133 // Now that package should be able to set and retrieve app restrictions.
1134 mContext.binder.callingUid = appRestrictionsManagerUid;
1135 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1136 dpm.setApplicationRestrictions(null, "pkg1", rest);
1137 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1138 assertEquals(1, returned.size(), 1);
1139 assertEquals("Foo1", returned.get("KEY_STRING"));
1141 // The same app running on a separate user shouldn't be able to manage app restrictions.
1142 mContext.binder.callingUid = UserHandle.getUid(
1143 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1144 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1146 dpm.setApplicationRestrictions(null, "pkg1", rest);
1147 fail("Didn't throw expected SecurityException");
1148 } catch (SecurityException expected) {
1149 MoreAsserts.assertContainsRegex(
1150 "caller cannot manage application restrictions", expected.getMessage());
1153 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1155 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1156 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1157 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1158 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1160 // Removing the ability for the package to manage app restrictions.
1161 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1162 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1163 mContext.binder.callingUid = appRestrictionsManagerUid;
1164 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1166 dpm.setApplicationRestrictions(null, "pkg1", null);
1167 fail("Didn't throw expected SecurityException");
1168 } catch (SecurityException expected) {
1169 MoreAsserts.assertContainsRegex(
1170 "caller cannot manage application restrictions", expected.getMessage());
1174 public void testSetUserRestriction_asDo() throws Exception {
1175 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1176 mContext.callerPermissions.add(permission.MANAGE_USERS);
1177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1178 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1182 // Call from a process on the system user.
1183 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1185 // Make sure admin1 is installed on system user.
1186 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1189 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1190 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1191 UserHandle.USER_SYSTEM));
1193 DpmTestUtils.assertRestrictions(
1194 DpmTestUtils.newRestrictions(),
1195 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1197 DpmTestUtils.assertRestrictions(
1198 DpmTestUtils.newRestrictions(),
1199 dpm.getUserRestrictions(admin1)
1202 reset(mContext.userManagerInternal);
1204 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1205 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1206 eq(UserHandle.USER_SYSTEM),
1207 MockUtils.checkUserRestrictions(),
1208 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1210 reset(mContext.userManagerInternal);
1212 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1213 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1214 eq(UserHandle.USER_SYSTEM),
1215 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1216 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1218 reset(mContext.userManagerInternal);
1220 DpmTestUtils.assertRestrictions(
1221 DpmTestUtils.newRestrictions(
1222 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1223 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1225 DpmTestUtils.assertRestrictions(
1226 DpmTestUtils.newRestrictions(
1227 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1228 dpm.getUserRestrictions(admin1)
1231 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1232 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1233 eq(UserHandle.USER_SYSTEM),
1234 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1235 MockUtils.checkUserRestrictions()
1237 reset(mContext.userManagerInternal);
1239 DpmTestUtils.assertRestrictions(
1240 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1241 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1243 DpmTestUtils.assertRestrictions(
1244 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1245 dpm.getUserRestrictions(admin1)
1248 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1249 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1250 eq(UserHandle.USER_SYSTEM),
1251 MockUtils.checkUserRestrictions(),
1252 MockUtils.checkUserRestrictions()
1254 reset(mContext.userManagerInternal);
1256 DpmTestUtils.assertRestrictions(
1257 DpmTestUtils.newRestrictions(),
1258 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1260 DpmTestUtils.assertRestrictions(
1261 DpmTestUtils.newRestrictions(),
1262 dpm.getUserRestrictions(admin1)
1265 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1266 // DO sets them, the scope is global.
1267 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1268 reset(mContext.userManagerInternal);
1269 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1270 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1271 eq(UserHandle.USER_SYSTEM),
1272 MockUtils.checkUserRestrictions(),
1273 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1274 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1276 reset(mContext.userManagerInternal);
1278 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1279 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1283 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1284 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1285 eq(UserHandle.USER_SYSTEM),
1286 MockUtils.checkUserRestrictions(),
1287 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1289 reset(mContext.userManagerInternal);
1291 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1292 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1293 eq(UserHandle.USER_SYSTEM),
1294 MockUtils.checkUserRestrictions(),
1295 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1296 UserManager.DISALLOW_ADD_USER)
1298 reset(mContext.userManagerInternal);
1300 dpm.setCameraDisabled(admin1, true);
1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1302 eq(UserHandle.USER_SYSTEM),
1303 // DISALLOW_CAMERA will be applied to both local and global.
1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1305 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1306 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1308 reset(mContext.userManagerInternal);
1310 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1312 dpm.setCameraDisabled(admin1, false);
1313 reset(mContext.userManagerInternal);
1315 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1316 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1317 dpm.setCameraDisabled(admin2, true);
1319 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1320 eq(UserHandle.USER_SYSTEM),
1321 // DISALLOW_CAMERA will be applied to both local and global.
1322 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1323 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1324 UserManager.DISALLOW_ADD_USER)
1326 reset(mContext.userManagerInternal);
1327 // TODO Make sure restrictions are written to the file.
1330 public void testSetUserRestriction_asPo() {
1331 setAsProfileOwner(admin1);
1333 DpmTestUtils.assertRestrictions(
1334 DpmTestUtils.newRestrictions(),
1335 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1336 .ensureUserRestrictions()
1339 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1340 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1341 eq(DpmMockContext.CALLER_USER_HANDLE),
1342 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1343 isNull(Bundle.class)
1345 reset(mContext.userManagerInternal);
1347 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1348 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1349 eq(DpmMockContext.CALLER_USER_HANDLE),
1350 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1351 UserManager.DISALLOW_OUTGOING_CALLS),
1352 isNull(Bundle.class)
1354 reset(mContext.userManagerInternal);
1356 DpmTestUtils.assertRestrictions(
1357 DpmTestUtils.newRestrictions(
1358 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1359 UserManager.DISALLOW_OUTGOING_CALLS
1361 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1362 .ensureUserRestrictions()
1364 DpmTestUtils.assertRestrictions(
1365 DpmTestUtils.newRestrictions(
1366 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1367 UserManager.DISALLOW_OUTGOING_CALLS
1369 dpm.getUserRestrictions(admin1)
1372 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1373 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1374 eq(DpmMockContext.CALLER_USER_HANDLE),
1375 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1376 isNull(Bundle.class)
1378 reset(mContext.userManagerInternal);
1380 DpmTestUtils.assertRestrictions(
1381 DpmTestUtils.newRestrictions(
1382 UserManager.DISALLOW_OUTGOING_CALLS
1384 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1385 .ensureUserRestrictions()
1387 DpmTestUtils.assertRestrictions(
1388 DpmTestUtils.newRestrictions(
1389 UserManager.DISALLOW_OUTGOING_CALLS
1391 dpm.getUserRestrictions(admin1)
1394 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1395 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1396 eq(DpmMockContext.CALLER_USER_HANDLE),
1397 MockUtils.checkUserRestrictions(),
1398 isNull(Bundle.class)
1400 reset(mContext.userManagerInternal);
1402 DpmTestUtils.assertRestrictions(
1403 DpmTestUtils.newRestrictions(),
1404 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1405 .ensureUserRestrictions()
1407 DpmTestUtils.assertRestrictions(
1408 DpmTestUtils.newRestrictions(),
1409 dpm.getUserRestrictions(admin1)
1412 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1413 // though when DO sets them they'll be applied globally.
1414 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1415 reset(mContext.userManagerInternal);
1416 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1417 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1418 eq(DpmMockContext.CALLER_USER_HANDLE),
1419 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1420 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1421 isNull(Bundle.class)
1423 reset(mContext.userManagerInternal);
1425 dpm.setCameraDisabled(admin1, true);
1426 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1427 eq(DpmMockContext.CALLER_USER_HANDLE),
1428 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1429 UserManager.DISALLOW_ADJUST_VOLUME,
1430 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1431 isNull(Bundle.class)
1433 reset(mContext.userManagerInternal);
1435 // TODO Make sure restrictions are written to the file.
1438 public void testGetMacAddress() throws Exception {
1439 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1440 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1441 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1443 // In this test, change the caller user to "system".
1444 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1446 // Make sure admin1 is installed on system user.
1447 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1449 // Test 1. Caller doesn't have DO or DA.
1451 dpm.getWifiMacAddress(admin1);
1453 } catch (SecurityException e) {
1454 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
1457 // DO needs to be an DA.
1458 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1459 assertTrue(dpm.isAdminActive(admin1));
1461 // Test 2. Caller has DA, but not DO.
1463 dpm.getWifiMacAddress(admin1);
1465 } catch (SecurityException e) {
1466 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1469 // Test 3. Caller has PO, but not DO.
1470 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1472 dpm.getWifiMacAddress(admin1);
1474 } catch (SecurityException e) {
1475 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
1479 dpm.clearProfileOwner(admin1);
1481 // Test 4, Caller is DO now.
1482 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1484 // 4-1. But no WifiInfo.
1485 assertNull(dpm.getWifiMacAddress(admin1));
1487 // 4-2. Returns WifiInfo, but with the default MAC.
1488 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
1489 assertNull(dpm.getWifiMacAddress(admin1));
1491 // 4-3. With a real MAC address.
1492 final WifiInfo wi = new WifiInfo();
1493 wi.setMacAddress("11:22:33:44:55:66");
1494 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
1495 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
1498 public void testReboot() throws Exception {
1499 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1500 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1502 // In this test, change the caller user to "system".
1503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1505 // Make sure admin1 is installed on system user.
1506 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1508 // Set admin1 as DA.
1509 dpm.setActiveAdmin(admin1, false);
1510 assertTrue(dpm.isAdminActive(admin1));
1513 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1514 } catch (SecurityException expected) {
1515 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1518 // Set admin1 as PO.
1519 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1522 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1523 } catch (SecurityException expected) {
1524 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1527 // Remove PO and add DO.
1528 dpm.clearProfileOwner(admin1);
1529 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1532 // Set current call state of device to ringing.
1533 when(mContext.telephonyManager.getCallState())
1534 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1537 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1538 } catch (IllegalStateException expected) {
1539 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1542 // Set current call state of device to dialing/active.
1543 when(mContext.telephonyManager.getCallState())
1544 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1547 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1548 } catch (IllegalStateException expected) {
1549 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1552 // Set current call state of device to idle.
1553 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
1557 public void testSetGetSupportText() {
1558 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1559 dpm.setActiveAdmin(admin1, true);
1560 dpm.setActiveAdmin(admin2, true);
1561 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1563 // Null default support messages.
1565 assertNull(dpm.getLongSupportMessage(admin1));
1566 assertNull(dpm.getShortSupportMessage(admin1));
1567 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1568 assertNull(dpm.getShortSupportMessageForUser(admin1,
1569 DpmMockContext.CALLER_USER_HANDLE));
1570 assertNull(dpm.getLongSupportMessageForUser(admin1,
1571 DpmMockContext.CALLER_USER_HANDLE));
1572 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1575 // Only system can call the per user versions.
1578 dpm.getShortSupportMessageForUser(admin1,
1579 DpmMockContext.CALLER_USER_HANDLE);
1580 fail("Only system should be able to call getXXXForUser versions");
1581 } catch (SecurityException expected) {
1582 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1585 dpm.getLongSupportMessageForUser(admin1,
1586 DpmMockContext.CALLER_USER_HANDLE);
1587 fail("Only system should be able to call getXXXForUser versions");
1588 } catch (SecurityException expected) {
1589 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1593 // Can't set message for admin in another uid.
1595 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1597 dpm.setShortSupportMessage(admin1, "Some text");
1598 fail("Admins should only be able to change their own support text.");
1599 } catch (SecurityException expected) {
1600 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1602 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1605 // Set/Get short returns what it sets and other admins text isn't changed.
1607 final String supportText = "Some text to test with.";
1608 dpm.setShortSupportMessage(admin1, supportText);
1609 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1610 assertNull(dpm.getLongSupportMessage(admin1));
1611 assertNull(dpm.getShortSupportMessage(admin2));
1613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1614 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1615 DpmMockContext.CALLER_USER_HANDLE));
1616 assertNull(dpm.getShortSupportMessageForUser(admin2,
1617 DpmMockContext.CALLER_USER_HANDLE));
1618 assertNull(dpm.getLongSupportMessageForUser(admin1,
1619 DpmMockContext.CALLER_USER_HANDLE));
1620 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1622 dpm.setShortSupportMessage(admin1, null);
1623 assertNull(dpm.getShortSupportMessage(admin1));
1626 // Set/Get long returns what it sets and other admins text isn't changed.
1628 final String supportText = "Some text to test with.\nWith more text.";
1629 dpm.setLongSupportMessage(admin1, supportText);
1630 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1631 assertNull(dpm.getShortSupportMessage(admin1));
1632 assertNull(dpm.getLongSupportMessage(admin2));
1634 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1635 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1636 DpmMockContext.CALLER_USER_HANDLE));
1637 assertNull(dpm.getLongSupportMessageForUser(admin2,
1638 DpmMockContext.CALLER_USER_HANDLE));
1639 assertNull(dpm.getShortSupportMessageForUser(admin1,
1640 DpmMockContext.CALLER_USER_HANDLE));
1641 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1643 dpm.setLongSupportMessage(admin1, null);
1644 assertNull(dpm.getLongSupportMessage(admin1));
1650 * {@link DevicePolicyManager#setAffiliationIds}
1651 * {@link DevicePolicyManager#isAffiliatedUser}
1653 public void testUserAffiliation() throws Exception {
1654 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1655 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1656 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1658 // Check that the system user is unaffiliated.
1659 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1660 assertFalse(dpm.isAffiliatedUser());
1662 // Set a device owner on the system user. Check that the system user becomes affiliated.
1663 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1664 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1665 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1666 assertTrue(dpm.isAffiliatedUser());
1668 // Install a profile owner whose package name matches the device owner on a test user. Check
1669 // that the test user is unaffiliated.
1670 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1671 setAsProfileOwner(admin2);
1672 assertFalse(dpm.isAffiliatedUser());
1674 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1676 final Set<String> userAffiliationIds = new ArraySet<>();
1677 userAffiliationIds.add("red");
1678 userAffiliationIds.add("green");
1679 userAffiliationIds.add("blue");
1680 dpm.setAffiliationIds(admin2, userAffiliationIds);
1681 assertFalse(dpm.isAffiliatedUser());
1683 // Have the device owner specify a set of affiliation ids that do not intersect with those
1684 // specified by the profile owner. Check that the test user remains unaffiliated.
1685 final Set<String> deviceAffiliationIds = new ArraySet<>();
1686 deviceAffiliationIds.add("cyan");
1687 deviceAffiliationIds.add("yellow");
1688 deviceAffiliationIds.add("magenta");
1689 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1690 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
1691 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1692 assertFalse(dpm.isAffiliatedUser());
1694 // Have the profile owner specify a set of affiliation ids that intersect with those
1695 // specified by the device owner. Check that the test user becomes affiliated.
1696 userAffiliationIds.add("yellow");
1697 dpm.setAffiliationIds(admin2, userAffiliationIds);
1698 assertTrue(dpm.isAffiliatedUser());
1700 // Change the profile owner to one whose package name does not match the device owner. Check
1701 // that the test user is not affiliated anymore.
1702 dpm.clearProfileOwner(admin2);
1703 final ComponentName admin = new ComponentName("test", "test");
1705 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID,
1706 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
1707 /* appTargetSdk = */ null, admin2);
1709 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE);
1710 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1711 assertFalse(dpm.isAffiliatedUser());
1713 // Check that the system user remains affiliated.
1714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1715 assertTrue(dpm.isAffiliatedUser());
1718 public void testGetUserProvisioningState_defaultResult() {
1719 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1722 public void testSetUserProvisioningState_permission() throws Exception {
1723 setupProfileOwner();
1724 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1726 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1727 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1730 public void testSetUserProvisioningState_unprivileged() throws Exception {
1731 setupProfileOwner();
1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1734 DpmMockContext.CALLER_USER_HANDLE);
1735 fail("Expected SecurityException");
1736 } catch (SecurityException expected) {
1740 public void testSetUserProvisioningState_noManagement() {
1741 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1743 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1744 DpmMockContext.CALLER_USER_HANDLE);
1745 fail("IllegalStateException expected");
1746 } catch (IllegalStateException e) {
1747 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1750 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1754 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1756 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1758 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1759 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1760 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1763 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1765 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1769 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1770 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1771 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1774 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1779 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1780 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1785 setupProfileOwner();
1786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1788 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1789 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1790 DevicePolicyManager.STATE_USER_UNMANAGED);
1793 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1795 setupProfileOwner();
1796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1798 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1799 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1800 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1803 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1804 setupProfileOwner();
1805 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1807 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1808 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1811 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1812 setupProfileOwner();
1813 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1816 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1817 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1818 DevicePolicyManager.STATE_USER_UNMANAGED);
1819 fail("Expected IllegalStateException");
1820 } catch (IllegalStateException e) {
1821 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1826 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1828 setupProfileOwner();
1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1832 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1833 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1834 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1835 fail("Expected IllegalStateException");
1836 } catch (IllegalStateException e) {
1837 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1842 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1843 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1844 for (int state : states) {
1845 dpm.setUserProvisioningState(state, userId);
1846 assertEquals(state, dpm.getUserProvisioningState());
1850 private void setupProfileOwner() throws Exception {
1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1854 dpm.setActiveAdmin(admin1, false);
1855 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1860 private void setupDeviceOwner() throws Exception {
1861 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1863 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1864 dpm.setActiveAdmin(admin1, false);
1865 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1867 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1870 public void testSetMaximumTimeToLock() {
1871 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1873 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1874 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1876 reset(mMockContext.powerManagerInternal);
1877 reset(mMockContext.settings);
1879 dpm.setMaximumTimeToLock(admin1, 0);
1880 verifyScreenTimeoutCall(null, false);
1881 reset(mMockContext.powerManagerInternal);
1882 reset(mMockContext.settings);
1884 dpm.setMaximumTimeToLock(admin1, 1);
1885 verifyScreenTimeoutCall(1, true);
1886 reset(mMockContext.powerManagerInternal);
1887 reset(mMockContext.settings);
1889 dpm.setMaximumTimeToLock(admin2, 10);
1890 verifyScreenTimeoutCall(null, false);
1891 reset(mMockContext.powerManagerInternal);
1892 reset(mMockContext.settings);
1894 dpm.setMaximumTimeToLock(admin1, 5);
1895 verifyScreenTimeoutCall(5, true);
1896 reset(mMockContext.powerManagerInternal);
1897 reset(mMockContext.settings);
1899 dpm.setMaximumTimeToLock(admin2, 4);
1900 verifyScreenTimeoutCall(4, true);
1901 reset(mMockContext.powerManagerInternal);
1902 reset(mMockContext.settings);
1904 dpm.setMaximumTimeToLock(admin1, 0);
1905 reset(mMockContext.powerManagerInternal);
1906 reset(mMockContext.settings);
1908 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1909 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1910 reset(mMockContext.powerManagerInternal);
1911 reset(mMockContext.settings);
1913 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1914 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1915 reset(mMockContext.powerManagerInternal);
1916 reset(mMockContext.settings);
1918 dpm.setMaximumTimeToLock(admin2, 10);
1919 verifyScreenTimeoutCall(10, true);
1920 reset(mMockContext.powerManagerInternal);
1921 reset(mMockContext.settings);
1923 // There's no restriction; shold be set to MAX.
1924 dpm.setMaximumTimeToLock(admin2, 0);
1925 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1928 private void verifyScreenTimeoutCall(Integer expectedTimeout,
1929 boolean shouldStayOnWhilePluggedInBeCleared) {
1930 if (expectedTimeout == null) {
1931 verify(mMockContext.powerManagerInternal, times(0))
1932 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
1934 verify(mMockContext.powerManagerInternal, times(1))
1935 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
1937 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
1938 // UnfinishedVerificationException.
1941 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
1942 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
1944 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
1947 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
1948 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
1950 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
1952 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1954 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
1955 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
1956 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
1958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
1961 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
1962 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
1965 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
1966 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
1968 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
1970 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1972 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
1973 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
1974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
1976 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
1978 // Test again when split user is on
1979 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
1981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
1982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
1984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
1987 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
1988 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
1990 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
1991 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
1993 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
1995 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1997 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
1998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
1999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2000 false /* because of non-split user */);
2001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2002 false /* because of non-split user */);
2005 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2007 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2009 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2010 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2012 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2014 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2016 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2017 false/* because of completed device setup */);
2018 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2019 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2020 false/* because of non-split user */);
2021 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2022 false/* because of non-split user */);
2025 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2026 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2028 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2029 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2031 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2033 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2037 false /* because canAddMoreManagedProfiles returns false */);
2038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2040 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2041 false/* because calling uid is system user */);
2045 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2046 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2048 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2049 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2051 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2053 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2056 true/* it's undefined behavior. Can be changed into false in the future */);
2057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2058 false /* because canAddMoreManagedProfiles returns false */);
2059 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2060 true/* it's undefined behavior. Can be changed into false in the future */);
2061 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2062 false/* because calling uid is system user */);
2065 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2066 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2068 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2069 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2070 true)).thenReturn(true);
2071 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2073 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2075 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2077 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2079 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2083 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2085 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2087 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2088 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2089 true)).thenReturn(true);
2090 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2092 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2094 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2095 true/* it's undefined behavior. Can be changed into false in the future */);
2096 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2098 true/* it's undefined behavior. Can be changed into false in the future */);
2099 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2100 false/* because user setup completed */);
2103 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2107 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2109 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2110 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2112 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2117 false /* can't provision managed profile on system user */);
2120 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2124 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2126 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2127 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2128 true)).thenReturn(true);
2129 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2131 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2136 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2137 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2138 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2139 dpms.notifyChangeToContentObserver(
2140 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2143 private void assertProvisioningAllowed(String action, boolean expected) {
2144 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2145 dpm.isProvisioningAllowed(action));