blob: f1eaf9b5eda3647586ca64043eb28758b65449fe [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Makoto Onukif76b06a2015-09-22 15:03:44 -070018import android.Manifest.permission;
19import android.app.Activity;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070020import android.app.admin.DeviceAdminReceiver;
21import android.app.admin.DevicePolicyManager;
22import android.app.admin.DevicePolicyManagerInternal;
Makoto Onukif76b06a2015-09-22 15:03:44 -070023import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070024import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000025import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.pm.PackageManager;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010031import android.content.res.Resources;
32import android.graphics.Color;
33import android.net.IIpConnectivityMetrics;
Tony Mak2f26b792016-11-28 17:54:51 +000034import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080035import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080036import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070037import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000038import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080039import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070040import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070041import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080042import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000043import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000045import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010046import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070047import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070048
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010049import com.android.internal.R;
Alan Treadwayafad8782016-01-19 15:15:08 +000050import com.android.server.LocalServices;
51import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000052import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000053
Makoto Onukib643fb02015-09-22 15:03:44 -070054import org.mockito.invocation.InvocationOnMock;
55import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056
Makoto Onukic8a5a552015-11-19 14:29:12 -080057import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000058import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000059import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070060import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070062import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010063import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064
65import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070066import static org.mockito.Matchers.anyInt;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010067import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070068import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000071import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070072import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073import static org.mockito.Mockito.doReturn;
Robin Leed2a73ed2016-12-19 09:07:16 +000074import static org.mockito.Mockito.never;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080075import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070076import static org.mockito.Mockito.times;
77import static org.mockito.Mockito.verify;
78import static org.mockito.Mockito.when;
79
80/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070081 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000082 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083 m FrameworksServicesTests &&
84 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000085 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070086 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080087 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088
89 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +000090 *
91 * , or:
92 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093 */
Benjamin Franz6d009032016-01-25 18:56:38 +000094@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000096 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
97 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
98 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
99
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700100 private DpmMockContext mContext;
101 public DevicePolicyManager dpm;
102 public DevicePolicyManagerServiceTestable dpms;
103
104 @Override
105 protected void setUp() throws Exception {
106 super.setUp();
107
108 mContext = getContext();
109
110 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
111 .thenReturn(true);
112
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800113 // By default, pretend all users are running and unlocked.
114 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
115
Makoto Onukia52562c2015-10-01 16:12:31 -0700116 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700117
Makoto Onukid932f762015-09-29 16:53:38 -0700118 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
119 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
120 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800121 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700122
Makoto Onukib643fb02015-09-22 15:03:44 -0700123 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700124 }
125
Makoto Onukia52562c2015-10-01 16:12:31 -0700126 private void initializeDpms() {
127 // Need clearCallingIdentity() to pass permission checks.
128 final long ident = mContext.binder.clearCallingIdentity();
129 try {
130 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
131
132 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
133
134 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
135 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
136
137 dpm = new DevicePolicyManagerTestable(mContext, dpms);
138 } finally {
139 mContext.binder.restoreCallingIdentity(ident);
140 }
141 }
142
Makoto Onukib643fb02015-09-22 15:03:44 -0700143 private void setUpUserManager() {
144 // Emulate UserManager.set/getApplicationRestriction().
145 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
146
147 // UM.setApplicationRestrictions() will save to appRestrictions.
148 doAnswer(new Answer<Void>() {
149 @Override
150 public Void answer(InvocationOnMock invocation) throws Throwable {
151 String pkg = (String) invocation.getArguments()[0];
152 Bundle bundle = (Bundle) invocation.getArguments()[1];
153 UserHandle user = (UserHandle) invocation.getArguments()[2];
154
155 appRestrictions.put(Pair.create(pkg, user), bundle);
156
157 return null;
158 }
159 }).when(mContext.userManager).setApplicationRestrictions(
160 anyString(), any(Bundle.class), any(UserHandle.class));
161
162 // UM.getApplicationRestrictions() will read from appRestrictions.
163 doAnswer(new Answer<Bundle>() {
164 @Override
165 public Bundle answer(InvocationOnMock invocation) throws Throwable {
166 String pkg = (String) invocation.getArguments()[0];
167 UserHandle user = (UserHandle) invocation.getArguments()[1];
168
169 return appRestrictions.get(Pair.create(pkg, user));
170 }
171 }).when(mContext.userManager).getApplicationRestrictions(
172 anyString(), any(UserHandle.class));
173
Makoto Onukid932f762015-09-29 16:53:38 -0700174 // Add the first secondary user.
175 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700176 }
177
178 private void setAsProfileOwner(ComponentName admin) {
179 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
180 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
181
Makoto Onukia4f11972015-10-01 13:19:58 -0700182 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700183 dpm.setActiveAdmin(admin, /* replace =*/ false);
184
185 // Fire!
186 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
187
188 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700189 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700190 }
191
192 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700193 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
194 .thenReturn(false);
195
196 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
197 new DevicePolicyManagerServiceTestable(mContext, dataDir);
198
199 // If the device has no DPMS feature, it shouldn't register the local service.
200 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
201 }
202
203 /**
204 * Caller doesn't have proper permissions.
205 */
206 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700207 // 1. Failure cases.
208
209 // Caller doesn't have MANAGE_DEVICE_ADMINS.
210 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700211 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700212 fail("Didn't throw SecurityException");
213 } catch (SecurityException expected) {
214 }
215
216 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
217 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
218 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700219 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700220 fail("Didn't throw SecurityException");
221 } catch (SecurityException expected) {
222 }
223 }
224
Makoto Onukif76b06a2015-09-22 15:03:44 -0700225 /**
226 * Test for:
227 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800228 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700229 * {@link DevicePolicyManager#isAdminActive}
230 * {@link DevicePolicyManager#isAdminActiveAsUser}
231 * {@link DevicePolicyManager#getActiveAdmins}
232 * {@link DevicePolicyManager#getActiveAdminsAsUser}
233 */
234 public void testSetActiveAdmin() throws Exception {
235 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700236 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
237
Makoto Onukif76b06a2015-09-22 15:03:44 -0700238 // 2. Call the API.
239 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700240
241 // 3. Verify internal calls.
242
243 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700244 verify(mContext.spiedContext).sendBroadcastAsUser(
245 MockUtils.checkIntentAction(
246 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
247 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
248 verify(mContext.spiedContext).sendBroadcastAsUser(
249 MockUtils.checkIntentAction(
250 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700251 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
252
Makoto Onukif76b06a2015-09-22 15:03:44 -0700253 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
254 eq(admin1.getPackageName()),
255 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
256 eq(PackageManager.DONT_KILL_APP),
257 eq(DpmMockContext.CALLER_USER_HANDLE),
258 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700259
260 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700261
262 // Make sure it's active admin1.
263 assertTrue(dpm.isAdminActive(admin1));
264 assertFalse(dpm.isAdminActive(admin2));
265 assertFalse(dpm.isAdminActive(admin3));
266
267 // But not admin1 for a different user.
268
269 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
270 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
271 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
272
273 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
274 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
275
276 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
277
278 // Next, add one more admin.
279 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700280 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
281 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700282
283 dpm.setActiveAdmin(admin2, /* replace =*/ false);
284
285 // Now we have two admins.
286 assertTrue(dpm.isAdminActive(admin1));
287 assertTrue(dpm.isAdminActive(admin2));
288 assertFalse(dpm.isAdminActive(admin3));
289
290 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
291 // again. (times(1) because it was previously called for admin1)
292 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
293 eq(admin1.getPackageName()),
294 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
295 eq(PackageManager.DONT_KILL_APP),
296 eq(DpmMockContext.CALLER_USER_HANDLE),
297 anyString());
298
299 // 4. Add the same admin1 again without replace, which should throw.
300 try {
301 dpm.setActiveAdmin(admin1, /* replace =*/ false);
302 fail("Didn't throw");
303 } catch (IllegalArgumentException expected) {
304 }
305
306 // 5. Add the same admin1 again with replace, which should succeed.
307 dpm.setActiveAdmin(admin1, /* replace =*/ true);
308
309 // TODO make sure it's replaced.
310
311 // 6. Test getActiveAdmins()
312 List<ComponentName> admins = dpm.getActiveAdmins();
313 assertEquals(2, admins.size());
314 assertEquals(admin1, admins.get(0));
315 assertEquals(admin2, admins.get(1));
316
317 // Another user has no admins.
318 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
319
320 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
321 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
322
323 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
324 }
325
Makoto Onukid932f762015-09-29 16:53:38 -0700326 public void testSetActiveAdmin_multiUsers() throws Exception {
327
328 final int ANOTHER_USER_ID = 100;
329 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
330
331 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
332
333 // Set up pacakge manager for the other user.
334 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700335
336 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
337
338 dpm.setActiveAdmin(admin1, /* replace =*/ false);
339
340 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
341 dpm.setActiveAdmin(admin2, /* replace =*/ false);
342
343
344 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
345 assertTrue(dpm.isAdminActive(admin1));
346 assertFalse(dpm.isAdminActive(admin2));
347
348 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
349 assertFalse(dpm.isAdminActive(admin1));
350 assertTrue(dpm.isAdminActive(admin2));
351 }
352
Makoto Onukif76b06a2015-09-22 15:03:44 -0700353 /**
354 * Test for:
355 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800356 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700357 */
358 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
359 // 1. Make sure the caller has proper permissions.
360 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
361
362 dpm.setActiveAdmin(admin1, /* replace =*/ false);
363 assertTrue(dpm.isAdminActive(admin1));
364
365 // Add the same admin1 again without replace, which should throw.
366 try {
367 dpm.setActiveAdmin(admin1, /* replace =*/ false);
368 fail("Didn't throw");
369 } catch (IllegalArgumentException expected) {
370 }
371 }
372
373 /**
374 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800375 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
376 * BIND_DEVICE_ADMIN.
377 */
378 public void testSetActiveAdmin_permissionCheck() throws Exception {
379 // 1. Make sure the caller has proper permissions.
380 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
381
382 try {
383 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
384 fail();
385 } catch (IllegalArgumentException expected) {
386 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
387 }
388 assertFalse(dpm.isAdminActive(adminNoPerm));
389
390 // Change the target API level to MNC. Now it can be set as DA.
391 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
392 VERSION_CODES.M);
393 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
394 assertTrue(dpm.isAdminActive(adminNoPerm));
395
396 // TODO Test the "load from the file" case where DA will still be loaded even without
397 // BIND_DEVICE_ADMIN and target API is N.
398 }
399
400 /**
401 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700402 * {@link DevicePolicyManager#removeActiveAdmin}
403 */
404 public void testRemoveActiveAdmin_SecurityException() {
405 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
406
407 // Add admin.
408
409 dpm.setActiveAdmin(admin1, /* replace =*/ false);
410
411 assertTrue(dpm.isAdminActive(admin1));
412
413 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
414
415 // Directly call the DPMS method with a different userid, which should fail.
416 try {
417 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
418 fail("Didn't throw SecurityException");
419 } catch (SecurityException expected) {
420 }
421
422 // Try to remove active admin with a different caller userid should fail too, without
423 // having MANAGE_DEVICE_ADMINS.
424 mContext.callerPermissions.clear();
425
Makoto Onukid932f762015-09-29 16:53:38 -0700426 // Change the caller, and call into DPMS directly with a different user-id.
427
Makoto Onukif76b06a2015-09-22 15:03:44 -0700428 mContext.binder.callingUid = 1234567;
429 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700430 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431 fail("Didn't throw SecurityException");
432 } catch (SecurityException expected) {
433 }
434 }
435
436 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800437 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
438 * (because we can't send the remove broadcast).
439 */
440 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
441 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
442
443 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
444
445 // Add admin.
446
447 dpm.setActiveAdmin(admin1, /* replace =*/ false);
448
449 assertTrue(dpm.isAdminActive(admin1));
450
451 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
452
453 // 1. User not unlocked.
454 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
455 .thenReturn(false);
456 try {
457 dpm.removeActiveAdmin(admin1);
458 fail("Didn't throw IllegalStateException");
459 } catch (IllegalStateException expected) {
460 MoreAsserts.assertContainsRegex(
461 "User must be running and unlocked", expected.getMessage());
462 }
463
464 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
465
466 // 2. User unlocked.
467 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
468 .thenReturn(true);
469
470 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700471 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800472 }
473
474 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700475 * Test for:
476 * {@link DevicePolicyManager#removeActiveAdmin}
477 */
Makoto Onukid932f762015-09-29 16:53:38 -0700478 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700479 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
480
481 // Add admin1.
482
483 dpm.setActiveAdmin(admin1, /* replace =*/ false);
484
485 assertTrue(dpm.isAdminActive(admin1));
486 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
487
488 // Different user, but should work, because caller has proper permissions.
489 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700490
491 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700492 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700493
494 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700495 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496
497 // TODO DO Still can't be removed in this case.
498 }
499
500 /**
501 * Test for:
502 * {@link DevicePolicyManager#removeActiveAdmin}
503 */
504 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
505 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
506 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
507
508 // Add admin1.
509
510 dpm.setActiveAdmin(admin1, /* replace =*/ false);
511
512 assertTrue(dpm.isAdminActive(admin1));
513 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
514
515 // Broadcast from saveSettingsLocked().
516 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
517 MockUtils.checkIntentAction(
518 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
519 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
520
521 // Remove. No permissions, but same user, so it'll work.
522 mContext.callerPermissions.clear();
523 dpm.removeActiveAdmin(admin1);
524
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
526 MockUtils.checkIntentAction(
527 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
528 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
529 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700530 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700531 eq(dpms.mHandler),
532 eq(Activity.RESULT_OK),
533 isNull(String.class),
534 isNull(Bundle.class));
535
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700536 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700537
538 // Again broadcast from saveSettingsLocked().
539 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
540 MockUtils.checkIntentAction(
541 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
542 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
543
544 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700545 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700546
547 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000548 * Test for: @{link DevicePolicyManager#setActivePasswordState}
549 *
550 * Validates that when the password for a user changes, the notification broadcast intent
551 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
552 * addition to ones in the original user.
553 */
554 public void testSetActivePasswordState_sendToProfiles() throws Exception {
555 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
556
557 final int MANAGED_PROFILE_USER_ID = 78;
558 final int MANAGED_PROFILE_ADMIN_UID =
559 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
560
561 // Setup device owner.
562 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
563 mContext.packageName = admin1.getPackageName();
564 setupDeviceOwner();
565
566 // Add a managed profile belonging to the system user.
567 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
568
569 // Change the parent user's password.
570 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
571
572 // Both the device owner and the managed profile owner should receive this broadcast.
573 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
574 intent.setComponent(admin1);
575 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
576
577 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
578 MockUtils.checkIntent(intent),
579 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
580 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
581 MockUtils.checkIntent(intent),
582 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
583 }
584
585 /**
586 * Test for: @{link DevicePolicyManager#setActivePasswordState}
587 *
588 * Validates that when the password for a managed profile changes, the notification broadcast
589 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
590 * its parent.
591 */
592 public void testSetActivePasswordState_notSentToParent() throws Exception {
593 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
594
595 final int MANAGED_PROFILE_USER_ID = 78;
596 final int MANAGED_PROFILE_ADMIN_UID =
597 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
598
599 // Setup device owner.
600 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
601 mContext.packageName = admin1.getPackageName();
602 doReturn(true).when(mContext.lockPatternUtils)
603 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
604 setupDeviceOwner();
605
606 // Add a managed profile belonging to the system user.
607 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
608
609 // Change the profile's password.
610 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
611
612 // Both the device owner and the managed profile owner should receive this broadcast.
613 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
614 intent.setComponent(admin1);
615 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
616
617 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
618 MockUtils.checkIntent(intent),
619 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
620 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
621 MockUtils.checkIntent(intent),
622 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
623 }
624 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000625 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700626 */
627 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000628 setDeviceOwner();
629
630 // Try to set a profile owner on the same user, which should fail.
631 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
632 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
633 try {
634 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
635 fail("IllegalStateException not thrown");
636 } catch (IllegalStateException expected) {
637 assertTrue("Message was: " + expected.getMessage(),
638 expected.getMessage().contains("already has a device owner"));
639 }
640
641 // DO admin can't be deactivated.
642 dpm.removeActiveAdmin(admin1);
643 assertTrue(dpm.isAdminActive(admin1));
644
645 // TODO Test getDeviceOwnerName() too. To do so, we need to change
646 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
647 }
648
649 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700650 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800651 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700652 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
653 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
654
Makoto Onukid932f762015-09-29 16:53:38 -0700655 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
657
Makoto Onukid932f762015-09-29 16:53:38 -0700658 // Make sure admin1 is installed on system user.
659 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700660
Makoto Onukic8a5a552015-11-19 14:29:12 -0800661 // Check various get APIs.
662 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
663
Makoto Onukib643fb02015-09-22 15:03:44 -0700664 // DO needs to be an DA.
665 dpm.setActiveAdmin(admin1, /* replace =*/ false);
666
667 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700668 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700669
Makoto Onukic8a5a552015-11-19 14:29:12 -0800670 // getDeviceOwnerComponent should return the admin1 component.
671 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
672 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
673
674 // Check various get APIs.
675 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
676
677 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
678 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
679 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
680 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
681
682 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
683
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000684 // Verify internal calls.
685 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
686 eq(admin1.getPackageName()));
687
Makoto Onukib643fb02015-09-22 15:03:44 -0700688 // TODO We should check if the caller has called clearCallerIdentity().
689 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
690 eq(UserHandle.USER_SYSTEM), eq(false));
691
692 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
693 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
694 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
695
Makoto Onukic8a5a552015-11-19 14:29:12 -0800696 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700697 }
698
Makoto Onukic8a5a552015-11-19 14:29:12 -0800699 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
700 final int origCallingUser = mContext.binder.callingUid;
701 final List origPermissions = new ArrayList(mContext.callerPermissions);
702 mContext.callerPermissions.clear();
703
704 mContext.callerPermissions.add(permission.MANAGE_USERS);
705
706 mContext.binder.callingUid = Process.SYSTEM_UID;
707
708 // TODO Test getDeviceOwnerName() too. To do so, we need to change
709 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
710 if (hasDeviceOwner) {
711 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
712 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
713 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
714
715 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
716 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
717 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
718 } else {
719 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
720 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
721 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
722
723 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
724 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
725 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
726 }
727
728 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
729 if (hasDeviceOwner) {
730 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
731 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
732 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
733
734 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
735 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
736 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
737 } else {
738 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
739 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
740 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
741
742 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
743 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
744 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
745 }
746
747 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
748 // Still with MANAGE_USERS.
749 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
750 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
751 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
752
753 if (hasDeviceOwner) {
754 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
755 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
756 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
757 } else {
758 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
759 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
760 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
761 }
762
763 mContext.binder.callingUid = Process.SYSTEM_UID;
764 mContext.callerPermissions.remove(permission.MANAGE_USERS);
765 // System can still call "OnAnyUser" without MANAGE_USERS.
766 if (hasDeviceOwner) {
767 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
768 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
769 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
770
771 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
772 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
773 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
774 } else {
775 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
776 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
777 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
778
779 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
780 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
781 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
782 }
783
784 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
785 // Still no MANAGE_USERS.
786 if (hasDeviceOwner) {
787 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
788 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
789 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
790 } else {
791 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
792 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
793 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
794 }
795
796 try {
797 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
798 fail();
799 } catch (SecurityException expected) {
800 }
801 try {
802 dpm.getDeviceOwnerComponentOnAnyUser();
803 fail();
804 } catch (SecurityException expected) {
805 }
806 try {
807 dpm.getDeviceOwnerUserId();
808 fail();
809 } catch (SecurityException expected) {
810 }
811 try {
812 dpm.getDeviceOwnerNameOnAnyUser();
813 fail();
814 } catch (SecurityException expected) {
815 }
816
817 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
818 // Still no MANAGE_USERS.
819 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
820 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
821 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
822
823 try {
824 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
825 fail();
826 } catch (SecurityException expected) {
827 }
828 try {
829 dpm.getDeviceOwnerComponentOnAnyUser();
830 fail();
831 } catch (SecurityException expected) {
832 }
833 try {
834 dpm.getDeviceOwnerUserId();
835 fail();
836 } catch (SecurityException expected) {
837 }
838 try {
839 dpm.getDeviceOwnerNameOnAnyUser();
840 fail();
841 } catch (SecurityException expected) {
842 }
843
844 // Restore.
845 mContext.binder.callingUid = origCallingUser;
846 mContext.callerPermissions.addAll(origPermissions);
847 }
848
849
Makoto Onukib643fb02015-09-22 15:03:44 -0700850 /**
851 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
852 */
853 public void testSetDeviceOwner_noSuchPackage() {
854 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800855 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700856 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
857 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
858
859 // Call from a process on the system user.
860 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
861
Makoto Onukib643fb02015-09-22 15:03:44 -0700862 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700863 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 fail("Didn't throw IllegalArgumentException");
865 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700866 assertTrue("Message was: " + expected.getMessage(),
867 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700868 }
869 }
870
871 public void testSetDeviceOwner_failures() throws Exception {
872 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
873 }
874
Makoto Onukia52562c2015-10-01 16:12:31 -0700875 public void testClearDeviceOwner() throws Exception {
876 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700878 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
879 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
880
881 // Set admin1 as a DA to the secondary user.
882 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
883
884 dpm.setActiveAdmin(admin1, /* replace =*/ false);
885
886 // Set admin 1 as the DO to the system user.
887
888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
889 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
890 dpm.setActiveAdmin(admin1, /* replace =*/ false);
891 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
892
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000893 // Verify internal calls.
894 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
895 eq(admin1.getPackageName()));
896
Makoto Onukic8a5a552015-11-19 14:29:12 -0800897 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700898
Makoto Onuki90b89652016-01-28 14:44:18 -0800899 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
900
901 assertTrue(dpm.isAdminActive(admin1));
902 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
903
Makoto Onukia52562c2015-10-01 16:12:31 -0700904 // Set up other mocks.
905 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
906
907 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700908 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700909 eq(admin1.getPackageName()),
910 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800911
912 // But first pretend the user is locked. Then it should fail.
913 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
914 try {
915 dpm.clearDeviceOwnerApp(admin1.getPackageName());
916 fail("Didn't throw IllegalStateException");
917 } catch (IllegalStateException expected) {
918 MoreAsserts.assertContainsRegex(
919 "User must be running and unlocked", expected.getMessage());
920 }
921
922 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800923 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700924 dpm.clearDeviceOwnerApp(admin1.getPackageName());
925
926 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800927 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700928
Makoto Onuki90b89652016-01-28 14:44:18 -0800929 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
930 eq(UserHandle.USER_SYSTEM),
931 MockUtils.checkUserRestrictions(),
932 MockUtils.checkUserRestrictions()
933 );
934
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700935 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100936
937 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
938 // and once for clearing it.
939 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
940 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
941 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700942 // TODO Check other calls.
943 }
944
945 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
946 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800947 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700948 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
949 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
950
951 // Set admin1 as a DA to the secondary user.
952 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
953
954 dpm.setActiveAdmin(admin1, /* replace =*/ false);
955
956 // Set admin 1 as the DO to the system user.
957
958 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
959 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
960 dpm.setActiveAdmin(admin1, /* replace =*/ false);
961 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
962
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000963 // Verify internal calls.
964 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
965 eq(admin1.getPackageName()));
966
Makoto Onukic8a5a552015-11-19 14:29:12 -0800967 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700968
969 // Now call clear from the secondary user, which should throw.
970 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
971
972 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700973 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700974 eq(admin1.getPackageName()),
975 anyInt());
976 try {
977 dpm.clearDeviceOwnerApp(admin1.getPackageName());
978 fail("Didn't throw");
979 } catch (SecurityException e) {
980 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
981 }
982
Makoto Onukic8a5a552015-11-19 14:29:12 -0800983 // DO shouldn't be removed.
984 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700985 }
986
Makoto Onukib643fb02015-09-22 15:03:44 -0700987 public void testSetProfileOwner() throws Exception {
988 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700989
Makoto Onuki90b89652016-01-28 14:44:18 -0800990 // PO admin can't be deactivated.
991 dpm.removeActiveAdmin(admin1);
992 assertTrue(dpm.isAdminActive(admin1));
993
Makoto Onuki803d6752015-10-30 12:58:39 -0700994 // Try setting DO on the same user, which should fail.
995 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
996 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
997 try {
998 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
999 fail("IllegalStateException not thrown");
1000 } catch (IllegalStateException expected) {
1001 assertTrue("Message was: " + expected.getMessage(),
1002 expected.getMessage().contains("already has a profile owner"));
1003 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001004 }
1005
Makoto Onuki90b89652016-01-28 14:44:18 -08001006 public void testClearProfileOwner() throws Exception {
1007 setAsProfileOwner(admin1);
1008
1009 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1010
1011 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1012 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1013
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001014 // First try when the user is locked, which should fail.
1015 when(mContext.userManager.isUserUnlocked(anyInt()))
1016 .thenReturn(false);
1017 try {
1018 dpm.clearProfileOwner(admin1);
1019 fail("Didn't throw IllegalStateException");
1020 } catch (IllegalStateException expected) {
1021 MoreAsserts.assertContainsRegex(
1022 "User must be running and unlocked", expected.getMessage());
1023 }
1024 // Clear, really.
1025 when(mContext.userManager.isUserUnlocked(anyInt()))
1026 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001027 dpm.clearProfileOwner(admin1);
1028
1029 // Check
1030 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001031 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001032 }
1033
Makoto Onukib643fb02015-09-22 15:03:44 -07001034 public void testSetProfileOwner_failures() throws Exception {
1035 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1036 }
1037
Makoto Onukia52562c2015-10-01 16:12:31 -07001038 public void testGetDeviceOwnerAdminLocked() throws Exception {
1039 checkDeviceOwnerWithMultipleDeviceAdmins();
1040 }
1041
1042 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1043 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1044 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1045 // make sure it gets the right component from the right user.
1046
1047 final int ANOTHER_USER_ID = 100;
1048 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1049
1050 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1051
1052 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001053 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001054 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1055 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1056
1057 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1058
Victor Change29cd472016-03-02 20:57:42 +00001059 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1060
Makoto Onukia52562c2015-10-01 16:12:31 -07001061 // Make sure the admin packge is installed to each user.
1062 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1063 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1064
1065 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1066 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1067
1068 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1069
1070
1071 // Set active admins to the users.
1072 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1073 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1074
1075 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1076 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1077
1078 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1079
1080 // Set DO on the first non-system user.
1081 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1082 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1083
Makoto Onukic8a5a552015-11-19 14:29:12 -08001084 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001085
1086 // Then check getDeviceOwnerAdminLocked().
1087 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1088 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1089 }
1090
1091 /**
1092 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001093 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1094 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001095 *
1096 * We didn't use to persist the DO component class name, but now we do, and the above method
1097 * finds the right component from a package name upon migration.
1098 */
1099 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001100 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 checkDeviceOwnerWithMultipleDeviceAdmins();
1102
1103 // Overwrite the device owner setting and clears the clas name.
1104 dpms.mOwners.setDeviceOwner(
1105 new ComponentName(admin2.getPackageName(), ""),
1106 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1107 dpms.mOwners.writeDeviceOwner();
1108
1109 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001110 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001111
1112 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001113 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1114 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001115 initializeDpms();
1116
1117 // Now the DO component name is a full name.
1118 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1119 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001121 }
1122
Makoto Onukib643fb02015-09-22 15:03:44 -07001123 public void testSetGetApplicationRestriction() {
1124 setAsProfileOwner(admin1);
1125
1126 {
1127 Bundle rest = new Bundle();
1128 rest.putString("KEY_STRING", "Foo1");
1129 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1130 }
1131
1132 {
1133 Bundle rest = new Bundle();
1134 rest.putString("KEY_STRING", "Foo2");
1135 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1136 }
1137
1138 {
1139 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1140 assertNotNull(returned);
1141 assertEquals(returned.size(), 1);
1142 assertEquals(returned.get("KEY_STRING"), "Foo1");
1143 }
1144
1145 {
1146 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1147 assertNotNull(returned);
1148 assertEquals(returned.size(), 1);
1149 assertEquals(returned.get("KEY_STRING"), "Foo2");
1150 }
1151
1152 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1153 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1154 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001155
Esteban Talaverabf60f722015-12-10 16:26:44 +00001156 public void testApplicationRestrictionsManagingApp() throws Exception {
1157 setAsProfileOwner(admin1);
1158
Rubin Xued1928a2016-02-11 17:23:06 +00001159 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001160 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1161 final int appRestrictionsManagerAppId = 20987;
1162 final int appRestrictionsManagerUid = UserHandle.getUid(
1163 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001164 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001165 eq(appRestrictionsManagerPackage),
1166 eq(DpmMockContext.CALLER_USER_HANDLE));
1167 mContext.binder.callingUid = appRestrictionsManagerUid;
1168
Rubin Xued1928a2016-02-11 17:23:06 +00001169 final PackageInfo pi = new PackageInfo();
1170 pi.applicationInfo = new ApplicationInfo();
1171 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1172 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1173 eq(appRestrictionsManagerPackage),
1174 anyInt(),
1175 eq(DpmMockContext.CALLER_USER_HANDLE));
1176
Esteban Talaverabf60f722015-12-10 16:26:44 +00001177 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1178 // delegated that permission yet.
1179 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1180 Bundle rest = new Bundle();
1181 rest.putString("KEY_STRING", "Foo1");
1182 try {
1183 dpm.setApplicationRestrictions(null, "pkg1", rest);
1184 fail("Didn't throw expected SecurityException");
1185 } catch (SecurityException expected) {
1186 MoreAsserts.assertContainsRegex(
1187 "caller cannot manage application restrictions", expected.getMessage());
1188 }
1189 try {
1190 dpm.getApplicationRestrictions(null, "pkg1");
1191 fail("Didn't throw expected SecurityException");
1192 } catch (SecurityException expected) {
1193 MoreAsserts.assertContainsRegex(
1194 "caller cannot manage application restrictions", expected.getMessage());
1195 }
1196
1197 // Check via the profile owner that no restrictions were set.
1198 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1199 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1200
Rubin Xued1928a2016-02-11 17:23:06 +00001201 // Check the API does not allow setting a non-existent package
1202 try {
1203 dpm.setApplicationRestrictionsManagingPackage(admin1,
1204 nonExistAppRestrictionsManagerPackage);
1205 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001206 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001207 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001208 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001209 }
1210
Esteban Talaverabf60f722015-12-10 16:26:44 +00001211 // Let appRestrictionsManagerPackage manage app restrictions
1212 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1213 assertEquals(appRestrictionsManagerPackage,
1214 dpm.getApplicationRestrictionsManagingPackage(admin1));
1215
1216 // Now that package should be able to set and retrieve app restrictions.
1217 mContext.binder.callingUid = appRestrictionsManagerUid;
1218 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1219 dpm.setApplicationRestrictions(null, "pkg1", rest);
1220 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1221 assertEquals(1, returned.size(), 1);
1222 assertEquals("Foo1", returned.get("KEY_STRING"));
1223
1224 // The same app running on a separate user shouldn't be able to manage app restrictions.
1225 mContext.binder.callingUid = UserHandle.getUid(
1226 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1227 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1228 try {
1229 dpm.setApplicationRestrictions(null, "pkg1", rest);
1230 fail("Didn't throw expected SecurityException");
1231 } catch (SecurityException expected) {
1232 MoreAsserts.assertContainsRegex(
1233 "caller cannot manage application restrictions", expected.getMessage());
1234 }
1235
1236 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1237 // too.
1238 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1239 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1240 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1241 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1242
1243 // Removing the ability for the package to manage app restrictions.
1244 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1245 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1246 mContext.binder.callingUid = appRestrictionsManagerUid;
1247 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1248 try {
1249 dpm.setApplicationRestrictions(null, "pkg1", null);
1250 fail("Didn't throw expected SecurityException");
1251 } catch (SecurityException expected) {
1252 MoreAsserts.assertContainsRegex(
1253 "caller cannot manage application restrictions", expected.getMessage());
1254 }
1255 }
1256
Makoto Onukia4f11972015-10-01 13:19:58 -07001257 public void testSetUserRestriction_asDo() throws Exception {
1258 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001259 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1261 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1262
1263 // First, set DO.
1264
1265 // Call from a process on the system user.
1266 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1267
1268 // Make sure admin1 is installed on system user.
1269 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001270
1271 // Call.
1272 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001273 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001274 UserHandle.USER_SYSTEM));
1275
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001276 // Check that the user restrictions that are enabled by default are set. Then unset them.
1277 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001278 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001279 DpmTestUtils.assertRestrictions(
1280 DpmTestUtils.newRestrictions(defaultRestrictions),
1281 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1282 );
1283 DpmTestUtils.assertRestrictions(
1284 DpmTestUtils.newRestrictions(defaultRestrictions),
1285 dpm.getUserRestrictions(admin1)
1286 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001287 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1288 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001289 MockUtils.checkUserRestrictions(defaultRestrictions),
1290 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001291 );
1292 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001293
1294 for (String restriction : defaultRestrictions) {
1295 dpm.clearUserRestriction(admin1, restriction);
1296 }
1297
Esteban Talavera548a04b2016-12-20 15:22:30 +00001298 assertNoDeviceOwnerRestrictions();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001299
1300 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1301 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1302 eq(UserHandle.USER_SYSTEM),
1303 MockUtils.checkUserRestrictions(),
1304 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001305 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001306 reset(mContext.userManagerInternal);
1307
Makoto Onukia4f11972015-10-01 13:19:58 -07001308 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1310 eq(UserHandle.USER_SYSTEM),
1311 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1313 );
1314 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001315
Makoto Onuki068c54a2015-10-13 14:34:03 -07001316 DpmTestUtils.assertRestrictions(
1317 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001318 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1320 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001321 DpmTestUtils.assertRestrictions(
1322 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001324 dpm.getUserRestrictions(admin1)
1325 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001326
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001327 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1328 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1329 eq(UserHandle.USER_SYSTEM),
1330 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1331 MockUtils.checkUserRestrictions()
1332 );
1333 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001334
Makoto Onuki068c54a2015-10-13 14:34:03 -07001335 DpmTestUtils.assertRestrictions(
1336 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1337 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1338 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001339 DpmTestUtils.assertRestrictions(
1340 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1341 dpm.getUserRestrictions(admin1)
1342 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001343
1344 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1346 eq(UserHandle.USER_SYSTEM),
1347 MockUtils.checkUserRestrictions(),
1348 MockUtils.checkUserRestrictions()
1349 );
1350 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001351
Esteban Talavera548a04b2016-12-20 15:22:30 +00001352 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001353
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001354 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1355 // DO sets them, the scope is global.
1356 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1357 reset(mContext.userManagerInternal);
1358 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1359 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1360 eq(UserHandle.USER_SYSTEM),
1361 MockUtils.checkUserRestrictions(),
1362 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1363 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1364 );
1365 reset(mContext.userManagerInternal);
1366
1367 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1368 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1369
1370
1371 // More tests.
1372 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1373 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1374 eq(UserHandle.USER_SYSTEM),
1375 MockUtils.checkUserRestrictions(),
1376 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1377 );
1378 reset(mContext.userManagerInternal);
1379
1380 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1381 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1382 eq(UserHandle.USER_SYSTEM),
1383 MockUtils.checkUserRestrictions(),
1384 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1385 UserManager.DISALLOW_ADD_USER)
1386 );
1387 reset(mContext.userManagerInternal);
1388
1389 dpm.setCameraDisabled(admin1, true);
1390 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1391 eq(UserHandle.USER_SYSTEM),
1392 // DISALLOW_CAMERA will be applied to both local and global.
1393 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1394 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1395 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1396 );
1397 reset(mContext.userManagerInternal);
1398
1399 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1400 // locally.
1401 dpm.setCameraDisabled(admin1, false);
1402 reset(mContext.userManagerInternal);
1403
1404 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1405 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1406 dpm.setCameraDisabled(admin2, true);
1407
1408 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1409 eq(UserHandle.USER_SYSTEM),
1410 // DISALLOW_CAMERA will be applied to both local and global.
1411 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1412 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1413 UserManager.DISALLOW_ADD_USER)
1414 );
1415 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001416 // TODO Make sure restrictions are written to the file.
1417 }
1418
1419 public void testSetUserRestriction_asPo() {
1420 setAsProfileOwner(admin1);
1421
Makoto Onuki068c54a2015-10-13 14:34:03 -07001422 DpmTestUtils.assertRestrictions(
1423 DpmTestUtils.newRestrictions(),
1424 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1425 .ensureUserRestrictions()
1426 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001427
1428 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1430 eq(DpmMockContext.CALLER_USER_HANDLE),
1431 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1432 isNull(Bundle.class)
1433 );
1434 reset(mContext.userManagerInternal);
1435
Makoto Onukia4f11972015-10-01 13:19:58 -07001436 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001437 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1438 eq(DpmMockContext.CALLER_USER_HANDLE),
1439 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1440 UserManager.DISALLOW_OUTGOING_CALLS),
1441 isNull(Bundle.class)
1442 );
1443 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001444
Makoto Onuki068c54a2015-10-13 14:34:03 -07001445 DpmTestUtils.assertRestrictions(
1446 DpmTestUtils.newRestrictions(
1447 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1448 UserManager.DISALLOW_OUTGOING_CALLS
1449 ),
1450 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1451 .ensureUserRestrictions()
1452 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001453 DpmTestUtils.assertRestrictions(
1454 DpmTestUtils.newRestrictions(
1455 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1456 UserManager.DISALLOW_OUTGOING_CALLS
1457 ),
1458 dpm.getUserRestrictions(admin1)
1459 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001460
1461 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1463 eq(DpmMockContext.CALLER_USER_HANDLE),
1464 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1465 isNull(Bundle.class)
1466 );
1467 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001468
1469 DpmTestUtils.assertRestrictions(
1470 DpmTestUtils.newRestrictions(
1471 UserManager.DISALLOW_OUTGOING_CALLS
1472 ),
1473 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1474 .ensureUserRestrictions()
1475 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001476 DpmTestUtils.assertRestrictions(
1477 DpmTestUtils.newRestrictions(
1478 UserManager.DISALLOW_OUTGOING_CALLS
1479 ),
1480 dpm.getUserRestrictions(admin1)
1481 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001482
1483 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001484 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1485 eq(DpmMockContext.CALLER_USER_HANDLE),
1486 MockUtils.checkUserRestrictions(),
1487 isNull(Bundle.class)
1488 );
1489 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001490
Makoto Onuki068c54a2015-10-13 14:34:03 -07001491 DpmTestUtils.assertRestrictions(
1492 DpmTestUtils.newRestrictions(),
1493 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1494 .ensureUserRestrictions()
1495 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001496 DpmTestUtils.assertRestrictions(
1497 DpmTestUtils.newRestrictions(),
1498 dpm.getUserRestrictions(admin1)
1499 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001500
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1502 // though when DO sets them they'll be applied globally.
1503 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1504 reset(mContext.userManagerInternal);
1505 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1506 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1507 eq(DpmMockContext.CALLER_USER_HANDLE),
1508 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1509 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1510 isNull(Bundle.class)
1511 );
1512 reset(mContext.userManagerInternal);
1513
1514 dpm.setCameraDisabled(admin1, true);
1515 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1516 eq(DpmMockContext.CALLER_USER_HANDLE),
1517 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1518 UserManager.DISALLOW_ADJUST_VOLUME,
1519 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1520 isNull(Bundle.class)
1521 );
1522 reset(mContext.userManagerInternal);
1523
Makoto Onukia4f11972015-10-01 13:19:58 -07001524 // TODO Make sure restrictions are written to the file.
1525 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001526
Esteban Talavera548a04b2016-12-20 15:22:30 +00001527
1528 public void testDefaultEnabledUserRestrictions() throws Exception {
1529 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1530 mContext.callerPermissions.add(permission.MANAGE_USERS);
1531 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1532 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1533
1534 // First, set DO.
1535
1536 // Call from a process on the system user.
1537 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1538
1539 // Make sure admin1 is installed on system user.
1540 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1541
1542 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1543 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1544 UserHandle.USER_SYSTEM));
1545
1546 // Check that the user restrictions that are enabled by default are set. Then unset them.
1547 String[] defaultRestrictions = UserRestrictionsUtils
1548 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1549 assertTrue(defaultRestrictions.length > 0);
1550 DpmTestUtils.assertRestrictions(
1551 DpmTestUtils.newRestrictions(defaultRestrictions),
1552 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1553 );
1554 DpmTestUtils.assertRestrictions(
1555 DpmTestUtils.newRestrictions(defaultRestrictions),
1556 dpm.getUserRestrictions(admin1)
1557 );
1558 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1559 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001560 MockUtils.checkUserRestrictions(defaultRestrictions),
1561 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001562 );
1563 reset(mContext.userManagerInternal);
1564
1565 for (String restriction : defaultRestrictions) {
1566 dpm.clearUserRestriction(admin1, restriction);
1567 }
1568
1569 assertNoDeviceOwnerRestrictions();
1570
1571 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1572 reset(mContext.userManagerInternal);
1573 initializeDpms();
1574 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1575 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1576
1577 assertNoDeviceOwnerRestrictions();
1578
1579 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1580 // is set as it wasn't enabled during setDeviceOwner.
1581 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1582 assertFalse(UserRestrictionsUtils
1583 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1584 UserRestrictionsUtils
1585 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1586 try {
1587 reset(mContext.userManagerInternal);
1588 initializeDpms();
1589 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1590 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1591
1592 DpmTestUtils.assertRestrictions(
1593 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1594 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1595 );
1596 DpmTestUtils.assertRestrictions(
1597 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1598 dpm.getUserRestrictions(admin1)
1599 );
1600 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1601 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001602 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
1603 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001604 );
1605 reset(mContext.userManagerInternal);
1606
1607 // Remove the restriction.
1608 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1609
1610 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1611 initializeDpms();
1612 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1613 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1614 assertNoDeviceOwnerRestrictions();
1615 } finally {
1616 UserRestrictionsUtils
1617 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1618 }
1619 }
1620
1621 private void assertNoDeviceOwnerRestrictions() {
1622 DpmTestUtils.assertRestrictions(
1623 DpmTestUtils.newRestrictions(),
1624 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1625 );
1626 DpmTestUtils.assertRestrictions(
1627 DpmTestUtils.newRestrictions(),
1628 dpm.getUserRestrictions(admin1)
1629 );
1630 }
1631
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001632 public void testGetMacAddress() throws Exception {
1633 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1634 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1635 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1636
1637 // In this test, change the caller user to "system".
1638 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1639
1640 // Make sure admin1 is installed on system user.
1641 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1642
1643 // Test 1. Caller doesn't have DO or DA.
1644 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001645 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001646 fail();
1647 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001648 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001649 }
1650
1651 // DO needs to be an DA.
1652 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1653 assertTrue(dpm.isAdminActive(admin1));
1654
1655 // Test 2. Caller has DA, but not DO.
1656 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001657 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001658 fail();
1659 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001660 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001661 }
1662
1663 // Test 3. Caller has PO, but not DO.
1664 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1665 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001666 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001667 fail();
1668 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001669 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001670 }
1671
1672 // Remove PO.
1673 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001674 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001675 // Test 4, Caller is DO now.
1676 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1677
1678 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001679 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001680
1681 // 4-2. Returns WifiInfo, but with the default MAC.
1682 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001683 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001684
1685 // 4-3. With a real MAC address.
1686 final WifiInfo wi = new WifiInfo();
1687 wi.setMacAddress("11:22:33:44:55:66");
1688 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001689 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001690 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001691
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001692 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001693 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1694 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1695
1696 // In this test, change the caller user to "system".
1697 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1698
1699 // Make sure admin1 is installed on system user.
1700 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1701
1702 // Set admin1 as DA.
1703 dpm.setActiveAdmin(admin1, false);
1704 assertTrue(dpm.isAdminActive(admin1));
1705 try {
1706 dpm.reboot(admin1);
1707 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1708 } catch (SecurityException expected) {
1709 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1710 }
1711
1712 // Set admin1 as PO.
1713 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1714 try {
1715 dpm.reboot(admin1);
1716 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1717 } catch (SecurityException expected) {
1718 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1719 }
1720
1721 // Remove PO and add DO.
1722 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001723 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001724 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1725
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001726 // admin1 is DO.
1727 // Set current call state of device to ringing.
1728 when(mContext.telephonyManager.getCallState())
1729 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1730 try {
1731 dpm.reboot(admin1);
1732 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1733 } catch (IllegalStateException expected) {
1734 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1735 }
1736
1737 // Set current call state of device to dialing/active.
1738 when(mContext.telephonyManager.getCallState())
1739 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1740 try {
1741 dpm.reboot(admin1);
1742 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1743 } catch (IllegalStateException expected) {
1744 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1745 }
1746
1747 // Set current call state of device to idle.
1748 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001749 dpm.reboot(admin1);
1750 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001751
1752 public void testSetGetSupportText() {
1753 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1754 dpm.setActiveAdmin(admin1, true);
1755 dpm.setActiveAdmin(admin2, true);
1756 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1757
1758 // Null default support messages.
1759 {
1760 assertNull(dpm.getLongSupportMessage(admin1));
1761 assertNull(dpm.getShortSupportMessage(admin1));
1762 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1763 assertNull(dpm.getShortSupportMessageForUser(admin1,
1764 DpmMockContext.CALLER_USER_HANDLE));
1765 assertNull(dpm.getLongSupportMessageForUser(admin1,
1766 DpmMockContext.CALLER_USER_HANDLE));
1767 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1768 }
1769
1770 // Only system can call the per user versions.
1771 {
1772 try {
1773 dpm.getShortSupportMessageForUser(admin1,
1774 DpmMockContext.CALLER_USER_HANDLE);
1775 fail("Only system should be able to call getXXXForUser versions");
1776 } catch (SecurityException expected) {
1777 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1778 }
1779 try {
1780 dpm.getLongSupportMessageForUser(admin1,
1781 DpmMockContext.CALLER_USER_HANDLE);
1782 fail("Only system should be able to call getXXXForUser versions");
1783 } catch (SecurityException expected) {
1784 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1785 }
1786 }
1787
1788 // Can't set message for admin in another uid.
1789 {
1790 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1791 try {
1792 dpm.setShortSupportMessage(admin1, "Some text");
1793 fail("Admins should only be able to change their own support text.");
1794 } catch (SecurityException expected) {
1795 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1796 }
1797 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1798 }
1799
1800 // Set/Get short returns what it sets and other admins text isn't changed.
1801 {
1802 final String supportText = "Some text to test with.";
1803 dpm.setShortSupportMessage(admin1, supportText);
1804 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1805 assertNull(dpm.getLongSupportMessage(admin1));
1806 assertNull(dpm.getShortSupportMessage(admin2));
1807
1808 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1809 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1810 DpmMockContext.CALLER_USER_HANDLE));
1811 assertNull(dpm.getShortSupportMessageForUser(admin2,
1812 DpmMockContext.CALLER_USER_HANDLE));
1813 assertNull(dpm.getLongSupportMessageForUser(admin1,
1814 DpmMockContext.CALLER_USER_HANDLE));
1815 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1816
1817 dpm.setShortSupportMessage(admin1, null);
1818 assertNull(dpm.getShortSupportMessage(admin1));
1819 }
1820
1821 // Set/Get long returns what it sets and other admins text isn't changed.
1822 {
1823 final String supportText = "Some text to test with.\nWith more text.";
1824 dpm.setLongSupportMessage(admin1, supportText);
1825 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1826 assertNull(dpm.getShortSupportMessage(admin1));
1827 assertNull(dpm.getLongSupportMessage(admin2));
1828
1829 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1830 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1831 DpmMockContext.CALLER_USER_HANDLE));
1832 assertNull(dpm.getLongSupportMessageForUser(admin2,
1833 DpmMockContext.CALLER_USER_HANDLE));
1834 assertNull(dpm.getShortSupportMessageForUser(admin1,
1835 DpmMockContext.CALLER_USER_HANDLE));
1836 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1837
1838 dpm.setLongSupportMessage(admin1, null);
1839 assertNull(dpm.getLongSupportMessage(admin1));
1840 }
1841 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001842
1843 /**
1844 * Test for:
1845 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001846 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001847 * {@link DevicePolicyManager#isAffiliatedUser}
1848 */
1849 public void testUserAffiliation() throws Exception {
1850 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1852 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1853
1854 // Check that the system user is unaffiliated.
1855 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1856 assertFalse(dpm.isAffiliatedUser());
1857
1858 // Set a device owner on the system user. Check that the system user becomes affiliated.
1859 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1860 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1861 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1862 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001863 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001864
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001865 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001866 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1867 setAsProfileOwner(admin2);
1868 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001869 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001870
1871 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1872 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001873 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001874 userAffiliationIds.add("red");
1875 userAffiliationIds.add("green");
1876 userAffiliationIds.add("blue");
1877 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001878 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001879 assertFalse(dpm.isAffiliatedUser());
1880
1881 // Have the device owner specify a set of affiliation ids that do not intersect with those
1882 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001883 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001884 deviceAffiliationIds.add("cyan");
1885 deviceAffiliationIds.add("yellow");
1886 deviceAffiliationIds.add("magenta");
1887 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1888 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001889 MoreAsserts.assertContentsInAnyOrder(
1890 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001891 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1892 assertFalse(dpm.isAffiliatedUser());
1893
1894 // Have the profile owner specify a set of affiliation ids that intersect with those
1895 // specified by the device owner. Check that the test user becomes affiliated.
1896 userAffiliationIds.add("yellow");
1897 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001898 MoreAsserts.assertContentsInAnyOrder(
1899 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001900 assertTrue(dpm.isAffiliatedUser());
1901
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001902 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1903 dpm.setAffiliationIds(admin2, Collections.emptyList());
1904 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001905 assertFalse(dpm.isAffiliatedUser());
1906
1907 // Check that the system user remains affiliated.
1908 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1909 assertTrue(dpm.isAffiliatedUser());
1910 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001911
1912 public void testGetUserProvisioningState_defaultResult() {
1913 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1914 }
1915
1916 public void testSetUserProvisioningState_permission() throws Exception {
1917 setupProfileOwner();
1918 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1919
1920 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1921 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1922 }
1923
1924 public void testSetUserProvisioningState_unprivileged() throws Exception {
1925 setupProfileOwner();
1926 try {
1927 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1928 DpmMockContext.CALLER_USER_HANDLE);
1929 fail("Expected SecurityException");
1930 } catch (SecurityException expected) {
1931 }
1932 }
1933
1934 public void testSetUserProvisioningState_noManagement() {
1935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1936 try {
1937 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1938 DpmMockContext.CALLER_USER_HANDLE);
1939 fail("IllegalStateException expected");
1940 } catch (IllegalStateException e) {
1941 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1942 e.getMessage());
1943 }
1944 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1945 }
1946
1947 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1948 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1949 setupDeviceOwner();
1950 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1951
1952 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1953 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1954 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1955 }
1956
1957 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1958 throws Exception {
1959 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1960 setupDeviceOwner();
1961 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1962
1963 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1964 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1965 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1966 }
1967
1968 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1969 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1970 setupDeviceOwner();
1971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1972
1973 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1974 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1975 }
1976
1977 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1978 throws Exception {
1979 setupProfileOwner();
1980 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1981
1982 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1983 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1984 DevicePolicyManager.STATE_USER_UNMANAGED);
1985 }
1986
1987 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1988 throws Exception {
1989 setupProfileOwner();
1990 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1991
1992 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1993 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1994 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1995 }
1996
1997 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1998 setupProfileOwner();
1999 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2000
2001 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2002 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2003 }
2004
2005 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2006 setupProfileOwner();
2007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2008
2009 try {
2010 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2011 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2012 DevicePolicyManager.STATE_USER_UNMANAGED);
2013 fail("Expected IllegalStateException");
2014 } catch (IllegalStateException e) {
2015 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2016 e.getMessage());
2017 }
2018 }
2019
2020 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2021 throws Exception {
2022 setupProfileOwner();
2023 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2024
2025 try {
2026 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2027 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2028 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2029 fail("Expected IllegalStateException");
2030 } catch (IllegalStateException e) {
2031 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2032 e.getMessage());
2033 }
2034 }
2035
2036 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2037 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2038 for (int state : states) {
2039 dpm.setUserProvisioningState(state, userId);
2040 assertEquals(state, dpm.getUserProvisioningState());
2041 }
2042 }
2043
2044 private void setupProfileOwner() throws Exception {
2045 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2046
2047 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2048 dpm.setActiveAdmin(admin1, false);
2049 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2050
2051 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2052 }
2053
2054 private void setupDeviceOwner() throws Exception {
2055 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2056
2057 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2058 dpm.setActiveAdmin(admin1, false);
2059 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2060
2061 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2062 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002063
2064 public void testSetMaximumTimeToLock() {
2065 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2066
2067 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2068 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2069
2070 reset(mMockContext.powerManagerInternal);
2071 reset(mMockContext.settings);
2072
2073 dpm.setMaximumTimeToLock(admin1, 0);
2074 verifyScreenTimeoutCall(null, false);
2075 reset(mMockContext.powerManagerInternal);
2076 reset(mMockContext.settings);
2077
2078 dpm.setMaximumTimeToLock(admin1, 1);
2079 verifyScreenTimeoutCall(1, true);
2080 reset(mMockContext.powerManagerInternal);
2081 reset(mMockContext.settings);
2082
2083 dpm.setMaximumTimeToLock(admin2, 10);
2084 verifyScreenTimeoutCall(null, false);
2085 reset(mMockContext.powerManagerInternal);
2086 reset(mMockContext.settings);
2087
2088 dpm.setMaximumTimeToLock(admin1, 5);
2089 verifyScreenTimeoutCall(5, true);
2090 reset(mMockContext.powerManagerInternal);
2091 reset(mMockContext.settings);
2092
2093 dpm.setMaximumTimeToLock(admin2, 4);
2094 verifyScreenTimeoutCall(4, true);
2095 reset(mMockContext.powerManagerInternal);
2096 reset(mMockContext.settings);
2097
2098 dpm.setMaximumTimeToLock(admin1, 0);
2099 reset(mMockContext.powerManagerInternal);
2100 reset(mMockContext.settings);
2101
2102 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2103 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2104 reset(mMockContext.powerManagerInternal);
2105 reset(mMockContext.settings);
2106
2107 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2108 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2109 reset(mMockContext.powerManagerInternal);
2110 reset(mMockContext.settings);
2111
2112 dpm.setMaximumTimeToLock(admin2, 10);
2113 verifyScreenTimeoutCall(10, true);
2114 reset(mMockContext.powerManagerInternal);
2115 reset(mMockContext.settings);
2116
2117 // There's no restriction; shold be set to MAX.
2118 dpm.setMaximumTimeToLock(admin2, 0);
2119 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2120 }
2121
Michal Karpinski943aabd2016-10-06 11:09:25 +01002122 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2124 setupDeviceOwner();
2125 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2126
2127 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
2128 final long ONE_MINUTE = 60 * 1000;
2129
2130 // aggregation should be the default if unset by any admin
2131 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2132 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2133
2134 // admin not participating by default
2135 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2136
2137 //clamping from the top
2138 dpm.setRequiredStrongAuthTimeout(admin1,
2139 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2140 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2141 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2142 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2143 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2144
2145 // 0 means default
2146 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2147 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2148 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2149 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2150
2151 // clamping from the bottom
2152 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2153 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2154 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2155
2156 // value within range
2157 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2158 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2159 + ONE_MINUTE);
2160 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2161 + ONE_MINUTE);
2162
2163 // reset to default
2164 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2165 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2166 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2167 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2168
2169 // negative value
2170 try {
2171 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2172 fail("Didn't throw IllegalArgumentException");
2173 } catch (IllegalArgumentException iae) {
2174 }
2175 }
2176
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002177 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2178 boolean shouldStayOnWhilePluggedInBeCleared) {
2179 if (expectedTimeout == null) {
2180 verify(mMockContext.powerManagerInternal, times(0))
2181 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2182 } else {
2183 verify(mMockContext.powerManagerInternal, times(1))
2184 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2185 }
2186 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2187 // UnfinishedVerificationException.
2188 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002189
Esteban Talavera01576862016-12-15 11:16:44 +00002190 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002191 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2192 .thenReturn(false);
2193 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2194 .thenReturn(false);
2195 initializeDpms();
2196 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2197 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2198 .thenReturn(true);
2199 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2200
2201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002202 }
Victor Chang3e794af2016-03-04 13:48:17 +00002203
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002204 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2205 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002206 mContext.packageName = admin1.getPackageName();
2207 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002208 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2209 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2210 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2211 false);
2212 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2213 }
2214
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002215 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2216 setup_DeviceAdminFeatureOff();
2217 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2218 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2219 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2220 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2221 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2222 assertCheckProvisioningPreCondition(
2223 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2224 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2225 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2226 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2227 }
2228
Esteban Talavera01576862016-12-15 11:16:44 +00002229 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002230 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2231 .thenReturn(false);
2232 initializeDpms();
2233 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2234 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2235 .thenReturn(true);
2236 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2237
2238 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002239 }
Victor Chang3e794af2016-03-04 13:48:17 +00002240
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002241 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2242 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002243 mContext.packageName = admin1.getPackageName();
2244 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002245 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2246 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2247 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2248 false);
2249 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2250
2251 // Test again when split user is on
2252 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2253 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2255 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2256 true);
2257 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2258 }
2259
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002260 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2261 setup_ManagedProfileFeatureOff();
2262 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2264 DevicePolicyManager.CODE_OK);
2265 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2266 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2267 assertCheckProvisioningPreCondition(
2268 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2269 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2270 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2271 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2272
2273 // Test again when split user is on
2274 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2275 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2276 DevicePolicyManager.CODE_OK);
2277 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2278 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2279 assertCheckProvisioningPreCondition(
2280 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2281 DevicePolicyManager.CODE_OK);
2282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2283 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2284 }
2285
Esteban Talavera01576862016-12-15 11:16:44 +00002286 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002287 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2288 .thenReturn(true);
2289 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2290 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2291 .thenReturn(true);
2292 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2293
2294 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002295 }
Victor Chang3e794af2016-03-04 13:48:17 +00002296
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002297 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2298 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002299 mContext.packageName = admin1.getPackageName();
2300 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002301 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2302 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2303 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2304 false /* because of non-split user */);
2305 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2306 false /* because of non-split user */);
2307 }
2308
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002309 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002310 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002311 setup_nonSplitUser_firstBoot_primaryUser();
2312 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2313 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2314 DevicePolicyManager.CODE_OK);
2315 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2316 DevicePolicyManager.CODE_OK);
2317 assertCheckProvisioningPreCondition(
2318 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2319 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2320 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2321 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2322 }
2323
Esteban Talavera01576862016-12-15 11:16:44 +00002324 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002325 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2326 .thenReturn(true);
2327 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2328 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2329 .thenReturn(true);
2330 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2331
2332 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002333 }
Victor Chang3e794af2016-03-04 13:48:17 +00002334
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002335 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2336 throws Exception {
2337 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002338 mContext.packageName = admin1.getPackageName();
2339 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002340 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2341 false/* because of completed device setup */);
2342 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2343 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2344 false/* because of non-split user */);
2345 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2346 false/* because of non-split user */);
2347 }
2348
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002349 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2350 throws Exception {
2351 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2352 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2353 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2354 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2355 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2356 DevicePolicyManager.CODE_OK);
2357 assertCheckProvisioningPreCondition(
2358 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2359 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2360 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2361 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2362 }
2363
Esteban Talavera01576862016-12-15 11:16:44 +00002364 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2365 setDeviceOwner();
2366 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2367 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2368 mContext.packageName = admin1.getPackageName();
2369
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002370 final ComponentName adminDifferentPackage =
2371 new ComponentName("another.package", "whatever.random.class");
2372 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2373 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2374
Esteban Talavera01576862016-12-15 11:16:44 +00002375 // COMP mode is allowed.
2376 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2377
2378 when(mContext.userManager.hasUserRestriction(
2379 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2380 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2381 .thenReturn(true);
2382
2383 // The DO should be allowed to initiate provisioning if it set the restriction itself.
2384 when(mContext.userManager.getUserRestrictionSource(
2385 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2386 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2387 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2388 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2389
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002390 // But another app should not
2391 mContext.binder.callingUid = ANOTHER_UID;
2392 mContext.packageName = adminDifferentPackage.getPackageName();
2393 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2394
Esteban Talavera01576862016-12-15 11:16:44 +00002395 // The DO should not be allowed to initiate provisioning if the restriction is set by
2396 // another entity.
2397 when(mContext.userManager.getUserRestrictionSource(
2398 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2399 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2400 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
Nicolas Prevotc3bd7b72017-01-10 11:32:43 +00002401 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2402 mContext.packageName = admin1.getPackageName();
2403 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2404
2405 mContext.binder.callingUid = ANOTHER_UID;
2406 mContext.packageName = adminDifferentPackage.getPackageName();
2407 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2408 }
2409
2410 public void testIsProvisioningAllowed_nonSplitUser_comp() throws Exception {
2411 setDeviceOwner();
2412 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2413 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2414
2415 final ComponentName adminDifferentPackage =
2416 new ComponentName("another.package", "whatever.class");
2417 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 948);
2418 setUpPackageManagerForFakeAdmin(adminDifferentPackage, ANOTHER_UID, admin2);
2419
2420 final int MANAGED_PROFILE_USER_ID = 18;
2421 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2422 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2423
2424 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2425 false /* we can't remove a managed profile */)).thenReturn(false);
2426 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2427 true)).thenReturn(true);
2428
2429 // We can delete the managed profile to create a new one, so provisioning is allowed.
2430 mContext.packageName = admin1.getPackageName();
2431 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2432 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2433
2434 mContext.packageName = adminDifferentPackage.getPackageName();
2435 mContext.binder.callingUid = ANOTHER_UID;
2436 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2437
2438 when(mContext.userManager.hasUserRestriction(
2439 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2440 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
2441 .thenReturn(true);
2442
2443 // Now, we can't remove the profile any more to create a new one.
2444 mContext.packageName = admin1.getPackageName();
2445 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2446 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2447
2448 mContext.packageName = adminDifferentPackage.getPackageName();
2449 mContext.binder.callingUid = ANOTHER_UID;
Esteban Talavera01576862016-12-15 11:16:44 +00002450 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2451 }
2452
2453 public void
2454 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2455 setDeviceOwner();
2456 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2457 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2458
2459 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2460 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2461
2462 // COMP mode is allowed.
2463 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2464 DevicePolicyManager.CODE_OK);
2465
2466 // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2467 assertCheckProvisioningPreCondition(
2468 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2469 "some.other.dpc.package.name",
2470 DevicePolicyManager.CODE_OK);
2471
2472 when(mContext.userManager.hasUserRestriction(
2473 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2474 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2475 .thenReturn(true);
2476
2477 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2478 // other packages should be forbidden.
2479 when(mContext.userManager.getUserRestrictionSource(
2480 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2481 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2482 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2483 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2484 DevicePolicyManager.CODE_OK);
2485 assertCheckProvisioningPreCondition(
2486 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2487 "some.other.dpc.package.name",
2488 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2489
2490 // The DO should not be allowed to initiate provisioning if the restriction is set by
2491 // another entity.
2492 when(mContext.userManager.getUserRestrictionSource(
2493 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2494 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2495 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2496 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2497 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2498 assertCheckProvisioningPreCondition(
2499 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2500 "some.other.dpc.package.name",
2501 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2502 }
2503
2504 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002505 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2506 .thenReturn(true);
2507 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2508 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2509 .thenReturn(false);
2510 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2511
2512 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002513 }
Victor Chang3e794af2016-03-04 13:48:17 +00002514
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002515 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2516 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002517 mContext.packageName = admin1.getPackageName();
2518 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002519 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2520 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2521 false /* because canAddMoreManagedProfiles returns false */);
2522 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2523 true);
2524 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2525 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002526 }
2527
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002528 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2529 throws Exception {
2530 setup_splitUser_firstBoot_systemUser();
2531 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2533 DevicePolicyManager.CODE_OK);
2534 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002535 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002536 assertCheckProvisioningPreCondition(
2537 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2538 DevicePolicyManager.CODE_OK);
2539 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2540 DevicePolicyManager.CODE_SYSTEM_USER);
2541 }
2542
Esteban Talavera01576862016-12-15 11:16:44 +00002543 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002544 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2545 .thenReturn(true);
2546 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2547 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2548 .thenReturn(false);
2549 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2550
2551 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002552 }
Victor Chang3e794af2016-03-04 13:48:17 +00002553
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002554 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2555 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002556 mContext.packageName = admin1.getPackageName();
2557 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002558 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2559 true/* it's undefined behavior. Can be changed into false in the future */);
2560 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2561 false /* because canAddMoreManagedProfiles returns false */);
2562 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2563 true/* it's undefined behavior. Can be changed into false in the future */);
2564 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2565 false/* because calling uid is system user */);
2566 }
2567
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002568 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2569 throws Exception {
2570 setup_splitUser_afterDeviceSetup_systemUser();
2571 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2572 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2573 DevicePolicyManager.CODE_OK);
2574 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002575 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002576 assertCheckProvisioningPreCondition(
2577 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2578 DevicePolicyManager.CODE_OK);
2579 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2580 DevicePolicyManager.CODE_SYSTEM_USER);
2581 }
2582
Esteban Talavera01576862016-12-15 11:16:44 +00002583 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002584 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2585 .thenReturn(true);
2586 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2587 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2588 true)).thenReturn(true);
2589 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2590
2591 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002592 }
Victor Chang3e794af2016-03-04 13:48:17 +00002593
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002594 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2595 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002596 mContext.packageName = admin1.getPackageName();
2597 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002598 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2599 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2600 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2601 true);
2602 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002603 }
2604
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002605 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002606 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002607 setup_splitUser_firstBoot_primaryUser();
2608 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2609 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2610 DevicePolicyManager.CODE_OK);
2611 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2612 DevicePolicyManager.CODE_OK);
2613 assertCheckProvisioningPreCondition(
2614 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2615 DevicePolicyManager.CODE_OK);
2616 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2617 DevicePolicyManager.CODE_OK);
2618 }
2619
Esteban Talavera01576862016-12-15 11:16:44 +00002620 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002621 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2622 .thenReturn(true);
2623 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2624 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2625 true)).thenReturn(true);
2626 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2627
2628 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002629 }
Victor Chang3e794af2016-03-04 13:48:17 +00002630
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002631 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2632 throws Exception {
2633 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002634 mContext.packageName = admin1.getPackageName();
2635 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002636 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2637 true/* it's undefined behavior. Can be changed into false in the future */);
2638 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2639 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2640 true/* it's undefined behavior. Can be changed into false in the future */);
2641 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2642 false/* because user setup completed */);
2643 }
2644
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002645 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002646 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002647 setup_splitUser_afterDeviceSetup_primaryUser();
2648 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2649 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2650 DevicePolicyManager.CODE_OK);
2651 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2652 DevicePolicyManager.CODE_OK);
2653 assertCheckProvisioningPreCondition(
2654 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2655 DevicePolicyManager.CODE_OK);
2656 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2657 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2658 }
2659
Esteban Talavera01576862016-12-15 11:16:44 +00002660 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002661 setDeviceOwner();
2662
2663 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2664 .thenReturn(true);
2665 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2666 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2667 .thenReturn(false);
2668 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2669
2670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002671 }
Victor Chang3e794af2016-03-04 13:48:17 +00002672
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002673 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2674 throws Exception {
2675 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002676 mContext.packageName = admin1.getPackageName();
2677 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002678 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2679 false /* can't provision managed profile on system user */);
2680 }
2681
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002682 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002683 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002684 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2685 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2686 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2687 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2688 }
2689
2690 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002691 setDeviceOwner();
2692
2693 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2694 .thenReturn(true);
2695 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2696 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2697 true)).thenReturn(true);
2698 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2699
2700 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002701 }
Victor Chang3e794af2016-03-04 13:48:17 +00002702
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002703 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2704 throws Exception {
2705 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002706 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2707 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2709 }
2710
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002711 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002712 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002713 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002715
2716 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002717 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2718 DevicePolicyManager.CODE_OK);
2719 }
2720
2721 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002722 setDeviceOwner();
2723
2724 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2725 .thenReturn(true);
2726 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002727 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002728 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2729 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002730 .thenReturn(true);
2731 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002732 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002733 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2734 true)).thenReturn(true);
2735 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2736
2737 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002739
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002740 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2741 throws Exception {
2742 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002743 mContext.packageName = admin1.getPackageName();
2744 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2746 }
2747
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002748 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2749 throws Exception {
2750 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2751 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2752 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2753 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2754 }
2755
2756 public void testCheckProvisioningPreCondition_permission() {
2757 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2758 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002759 dpm.checkProvisioningPreCondition(
2760 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002761 fail("Didn't throw SecurityException");
2762 } catch (SecurityException expected) {
2763 }
2764 }
2765
Victor Chang3577ed22016-08-25 18:49:26 +01002766 public void testForceUpdateUserSetupComplete_permission() {
2767 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2768 try {
2769 dpm.forceUpdateUserSetupComplete();
2770 fail("Didn't throw SecurityException");
2771 } catch (SecurityException expected) {
2772 }
2773 }
2774
2775 public void testForceUpdateUserSetupComplete_systemUser() {
2776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2777 // GIVEN calling from user 20
2778 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2779 try {
2780 dpm.forceUpdateUserSetupComplete();
2781 fail("Didn't throw SecurityException");
2782 } catch (SecurityException expected) {
2783 }
2784 }
2785
2786 public void testForceUpdateUserSetupComplete_userbuild() {
2787 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2788 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2789
2790 final int userId = UserHandle.USER_SYSTEM;
2791 // GIVEN userComplete is false in SettingsProvider
2792 setUserSetupCompleteForUser(false, userId);
2793
2794 // GIVEN userComplete is true in DPM
2795 DevicePolicyManagerService.DevicePolicyData userData =
2796 new DevicePolicyManagerService.DevicePolicyData(userId);
2797 userData.mUserSetupComplete = true;
2798 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2799
2800 // GIVEN it's user build
2801 mContext.buildMock.isDebuggable = false;
2802
2803 assertTrue(dpms.hasUserSetupCompleted());
2804
2805 dpm.forceUpdateUserSetupComplete();
2806
2807 // THEN the state in dpms is not changed
2808 assertTrue(dpms.hasUserSetupCompleted());
2809 }
2810
2811 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2812 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2813 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2814
2815 final int userId = UserHandle.USER_SYSTEM;
2816 // GIVEN userComplete is false in SettingsProvider
2817 setUserSetupCompleteForUser(false, userId);
2818
2819 // GIVEN userComplete is true in DPM
2820 DevicePolicyManagerService.DevicePolicyData userData =
2821 new DevicePolicyManagerService.DevicePolicyData(userId);
2822 userData.mUserSetupComplete = true;
2823 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2824
2825 // GIVEN it's userdebug build
2826 mContext.buildMock.isDebuggable = true;
2827
2828 assertTrue(dpms.hasUserSetupCompleted());
2829
2830 dpm.forceUpdateUserSetupComplete();
2831
2832 // THEN the state in dpms is not changed
2833 assertFalse(dpms.hasUserSetupCompleted());
2834 }
2835
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002836 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002837 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002838 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2839 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2840 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2841 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002842 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002843 }
2844
2845 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2847 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002848
2849 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2850 // feature is disabled because there are non-affiliated secondary users.
2851 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002852 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2853 .thenReturn(true);
2854
2855 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002856 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002857
2858 // Enabling logging should not change the timestamp.
2859 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00002860 verify(mContext.settings)
2861 .securityLogSetLoggingEnabledProperty(true);
2862 when(mContext.settings.securityLogGetLoggingEnabledProperty())
2863 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002864 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002865
2866 // Retrieving the logs should update the timestamp.
2867 final long beforeRetrieval = System.currentTimeMillis();
2868 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002869 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002870 final long afterRetrieval = System.currentTimeMillis();
2871 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2872 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2873
2874 // Retrieving the pre-boot logs should update the timestamp.
2875 Thread.sleep(2);
2876 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002877 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002878 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2879
2880 // Checking the timestamp again should not change it.
2881 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002882 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002883
2884 // Retrieving the logs again should update the timestamp.
2885 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002886 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002887 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2888
2889 // Disabling logging should not change the timestamp.
2890 Thread.sleep(2);
2891 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002892 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002893
2894 // Restarting the DPMS should not lose the timestamp.
2895 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002896 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002897
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002898 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2899 mContext.binder.callingUid = 1234567;
2900 mContext.callerPermissions.add(permission.MANAGE_USERS);
2901 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2902 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2903
2904 // System can retrieve the timestamp.
2905 mContext.binder.clearCallingIdentity();
2906 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2907
2908 // Removing the device owner should clear the timestamp.
2909 clearDeviceOwner();
2910 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002911 }
2912
2913 public void testGetLastBugReportRequestTime() throws Exception {
2914 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2915 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002916
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002917 mContext.packageName = admin1.getPackageName();
2918 mContext.applicationInfo = new ApplicationInfo();
2919 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2920 .thenReturn(Color.WHITE);
2921 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2922 anyObject())).thenReturn(Color.WHITE);
2923
Esteban Talaverad36dd152016-12-15 08:51:45 +00002924 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2925 // feature is disabled because there are non-affiliated secondary users.
2926 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
2927
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002928 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002929 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002930
2931 // Requesting a bug report should update the timestamp.
2932 final long beforeRequest = System.currentTimeMillis();
2933 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002934 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002935 final long afterRequest = System.currentTimeMillis();
2936 assertTrue(bugReportRequestTime >= beforeRequest);
2937 assertTrue(bugReportRequestTime <= afterRequest);
2938
2939 // Checking the timestamp again should not change it.
2940 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002941 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002942
2943 // Restarting the DPMS should not lose the timestamp.
2944 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002945 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002946
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002947 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2948 mContext.binder.callingUid = 1234567;
2949 mContext.callerPermissions.add(permission.MANAGE_USERS);
2950 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2951 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2952
2953 // System can retrieve the timestamp.
2954 mContext.binder.clearCallingIdentity();
2955 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2956
2957 // Removing the device owner should clear the timestamp.
2958 clearDeviceOwner();
2959 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002960 }
2961
2962 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2963 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2964 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00002965 mContext.packageName = admin1.getPackageName();
2966 mContext.applicationInfo = new ApplicationInfo();
2967 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2968 .thenReturn(Color.WHITE);
2969 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2970 anyObject())).thenReturn(Color.WHITE);
2971
2972 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
2973 // feature is disabled because there are non-affiliated secondary users.
2974 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002975 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2976 .thenReturn(true);
2977
2978 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002979 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002980
2981 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2982 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002983 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002984
2985 // Enabling logging should not change the timestamp.
2986 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002987 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002988
2989 // Retrieving the logs should update the timestamp.
2990 final long beforeRetrieval = System.currentTimeMillis();
2991 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002992 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002993 final long afterRetrieval = System.currentTimeMillis();
2994 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2995 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2996
2997 // Checking the timestamp again should not change it.
2998 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002999 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003000
3001 // Retrieving the logs again should update the timestamp.
3002 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003003 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003004 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3005
3006 // Disabling logging should not change the timestamp.
3007 Thread.sleep(2);
3008 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003009 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003010
3011 // Restarting the DPMS should not lose the timestamp.
3012 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003013 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3014
3015 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3016 mContext.binder.callingUid = 1234567;
3017 mContext.callerPermissions.add(permission.MANAGE_USERS);
3018 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3019 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3020
3021 // System can retrieve the timestamp.
3022 mContext.binder.clearCallingIdentity();
3023 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3024
3025 // Removing the device owner should clear the timestamp.
3026 clearDeviceOwner();
3027 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003028 }
3029
Tony Mak2f26b792016-11-28 17:54:51 +00003030 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3031 // Setup device owner.
3032 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3033 setupDeviceOwner();
3034
3035 // Only device owner is setup, the result list should be empty.
3036 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3037 MoreAsserts.assertEmpty(targetUsers);
3038
3039 // Setup a managed profile managed by the same admin.
3040 final int MANAGED_PROFILE_USER_ID = 15;
3041 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3042 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3043
3044 // Add a secondary user, it should never talk with.
3045 final int ANOTHER_USER_ID = 36;
3046 mContext.addUser(ANOTHER_USER_ID, 0);
3047
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003048 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3049 // other.
3050 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3051 MoreAsserts.assertEmpty(targetUsers);
3052
3053 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3054 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3055 MoreAsserts.assertEmpty(targetUsers);
3056
3057 // Setting affiliation ids
3058 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3060 dpm.setAffiliationIds(admin1, userAffiliationIds);
3061
3062 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3063 dpm.setAffiliationIds(admin1, userAffiliationIds);
3064
Tony Mak2f26b792016-11-28 17:54:51 +00003065 // Calling from device owner admin, the result list should just contain the managed
3066 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003067 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003068 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3069 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3070
3071 // Calling from managed profile admin, the result list should just contain the system
3072 // user id.
3073 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3074 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3075 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003076
3077 // Changing affiliation ids in one
3078 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3079
3080 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3081 // to each other.
3082 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3083 MoreAsserts.assertEmpty(targetUsers);
3084
3085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3086 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3087 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003088 }
3089
3090 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3091 // Setup a device owner.
3092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3093 setupDeviceOwner();
3094
3095 // Set up a managed profile managed by different package.
3096 final int MANAGED_PROFILE_USER_ID = 15;
3097 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3098 final ComponentName adminDifferentPackage =
3099 new ComponentName("another.package", "whatever.class");
3100 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3101
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003102 // Setting affiliation ids
3103 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3104 dpm.setAffiliationIds(admin1, userAffiliationIds);
3105
3106 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3107 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3108
Tony Mak2f26b792016-11-28 17:54:51 +00003109 // Calling from device owner admin, we should get zero bind device admin target users as
3110 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003111 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003112 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3113 MoreAsserts.assertEmpty(targetUsers);
3114
3115 // Calling from managed profile admin, we should still get zero target users for the same
3116 // reason.
3117 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3118 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3119 MoreAsserts.assertEmpty(targetUsers);
3120 }
3121
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003122 public void testIsDeviceManaged() throws Exception {
3123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3124 setupDeviceOwner();
3125
3126 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3127 // find out that the device has a device owner.
3128 assertTrue(dpm.isDeviceManaged());
3129 mContext.binder.callingUid = 1234567;
3130 mContext.callerPermissions.add(permission.MANAGE_USERS);
3131 assertTrue(dpm.isDeviceManaged());
3132 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3133 mContext.binder.clearCallingIdentity();
3134 assertTrue(dpm.isDeviceManaged());
3135
3136 clearDeviceOwner();
3137
3138 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3139 // not have a device owner.
3140 mContext.binder.callingUid = 1234567;
3141 mContext.callerPermissions.add(permission.MANAGE_USERS);
3142 assertFalse(dpm.isDeviceManaged());
3143 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3144 mContext.binder.clearCallingIdentity();
3145 assertFalse(dpm.isDeviceManaged());
3146 }
3147
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003148 public void testDeviceOwnerOrganizationName() throws Exception {
3149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3150 setupDeviceOwner();
3151
3152 dpm.setOrganizationName(admin1, "organization");
3153
3154 // Device owner can retrieve organization managing the device.
3155 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3156
3157 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3158 mContext.binder.callingUid = 1234567;
3159 mContext.callerPermissions.add(permission.MANAGE_USERS);
3160 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3161 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3162
3163 // System can retrieve organization managing the device.
3164 mContext.binder.clearCallingIdentity();
3165 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3166
3167 // Removing the device owner clears the organization managing the device.
3168 clearDeviceOwner();
3169 assertNull(dpm.getDeviceOwnerOrganizationName());
3170 }
3171
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003172 public void testWipeDataManagedProfile() throws Exception {
3173 final int MANAGED_PROFILE_USER_ID = 15;
3174 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3175 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3176 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3177
3178 // Even if the caller is the managed profile, the current user is the user 0
3179 when(mContext.iactivityManager.getCurrentUser())
3180 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3181
3182 dpm.wipeData(0);
3183 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3184 MANAGED_PROFILE_USER_ID);
3185 }
3186
3187 public void testWipeDataManagedProfileDisallowed() throws Exception {
3188 final int MANAGED_PROFILE_USER_ID = 15;
3189 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3190 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3191
3192 // Even if the caller is the managed profile, the current user is the user 0
3193 when(mContext.iactivityManager.getCurrentUser())
3194 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3195
3196 when(mContext.userManager.getUserRestrictionSource(
3197 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3198 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3199 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3200 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3201 try {
3202 // The PO is not allowed to remove the profile if the user restriction was set on the
3203 // profile by the system
3204 dpm.wipeData(0);
3205 fail("SecurityException not thrown");
3206 } catch (SecurityException expected) {
3207 }
3208 }
3209
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003210 public void testGetPermissionGrantState() throws Exception {
3211 final String permission = "some.permission";
3212 final String app1 = "com.example.app1";
3213 final String app2 = "com.example.app2";
3214
3215 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3216 .thenReturn(PackageManager.PERMISSION_GRANTED);
3217 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3218 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3219 when(mContext.packageManager.getPermissionFlags(permission, app1,
3220 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3221 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3222 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3223 .thenReturn(PackageManager.PERMISSION_DENIED);
3224 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3225 UserHandle.SYSTEM);
3226 when(mContext.packageManager.getPermissionFlags(permission, app2,
3227 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3228
3229 // System can retrieve permission grant state.
3230 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3231 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3232 dpm.getPermissionGrantState(null, app1, permission));
3233 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3234 dpm.getPermissionGrantState(null, app2, permission));
3235
3236 // A regular app cannot retrieve permission grant state.
3237 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
3238 try {
3239 dpm.getPermissionGrantState(null, app1, permission);
3240 fail("Didn't throw IllegalStateException");
3241 } catch (IllegalStateException expected) {
3242 }
3243
3244 // Profile owner can retrieve permission grant state.
3245 setAsProfileOwner(admin1);
3246 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3247 dpm.getPermissionGrantState(admin1, app1, permission));
3248 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3249 dpm.getPermissionGrantState(admin1, app2, permission));
3250 }
3251
Victor Chang3e794af2016-03-04 13:48:17 +00003252 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3253 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3254 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3255 dpms.notifyChangeToContentObserver(
3256 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3257 }
3258
3259 private void assertProvisioningAllowed(String action, boolean expected) {
3260 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3261 dpm.isProvisioningAllowed(action));
3262 }
Tony Mak2f26b792016-11-28 17:54:51 +00003263
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003264 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003265 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3266 }
3267
3268 private void assertCheckProvisioningPreCondition(
3269 String action, String packageName, int provisioningCondition) {
3270 assertEquals("checkProvisioningPreCondition("
3271 + action + ", " + packageName + ") returning unexpected result",
3272 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 }
3274
Tony Mak2f26b792016-11-28 17:54:51 +00003275 /**
3276 * Setup a managed profile with the specified admin and its uid.
3277 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3278 * @param adminUid uid of the admin package.
3279 * @param copyFromAdmin package information for {@code admin} will be built based on this
3280 * component's information.
3281 */
3282 private void addManagedProfile(
3283 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3284 final int userId = UserHandle.getUserId(adminUid);
3285 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3286 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3287 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3288 dpm.setActiveAdmin(admin, false, userId);
3289 assertTrue(dpm.setProfileOwner(admin, null, userId));
3290 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3291 }
Victor Chang3e794af2016-03-04 13:48:17 +00003292}