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 static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
20 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
21 import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
22 import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
23 import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
25 import static com.android.server.testutis.TestUtils.assertExpectException;
27 import static org.mockito.Matchers.any;
28 import static org.mockito.Matchers.anyInt;
29 import static org.mockito.Matchers.anyLong;
30 import static org.mockito.Matchers.anyObject;
31 import static org.mockito.Matchers.anyString;
32 import static org.mockito.Matchers.eq;
33 import static org.mockito.Matchers.isNull;
34 import static org.mockito.Mockito.atLeast;
35 import static org.mockito.Mockito.doAnswer;
36 import static org.mockito.Mockito.doReturn;
37 import static org.mockito.Mockito.mock;
38 import static org.mockito.Mockito.never;
39 import static org.mockito.Mockito.nullable;
40 import static org.mockito.Mockito.reset;
41 import static org.mockito.Mockito.timeout;
42 import static org.mockito.Mockito.times;
43 import static org.mockito.Mockito.verify;
44 import static org.mockito.Mockito.verifyZeroInteractions;
45 import static org.mockito.Mockito.when;
46 import static org.mockito.hamcrest.MockitoHamcrest.argThat;
48 import android.Manifest.permission;
49 import android.app.Activity;
50 import android.app.Notification;
51 import android.app.admin.DeviceAdminReceiver;
52 import android.app.admin.DevicePolicyManager;
53 import android.app.admin.DevicePolicyManagerInternal;
54 import android.app.admin.PasswordMetrics;
55 import android.content.BroadcastReceiver;
56 import android.content.ComponentName;
57 import android.content.Context;
58 import android.content.Intent;
59 import android.content.pm.ApplicationInfo;
60 import android.content.pm.PackageInfo;
61 import android.content.pm.PackageManager;
62 import android.content.pm.StringParceledListSlice;
63 import android.content.pm.UserInfo;
64 import android.graphics.Color;
65 import android.net.Uri;
66 import android.net.wifi.WifiInfo;
67 import android.os.Build.VERSION_CODES;
68 import android.os.Bundle;
69 import android.os.Process;
70 import android.os.UserHandle;
71 import android.os.UserManager;
72 import android.provider.Settings;
73 import android.security.KeyChain;
74 import android.telephony.TelephonyManager;
75 import android.test.MoreAsserts;
76 import android.test.suitebuilder.annotation.SmallTest;
77 import android.util.ArraySet;
78 import android.util.Pair;
80 import com.android.internal.R;
81 import com.android.internal.widget.LockPatternUtils;
82 import com.android.server.LocalServices;
83 import com.android.server.SystemService;
84 import com.android.server.pm.UserRestrictionsUtils;
86 import org.hamcrest.BaseMatcher;
87 import org.hamcrest.Description;
88 import org.mockito.invocation.InvocationOnMock;
89 import org.mockito.stubbing.Answer;
91 import java.util.ArrayList;
92 import java.util.Arrays;
93 import java.util.Collections;
94 import java.util.HashMap;
95 import java.util.List;
98 import java.util.concurrent.TimeUnit;
101 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
102 * You can run them via:
103 m FrameworksServicesTests &&
105 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
106 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
107 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
109 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
112 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
115 public class DevicePolicyManagerTest extends DpmTestBase {
116 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
117 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
118 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
119 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
120 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
122 // TODO replace all instances of this with explicit {@link #mServiceContext}.
124 private DpmMockContext mContext;
126 private DpmMockContext mServiceContext;
127 private DpmMockContext mAdmin1Context;
128 public DevicePolicyManager dpm;
129 public DevicePolicyManagerServiceTestable dpms;
132 * The CA cert below is the content of cacert.pem as generated by:
134 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
136 private static final String TEST_CA =
137 "-----BEGIN CERTIFICATE-----\n" +
138 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
139 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
140 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
141 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
142 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
143 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
144 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
145 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
146 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
147 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
148 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
149 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
150 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
151 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
152 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
153 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
154 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
155 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
157 "-----END CERTIFICATE-----\n";
160 protected void setUp() throws Exception {
163 mContext = getContext();
164 mServiceContext = mContext;
165 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
166 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
169 // By default, pretend all users are running and unlocked.
170 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
174 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
175 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
176 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
177 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
179 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
180 mAdmin1Context.packageName = admin1.getPackageName();
181 mAdmin1Context.applicationInfo = new ApplicationInfo();
182 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
188 protected void tearDown() throws Exception {
193 private void initializeDpms() {
194 // Need clearCallingIdentity() to pass permission checks.
195 final long ident = mContext.binder.clearCallingIdentity();
196 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
198 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
199 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
200 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
202 dpm = new DevicePolicyManagerTestable(mContext, dpms);
204 mContext.binder.restoreCallingIdentity(ident);
207 private void setUpUserManager() {
208 // Emulate UserManager.set/getApplicationRestriction().
209 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
211 // UM.setApplicationRestrictions() will save to appRestrictions.
212 doAnswer(new Answer<Void>() {
214 public Void answer(InvocationOnMock invocation) throws Throwable {
215 String pkg = (String) invocation.getArguments()[0];
216 Bundle bundle = (Bundle) invocation.getArguments()[1];
217 UserHandle user = (UserHandle) invocation.getArguments()[2];
219 appRestrictions.put(Pair.create(pkg, user), bundle);
223 }).when(getServices().userManager).setApplicationRestrictions(
224 anyString(), nullable(Bundle.class), any(UserHandle.class));
226 // UM.getApplicationRestrictions() will read from appRestrictions.
227 doAnswer(new Answer<Bundle>() {
229 public Bundle answer(InvocationOnMock invocation) throws Throwable {
230 String pkg = (String) invocation.getArguments()[0];
231 UserHandle user = (UserHandle) invocation.getArguments()[1];
233 return appRestrictions.get(Pair.create(pkg, user));
235 }).when(getServices().userManager).getApplicationRestrictions(
236 anyString(), any(UserHandle.class));
238 // Add the first secondary user.
239 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
242 private void setAsProfileOwner(ComponentName admin) {
243 final long ident = mServiceContext.binder.clearCallingIdentity();
245 mServiceContext.binder.callingUid =
246 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
247 runAsCaller(mServiceContext, dpms, dpm -> {
248 // PO needs to be a DA.
249 dpm.setActiveAdmin(admin, /*replace=*/ false);
251 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
253 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
256 mServiceContext.binder.restoreCallingIdentity(ident);
259 public void testHasNoFeature() throws Exception {
260 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
263 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
264 new DevicePolicyManagerServiceTestable(getServices(), mContext);
266 // If the device has no DPMS feature, it shouldn't register the local service.
267 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
271 * Caller doesn't have proper permissions.
273 public void testSetActiveAdmin_SecurityException() {
276 // Caller doesn't have MANAGE_DEVICE_ADMINS.
277 assertExpectException(SecurityException.class, /* messageRegex= */ null,
278 () -> dpm.setActiveAdmin(admin1, false));
280 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
281 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
283 assertExpectException(SecurityException.class, /* messageRegex= */ null,
284 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
289 * {@link DevicePolicyManager#setActiveAdmin}
290 * with replace=false and replace=true
291 * {@link DevicePolicyManager#isAdminActive}
292 * {@link DevicePolicyManager#isAdminActiveAsUser}
293 * {@link DevicePolicyManager#getActiveAdmins}
294 * {@link DevicePolicyManager#getActiveAdminsAsUser}
296 public void testSetActiveAdmin() throws Exception {
297 // 1. Make sure the caller has proper permissions.
298 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
301 dpm.setActiveAdmin(admin1, /* replace =*/ false);
303 // 3. Verify internal calls.
305 // Check if the boradcast is sent.
306 verify(mContext.spiedContext).sendBroadcastAsUser(
307 MockUtils.checkIntentAction(
308 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
309 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
310 verify(mContext.spiedContext).sendBroadcastAsUser(
311 MockUtils.checkIntentAction(
312 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
313 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
315 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
316 eq(admin1.getPackageName()),
317 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
318 eq(PackageManager.DONT_KILL_APP),
319 eq(DpmMockContext.CALLER_USER_HANDLE),
322 // TODO Verify other calls too.
324 // Make sure it's active admin1.
325 assertTrue(dpm.isAdminActive(admin1));
326 assertFalse(dpm.isAdminActive(admin2));
327 assertFalse(dpm.isAdminActive(admin3));
329 // But not admin1 for a different user.
331 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
332 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
333 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
335 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
336 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
338 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
340 // Next, add one more admin.
341 // Before doing so, update the application info, now it's enabled.
342 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
343 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
345 dpm.setActiveAdmin(admin2, /* replace =*/ false);
347 // Now we have two admins.
348 assertTrue(dpm.isAdminActive(admin1));
349 assertTrue(dpm.isAdminActive(admin2));
350 assertFalse(dpm.isAdminActive(admin3));
352 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
353 // again. (times(1) because it was previously called for admin1)
354 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
355 eq(admin1.getPackageName()),
356 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
357 eq(PackageManager.DONT_KILL_APP),
358 eq(DpmMockContext.CALLER_USER_HANDLE),
361 // 4. Add the same admin1 again without replace, which should throw.
362 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
363 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
365 // 5. Add the same admin1 again with replace, which should succeed.
366 dpm.setActiveAdmin(admin1, /* replace =*/ true);
368 // TODO make sure it's replaced.
370 // 6. Test getActiveAdmins()
371 List<ComponentName> admins = dpm.getActiveAdmins();
372 assertEquals(2, admins.size());
373 assertEquals(admin1, admins.get(0));
374 assertEquals(admin2, admins.get(1));
376 // Another user has no admins.
377 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
379 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
380 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
382 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
385 public void testSetActiveAdmin_multiUsers() throws Exception {
387 final int ANOTHER_USER_ID = 100;
388 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
390 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
392 // Set up pacakge manager for the other user.
393 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
395 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
397 dpm.setActiveAdmin(admin1, /* replace =*/ false);
399 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
400 dpm.setActiveAdmin(admin2, /* replace =*/ false);
403 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
404 assertTrue(dpm.isAdminActive(admin1));
405 assertFalse(dpm.isAdminActive(admin2));
407 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
408 assertFalse(dpm.isAdminActive(admin1));
409 assertTrue(dpm.isAdminActive(admin2));
414 * {@link DevicePolicyManager#setActiveAdmin}
417 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
418 // 1. Make sure the caller has proper permissions.
419 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
421 dpm.setActiveAdmin(admin1, /* replace =*/ false);
422 assertTrue(dpm.isAdminActive(admin1));
424 // Add the same admin1 again without replace, which should throw.
425 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
426 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
431 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
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);
438 assertExpectException(IllegalArgumentException.class,
439 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
440 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
441 assertFalse(dpm.isAdminActive(adminNoPerm));
443 // Change the target API level to MNC. Now it can be set as DA.
444 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
446 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
447 assertTrue(dpm.isAdminActive(adminNoPerm));
449 // TODO Test the "load from the file" case where DA will still be loaded even without
450 // BIND_DEVICE_ADMIN and target API is N.
455 * {@link DevicePolicyManager#removeActiveAdmin}
457 public void testRemoveActiveAdmin_SecurityException() {
458 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
462 dpm.setActiveAdmin(admin1, /* replace =*/ false);
464 assertTrue(dpm.isAdminActive(admin1));
466 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
468 // Directly call the DPMS method with a different userid, which should fail.
469 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
470 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
472 // Try to remove active admin with a different caller userid should fail too, without
473 // having MANAGE_DEVICE_ADMINS.
474 mContext.callerPermissions.clear();
476 // Change the caller, and call into DPMS directly with a different user-id.
478 mContext.binder.callingUid = 1234567;
479 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
480 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
484 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
485 * (because we can't send the remove broadcast).
487 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
488 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
490 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
494 dpm.setActiveAdmin(admin1, /* replace =*/ false);
496 assertTrue(dpm.isAdminActive(admin1));
498 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
500 // 1. User not unlocked.
501 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
503 assertExpectException(IllegalStateException.class,
504 /* messageRegex= */ "User must be running and unlocked",
505 () -> dpm.removeActiveAdmin(admin1));
507 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
510 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
513 dpm.removeActiveAdmin(admin1);
514 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
519 * {@link DevicePolicyManager#removeActiveAdmin}
521 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
522 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
526 dpm.setActiveAdmin(admin1, /* replace =*/ false);
528 assertTrue(dpm.isAdminActive(admin1));
529 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
531 // Different user, but should work, because caller has proper permissions.
532 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
534 // Change the caller, and call into DPMS directly with a different user-id.
535 mContext.binder.callingUid = 1234567;
537 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
538 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
540 // TODO DO Still can't be removed in this case.
545 * {@link DevicePolicyManager#removeActiveAdmin}
547 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
548 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
549 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
553 dpm.setActiveAdmin(admin1, /* replace =*/ false);
555 assertTrue(dpm.isAdminActive(admin1));
556 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
558 // Broadcast from saveSettingsLocked().
559 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
560 MockUtils.checkIntentAction(
561 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
562 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
564 // Remove. No permissions, but same user, so it'll work.
565 mContext.callerPermissions.clear();
566 dpm.removeActiveAdmin(admin1);
568 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
569 MockUtils.checkIntentAction(
570 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
571 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
572 isNull(String.class),
573 any(BroadcastReceiver.class),
575 eq(Activity.RESULT_OK),
576 isNull(String.class),
577 isNull(Bundle.class));
579 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
581 // Again broadcast from saveSettingsLocked().
582 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
583 MockUtils.checkIntentAction(
584 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
585 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
587 // TODO Check other internal calls.
591 * Test for: @{link DevicePolicyManager#setActivePasswordState}
593 * Validates that when the password for a user changes, the notification broadcast intent
594 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
595 * addition to ones in the original user.
597 public void testSetActivePasswordState_sendToProfiles() throws Exception {
598 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
600 final int MANAGED_PROFILE_USER_ID = 78;
601 final int MANAGED_PROFILE_ADMIN_UID =
602 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
604 // Setup device owner.
605 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
606 mContext.packageName = admin1.getPackageName();
609 // Add a managed profile belonging to the system user.
610 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
612 // Change the parent user's password.
613 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
615 // Both the device owner and the managed profile owner should receive this broadcast.
616 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
617 intent.setComponent(admin1);
618 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
620 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
621 MockUtils.checkIntent(intent),
622 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
623 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
624 MockUtils.checkIntent(intent),
625 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
629 * Test for: @{link DevicePolicyManager#setActivePasswordState}
631 * Validates that when the password for a managed profile changes, the notification broadcast
632 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
635 public void testSetActivePasswordState_notSentToParent() throws Exception {
636 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
638 final int MANAGED_PROFILE_USER_ID = 78;
639 final int MANAGED_PROFILE_ADMIN_UID =
640 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
642 // Setup device owner.
643 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
644 mContext.packageName = admin1.getPackageName();
645 doReturn(true).when(getServices().lockPatternUtils)
646 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
649 // Add a managed profile belonging to the system user.
650 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
652 // Change the profile's password.
653 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
655 // Both the device owner and the managed profile owner should receive this broadcast.
656 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
657 intent.setComponent(admin1);
658 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
660 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
661 MockUtils.checkIntent(intent),
662 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
663 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
664 MockUtils.checkIntent(intent),
665 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
668 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
670 public void testSetDeviceOwner() throws Exception {
673 // Try to set a profile owner on the same user, which should fail.
674 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
675 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
676 assertExpectException(IllegalStateException.class,
677 /* messageRegex= */ "already has a device owner",
678 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
680 // DO admin can't be deactivated.
681 dpm.removeActiveAdmin(admin1);
682 assertTrue(dpm.isAdminActive(admin1));
684 // TODO Test getDeviceOwnerName() too. To do so, we need to change
685 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
688 private void setDeviceOwner() throws Exception {
689 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
690 mContext.callerPermissions.add(permission.MANAGE_USERS);
691 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
692 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
694 // In this test, change the caller user to "system".
695 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
697 // Make sure admin1 is installed on system user.
698 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
700 // Check various get APIs.
701 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
703 // DO needs to be an DA.
704 dpm.setActiveAdmin(admin1, /* replace =*/ false);
707 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
709 // getDeviceOwnerComponent should return the admin1 component.
710 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
711 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
713 // Check various get APIs.
714 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
716 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
717 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
718 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
719 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
721 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
723 // Verify internal calls.
724 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
725 eq(admin1.getPackageName()));
727 // TODO We should check if the caller has called clearCallerIdentity().
728 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
729 eq(UserHandle.USER_SYSTEM), eq(false));
731 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
732 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
733 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
735 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
738 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
739 final int origCallingUser = mContext.binder.callingUid;
740 final List origPermissions = new ArrayList(mContext.callerPermissions);
741 mContext.callerPermissions.clear();
743 mContext.callerPermissions.add(permission.MANAGE_USERS);
745 mContext.binder.callingUid = Process.SYSTEM_UID;
747 // TODO Test getDeviceOwnerName() too. To do so, we need to change
748 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
749 if (hasDeviceOwner) {
750 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
751 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
752 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
754 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
755 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
756 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
758 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
759 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
760 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
762 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
763 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
764 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
767 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
768 if (hasDeviceOwner) {
769 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
770 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
771 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
773 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
774 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
775 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
777 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
778 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
779 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
781 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
782 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
783 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
786 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
787 // Still with MANAGE_USERS.
788 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
789 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
790 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
792 if (hasDeviceOwner) {
793 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
794 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
795 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
797 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
798 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
799 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
802 mContext.binder.callingUid = Process.SYSTEM_UID;
803 mContext.callerPermissions.remove(permission.MANAGE_USERS);
804 // System can still call "OnAnyUser" without MANAGE_USERS.
805 if (hasDeviceOwner) {
806 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
807 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
808 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
810 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
811 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
812 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
814 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
815 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
816 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
818 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
819 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
820 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
823 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
824 // Still no MANAGE_USERS.
825 if (hasDeviceOwner) {
826 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
827 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
828 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
830 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
831 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
832 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
835 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
836 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
837 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
838 dpm::getDeviceOwnerComponentOnAnyUser);
839 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
840 dpm::getDeviceOwnerUserId);
841 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
842 dpm::getDeviceOwnerNameOnAnyUser);
844 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
845 // Still no MANAGE_USERS.
846 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
847 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
848 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
850 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
851 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
852 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
853 dpm::getDeviceOwnerComponentOnAnyUser);
854 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
855 dpm::getDeviceOwnerUserId);
856 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
857 dpm::getDeviceOwnerNameOnAnyUser);
860 mContext.binder.callingUid = origCallingUser;
861 mContext.callerPermissions.addAll(origPermissions);
866 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
868 public void testSetDeviceOwner_noSuchPackage() {
869 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
870 mContext.callerPermissions.add(permission.MANAGE_USERS);
871 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
872 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
874 // Call from a process on the system user.
875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
877 assertExpectException(IllegalArgumentException.class,
878 /* messageRegex= */ "Invalid component",
879 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
882 public void testSetDeviceOwner_failures() throws Exception {
883 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
886 public void testClearDeviceOwner() throws Exception {
887 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
888 mContext.callerPermissions.add(permission.MANAGE_USERS);
889 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
890 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
892 // Set admin1 as a DA to the secondary user.
893 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
895 dpm.setActiveAdmin(admin1, /* replace =*/ false);
897 // Set admin 1 as the DO to the system user.
899 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
900 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
901 dpm.setActiveAdmin(admin1, /* replace =*/ false);
902 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
904 // Verify internal calls.
905 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
906 eq(admin1.getPackageName()));
908 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
910 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
911 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
912 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
914 assertTrue(dpm.isAdminActive(admin1));
915 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
917 // Set up other mocks.
918 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
921 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
922 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
924 // But first pretend the user is locked. Then it should fail.
925 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
926 assertExpectException(IllegalStateException.class,
927 /* messageRegex= */ "User must be running and unlocked",
928 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
930 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
931 reset(getServices().userManagerInternal);
932 dpm.clearDeviceOwnerApp(admin1.getPackageName());
934 // Now DO shouldn't be set.
935 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
937 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
939 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
941 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
942 eq(UserHandle.USER_SYSTEM),
944 eq(true), eq(CAMERA_NOT_DISABLED));
946 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
948 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
949 // and once for clearing it.
950 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
951 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
952 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
953 // TODO Check other calls.
956 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
957 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
958 mContext.callerPermissions.add(permission.MANAGE_USERS);
959 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
960 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
962 // Set admin1 as a DA to the secondary user.
963 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
965 dpm.setActiveAdmin(admin1, /* replace =*/ false);
967 // Set admin 1 as the DO to the system user.
969 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
970 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
971 dpm.setActiveAdmin(admin1, /* replace =*/ false);
972 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
974 // Verify internal calls.
975 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
976 eq(admin1.getPackageName()));
978 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
980 // Now call clear from the secondary user, which should throw.
981 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
984 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
985 eq(admin1.getPackageName()),
987 assertExpectException(SecurityException.class,
988 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
989 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
991 // DO shouldn't be removed.
992 assertTrue(dpm.isDeviceManaged());
995 public void testSetProfileOwner() throws Exception {
996 setAsProfileOwner(admin1);
998 // PO admin can't be deactivated.
999 dpm.removeActiveAdmin(admin1);
1000 assertTrue(dpm.isAdminActive(admin1));
1002 // Try setting DO on the same user, which should fail.
1003 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1004 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1005 runAsCaller(mServiceContext, dpms, dpm -> {
1006 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1007 assertExpectException(IllegalStateException.class,
1008 /* messageRegex= */ "already has a profile owner",
1009 () -> dpm.setDeviceOwner(admin2, "owner-name",
1010 DpmMockContext.CALLER_USER_HANDLE));
1014 public void testClearProfileOwner() throws Exception {
1015 setAsProfileOwner(admin1);
1017 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1019 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1020 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1022 // First try when the user is locked, which should fail.
1023 when(getServices().userManager.isUserUnlocked(anyInt()))
1025 assertExpectException(IllegalStateException.class,
1026 /* messageRegex= */ "User must be running and unlocked",
1027 () -> dpm.clearProfileOwner(admin1));
1030 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1031 dpm.clearProfileOwner(admin1);
1034 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
1035 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
1038 public void testSetProfileOwner_failures() throws Exception {
1039 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1042 public void testGetDeviceOwnerAdminLocked() throws Exception {
1043 checkDeviceOwnerWithMultipleDeviceAdmins();
1046 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1047 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1048 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1049 // make sure it gets the right component from the right user.
1051 final int ANOTHER_USER_ID = 100;
1052 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1054 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
1056 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1057 mContext.callerPermissions.add(permission.MANAGE_USERS);
1058 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1059 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1061 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1063 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
1065 // Make sure the admin packge is installed to each user.
1066 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1067 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1069 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1070 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1072 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1075 // Set active admins to the users.
1076 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1077 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1079 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1080 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1082 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1084 // Set DO on the first non-system user.
1085 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1086 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1088 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1090 // Then check getDeviceOwnerAdminLocked().
1091 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1092 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1096 * This essentially tests
1097 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1100 * We didn't use to persist the DO component class name, but now we do, and the above method
1101 * finds the right component from a package name upon migration.
1103 public void testDeviceOwnerMigration() throws Exception {
1104 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
1105 checkDeviceOwnerWithMultipleDeviceAdmins();
1107 // Overwrite the device owner setting and clears the clas name.
1108 dpms.mOwners.setDeviceOwner(
1109 new ComponentName(admin2.getPackageName(), ""),
1110 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1111 dpms.mOwners.writeDeviceOwner();
1113 // Make sure the DO component name doesn't have a class name.
1114 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
1116 // Then create a new DPMS to have it load the settings from files.
1117 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
1118 .thenReturn(new Bundle());
1121 // Now the DO component name is a full name.
1122 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1124 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
1127 public void testSetGetApplicationRestriction() {
1128 setAsProfileOwner(admin1);
1129 mContext.packageName = admin1.getPackageName();
1132 Bundle rest = new Bundle();
1133 rest.putString("KEY_STRING", "Foo1");
1134 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1138 Bundle rest = new Bundle();
1139 rest.putString("KEY_STRING", "Foo2");
1140 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1144 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1145 assertNotNull(returned);
1146 assertEquals(returned.size(), 1);
1147 assertEquals(returned.get("KEY_STRING"), "Foo1");
1151 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1152 assertNotNull(returned);
1153 assertEquals(returned.size(), 1);
1154 assertEquals(returned.get("KEY_STRING"), "Foo2");
1157 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1158 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1162 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1163 * Useful for faking installed applications.
1165 * @param packageName the name of the package to be setup
1166 * @param appId the application ID to be given to the package
1167 * @return the UID of the package as known by the mock package manager
1169 private int setupPackageInPackageManager(final String packageName, final int appId)
1171 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
1172 ApplicationInfo.FLAG_HAS_CODE);
1176 * Setup a package in the package manager mock. Useful for faking installed applications.
1178 * @param packageName the name of the package to be setup
1179 * @param userId the user id where the package will be "installed"
1180 * @param appId the application ID to be given to the package
1181 * @param flags flags to set in the ApplicationInfo for this package
1182 * @return the UID of the package as known by the mock package manager
1184 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1185 int flags) throws Exception {
1186 final int uid = UserHandle.getUid(userId, appId);
1187 // Make the PackageManager return the package instead of throwing NameNotFoundException
1188 final PackageInfo pi = new PackageInfo();
1189 pi.applicationInfo = new ApplicationInfo();
1190 pi.applicationInfo.flags = flags;
1191 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
1195 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
1199 // Setup application UID with the PackageManager
1200 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
1203 // Associate packageName to uid
1204 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
1205 doReturn(new String[]{packageName})
1206 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
1210 public void testCertificateDisclosure() throws Exception {
1211 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1212 final UserHandle user = UserHandle.of(userId);
1214 mContext.applicationInfo = new ApplicationInfo();
1215 mContext.callerPermissions.add(permission.MANAGE_USERS);
1216 mContext.packageName = "com.android.frameworks.servicestests";
1217 getServices().addPackageContext(user, mContext);
1218 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1220 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1221 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
1223 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1224 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1226 // Given that we have exactly one certificate installed,
1227 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1228 // when that certificate is approved,
1229 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
1230 // a notification should not be shown.
1231 verify(getServices().notificationManager, timeout(1000))
1232 .cancelAsUser(anyString(), anyInt(), eq(user));
1234 // Given that we have four certificates installed,
1235 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1236 // when two of them are approved (one of them approved twice hence no action),
1237 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1238 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
1239 // a notification should be shown saying that there are two certificates left to approve.
1240 verify(getServices().notificationManager, timeout(1000))
1241 .notifyAsUser(anyString(), anyInt(), argThat(
1242 new BaseMatcher<Notification>() {
1244 public boolean matches(Object item) {
1245 final Notification noti = (Notification) item;
1246 return TEST_STRING.equals(
1247 noti.extras.getString(Notification.EXTRA_TITLE));
1250 public void describeTo(Description description) {
1251 description.appendText(
1252 "Notification{title=\"" + TEST_STRING + "\"}");
1258 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1259 * privileges can acually be exercised by a delegate are not covered here.
1261 public void testDelegation() throws Exception {
1262 setAsProfileOwner(admin1);
1264 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1266 // Given two packages
1267 final String CERT_DELEGATE = "com.delegate.certs";
1268 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1269 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1270 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1274 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1275 mContext.packageName = admin1.getPackageName();
1276 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1277 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1279 // DPMS correctly stores and retrieves the delegates
1280 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1281 assertEquals(2, policy.mDelegationMap.size());
1282 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1283 DELEGATION_CERT_INSTALL);
1284 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1285 DELEGATION_CERT_INSTALL);
1286 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1287 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1288 DELEGATION_APP_RESTRICTIONS);
1289 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1290 DELEGATION_APP_RESTRICTIONS);
1291 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1293 // On calling install certificate APIs from an unauthorized process
1294 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1295 mContext.packageName = RESTRICTIONS_DELEGATE;
1297 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1298 () -> dpm.installCaCert(null, null));
1300 // On calling install certificate APIs from an authorized process
1301 mContext.binder.callingUid = CERT_DELEGATE_UID;
1302 mContext.packageName = CERT_DELEGATE;
1304 // DPMS executes without a SecurityException
1306 dpm.installCaCert(null, null);
1307 } catch (SecurityException unexpected) {
1308 fail("Threw SecurityException on authorized access");
1309 } catch (NullPointerException expected) {
1312 // On removing a delegate
1313 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1314 mContext.packageName = admin1.getPackageName();
1315 dpm.setCertInstallerPackage(admin1, null);
1317 // DPMS does not allow access to ex-delegate
1318 mContext.binder.callingUid = CERT_DELEGATE_UID;
1319 mContext.packageName = CERT_DELEGATE;
1320 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1321 () -> dpm.installCaCert(null, null));
1323 // But still allows access to other existing delegates
1324 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1325 mContext.packageName = RESTRICTIONS_DELEGATE;
1327 dpm.getApplicationRestrictions(null, "pkg");
1328 } catch (SecurityException expected) {
1329 fail("Threw SecurityException on authorized access");
1333 public void testApplicationRestrictionsManagingApp() throws Exception {
1334 setAsProfileOwner(admin1);
1336 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
1337 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1338 final String nonDelegateExceptionMessageRegex =
1339 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
1340 final int appRestrictionsManagerAppId = 20987;
1341 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1342 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
1344 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1345 // delegated that permission yet.
1346 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1347 mContext.packageName = admin1.getPackageName();
1348 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1349 final Bundle rest = new Bundle();
1350 rest.putString("KEY_STRING", "Foo1");
1351 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1352 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
1354 // Check via the profile owner that no restrictions were set.
1355 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1356 mContext.packageName = admin1.getPackageName();
1357 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1359 // Check the API does not allow setting a non-existent package
1360 assertExpectException(PackageManager.NameNotFoundException.class,
1361 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1362 () -> dpm.setApplicationRestrictionsManagingPackage(
1363 admin1, nonExistAppRestrictionsManagerPackage));
1365 // Let appRestrictionsManagerPackage manage app restrictions
1366 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1367 assertEquals(appRestrictionsManagerPackage,
1368 dpm.getApplicationRestrictionsManagingPackage(admin1));
1370 // Now that package should be able to set and retrieve app restrictions.
1371 mContext.binder.callingUid = appRestrictionsManagerUid;
1372 mContext.packageName = appRestrictionsManagerPackage;
1373 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1374 dpm.setApplicationRestrictions(null, "pkg1", rest);
1375 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1376 assertEquals(1, returned.size(), 1);
1377 assertEquals("Foo1", returned.get("KEY_STRING"));
1379 // The same app running on a separate user shouldn't be able to manage app restrictions.
1380 mContext.binder.callingUid = UserHandle.getUid(
1381 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1382 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1383 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1384 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
1386 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1388 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1389 mContext.packageName = admin1.getPackageName();
1390 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1391 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1392 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1394 // Removing the ability for the package to manage app restrictions.
1395 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1396 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1397 mContext.binder.callingUid = appRestrictionsManagerUid;
1398 mContext.packageName = appRestrictionsManagerPackage;
1399 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1400 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1401 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
1404 public void testSetUserRestriction_asDo() throws Exception {
1405 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1406 mContext.callerPermissions.add(permission.MANAGE_USERS);
1407 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1408 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1412 // Call from a process on the system user.
1413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1415 // Make sure admin1 is installed on system user.
1416 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1419 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1420 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1421 UserHandle.USER_SYSTEM));
1423 // Check that the user restrictions that are enabled by default are set. Then unset them.
1424 final String[] defaultRestrictions = UserRestrictionsUtils
1425 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1426 DpmTestUtils.assertRestrictions(
1427 DpmTestUtils.newRestrictions(defaultRestrictions),
1428 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1430 DpmTestUtils.assertRestrictions(
1431 DpmTestUtils.newRestrictions(defaultRestrictions),
1432 dpm.getUserRestrictions(admin1)
1434 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1435 eq(UserHandle.USER_SYSTEM),
1436 MockUtils.checkUserRestrictions(defaultRestrictions),
1437 eq(true) /* isDeviceOwner */,
1438 eq(CAMERA_NOT_DISABLED)
1440 reset(getServices().userManagerInternal);
1442 for (String restriction : defaultRestrictions) {
1443 dpm.clearUserRestriction(admin1, restriction);
1446 assertNoDeviceOwnerRestrictions();
1447 reset(getServices().userManagerInternal);
1449 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1450 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1451 eq(UserHandle.USER_SYSTEM),
1452 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1453 eq(true), eq(CAMERA_NOT_DISABLED));
1454 reset(getServices().userManagerInternal);
1456 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1457 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1458 eq(UserHandle.USER_SYSTEM),
1459 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1460 UserManager.DISALLOW_ADD_USER),
1461 eq(true), eq(CAMERA_NOT_DISABLED));
1462 reset(getServices().userManagerInternal);
1464 DpmTestUtils.assertRestrictions(
1465 DpmTestUtils.newRestrictions(
1466 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1467 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1469 DpmTestUtils.assertRestrictions(
1470 DpmTestUtils.newRestrictions(
1471 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
1472 dpm.getUserRestrictions(admin1)
1475 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1476 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1477 eq(UserHandle.USER_SYSTEM),
1478 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1479 eq(true), eq(CAMERA_NOT_DISABLED));
1480 reset(getServices().userManagerInternal);
1482 DpmTestUtils.assertRestrictions(
1483 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1484 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1486 DpmTestUtils.assertRestrictions(
1487 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1488 dpm.getUserRestrictions(admin1)
1491 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1492 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1493 eq(UserHandle.USER_SYSTEM),
1494 MockUtils.checkUserRestrictions(),
1495 eq(true), eq(CAMERA_NOT_DISABLED));
1496 reset(getServices().userManagerInternal);
1498 assertNoDeviceOwnerRestrictions();
1500 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1501 // DO sets them, the scope is global.
1502 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1503 reset(getServices().userManagerInternal);
1504 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1505 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1506 eq(UserHandle.USER_SYSTEM),
1507 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1508 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1509 eq(true), eq(CAMERA_NOT_DISABLED));
1510 reset(getServices().userManagerInternal);
1512 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1513 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1514 reset(getServices().userManagerInternal);
1517 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1518 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1519 eq(UserHandle.USER_SYSTEM),
1520 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1521 eq(true), eq(CAMERA_NOT_DISABLED));
1522 reset(getServices().userManagerInternal);
1524 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1525 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1526 eq(UserHandle.USER_SYSTEM),
1527 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1528 UserManager.DISALLOW_ADD_USER),
1529 eq(true), eq(CAMERA_NOT_DISABLED));
1530 reset(getServices().userManagerInternal);
1532 dpm.setCameraDisabled(admin1, true);
1533 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1534 eq(UserHandle.USER_SYSTEM),
1535 // DISALLOW_CAMERA will be applied to both local and global.
1536 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1537 UserManager.DISALLOW_ADD_USER),
1538 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
1539 reset(getServices().userManagerInternal);
1541 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1543 dpm.setCameraDisabled(admin1, false);
1544 reset(getServices().userManagerInternal);
1546 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1547 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1548 dpm.setCameraDisabled(admin2, true);
1550 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1551 eq(UserHandle.USER_SYSTEM),
1552 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
1553 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1554 UserManager.DISALLOW_ADD_USER),
1555 eq(true), eq(CAMERA_DISABLED_LOCALLY));
1556 reset(getServices().userManagerInternal);
1557 // TODO Make sure restrictions are written to the file.
1560 public void testSetUserRestriction_asPo() {
1561 setAsProfileOwner(admin1);
1563 DpmTestUtils.assertRestrictions(
1564 DpmTestUtils.newRestrictions(),
1565 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1566 .ensureUserRestrictions()
1569 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1570 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1571 eq(DpmMockContext.CALLER_USER_HANDLE),
1572 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1573 eq(false), eq(CAMERA_NOT_DISABLED));
1574 reset(getServices().userManagerInternal);
1576 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1577 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1578 eq(DpmMockContext.CALLER_USER_HANDLE),
1579 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1580 UserManager.DISALLOW_OUTGOING_CALLS),
1581 eq(false), eq(CAMERA_NOT_DISABLED));
1582 reset(getServices().userManagerInternal);
1584 DpmTestUtils.assertRestrictions(
1585 DpmTestUtils.newRestrictions(
1586 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1587 UserManager.DISALLOW_OUTGOING_CALLS
1589 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1590 .ensureUserRestrictions()
1592 DpmTestUtils.assertRestrictions(
1593 DpmTestUtils.newRestrictions(
1594 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1595 UserManager.DISALLOW_OUTGOING_CALLS
1597 dpm.getUserRestrictions(admin1)
1600 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1601 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1602 eq(DpmMockContext.CALLER_USER_HANDLE),
1603 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1604 eq(false), eq(CAMERA_NOT_DISABLED));
1605 reset(getServices().userManagerInternal);
1607 DpmTestUtils.assertRestrictions(
1608 DpmTestUtils.newRestrictions(
1609 UserManager.DISALLOW_OUTGOING_CALLS
1611 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1612 .ensureUserRestrictions()
1614 DpmTestUtils.assertRestrictions(
1615 DpmTestUtils.newRestrictions(
1616 UserManager.DISALLOW_OUTGOING_CALLS
1618 dpm.getUserRestrictions(admin1)
1621 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
1622 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1623 eq(DpmMockContext.CALLER_USER_HANDLE),
1624 MockUtils.checkUserRestrictions(),
1625 eq(false), eq(CAMERA_NOT_DISABLED));
1626 reset(getServices().userManagerInternal);
1628 DpmTestUtils.assertRestrictions(
1629 DpmTestUtils.newRestrictions(),
1630 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1631 .ensureUserRestrictions()
1633 DpmTestUtils.assertRestrictions(
1634 DpmTestUtils.newRestrictions(),
1635 dpm.getUserRestrictions(admin1)
1638 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1639 // though when DO sets them they'll be applied globally.
1640 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1641 reset(getServices().userManagerInternal);
1642 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1643 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1644 eq(DpmMockContext.CALLER_USER_HANDLE),
1645 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1646 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1647 eq(false), eq(CAMERA_NOT_DISABLED));
1648 reset(getServices().userManagerInternal);
1650 dpm.setCameraDisabled(admin1, true);
1651 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1652 eq(DpmMockContext.CALLER_USER_HANDLE),
1653 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1654 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1655 eq(false), eq(CAMERA_DISABLED_LOCALLY));
1656 reset(getServices().userManagerInternal);
1658 // TODO Make sure restrictions are written to the file.
1662 public void testDefaultEnabledUserRestrictions() throws Exception {
1663 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1664 mContext.callerPermissions.add(permission.MANAGE_USERS);
1665 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1666 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1670 // Call from a process on the system user.
1671 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1673 // Make sure admin1 is installed on system user.
1674 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1676 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1677 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1678 UserHandle.USER_SYSTEM));
1680 // Check that the user restrictions that are enabled by default are set. Then unset them.
1681 String[] defaultRestrictions = UserRestrictionsUtils
1682 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1683 assertTrue(defaultRestrictions.length > 0);
1684 DpmTestUtils.assertRestrictions(
1685 DpmTestUtils.newRestrictions(defaultRestrictions),
1686 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1688 DpmTestUtils.assertRestrictions(
1689 DpmTestUtils.newRestrictions(defaultRestrictions),
1690 dpm.getUserRestrictions(admin1)
1692 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1693 eq(UserHandle.USER_SYSTEM),
1694 MockUtils.checkUserRestrictions(defaultRestrictions),
1695 eq(true) /* isDeviceOwner */,
1696 eq(CAMERA_NOT_DISABLED)
1698 reset(getServices().userManagerInternal);
1700 for (String restriction : defaultRestrictions) {
1701 dpm.clearUserRestriction(admin1, restriction);
1704 assertNoDeviceOwnerRestrictions();
1706 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1707 reset(getServices().userManagerInternal);
1709 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1710 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1712 assertNoDeviceOwnerRestrictions();
1714 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1715 // is set as it wasn't enabled during setDeviceOwner.
1716 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1717 assertFalse(UserRestrictionsUtils
1718 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1719 UserRestrictionsUtils
1720 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1722 reset(getServices().userManagerInternal);
1724 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1725 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1727 DpmTestUtils.assertRestrictions(
1728 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1729 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1733 dpm.getUserRestrictions(admin1)
1735 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1736 eq(UserHandle.USER_SYSTEM),
1737 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
1738 eq(true) /* isDeviceOwner */,
1739 eq(CAMERA_NOT_DISABLED)
1741 reset(getServices().userManagerInternal);
1743 // Remove the restriction.
1744 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1746 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1748 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1749 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1750 assertNoDeviceOwnerRestrictions();
1752 UserRestrictionsUtils
1753 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1757 private void assertNoDeviceOwnerRestrictions() {
1758 DpmTestUtils.assertRestrictions(
1759 DpmTestUtils.newRestrictions(),
1760 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1762 DpmTestUtils.assertRestrictions(
1763 DpmTestUtils.newRestrictions(),
1764 dpm.getUserRestrictions(admin1)
1768 public void testGetMacAddress() throws Exception {
1769 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1770 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1771 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1773 // In this test, change the caller user to "system".
1774 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1776 // Make sure admin1 is installed on system user.
1777 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1779 // Test 1. Caller doesn't have DO or DA.
1780 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1781 () -> dpm.getWifiMacAddress(admin1));
1783 // DO needs to be an DA.
1784 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1785 assertTrue(dpm.isAdminActive(admin1));
1787 // Test 2. Caller has DA, but not DO.
1788 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1789 () -> dpm.getWifiMacAddress(admin1));
1791 // Test 3. Caller has PO, but not DO.
1792 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1793 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1794 () -> dpm.getWifiMacAddress(admin1));
1797 dpm.clearProfileOwner(admin1);
1798 dpm.setActiveAdmin(admin1, false);
1799 // Test 4, Caller is DO now.
1800 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1802 // 4-1. But no WifiInfo.
1803 assertNull(dpm.getWifiMacAddress(admin1));
1805 // 4-2. Returns WifiInfo, but with the default MAC.
1806 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
1807 assertNull(dpm.getWifiMacAddress(admin1));
1809 // 4-3. With a real MAC address.
1810 final WifiInfo wi = new WifiInfo();
1811 wi.setMacAddress("11:22:33:44:55:66");
1812 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
1813 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
1816 public void testReboot() throws Exception {
1817 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1818 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1820 // In this test, change the caller user to "system".
1821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1823 // Make sure admin1 is installed on system user.
1824 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1826 // Set admin1 as DA.
1827 dpm.setActiveAdmin(admin1, false);
1828 assertTrue(dpm.isAdminActive(admin1));
1829 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1830 () -> dpm.reboot(admin1));
1832 // Set admin1 as PO.
1833 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1834 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1835 () -> dpm.reboot(admin1));
1837 // Remove PO and add DO.
1838 dpm.clearProfileOwner(admin1);
1839 dpm.setActiveAdmin(admin1, false);
1840 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1843 // Set current call state of device to ringing.
1844 when(getServices().telephonyManager.getCallState())
1845 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1846 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1847 () -> dpm.reboot(admin1));
1849 // Set current call state of device to dialing/active.
1850 when(getServices().telephonyManager.getCallState())
1851 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1852 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1853 () -> dpm.reboot(admin1));
1855 // Set current call state of device to idle.
1856 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
1860 public void testSetGetSupportText() {
1861 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1862 dpm.setActiveAdmin(admin1, true);
1863 dpm.setActiveAdmin(admin2, true);
1864 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1866 // Null default support messages.
1868 assertNull(dpm.getLongSupportMessage(admin1));
1869 assertNull(dpm.getShortSupportMessage(admin1));
1870 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1871 assertNull(dpm.getShortSupportMessageForUser(admin1,
1872 DpmMockContext.CALLER_USER_HANDLE));
1873 assertNull(dpm.getLongSupportMessageForUser(admin1,
1874 DpmMockContext.CALLER_USER_HANDLE));
1875 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1878 // Only system can call the per user versions.
1880 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1881 () -> dpm.getShortSupportMessageForUser(admin1,
1882 DpmMockContext.CALLER_USER_HANDLE));
1883 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
1884 () -> dpm.getLongSupportMessageForUser(admin1,
1885 DpmMockContext.CALLER_USER_HANDLE));
1888 // Can't set message for admin in another uid.
1890 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1891 assertExpectException(SecurityException.class,
1892 /* messageRegex= */ "is not owned by uid",
1893 () -> dpm.setShortSupportMessage(admin1, "Some text"));
1894 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1897 // Set/Get short returns what it sets and other admins text isn't changed.
1899 final String supportText = "Some text to test with.";
1900 dpm.setShortSupportMessage(admin1, supportText);
1901 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1902 assertNull(dpm.getLongSupportMessage(admin1));
1903 assertNull(dpm.getShortSupportMessage(admin2));
1905 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1906 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1907 DpmMockContext.CALLER_USER_HANDLE));
1908 assertNull(dpm.getShortSupportMessageForUser(admin2,
1909 DpmMockContext.CALLER_USER_HANDLE));
1910 assertNull(dpm.getLongSupportMessageForUser(admin1,
1911 DpmMockContext.CALLER_USER_HANDLE));
1912 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1914 dpm.setShortSupportMessage(admin1, null);
1915 assertNull(dpm.getShortSupportMessage(admin1));
1918 // Set/Get long returns what it sets and other admins text isn't changed.
1920 final String supportText = "Some text to test with.\nWith more text.";
1921 dpm.setLongSupportMessage(admin1, supportText);
1922 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1923 assertNull(dpm.getShortSupportMessage(admin1));
1924 assertNull(dpm.getLongSupportMessage(admin2));
1926 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1927 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1928 DpmMockContext.CALLER_USER_HANDLE));
1929 assertNull(dpm.getLongSupportMessageForUser(admin2,
1930 DpmMockContext.CALLER_USER_HANDLE));
1931 assertNull(dpm.getShortSupportMessageForUser(admin1,
1932 DpmMockContext.CALLER_USER_HANDLE));
1933 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1935 dpm.setLongSupportMessage(admin1, null);
1936 assertNull(dpm.getLongSupportMessage(admin1));
1940 public void testCreateAdminSupportIntent() throws Exception {
1941 // Setup device owner.
1942 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1945 // Nonexisting permission returns null
1946 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
1949 // Existing permission that is not set returns null
1950 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1953 // Existing permission that is not set by device/profile owner returns null
1954 when(getServices().userManager.hasUserRestriction(
1955 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1956 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1958 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1961 // Permission that is set by device owner returns correct intent
1962 when(getServices().userManager.getUserRestrictionSource(
1963 eq(UserManager.DISALLOW_ADJUST_VOLUME),
1964 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
1965 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
1966 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
1967 assertNotNull(intent);
1968 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
1969 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
1970 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
1971 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
1972 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
1973 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1975 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
1976 // user restrictions
1978 // Camera is not disabled
1979 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1982 // Camera is disabled
1983 dpm.setCameraDisabled(admin1, true);
1984 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
1985 assertNotNull(intent);
1986 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
1987 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
1989 // Screen capture is not disabled
1990 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1993 // Screen capture is disabled
1994 dpm.setScreenCaptureDisabled(admin1, true);
1995 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
1996 assertNotNull(intent);
1997 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
1998 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2000 // Same checks for different user
2001 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2002 // Camera should be disabled by device owner
2003 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2004 assertNotNull(intent);
2005 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2006 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2007 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2008 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2009 // ScreenCapture should not be disabled by device owner
2010 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2016 * {@link DevicePolicyManager#setAffiliationIds}
2017 * {@link DevicePolicyManager#getAffiliationIds}
2018 * {@link DevicePolicyManager#isAffiliatedUser}
2020 public void testUserAffiliation() throws Exception {
2021 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2022 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2023 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2025 // Check that the system user is unaffiliated.
2026 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2027 assertFalse(dpm.isAffiliatedUser());
2029 // Set a device owner on the system user. Check that the system user becomes affiliated.
2030 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2031 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2032 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2033 assertTrue(dpm.isAffiliatedUser());
2034 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
2036 // Install a profile owner. Check that the test user is unaffiliated.
2037 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2038 setAsProfileOwner(admin2);
2039 assertFalse(dpm.isAffiliatedUser());
2040 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
2042 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2044 final Set<String> userAffiliationIds = new ArraySet<>();
2045 userAffiliationIds.add("red");
2046 userAffiliationIds.add("green");
2047 userAffiliationIds.add("blue");
2048 dpm.setAffiliationIds(admin2, userAffiliationIds);
2049 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
2050 assertFalse(dpm.isAffiliatedUser());
2052 // Have the device owner specify a set of affiliation ids that do not intersect with those
2053 // specified by the profile owner. Check that the test user remains unaffiliated.
2054 final Set<String> deviceAffiliationIds = new ArraySet<>();
2055 deviceAffiliationIds.add("cyan");
2056 deviceAffiliationIds.add("yellow");
2057 deviceAffiliationIds.add("magenta");
2058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2059 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
2060 MoreAsserts.assertContentsInAnyOrder(
2061 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
2062 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2063 assertFalse(dpm.isAffiliatedUser());
2065 // Have the profile owner specify a set of affiliation ids that intersect with those
2066 // specified by the device owner. Check that the test user becomes affiliated.
2067 userAffiliationIds.add("yellow");
2068 dpm.setAffiliationIds(admin2, userAffiliationIds);
2069 MoreAsserts.assertContentsInAnyOrder(
2070 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
2071 assertTrue(dpm.isAffiliatedUser());
2073 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2074 dpm.setAffiliationIds(admin2, Collections.emptySet());
2075 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
2076 assertFalse(dpm.isAffiliatedUser());
2078 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2079 dpm.setAffiliationIds(admin2, userAffiliationIds);
2080 assertTrue(dpm.isAffiliatedUser());
2081 dpm.clearProfileOwner(admin2);
2082 assertFalse(dpm.isAffiliatedUser());
2084 // Check that the system user remains affiliated.
2085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2086 assertTrue(dpm.isAffiliatedUser());
2088 // Clear the device owner - the user becomes unaffiliated.
2090 assertFalse(dpm.isAffiliatedUser());
2093 public void testGetUserProvisioningState_defaultResult() {
2094 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2097 public void testSetUserProvisioningState_permission() throws Exception {
2098 setupProfileOwner();
2099 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2101 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2102 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2105 public void testSetUserProvisioningState_unprivileged() throws Exception {
2106 setupProfileOwner();
2107 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2108 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2109 DpmMockContext.CALLER_USER_HANDLE));
2112 public void testSetUserProvisioningState_noManagement() {
2113 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2114 assertExpectException(IllegalStateException.class,
2115 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2116 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2117 DpmMockContext.CALLER_USER_HANDLE));
2118 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2121 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2122 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2124 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2126 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2127 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2128 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2131 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2133 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2137 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2138 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2139 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2142 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2143 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2145 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2147 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2148 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2151 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2153 setupProfileOwner();
2154 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2156 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2157 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2158 DevicePolicyManager.STATE_USER_UNMANAGED);
2161 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2163 setupProfileOwner();
2164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2166 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2167 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2168 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2171 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2172 setupProfileOwner();
2173 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2175 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2176 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2179 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2180 setupProfileOwner();
2181 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2183 assertExpectException(IllegalStateException.class,
2184 /* messageRegex= */ "Cannot move to user provisioning state",
2185 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2186 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2187 DevicePolicyManager.STATE_USER_UNMANAGED));
2190 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2192 setupProfileOwner();
2193 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2195 assertExpectException(IllegalStateException.class,
2196 /* messageRegex= */ "Cannot move to user provisioning state",
2197 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2198 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2199 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
2202 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2203 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2204 for (int state : states) {
2205 dpm.setUserProvisioningState(state, userId);
2206 assertEquals(state, dpm.getUserProvisioningState());
2210 private void setupProfileOwner() throws Exception {
2211 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2213 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2214 dpm.setActiveAdmin(admin1, false);
2215 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2217 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2220 private void setupDeviceOwner() throws Exception {
2221 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2223 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2224 dpm.setActiveAdmin(admin1, false);
2225 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2227 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2230 public void testSetMaximumTimeToLock() {
2231 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2233 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2234 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2236 reset(getServices().powerManagerInternal);
2237 reset(getServices().settings);
2239 dpm.setMaximumTimeToLock(admin1, 0);
2240 verifyScreenTimeoutCall(null, false);
2241 reset(getServices().powerManagerInternal);
2242 reset(getServices().settings);
2244 dpm.setMaximumTimeToLock(admin1, 1);
2245 verifyScreenTimeoutCall(1, true);
2246 reset(getServices().powerManagerInternal);
2247 reset(getServices().settings);
2249 dpm.setMaximumTimeToLock(admin2, 10);
2250 verifyScreenTimeoutCall(null, false);
2251 reset(getServices().powerManagerInternal);
2252 reset(getServices().settings);
2254 dpm.setMaximumTimeToLock(admin1, 5);
2255 verifyScreenTimeoutCall(5, true);
2256 reset(getServices().powerManagerInternal);
2257 reset(getServices().settings);
2259 dpm.setMaximumTimeToLock(admin2, 4);
2260 verifyScreenTimeoutCall(4, true);
2261 reset(getServices().powerManagerInternal);
2262 reset(getServices().settings);
2264 dpm.setMaximumTimeToLock(admin1, 0);
2265 reset(getServices().powerManagerInternal);
2266 reset(getServices().settings);
2268 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2269 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2270 reset(getServices().powerManagerInternal);
2271 reset(getServices().settings);
2273 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2274 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2275 reset(getServices().powerManagerInternal);
2276 reset(getServices().settings);
2278 dpm.setMaximumTimeToLock(admin2, 10);
2279 verifyScreenTimeoutCall(10, true);
2280 reset(getServices().powerManagerInternal);
2281 reset(getServices().settings);
2283 // There's no restriction; shold be set to MAX.
2284 dpm.setMaximumTimeToLock(admin2, 0);
2285 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2288 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2291 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2293 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2294 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2295 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2296 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2299 // verify that the minimum timeout cannot be modified on user builds (system property is
2301 getServices().buildMock.isDebuggable = false;
2303 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2304 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2305 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2307 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
2309 // restore to the debuggable build state
2310 getServices().buildMock.isDebuggable = true;
2312 // Always return the default (second arg) when getting system property for long type
2313 when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2314 invocation -> invocation.getArguments()[1]
2317 // reset to default (0 means the admin is not participating, so default should be returned)
2318 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2320 // aggregation should be the default if unset by any admin
2321 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2322 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2324 // admin not participating by default
2325 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2327 //clamping from the top
2328 dpm.setRequiredStrongAuthTimeout(admin1,
2329 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2330 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2331 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2332 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2333 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2335 // 0 means the admin is not participating, so default should be returned
2336 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2337 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2338 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2339 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2341 // clamping from the bottom
2342 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2343 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2344 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2346 // values within range
2347 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2348 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2349 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2351 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2352 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2353 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2356 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2357 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2358 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2359 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2362 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2363 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
2366 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2367 boolean shouldStayOnWhilePluggedInBeCleared) {
2368 if (expectedTimeout == null) {
2369 verify(getServices().powerManagerInternal, times(0))
2370 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2372 verify(getServices().powerManagerInternal, times(1))
2373 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2375 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2376 // UnfinishedVerificationException.
2379 private void setup_DeviceAdminFeatureOff() throws Exception {
2380 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2382 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2385 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2386 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2388 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2390 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2393 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2394 setup_DeviceAdminFeatureOff();
2395 mContext.packageName = admin1.getPackageName();
2396 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2397 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2398 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2399 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2401 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2404 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2405 setup_DeviceAdminFeatureOff();
2406 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2407 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2408 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2409 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2410 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2411 assertCheckProvisioningPreCondition(
2412 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2413 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2414 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2415 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2418 private void setup_ManagedProfileFeatureOff() throws Exception {
2419 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2422 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2423 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2425 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2427 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2430 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2431 setup_ManagedProfileFeatureOff();
2432 mContext.packageName = admin1.getPackageName();
2433 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2434 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2435 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2438 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2440 // Test again when split user is on
2441 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2442 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2443 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2444 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2449 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2450 setup_ManagedProfileFeatureOff();
2451 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2452 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2453 DevicePolicyManager.CODE_OK);
2454 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2455 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2456 assertCheckProvisioningPreCondition(
2457 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2458 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2459 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2460 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2462 // Test again when split user is on
2463 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2464 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2465 DevicePolicyManager.CODE_OK);
2466 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2467 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2468 assertCheckProvisioningPreCondition(
2469 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2470 DevicePolicyManager.CODE_OK);
2471 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2472 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2475 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
2476 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2478 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2479 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2481 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2486 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2487 setup_nonSplitUser_firstBoot_primaryUser();
2488 mContext.packageName = admin1.getPackageName();
2489 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2490 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2491 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2492 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2493 false /* because of non-split user */);
2494 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2495 false /* because of non-split user */);
2498 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
2500 setup_nonSplitUser_firstBoot_primaryUser();
2501 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2502 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2503 DevicePolicyManager.CODE_OK);
2504 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2505 DevicePolicyManager.CODE_OK);
2506 assertCheckProvisioningPreCondition(
2507 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2508 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2509 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2510 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2513 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
2514 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2516 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2517 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2519 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2521 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2524 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2526 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2527 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2530 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2531 setup_nonSplitUser_withDo_primaryUser();
2532 final int MANAGED_PROFILE_USER_ID = 18;
2533 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2534 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2535 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2536 false /* we can't remove a managed profile */)).thenReturn(false);
2537 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2538 true)).thenReturn(true);
2541 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2543 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2544 mContext.packageName = admin1.getPackageName();
2545 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2546 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2547 false/* because of completed device setup */);
2548 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2549 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2550 false/* because of non-split user */);
2551 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2552 false/* because of non-split user */);
2555 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2557 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2558 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2559 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2560 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2561 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2562 DevicePolicyManager.CODE_OK);
2563 assertCheckProvisioningPreCondition(
2564 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2565 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2566 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2567 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2570 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2571 setup_nonSplitUser_withDo_primaryUser();
2572 mContext.packageName = admin1.getPackageName();
2573 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2575 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2576 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2577 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2579 // COMP mode is allowed.
2580 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2581 DevicePolicyManager.CODE_OK);
2582 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2584 // And other DPCs can also provision a managed profile (DO + BYOD case).
2585 assertCheckProvisioningPreCondition(
2586 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2587 DpmMockContext.ANOTHER_PACKAGE_NAME,
2588 DevicePolicyManager.CODE_OK);
2589 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2590 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2593 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2594 setup_nonSplitUser_withDo_primaryUser();
2595 mContext.packageName = admin1.getPackageName();
2596 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2597 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2598 // other packages should be forbidden.
2599 when(getServices().userManager.hasUserRestriction(
2600 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2601 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2603 when(getServices().userManager.getUserRestrictionSource(
2604 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2605 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2606 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2607 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2608 DevicePolicyManager.CODE_OK);
2609 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2610 assertCheckProvisioningPreCondition(
2611 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2612 DpmMockContext.ANOTHER_PACKAGE_NAME,
2613 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2614 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2615 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2618 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2620 setup_nonSplitUser_withDo_primaryUser();
2621 mContext.packageName = admin1.getPackageName();
2622 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2623 // The DO should not be allowed to initiate provisioning if the restriction is set by
2625 when(getServices().userManager.hasUserRestriction(
2626 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2627 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2629 when(getServices().userManager.getUserRestrictionSource(
2630 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2631 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2632 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2633 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2634 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2635 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2637 assertCheckProvisioningPreCondition(
2638 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2639 DpmMockContext.ANOTHER_PACKAGE_NAME,
2640 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2641 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2642 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2645 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2646 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2647 mContext.packageName = admin1.getPackageName();
2648 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2650 // We can delete the managed profile to create a new one, so provisioning is allowed.
2651 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2652 DevicePolicyManager.CODE_OK);
2653 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2654 assertCheckProvisioningPreCondition(
2655 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2656 DpmMockContext.ANOTHER_PACKAGE_NAME,
2657 DevicePolicyManager.CODE_OK);
2658 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2659 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2662 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2664 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2665 mContext.packageName = admin1.getPackageName();
2666 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2667 when(getServices().userManager.hasUserRestriction(
2668 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2669 eq(UserHandle.SYSTEM)))
2671 when(getServices().userManager.getUserRestrictionSource(
2672 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2673 eq(UserHandle.SYSTEM)))
2674 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2676 // We can't remove the profile to create a new one.
2677 assertCheckProvisioningPreCondition(
2678 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2679 DpmMockContext.ANOTHER_PACKAGE_NAME,
2680 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2681 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2682 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2684 // But the device owner can still do it because it has set the restriction itself.
2685 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2686 DevicePolicyManager.CODE_OK);
2687 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2690 private void setup_splitUser_firstBoot_systemUser() throws Exception {
2691 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2693 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2694 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2696 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2698 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2701 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2702 setup_splitUser_firstBoot_systemUser();
2703 mContext.packageName = admin1.getPackageName();
2704 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2705 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2707 false /* because canAddMoreManagedProfiles returns false */);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2710 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2711 false/* because calling uid is system user */);
2714 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2716 setup_splitUser_firstBoot_systemUser();
2717 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2718 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2719 DevicePolicyManager.CODE_OK);
2720 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2721 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2722 assertCheckProvisioningPreCondition(
2723 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2724 DevicePolicyManager.CODE_OK);
2725 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2726 DevicePolicyManager.CODE_SYSTEM_USER);
2729 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
2730 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2732 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2733 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2735 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2737 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2740 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2741 setup_splitUser_afterDeviceSetup_systemUser();
2742 mContext.packageName = admin1.getPackageName();
2743 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2745 true/* it's undefined behavior. Can be changed into false in the future */);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2747 false /* because canAddMoreManagedProfiles returns false */);
2748 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2749 true/* it's undefined behavior. Can be changed into false in the future */);
2750 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2751 false/* because calling uid is system user */);
2754 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2756 setup_splitUser_afterDeviceSetup_systemUser();
2757 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2759 DevicePolicyManager.CODE_OK);
2760 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2761 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2762 assertCheckProvisioningPreCondition(
2763 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2764 DevicePolicyManager.CODE_OK);
2765 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2766 DevicePolicyManager.CODE_SYSTEM_USER);
2769 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
2770 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2772 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2773 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2774 true)).thenReturn(true);
2775 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2777 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2780 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2781 setup_splitUser_firstBoot_primaryUser();
2782 mContext.packageName = admin1.getPackageName();
2783 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2785 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2791 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
2793 setup_splitUser_firstBoot_primaryUser();
2794 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2795 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2796 DevicePolicyManager.CODE_OK);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(
2800 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2801 DevicePolicyManager.CODE_OK);
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2803 DevicePolicyManager.CODE_OK);
2806 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
2807 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2809 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2810 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2811 true)).thenReturn(true);
2812 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2814 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2817 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2819 setup_splitUser_afterDeviceSetup_primaryUser();
2820 mContext.packageName = admin1.getPackageName();
2821 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2822 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2823 true/* it's undefined behavior. Can be changed into false in the future */);
2824 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2825 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2826 true/* it's undefined behavior. Can be changed into false in the future */);
2827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2828 false/* because user setup completed */);
2831 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
2833 setup_splitUser_afterDeviceSetup_primaryUser();
2834 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2835 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2836 DevicePolicyManager.CODE_OK);
2837 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2838 DevicePolicyManager.CODE_OK);
2839 assertCheckProvisioningPreCondition(
2840 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2841 DevicePolicyManager.CODE_OK);
2842 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2843 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2846 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
2849 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2851 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2852 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2854 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2856 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2859 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2861 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2862 mContext.packageName = admin1.getPackageName();
2863 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2865 false /* can't provision managed profile on system user */);
2868 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
2870 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2871 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2872 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2873 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2876 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
2879 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2881 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2882 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2883 true)).thenReturn(true);
2884 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2886 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2889 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2891 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2892 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2893 mContext.packageName = admin1.getPackageName();
2894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2897 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
2899 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2900 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2902 // COMP mode is allowed.
2903 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2904 DevicePolicyManager.CODE_OK);
2907 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
2910 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2912 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2913 when(getServices().userManager.hasUserRestriction(
2914 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2915 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
2917 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2918 false /* we can't remove a managed profile */)).thenReturn(false);
2919 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2920 true)).thenReturn(true);
2921 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2923 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2926 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2928 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2929 mContext.packageName = admin1.getPackageName();
2930 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2931 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2934 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2936 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2937 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2938 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2939 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2942 public void testCheckProvisioningPreCondition_permission() {
2943 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2944 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2945 () -> dpm.checkProvisioningPreCondition(
2946 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
2949 public void testForceUpdateUserSetupComplete_permission() {
2950 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2951 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2952 () -> dpm.forceUpdateUserSetupComplete());
2955 public void testForceUpdateUserSetupComplete_systemUser() {
2956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2957 // GIVEN calling from user 20
2958 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2959 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2960 () -> dpm.forceUpdateUserSetupComplete());
2963 public void testForceUpdateUserSetupComplete_userbuild() {
2964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2967 final int userId = UserHandle.USER_SYSTEM;
2968 // GIVEN userComplete is false in SettingsProvider
2969 setUserSetupCompleteForUser(false, userId);
2971 // GIVEN userComplete is true in DPM
2972 DevicePolicyManagerService.DevicePolicyData userData =
2973 new DevicePolicyManagerService.DevicePolicyData(userId);
2974 userData.mUserSetupComplete = true;
2975 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2977 // GIVEN it's user build
2978 getServices().buildMock.isDebuggable = false;
2980 assertTrue(dpms.hasUserSetupCompleted());
2982 dpm.forceUpdateUserSetupComplete();
2984 // THEN the state in dpms is not changed
2985 assertTrue(dpms.hasUserSetupCompleted());
2988 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2989 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2990 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2992 final int userId = UserHandle.USER_SYSTEM;
2993 // GIVEN userComplete is false in SettingsProvider
2994 setUserSetupCompleteForUser(false, userId);
2996 // GIVEN userComplete is true in DPM
2997 DevicePolicyManagerService.DevicePolicyData userData =
2998 new DevicePolicyManagerService.DevicePolicyData(userId);
2999 userData.mUserSetupComplete = true;
3000 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3002 // GIVEN it's userdebug build
3003 getServices().buildMock.isDebuggable = true;
3005 assertTrue(dpms.hasUserSetupCompleted());
3007 dpm.forceUpdateUserSetupComplete();
3009 // THEN the state in dpms is not changed
3010 assertFalse(dpms.hasUserSetupCompleted());
3013 private void clearDeviceOwner() throws Exception {
3014 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
3015 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3017 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3018 runAsCaller(mAdmin1Context, dpms, dpm -> {
3019 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3023 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3024 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3027 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3028 // feature is disabled because there are non-affiliated secondary users.
3029 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3030 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3033 // No logs were retrieved so far.
3034 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3036 // Enabling logging should not change the timestamp.
3037 dpm.setSecurityLoggingEnabled(admin1, true);
3038 verify(getServices().settings)
3039 .securityLogSetLoggingEnabledProperty(true);
3040 when(getServices().settings.securityLogGetLoggingEnabledProperty())
3042 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3044 // Retrieving the logs should update the timestamp.
3045 final long beforeRetrieval = System.currentTimeMillis();
3046 dpm.retrieveSecurityLogs(admin1);
3047 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3048 final long afterRetrieval = System.currentTimeMillis();
3049 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3050 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3052 // Retrieving the pre-boot logs should update the timestamp.
3054 dpm.retrievePreRebootSecurityLogs(admin1);
3055 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3056 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3058 // Checking the timestamp again should not change it.
3060 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3062 // Retrieving the logs again should update the timestamp.
3063 dpm.retrieveSecurityLogs(admin1);
3064 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
3065 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3067 // Disabling logging should not change the timestamp.
3069 dpm.setSecurityLoggingEnabled(admin1, false);
3070 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3072 // Restarting the DPMS should not lose the timestamp.
3074 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3076 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3077 mContext.binder.callingUid = 1234567;
3078 mContext.callerPermissions.add(permission.MANAGE_USERS);
3079 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3080 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3082 // System can retrieve the timestamp.
3083 mContext.binder.clearCallingIdentity();
3084 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3086 // Removing the device owner should clear the timestamp.
3088 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
3091 public void testGetLastBugReportRequestTime() throws Exception {
3092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3095 mContext.packageName = admin1.getPackageName();
3096 mContext.applicationInfo = new ApplicationInfo();
3097 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3098 .thenReturn(Color.WHITE);
3099 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3100 anyObject())).thenReturn(Color.WHITE);
3102 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3103 // feature is disabled because there are non-affiliated secondary users.
3104 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3106 // No bug reports were requested so far.
3107 assertEquals(-1, dpm.getLastBugReportRequestTime());
3109 // Requesting a bug report should update the timestamp.
3110 final long beforeRequest = System.currentTimeMillis();
3111 dpm.requestBugreport(admin1);
3112 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
3113 final long afterRequest = System.currentTimeMillis();
3114 assertTrue(bugReportRequestTime >= beforeRequest);
3115 assertTrue(bugReportRequestTime <= afterRequest);
3117 // Checking the timestamp again should not change it.
3119 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3121 // Restarting the DPMS should not lose the timestamp.
3123 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3125 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3126 mContext.binder.callingUid = 1234567;
3127 mContext.callerPermissions.add(permission.MANAGE_USERS);
3128 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3129 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3131 // System can retrieve the timestamp.
3132 mContext.binder.clearCallingIdentity();
3133 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3135 // Removing the device owner should clear the timestamp.
3137 assertEquals(-1, dpm.getLastBugReportRequestTime());
3140 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3141 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3143 mContext.packageName = admin1.getPackageName();
3144 mContext.applicationInfo = new ApplicationInfo();
3145 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3146 .thenReturn(Color.WHITE);
3147 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3148 anyObject())).thenReturn(Color.WHITE);
3150 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3151 // feature is disabled because there are non-affiliated secondary users.
3152 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
3153 when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3156 // No logs were retrieved so far.
3157 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3159 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3160 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3161 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3163 // Enabling logging should not change the timestamp.
3164 dpm.setNetworkLoggingEnabled(admin1, true);
3165 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3167 // Retrieving the logs should update the timestamp.
3168 final long beforeRetrieval = System.currentTimeMillis();
3169 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3170 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
3171 final long afterRetrieval = System.currentTimeMillis();
3172 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3173 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3175 // Checking the timestamp again should not change it.
3177 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3179 // Retrieving the logs again should update the timestamp.
3180 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
3181 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
3182 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3184 // Disabling logging should not change the timestamp.
3186 dpm.setNetworkLoggingEnabled(admin1, false);
3187 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3189 // Restarting the DPMS should not lose the timestamp.
3191 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3193 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3194 mContext.binder.callingUid = 1234567;
3195 mContext.callerPermissions.add(permission.MANAGE_USERS);
3196 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3197 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3199 // System can retrieve the timestamp.
3200 mContext.binder.clearCallingIdentity();
3201 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3203 // Removing the device owner should clear the timestamp.
3205 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
3208 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3209 // Setup device owner.
3210 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3213 // Only device owner is setup, the result list should be empty.
3214 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3215 MoreAsserts.assertEmpty(targetUsers);
3217 // Setup a managed profile managed by the same admin.
3218 final int MANAGED_PROFILE_USER_ID = 15;
3219 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3220 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3222 // Add a secondary user, it should never talk with.
3223 final int ANOTHER_USER_ID = 36;
3224 getServices().addUser(ANOTHER_USER_ID, 0);
3226 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3228 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3229 MoreAsserts.assertEmpty(targetUsers);
3231 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3232 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3233 MoreAsserts.assertEmpty(targetUsers);
3235 // Setting affiliation ids
3236 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
3237 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3238 dpm.setAffiliationIds(admin1, userAffiliationIds);
3240 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3241 dpm.setAffiliationIds(admin1, userAffiliationIds);
3243 // Calling from device owner admin, the result list should just contain the managed
3245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3246 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3247 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3249 // Calling from managed profile admin, the result list should just contain the system
3251 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3252 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3253 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
3255 // Changing affiliation ids in one
3256 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
3258 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3260 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3261 MoreAsserts.assertEmpty(targetUsers);
3263 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3264 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3265 MoreAsserts.assertEmpty(targetUsers);
3268 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3269 // Setup a device owner.
3270 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3273 // Set up a managed profile managed by different package.
3274 final int MANAGED_PROFILE_USER_ID = 15;
3275 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3276 final ComponentName adminDifferentPackage =
3277 new ComponentName("another.package", "whatever.class");
3278 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3280 // Setting affiliation ids
3281 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
3282 dpm.setAffiliationIds(admin1, userAffiliationIds);
3284 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3285 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3287 // Calling from device owner admin, we should get zero bind device admin target users as
3288 // their packages are different.
3289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3290 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3291 MoreAsserts.assertEmpty(targetUsers);
3293 // Calling from managed profile admin, we should still get zero target users for the same
3295 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3296 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3297 MoreAsserts.assertEmpty(targetUsers);
3300 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3301 // Setup a device owner.
3302 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3304 // Lock task packages are updated when loading user data.
3305 verify(getServices().iactivityManager)
3306 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3308 // Set up a managed profile managed by different package (package name shouldn't matter)
3309 final int MANAGED_PROFILE_USER_ID = 15;
3310 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3311 final ComponentName adminDifferentPackage =
3312 new ComponentName("another.package", "whatever.class");
3313 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3314 verify(getServices().iactivityManager)
3315 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3317 // The DO can still set lock task packages
3318 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3319 final String[] doPackages = {"doPackage1", "doPackage2"};
3320 dpm.setLockTaskPackages(admin1, doPackages);
3321 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3322 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3323 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3324 verify(getServices().iactivityManager)
3325 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3327 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3328 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3329 final String[] poPackages = {"poPackage1", "poPackage2"};
3330 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3331 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3332 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3333 () -> dpm.getLockTaskPackages(adminDifferentPackage));
3334 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3336 // Setting same affiliation ids
3337 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
3338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3339 dpm.setAffiliationIds(admin1, userAffiliationIds);
3341 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3342 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3344 // Now the managed profile can set lock task packages.
3345 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3346 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3347 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3348 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3349 verify(getServices().iactivityManager)
3350 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3352 // Unaffiliate the profile, lock task mode no longer available on the profile.
3353 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
3354 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3355 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3356 verify(getServices().iactivityManager, times(2))
3357 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3359 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3360 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3363 public void testIsDeviceManaged() throws Exception {
3364 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3367 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3368 // find out that the device has a device owner.
3369 assertTrue(dpm.isDeviceManaged());
3370 mContext.binder.callingUid = 1234567;
3371 mContext.callerPermissions.add(permission.MANAGE_USERS);
3372 assertTrue(dpm.isDeviceManaged());
3373 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3374 mContext.binder.clearCallingIdentity();
3375 assertTrue(dpm.isDeviceManaged());
3379 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3380 // not have a device owner.
3381 mContext.binder.callingUid = 1234567;
3382 mContext.callerPermissions.add(permission.MANAGE_USERS);
3383 assertFalse(dpm.isDeviceManaged());
3384 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3385 mContext.binder.clearCallingIdentity();
3386 assertFalse(dpm.isDeviceManaged());
3389 public void testDeviceOwnerOrganizationName() throws Exception {
3390 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3393 dpm.setOrganizationName(admin1, "organization");
3395 // Device owner can retrieve organization managing the device.
3396 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3398 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3399 mContext.binder.callingUid = 1234567;
3400 mContext.callerPermissions.add(permission.MANAGE_USERS);
3401 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3402 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3404 // System can retrieve organization managing the device.
3405 mContext.binder.clearCallingIdentity();
3406 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3408 // Removing the device owner clears the organization managing the device.
3410 assertNull(dpm.getDeviceOwnerOrganizationName());
3413 public void testWipeDataManagedProfile() throws Exception {
3414 final int MANAGED_PROFILE_USER_ID = 15;
3415 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3416 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3417 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3419 // Even if the caller is the managed profile, the current user is the user 0
3420 when(getServices().iactivityManager.getCurrentUser())
3421 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3424 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
3425 MANAGED_PROFILE_USER_ID);
3428 public void testWipeDataManagedProfileDisallowed() throws Exception {
3429 final int MANAGED_PROFILE_USER_ID = 15;
3430 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3431 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3433 // Even if the caller is the managed profile, the current user is the user 0
3434 when(getServices().iactivityManager.getCurrentUser())
3435 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3437 when(getServices().userManager.getUserRestrictionSource(
3438 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3439 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3440 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3441 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3442 // The PO is not allowed to remove the profile if the user restriction was set on the
3443 // profile by the system
3444 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3445 () -> dpm.wipeData(0));
3448 public void testWipeDataDeviceOwner() throws Exception {
3450 when(getServices().userManager.getUserRestrictionSource(
3451 UserManager.DISALLOW_FACTORY_RESET,
3453 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3456 verify(getServices().recoverySystem).rebootWipeUserData(
3457 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3458 /*wipeEuicc=*/ eq(false));
3461 public void testWipeEuiccDataEnabled() throws Exception {
3463 when(getServices().userManager.getUserRestrictionSource(
3464 UserManager.DISALLOW_FACTORY_RESET,
3466 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3468 dpm.wipeData(WIPE_EUICC);
3469 verify(getServices().recoverySystem).rebootWipeUserData(
3470 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3471 /*wipeEuicc=*/ eq(true));
3474 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3476 when(getServices().userManager.getUserRestrictionSource(
3477 UserManager.DISALLOW_FACTORY_RESET,
3479 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3480 // The DO is not allowed to wipe the device if the user restriction was set
3482 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3483 () -> dpm.wipeData(0));
3486 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3487 final int MANAGED_PROFILE_USER_ID = 15;
3488 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3489 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3491 // Even if the caller is the managed profile, the current user is the user 0
3492 when(getServices().iactivityManager.getCurrentUser())
3493 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3495 when(getServices().userManager.getUserRestrictionSource(
3496 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3497 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3498 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3500 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3501 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3503 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3504 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3505 // Failed password attempts on the parent user are taken into account, as there isn't a
3506 // separate work challenge.
3507 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3508 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3509 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3511 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3512 // both the user restriction and the policy were set by the PO.
3513 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
3514 MANAGED_PROFILE_USER_ID);
3515 verifyZeroInteractions(getServices().recoverySystem);
3518 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3520 final int MANAGED_PROFILE_USER_ID = 15;
3521 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3522 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3524 // Even if the caller is the managed profile, the current user is the user 0
3525 when(getServices().iactivityManager.getCurrentUser())
3526 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3528 when(getServices().userManager.getUserRestrictionSource(
3529 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3530 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3531 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3533 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3534 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3536 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3537 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3538 // Failed password attempts on the parent user are taken into account, as there isn't a
3539 // separate work challenge.
3540 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3541 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3542 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3544 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3546 verify(getServices().userManagerInternal, never())
3547 .removeUserEvenWhenDisallowed(anyInt());
3548 verifyZeroInteractions(getServices().recoverySystem);
3551 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3553 when(getServices().userManager.getUserRestrictionSource(
3554 UserManager.DISALLOW_FACTORY_RESET,
3556 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3558 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3560 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3561 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3562 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3563 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3564 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3566 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3567 // user restriction and the policy were set by the DO.
3568 verify(getServices().recoverySystem).rebootWipeUserData(
3569 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3570 /*wipeEuicc=*/ eq(false));
3573 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3575 when(getServices().userManager.getUserRestrictionSource(
3576 UserManager.DISALLOW_FACTORY_RESET,
3578 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3580 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3582 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3583 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3584 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3585 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3586 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3588 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3589 verifyZeroInteractions(getServices().recoverySystem);
3590 verify(getServices().userManagerInternal, never())
3591 .removeUserEvenWhenDisallowed(anyInt());
3594 public void testGetPermissionGrantState() throws Exception {
3595 final String permission = "some.permission";
3596 final String app1 = "com.example.app1";
3597 final String app2 = "com.example.app2";
3599 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3600 .thenReturn(PackageManager.PERMISSION_GRANTED);
3601 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
3602 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3603 when(getServices().packageManager.getPermissionFlags(permission, app1,
3604 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3605 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3606 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3607 .thenReturn(PackageManager.PERMISSION_DENIED);
3608 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
3610 when(getServices().packageManager.getPermissionFlags(permission, app2,
3611 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3613 // System can retrieve permission grant state.
3614 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3615 mContext.packageName = "com.example.system";
3616 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3617 dpm.getPermissionGrantState(null, app1, permission));
3618 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3619 dpm.getPermissionGrantState(null, app2, permission));
3621 // A regular app cannot retrieve permission grant state.
3622 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3623 mContext.packageName = app1;
3624 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3625 () -> dpm.getPermissionGrantState(null, app1, permission));
3627 // Profile owner can retrieve permission grant state.
3628 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3629 mContext.packageName = admin1.getPackageName();
3630 setAsProfileOwner(admin1);
3631 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3632 dpm.getPermissionGrantState(admin1, app1, permission));
3633 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3634 dpm.getPermissionGrantState(admin1, app2, permission));
3637 public void testResetPasswordWithToken() throws Exception {
3638 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3640 // test token validation
3641 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3642 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3644 // test adding a token
3645 final byte[] token = new byte[32];
3646 final long handle = 123456;
3647 final String password = "password";
3648 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3649 .thenReturn(handle);
3650 assertTrue(dpm.setResetPasswordToken(admin1, token));
3652 // test password activation
3653 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3655 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3657 // test reset password with token
3658 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
3659 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3660 eq(UserHandle.USER_SYSTEM)))
3662 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3664 // test removing a token
3665 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3667 assertTrue(dpm.clearResetPasswordToken(admin1));
3670 public void testIsActivePasswordSufficient() throws Exception {
3671 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3672 mContext.packageName = admin1.getPackageName();
3675 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3676 dpm.setPasswordMinimumLength(admin1, 8);
3677 dpm.setPasswordMinimumLetters(admin1, 6);
3678 dpm.setPasswordMinimumLowerCase(admin1, 3);
3679 dpm.setPasswordMinimumUpperCase(admin1, 1);
3680 dpm.setPasswordMinimumNonLetter(admin1, 1);
3681 dpm.setPasswordMinimumNumeric(admin1, 1);
3682 dpm.setPasswordMinimumSymbols(admin1, 0);
3684 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3685 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3690 setActivePasswordState(passwordMetricsNoSymbols);
3691 assertTrue(dpm.isActivePasswordSufficient());
3694 reset(mContext.spiedContext);
3695 assertTrue(dpm.isActivePasswordSufficient());
3697 // This call simulates the user entering the password for the first time after a reboot.
3698 // This causes password metrics to be reloaded into memory. Until this happens,
3699 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3700 // even if the DPC changes password requirements so that the password no longer meets the
3701 // requirements. This is a known limitation of the current implementation of
3702 // isActivePasswordSufficient() - see b/34218769.
3703 setActivePasswordState(passwordMetricsNoSymbols);
3704 assertTrue(dpm.isActivePasswordSufficient());
3706 dpm.setPasswordMinimumSymbols(admin1, 1);
3707 // This assertion would fail if we had not called setActivePasswordState() again after
3708 // initializeDpms() - see previous comment.
3709 assertFalse(dpm.isActivePasswordSufficient());
3712 reset(mContext.spiedContext);
3713 assertFalse(dpm.isActivePasswordSufficient());
3715 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3716 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3721 setActivePasswordState(passwordMetricsWithSymbols);
3722 assertTrue(dpm.isActivePasswordSufficient());
3725 private void setActivePasswordState(PasswordMetrics passwordMetrics)
3727 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
3728 final long ident = mContext.binder.clearCallingIdentity();
3730 dpm.setActivePasswordState(passwordMetrics, userHandle);
3731 dpm.reportPasswordChanged(userHandle);
3733 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3734 intent.setComponent(admin1);
3735 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3737 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3738 MockUtils.checkIntent(intent),
3739 MockUtils.checkUserHandle(userHandle));
3741 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
3742 // let it finish with system uid, otherwise it will throw and crash.
3745 mContext.binder.restoreCallingIdentity(ident);
3748 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3749 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3750 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3751 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3752 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3753 DpmMockContext.SYSTEM_UID);
3754 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3755 DpmMockContext.SYSTEM_UID);
3757 // Set up a device owner.
3758 mContext.binder.callingUid = deviceOwnerUid;
3761 // First and second user set IMEs manually.
3762 mContext.binder.callingUid = firstUserSystemUid;
3763 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3764 mContext.binder.callingUid = secondUserSystemUid;
3765 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3767 // Device owner changes IME for first user.
3768 mContext.binder.callingUid = deviceOwnerUid;
3769 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
3770 .thenReturn("ime1");
3771 dpm.setSecureSetting(admin1, currentIme, "ime2");
3772 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
3773 UserHandle.USER_SYSTEM);
3774 reset(getServices().settings);
3775 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3776 mContext.binder.callingUid = firstUserSystemUid;
3777 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3778 mContext.binder.callingUid = secondUserSystemUid;
3779 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3781 // Second user changes IME manually.
3782 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3783 mContext.binder.callingUid = firstUserSystemUid;
3784 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3785 mContext.binder.callingUid = secondUserSystemUid;
3786 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3788 // First user changes IME manually.
3789 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3790 mContext.binder.callingUid = firstUserSystemUid;
3791 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3792 mContext.binder.callingUid = secondUserSystemUid;
3793 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3795 // Device owner changes IME for first user again.
3796 mContext.binder.callingUid = deviceOwnerUid;
3797 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
3798 .thenReturn("ime2");
3799 dpm.setSecureSetting(admin1, currentIme, "ime3");
3800 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
3801 UserHandle.USER_SYSTEM);
3802 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3803 mContext.binder.callingUid = firstUserSystemUid;
3804 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3805 mContext.binder.callingUid = secondUserSystemUid;
3806 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3808 // Restarting the DPMS should not lose information.
3810 mContext.binder.callingUid = firstUserSystemUid;
3811 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3812 mContext.binder.callingUid = secondUserSystemUid;
3813 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3815 // Device owner can find out whether it set the current IME itself.
3816 mContext.binder.callingUid = deviceOwnerUid;
3817 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3819 // Removing the device owner should clear the information that it set the current IME.
3821 mContext.binder.callingUid = firstUserSystemUid;
3822 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3823 mContext.binder.callingUid = secondUserSystemUid;
3824 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3827 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3828 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3829 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3830 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3831 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3832 DpmMockContext.SYSTEM_UID);
3833 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3834 DpmMockContext.SYSTEM_UID);
3836 // Set up a profile owner.
3837 mContext.binder.callingUid = profileOwnerUid;
3838 setupProfileOwner();
3840 // First and second user set IMEs manually.
3841 mContext.binder.callingUid = firstUserSystemUid;
3842 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3843 mContext.binder.callingUid = secondUserSystemUid;
3844 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3846 // Profile owner changes IME for second user.
3847 mContext.binder.callingUid = profileOwnerUid;
3848 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
3849 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
3850 dpm.setSecureSetting(admin1, currentIme, "ime2");
3851 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
3852 DpmMockContext.CALLER_USER_HANDLE);
3853 reset(getServices().settings);
3854 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3855 mContext.binder.callingUid = firstUserSystemUid;
3856 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3857 mContext.binder.callingUid = secondUserSystemUid;
3858 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3860 // First user changes IME manually.
3861 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3862 mContext.binder.callingUid = firstUserSystemUid;
3863 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3864 mContext.binder.callingUid = secondUserSystemUid;
3865 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3867 // Second user changes IME manually.
3868 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3869 mContext.binder.callingUid = firstUserSystemUid;
3870 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3871 mContext.binder.callingUid = secondUserSystemUid;
3872 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3874 // Profile owner changes IME for second user again.
3875 mContext.binder.callingUid = profileOwnerUid;
3876 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
3877 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
3878 dpm.setSecureSetting(admin1, currentIme, "ime3");
3879 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
3880 DpmMockContext.CALLER_USER_HANDLE);
3881 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3882 mContext.binder.callingUid = firstUserSystemUid;
3883 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3884 mContext.binder.callingUid = secondUserSystemUid;
3885 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3887 // Restarting the DPMS should not lose information.
3889 mContext.binder.callingUid = firstUserSystemUid;
3890 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3891 mContext.binder.callingUid = secondUserSystemUid;
3892 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3894 // Profile owner can find out whether it set the current IME itself.
3895 mContext.binder.callingUid = profileOwnerUid;
3896 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3898 // Removing the profile owner should clear the information that it set the current IME.
3899 dpm.clearProfileOwner(admin1);
3900 mContext.binder.callingUid = firstUserSystemUid;
3901 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3902 mContext.binder.callingUid = secondUserSystemUid;
3903 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3906 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
3908 // Set up a device owner.
3909 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3911 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3914 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
3916 // Set up a profile owner.
3917 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3918 setupProfileOwner();
3919 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
3922 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
3923 int adminUid) throws Exception {
3924 mContext.binder.callingUid = adminUid;
3925 final int userId = UserHandle.getUserId(adminUid);
3927 final String packageName = "some.package";
3928 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3929 admin1, Collections.singletonList(packageName)));
3930 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3932 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3933 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3935 // Attempt to set to empty list (which means no listener is whitelisted)
3936 mContext.binder.callingUid = adminUid;
3937 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
3938 admin1, Collections.emptyList()));
3939 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
3941 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3942 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
3945 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
3946 // Set up a managed profile
3947 final int MANAGED_PROFILE_USER_ID = 15;
3948 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3949 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3950 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3952 final String permittedListener = "some.package";
3953 setupPackageInPackageManager(
3955 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3956 /*appId=*/ 12345, /*flags=*/ 0);
3958 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
3959 admin1, Collections.singletonList(permittedListener)));
3961 // isNotificationListenerServicePermitted should throw if not called from System.
3962 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3963 () -> dpms.isNotificationListenerServicePermitted(
3964 permittedListener, MANAGED_PROFILE_USER_ID));
3966 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3967 assertTrue(dpms.isNotificationListenerServicePermitted(
3968 permittedListener, MANAGED_PROFILE_USER_ID));
3971 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
3973 // Set up a managed profile
3974 final int MANAGED_PROFILE_USER_ID = 15;
3975 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3976 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3977 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3979 final String permittedListener = "permitted.package";
3981 setupPackageInPackageManager(
3983 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3984 appId, /*flags=*/ 0);
3986 final String notPermittedListener = "not.permitted.package";
3987 setupPackageInPackageManager(
3988 notPermittedListener,
3989 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3990 ++appId, /*flags=*/ 0);
3992 final String systemListener = "system.package";
3993 setupPackageInPackageManager(
3995 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
3996 ++appId, ApplicationInfo.FLAG_SYSTEM);
3998 // By default all packages are allowed
3999 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4001 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4002 assertTrue(dpms.isNotificationListenerServicePermitted(
4003 permittedListener, MANAGED_PROFILE_USER_ID));
4004 assertTrue(dpms.isNotificationListenerServicePermitted(
4005 notPermittedListener, MANAGED_PROFILE_USER_ID));
4006 assertTrue(dpms.isNotificationListenerServicePermitted(
4007 systemListener, MANAGED_PROFILE_USER_ID));
4009 // Setting only one package in the whitelist
4010 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4011 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4012 admin1, Collections.singletonList(permittedListener)));
4013 final List<String> permittedListeners =
4014 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4015 assertEquals(1, permittedListeners.size());
4016 assertEquals(permittedListener, permittedListeners.get(0));
4018 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4019 assertTrue(dpms.isNotificationListenerServicePermitted(
4020 permittedListener, MANAGED_PROFILE_USER_ID));
4021 assertFalse(dpms.isNotificationListenerServicePermitted(
4022 notPermittedListener, MANAGED_PROFILE_USER_ID));
4023 // System packages are always allowed (even if not in the whitelist)
4024 assertTrue(dpms.isNotificationListenerServicePermitted(
4025 systemListener, MANAGED_PROFILE_USER_ID));
4027 // Setting an empty whitelist - only system listeners allowed
4028 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4029 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4030 admin1, Collections.emptyList()));
4031 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4033 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4034 assertFalse(dpms.isNotificationListenerServicePermitted(
4035 permittedListener, MANAGED_PROFILE_USER_ID));
4036 assertFalse(dpms.isNotificationListenerServicePermitted(
4037 notPermittedListener, MANAGED_PROFILE_USER_ID));
4038 // System packages are always allowed (even if not in the whitelist)
4039 assertTrue(dpms.isNotificationListenerServicePermitted(
4040 systemListener, MANAGED_PROFILE_USER_ID));
4042 // Setting a null whitelist - all listeners allowed
4043 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4044 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4045 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4047 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4048 assertTrue(dpms.isNotificationListenerServicePermitted(
4049 permittedListener, MANAGED_PROFILE_USER_ID));
4050 assertTrue(dpms.isNotificationListenerServicePermitted(
4051 notPermittedListener, MANAGED_PROFILE_USER_ID));
4052 assertTrue(dpms.isNotificationListenerServicePermitted(
4053 systemListener, MANAGED_PROFILE_USER_ID));
4056 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4058 // Set up a managed profile
4059 final int MANAGED_PROFILE_USER_ID = 15;
4060 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4061 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4062 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4064 final String nonSystemPackage = "non.system.package";
4066 setupPackageInPackageManager(
4068 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4069 appId, /*flags=*/ 0);
4071 final String systemListener = "system.package";
4072 setupPackageInPackageManager(
4074 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4075 ++appId, ApplicationInfo.FLAG_SYSTEM);
4077 // By default all packages are allowed (for all profiles)
4078 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4080 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4081 assertTrue(dpms.isNotificationListenerServicePermitted(
4082 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4083 assertTrue(dpms.isNotificationListenerServicePermitted(
4084 systemListener, MANAGED_PROFILE_USER_ID));
4085 assertTrue(dpms.isNotificationListenerServicePermitted(
4086 nonSystemPackage, UserHandle.USER_SYSTEM));
4087 assertTrue(dpms.isNotificationListenerServicePermitted(
4088 systemListener, UserHandle.USER_SYSTEM));
4090 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4091 // all allowed in primary profile
4092 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4093 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4094 admin1, Collections.emptyList()));
4095 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4097 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4098 assertFalse(dpms.isNotificationListenerServicePermitted(
4099 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4100 assertTrue(dpms.isNotificationListenerServicePermitted(
4101 systemListener, MANAGED_PROFILE_USER_ID));
4102 assertTrue(dpms.isNotificationListenerServicePermitted(
4103 nonSystemPackage, UserHandle.USER_SYSTEM));
4104 assertTrue(dpms.isNotificationListenerServicePermitted(
4105 systemListener, UserHandle.USER_SYSTEM));
4108 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
4109 mServiceContext.packageName = mRealTestContext.getPackageName();
4110 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4111 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4114 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4117 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
4118 mServiceContext.packageName = mRealTestContext.getPackageName();
4119 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4120 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
4121 setAsProfileOwner(admin1);
4123 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4124 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
4127 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
4128 mServiceContext.packageName = mRealTestContext.getPackageName();
4129 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4130 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
4131 setAsProfileOwner(admin1);
4133 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4134 caller.packageName = "com.example.delegate";
4135 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4136 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
4138 // Make caller a delegated cert installer.
4139 runAsCaller(mAdmin1Context, dpms,
4140 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
4142 verifyCanGetOwnerInstalledCaCerts(null, caller);
4143 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
4146 private void verifyCanGetOwnerInstalledCaCerts(
4147 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
4148 final String alias = "cert";
4149 final byte[] caCert = TEST_CA.getBytes();
4151 // device admin (used for posting the tls notification)
4152 DpmMockContext admin1Context = mAdmin1Context;
4153 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4154 admin1Context = callerContext;
4156 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4158 // caller: device admin or delegated certificate installer
4159 callerContext.applicationInfo = new ApplicationInfo();
4160 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4163 final DpmMockContext serviceContext = mContext;
4164 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4165 getServices().addPackageContext(callerUser, admin1Context);
4166 getServices().addPackageContext(callerUser, callerContext);
4168 // Install a CA cert.
4169 runAsCaller(callerContext, dpms, (dpm) -> {
4170 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
4172 assertTrue(dpm.installCaCert(caller, caCert));
4173 when(getServices().keyChainConnection.getService().getUserCaAliases())
4174 .thenReturn(asSlice(new String[] {alias}));
4177 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4178 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4179 callerUser.getIdentifier());
4182 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4184 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
4185 runAsCaller(admin1Context, dpms, (dpm) -> {
4186 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4187 assertEquals(Collections.singletonList(alias), installedCaCerts);
4188 ownerInstalledCaCerts.addAll(installedCaCerts);
4191 // Restarting the DPMS should not lose information.
4193 runAsCaller(admin1Context, dpms, (dpm) ->
4194 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
4196 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
4197 runAsCaller(serviceContext, dpms, (dpm) -> {
4198 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
4200 // Remove the CA cert.
4201 reset(getServices().keyChainConnection.getService());
4204 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4205 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4206 callerUser.getIdentifier());
4209 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4211 runAsCaller(admin1Context, dpms, (dpm) -> {
4212 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4216 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4217 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
4218 final String alias = "cert";
4219 final byte[] caCert = TEST_CA.getBytes();
4221 // device admin (used for posting the tls notification)
4222 DpmMockContext admin1Context = mAdmin1Context;
4223 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4224 admin1Context = callerContext;
4226 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4228 // caller: device admin or delegated certificate installer
4229 callerContext.applicationInfo = new ApplicationInfo();
4230 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4233 final DpmMockContext serviceContext = mContext;
4234 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4235 getServices().addPackageContext(callerUser, admin1Context);
4236 getServices().addPackageContext(callerUser, callerContext);
4238 // Install a CA cert as caller
4239 runAsCaller(callerContext, dpms, (dpm) -> {
4240 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
4242 assertTrue(dpm.installCaCert(callerName, caCert));
4245 // Fake the CA cert as having been installed
4246 when(getServices().keyChainConnection.getService().getUserCaAliases())
4247 .thenReturn(asSlice(new String[] {alias}));
4248 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4249 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4250 callerUser.getIdentifier());
4253 // Removing the Profile Owner should clear the information on which CA certs were installed
4254 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
4256 runAsCaller(serviceContext, dpms, (dpm) -> {
4257 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4258 assertNotNull(ownerInstalledCaCerts);
4259 assertTrue(ownerInstalledCaCerts.isEmpty());
4263 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4264 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4265 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4266 dpms.notifyChangeToContentObserver(
4267 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4270 private void assertProvisioningAllowed(String action, boolean expected) {
4271 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4272 dpm.isProvisioningAllowed(action));
4275 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4277 final String previousPackageName = mContext.packageName;
4278 final int previousUid = mMockContext.binder.callingUid;
4280 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4281 mContext.packageName = packageName;
4282 mMockContext.binder.callingUid = uid;
4283 assertProvisioningAllowed(action, expected);
4285 // Set the previous package name / calling uid to go back to the initial state.
4286 mContext.packageName = previousPackageName;
4287 mMockContext.binder.callingUid = previousUid;
4290 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
4291 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4294 private void assertCheckProvisioningPreCondition(
4295 String action, String packageName, int provisioningCondition) {
4296 assertEquals("checkProvisioningPreCondition("
4297 + action + ", " + packageName + ") returning unexpected result",
4298 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
4302 * Setup a managed profile with the specified admin and its uid.
4303 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4304 * @param adminUid uid of the admin package.
4305 * @param copyFromAdmin package information for {@code admin} will be built based on this
4306 * component's information.
4308 private void addManagedProfile(
4309 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4310 final int userId = UserHandle.getUserId(adminUid);
4311 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4312 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4313 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4314 dpm.setActiveAdmin(admin, false, userId);
4315 assertTrue(dpm.setProfileOwner(admin, null, userId));
4316 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4320 * Convert String[] to StringParceledListSlice.
4322 private static StringParceledListSlice asSlice(String[] s) {
4323 return new StringParceledListSlice(Arrays.asList(s));
4326 private void flushTasks() throws Exception {
4327 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4328 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
4330 // We can't let exceptions happen on the background thread. Throw them here if they happen
4331 // so they still cause the test to fail despite being suppressed.
4332 getServices().rethrowBackgroundBroadcastExceptions();