blob: d39245992d4992a7926c4a1f60c80b09fe484862 [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;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080074import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import static org.mockito.Mockito.times;
76import static org.mockito.Mockito.verify;
77import static org.mockito.Mockito.when;
78
79/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070080 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +000081 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070082 m FrameworksServicesTests &&
83 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000084 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080086 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070087
88 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +000089 *
90 * , or:
91 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092 */
Benjamin Franz6d009032016-01-25 18:56:38 +000093@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070094public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000095 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
96 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
97 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
98
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099 private DpmMockContext mContext;
100 public DevicePolicyManager dpm;
101 public DevicePolicyManagerServiceTestable dpms;
102
103 @Override
104 protected void setUp() throws Exception {
105 super.setUp();
106
107 mContext = getContext();
108
109 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
110 .thenReturn(true);
111
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800112 // By default, pretend all users are running and unlocked.
113 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
114
Makoto Onukia52562c2015-10-01 16:12:31 -0700115 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700116
Makoto Onukid932f762015-09-29 16:53:38 -0700117 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
118 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
119 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800120 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700121
Makoto Onukib643fb02015-09-22 15:03:44 -0700122 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700123 }
124
Makoto Onukia52562c2015-10-01 16:12:31 -0700125 private void initializeDpms() {
126 // Need clearCallingIdentity() to pass permission checks.
127 final long ident = mContext.binder.clearCallingIdentity();
128 try {
129 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
130
131 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
132
133 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
134 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
135
136 dpm = new DevicePolicyManagerTestable(mContext, dpms);
137 } finally {
138 mContext.binder.restoreCallingIdentity(ident);
139 }
140 }
141
Makoto Onukib643fb02015-09-22 15:03:44 -0700142 private void setUpUserManager() {
143 // Emulate UserManager.set/getApplicationRestriction().
144 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
145
146 // UM.setApplicationRestrictions() will save to appRestrictions.
147 doAnswer(new Answer<Void>() {
148 @Override
149 public Void answer(InvocationOnMock invocation) throws Throwable {
150 String pkg = (String) invocation.getArguments()[0];
151 Bundle bundle = (Bundle) invocation.getArguments()[1];
152 UserHandle user = (UserHandle) invocation.getArguments()[2];
153
154 appRestrictions.put(Pair.create(pkg, user), bundle);
155
156 return null;
157 }
158 }).when(mContext.userManager).setApplicationRestrictions(
159 anyString(), any(Bundle.class), any(UserHandle.class));
160
161 // UM.getApplicationRestrictions() will read from appRestrictions.
162 doAnswer(new Answer<Bundle>() {
163 @Override
164 public Bundle answer(InvocationOnMock invocation) throws Throwable {
165 String pkg = (String) invocation.getArguments()[0];
166 UserHandle user = (UserHandle) invocation.getArguments()[1];
167
168 return appRestrictions.get(Pair.create(pkg, user));
169 }
170 }).when(mContext.userManager).getApplicationRestrictions(
171 anyString(), any(UserHandle.class));
172
Makoto Onukid932f762015-09-29 16:53:38 -0700173 // Add the first secondary user.
174 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700175 }
176
177 private void setAsProfileOwner(ComponentName admin) {
178 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
180
Makoto Onukia4f11972015-10-01 13:19:58 -0700181 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700182 dpm.setActiveAdmin(admin, /* replace =*/ false);
183
184 // Fire!
185 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
186
187 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700188 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700189 }
190
191 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700192 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
193 .thenReturn(false);
194
195 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
196 new DevicePolicyManagerServiceTestable(mContext, dataDir);
197
198 // If the device has no DPMS feature, it shouldn't register the local service.
199 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
200 }
201
202 /**
203 * Caller doesn't have proper permissions.
204 */
205 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700206 // 1. Failure cases.
207
208 // Caller doesn't have MANAGE_DEVICE_ADMINS.
209 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700210 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700211 fail("Didn't throw SecurityException");
212 } catch (SecurityException expected) {
213 }
214
215 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
216 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
217 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700218 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700219 fail("Didn't throw SecurityException");
220 } catch (SecurityException expected) {
221 }
222 }
223
Makoto Onukif76b06a2015-09-22 15:03:44 -0700224 /**
225 * Test for:
226 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800227 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700228 * {@link DevicePolicyManager#isAdminActive}
229 * {@link DevicePolicyManager#isAdminActiveAsUser}
230 * {@link DevicePolicyManager#getActiveAdmins}
231 * {@link DevicePolicyManager#getActiveAdminsAsUser}
232 */
233 public void testSetActiveAdmin() throws Exception {
234 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700235 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
236
Makoto Onukif76b06a2015-09-22 15:03:44 -0700237 // 2. Call the API.
238 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700239
240 // 3. Verify internal calls.
241
242 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700243 verify(mContext.spiedContext).sendBroadcastAsUser(
244 MockUtils.checkIntentAction(
245 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
246 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
247 verify(mContext.spiedContext).sendBroadcastAsUser(
248 MockUtils.checkIntentAction(
249 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700250 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
251
Makoto Onukif76b06a2015-09-22 15:03:44 -0700252 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
253 eq(admin1.getPackageName()),
254 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
255 eq(PackageManager.DONT_KILL_APP),
256 eq(DpmMockContext.CALLER_USER_HANDLE),
257 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700258
259 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700260
261 // Make sure it's active admin1.
262 assertTrue(dpm.isAdminActive(admin1));
263 assertFalse(dpm.isAdminActive(admin2));
264 assertFalse(dpm.isAdminActive(admin3));
265
266 // But not admin1 for a different user.
267
268 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
269 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
270 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
271
272 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
273 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
274
275 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
276
277 // Next, add one more admin.
278 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700279 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
280 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700281
282 dpm.setActiveAdmin(admin2, /* replace =*/ false);
283
284 // Now we have two admins.
285 assertTrue(dpm.isAdminActive(admin1));
286 assertTrue(dpm.isAdminActive(admin2));
287 assertFalse(dpm.isAdminActive(admin3));
288
289 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
290 // again. (times(1) because it was previously called for admin1)
291 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
292 eq(admin1.getPackageName()),
293 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
294 eq(PackageManager.DONT_KILL_APP),
295 eq(DpmMockContext.CALLER_USER_HANDLE),
296 anyString());
297
298 // 4. Add the same admin1 again without replace, which should throw.
299 try {
300 dpm.setActiveAdmin(admin1, /* replace =*/ false);
301 fail("Didn't throw");
302 } catch (IllegalArgumentException expected) {
303 }
304
305 // 5. Add the same admin1 again with replace, which should succeed.
306 dpm.setActiveAdmin(admin1, /* replace =*/ true);
307
308 // TODO make sure it's replaced.
309
310 // 6. Test getActiveAdmins()
311 List<ComponentName> admins = dpm.getActiveAdmins();
312 assertEquals(2, admins.size());
313 assertEquals(admin1, admins.get(0));
314 assertEquals(admin2, admins.get(1));
315
316 // Another user has no admins.
317 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
318
319 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
320 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
321
322 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
323 }
324
Makoto Onukid932f762015-09-29 16:53:38 -0700325 public void testSetActiveAdmin_multiUsers() throws Exception {
326
327 final int ANOTHER_USER_ID = 100;
328 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
329
330 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
331
332 // Set up pacakge manager for the other user.
333 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700334
335 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
336
337 dpm.setActiveAdmin(admin1, /* replace =*/ false);
338
339 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
340 dpm.setActiveAdmin(admin2, /* replace =*/ false);
341
342
343 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
344 assertTrue(dpm.isAdminActive(admin1));
345 assertFalse(dpm.isAdminActive(admin2));
346
347 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
348 assertFalse(dpm.isAdminActive(admin1));
349 assertTrue(dpm.isAdminActive(admin2));
350 }
351
Makoto Onukif76b06a2015-09-22 15:03:44 -0700352 /**
353 * Test for:
354 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800355 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700356 */
357 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
358 // 1. Make sure the caller has proper permissions.
359 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
360
361 dpm.setActiveAdmin(admin1, /* replace =*/ false);
362 assertTrue(dpm.isAdminActive(admin1));
363
364 // Add the same admin1 again without replace, which should throw.
365 try {
366 dpm.setActiveAdmin(admin1, /* replace =*/ false);
367 fail("Didn't throw");
368 } catch (IllegalArgumentException expected) {
369 }
370 }
371
372 /**
373 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800374 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
375 * BIND_DEVICE_ADMIN.
376 */
377 public void testSetActiveAdmin_permissionCheck() throws Exception {
378 // 1. Make sure the caller has proper permissions.
379 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
380
381 try {
382 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
383 fail();
384 } catch (IllegalArgumentException expected) {
385 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
386 }
387 assertFalse(dpm.isAdminActive(adminNoPerm));
388
389 // Change the target API level to MNC. Now it can be set as DA.
390 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
391 VERSION_CODES.M);
392 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
393 assertTrue(dpm.isAdminActive(adminNoPerm));
394
395 // TODO Test the "load from the file" case where DA will still be loaded even without
396 // BIND_DEVICE_ADMIN and target API is N.
397 }
398
399 /**
400 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700401 * {@link DevicePolicyManager#removeActiveAdmin}
402 */
403 public void testRemoveActiveAdmin_SecurityException() {
404 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
405
406 // Add admin.
407
408 dpm.setActiveAdmin(admin1, /* replace =*/ false);
409
410 assertTrue(dpm.isAdminActive(admin1));
411
412 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
413
414 // Directly call the DPMS method with a different userid, which should fail.
415 try {
416 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
417 fail("Didn't throw SecurityException");
418 } catch (SecurityException expected) {
419 }
420
421 // Try to remove active admin with a different caller userid should fail too, without
422 // having MANAGE_DEVICE_ADMINS.
423 mContext.callerPermissions.clear();
424
Makoto Onukid932f762015-09-29 16:53:38 -0700425 // Change the caller, and call into DPMS directly with a different user-id.
426
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 mContext.binder.callingUid = 1234567;
428 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700429 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 fail("Didn't throw SecurityException");
431 } catch (SecurityException expected) {
432 }
433 }
434
435 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800436 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
437 * (because we can't send the remove broadcast).
438 */
439 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
440 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
441
442 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
443
444 // Add admin.
445
446 dpm.setActiveAdmin(admin1, /* replace =*/ false);
447
448 assertTrue(dpm.isAdminActive(admin1));
449
450 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
451
452 // 1. User not unlocked.
453 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
454 .thenReturn(false);
455 try {
456 dpm.removeActiveAdmin(admin1);
457 fail("Didn't throw IllegalStateException");
458 } catch (IllegalStateException expected) {
459 MoreAsserts.assertContainsRegex(
460 "User must be running and unlocked", expected.getMessage());
461 }
462
463 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
464
465 // 2. User unlocked.
466 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
467 .thenReturn(true);
468
469 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700470 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800471 }
472
473 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700474 * Test for:
475 * {@link DevicePolicyManager#removeActiveAdmin}
476 */
Makoto Onukid932f762015-09-29 16:53:38 -0700477 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700478 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
479
480 // Add admin1.
481
482 dpm.setActiveAdmin(admin1, /* replace =*/ false);
483
484 assertTrue(dpm.isAdminActive(admin1));
485 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
486
487 // Different user, but should work, because caller has proper permissions.
488 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700489
490 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700491 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700492
493 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700494 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700495
496 // TODO DO Still can't be removed in this case.
497 }
498
499 /**
500 * Test for:
501 * {@link DevicePolicyManager#removeActiveAdmin}
502 */
503 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
504 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
505 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
506
507 // Add admin1.
508
509 dpm.setActiveAdmin(admin1, /* replace =*/ false);
510
511 assertTrue(dpm.isAdminActive(admin1));
512 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
513
514 // Broadcast from saveSettingsLocked().
515 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
516 MockUtils.checkIntentAction(
517 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
518 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
519
520 // Remove. No permissions, but same user, so it'll work.
521 mContext.callerPermissions.clear();
522 dpm.removeActiveAdmin(admin1);
523
Makoto Onukif76b06a2015-09-22 15:03:44 -0700524 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
525 MockUtils.checkIntentAction(
526 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
527 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
528 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700529 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700530 eq(dpms.mHandler),
531 eq(Activity.RESULT_OK),
532 isNull(String.class),
533 isNull(Bundle.class));
534
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700535 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536
537 // Again broadcast from saveSettingsLocked().
538 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
539 MockUtils.checkIntentAction(
540 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
541 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
542
543 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700544 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700545
546 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000547 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700548 */
549 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000550 setDeviceOwner();
551
552 // Try to set a profile owner on the same user, which should fail.
553 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
554 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
555 try {
556 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
557 fail("IllegalStateException not thrown");
558 } catch (IllegalStateException expected) {
559 assertTrue("Message was: " + expected.getMessage(),
560 expected.getMessage().contains("already has a device owner"));
561 }
562
563 // DO admin can't be deactivated.
564 dpm.removeActiveAdmin(admin1);
565 assertTrue(dpm.isAdminActive(admin1));
566
567 // TODO Test getDeviceOwnerName() too. To do so, we need to change
568 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
569 }
570
571 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700572 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800573 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700574 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
575 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
576
Makoto Onukid932f762015-09-29 16:53:38 -0700577 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700578 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
579
Makoto Onukid932f762015-09-29 16:53:38 -0700580 // Make sure admin1 is installed on system user.
581 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700582
Makoto Onukic8a5a552015-11-19 14:29:12 -0800583 // Check various get APIs.
584 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
585
Makoto Onukib643fb02015-09-22 15:03:44 -0700586 // DO needs to be an DA.
587 dpm.setActiveAdmin(admin1, /* replace =*/ false);
588
589 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700590 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700591
Makoto Onukic8a5a552015-11-19 14:29:12 -0800592 // getDeviceOwnerComponent should return the admin1 component.
593 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
594 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
595
596 // Check various get APIs.
597 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
598
599 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
600 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
601 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
602 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
603
604 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
605
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000606 // Verify internal calls.
607 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
608 eq(admin1.getPackageName()));
609
Makoto Onukib643fb02015-09-22 15:03:44 -0700610 // TODO We should check if the caller has called clearCallerIdentity().
611 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
612 eq(UserHandle.USER_SYSTEM), eq(false));
613
614 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
615 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
616 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
617
Makoto Onukic8a5a552015-11-19 14:29:12 -0800618 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700619 }
620
Makoto Onukic8a5a552015-11-19 14:29:12 -0800621 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
622 final int origCallingUser = mContext.binder.callingUid;
623 final List origPermissions = new ArrayList(mContext.callerPermissions);
624 mContext.callerPermissions.clear();
625
626 mContext.callerPermissions.add(permission.MANAGE_USERS);
627
628 mContext.binder.callingUid = Process.SYSTEM_UID;
629
630 // TODO Test getDeviceOwnerName() too. To do so, we need to change
631 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
632 if (hasDeviceOwner) {
633 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
634 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
635 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
636
637 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
638 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
639 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
640 } else {
641 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
642 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
643 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
644
645 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
646 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
647 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
648 }
649
650 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
651 if (hasDeviceOwner) {
652 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
653 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
654 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
655
656 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
657 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
658 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
659 } else {
660 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
661 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
662 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
663
664 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
665 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
666 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
667 }
668
669 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
670 // Still with MANAGE_USERS.
671 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
672 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
673 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
674
675 if (hasDeviceOwner) {
676 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
677 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
678 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
679 } else {
680 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
681 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
682 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
683 }
684
685 mContext.binder.callingUid = Process.SYSTEM_UID;
686 mContext.callerPermissions.remove(permission.MANAGE_USERS);
687 // System can still call "OnAnyUser" without MANAGE_USERS.
688 if (hasDeviceOwner) {
689 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
690 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
691 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
692
693 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
694 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
695 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
696 } else {
697 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
698 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
699 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
700
701 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
702 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
703 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
704 }
705
706 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
707 // Still no MANAGE_USERS.
708 if (hasDeviceOwner) {
709 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
710 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
711 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
712 } else {
713 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
714 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
715 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
716 }
717
718 try {
719 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
720 fail();
721 } catch (SecurityException expected) {
722 }
723 try {
724 dpm.getDeviceOwnerComponentOnAnyUser();
725 fail();
726 } catch (SecurityException expected) {
727 }
728 try {
729 dpm.getDeviceOwnerUserId();
730 fail();
731 } catch (SecurityException expected) {
732 }
733 try {
734 dpm.getDeviceOwnerNameOnAnyUser();
735 fail();
736 } catch (SecurityException expected) {
737 }
738
739 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
740 // Still no MANAGE_USERS.
741 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
742 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
743 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
744
745 try {
746 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
747 fail();
748 } catch (SecurityException expected) {
749 }
750 try {
751 dpm.getDeviceOwnerComponentOnAnyUser();
752 fail();
753 } catch (SecurityException expected) {
754 }
755 try {
756 dpm.getDeviceOwnerUserId();
757 fail();
758 } catch (SecurityException expected) {
759 }
760 try {
761 dpm.getDeviceOwnerNameOnAnyUser();
762 fail();
763 } catch (SecurityException expected) {
764 }
765
766 // Restore.
767 mContext.binder.callingUid = origCallingUser;
768 mContext.callerPermissions.addAll(origPermissions);
769 }
770
771
Makoto Onukib643fb02015-09-22 15:03:44 -0700772 /**
773 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
774 */
775 public void testSetDeviceOwner_noSuchPackage() {
776 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800777 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700778 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
779 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
780
781 // Call from a process on the system user.
782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
783
Makoto Onukib643fb02015-09-22 15:03:44 -0700784 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700785 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700786 fail("Didn't throw IllegalArgumentException");
787 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700788 assertTrue("Message was: " + expected.getMessage(),
789 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700790 }
791 }
792
793 public void testSetDeviceOwner_failures() throws Exception {
794 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
795 }
796
Makoto Onukia52562c2015-10-01 16:12:31 -0700797 public void testClearDeviceOwner() throws Exception {
798 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800799 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700800 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
801 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
802
803 // Set admin1 as a DA to the secondary user.
804 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
805
806 dpm.setActiveAdmin(admin1, /* replace =*/ false);
807
808 // Set admin 1 as the DO to the system user.
809
810 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
811 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
812 dpm.setActiveAdmin(admin1, /* replace =*/ false);
813 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
814
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000815 // Verify internal calls.
816 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
817 eq(admin1.getPackageName()));
818
Makoto Onukic8a5a552015-11-19 14:29:12 -0800819 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700820
Makoto Onuki90b89652016-01-28 14:44:18 -0800821 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
822
823 assertTrue(dpm.isAdminActive(admin1));
824 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
825
Makoto Onukia52562c2015-10-01 16:12:31 -0700826 // Set up other mocks.
827 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
828
829 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700830 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700831 eq(admin1.getPackageName()),
832 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800833
834 // But first pretend the user is locked. Then it should fail.
835 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
836 try {
837 dpm.clearDeviceOwnerApp(admin1.getPackageName());
838 fail("Didn't throw IllegalStateException");
839 } catch (IllegalStateException expected) {
840 MoreAsserts.assertContainsRegex(
841 "User must be running and unlocked", expected.getMessage());
842 }
843
844 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800845 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700846 dpm.clearDeviceOwnerApp(admin1.getPackageName());
847
848 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800849 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700850
Makoto Onuki90b89652016-01-28 14:44:18 -0800851 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
852 eq(UserHandle.USER_SYSTEM),
853 MockUtils.checkUserRestrictions(),
854 MockUtils.checkUserRestrictions()
855 );
856
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700857 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100858
859 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
860 // and once for clearing it.
861 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
862 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
863 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700864 // TODO Check other calls.
865 }
866
867 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
868 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800869 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700870 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
871 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
872
873 // Set admin1 as a DA to the secondary user.
874 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
875
876 dpm.setActiveAdmin(admin1, /* replace =*/ false);
877
878 // Set admin 1 as the DO to the system user.
879
880 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
881 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
882 dpm.setActiveAdmin(admin1, /* replace =*/ false);
883 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
884
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000885 // Verify internal calls.
886 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
887 eq(admin1.getPackageName()));
888
Makoto Onukic8a5a552015-11-19 14:29:12 -0800889 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700890
891 // Now call clear from the secondary user, which should throw.
892 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
893
894 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700895 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700896 eq(admin1.getPackageName()),
897 anyInt());
898 try {
899 dpm.clearDeviceOwnerApp(admin1.getPackageName());
900 fail("Didn't throw");
901 } catch (SecurityException e) {
902 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
903 }
904
Makoto Onukic8a5a552015-11-19 14:29:12 -0800905 // DO shouldn't be removed.
906 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700907 }
908
Makoto Onukib643fb02015-09-22 15:03:44 -0700909 public void testSetProfileOwner() throws Exception {
910 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700911
Makoto Onuki90b89652016-01-28 14:44:18 -0800912 // PO admin can't be deactivated.
913 dpm.removeActiveAdmin(admin1);
914 assertTrue(dpm.isAdminActive(admin1));
915
Makoto Onuki803d6752015-10-30 12:58:39 -0700916 // Try setting DO on the same user, which should fail.
917 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
918 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
919 try {
920 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
921 fail("IllegalStateException not thrown");
922 } catch (IllegalStateException expected) {
923 assertTrue("Message was: " + expected.getMessage(),
924 expected.getMessage().contains("already has a profile owner"));
925 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700926 }
927
Makoto Onuki90b89652016-01-28 14:44:18 -0800928 public void testClearProfileOwner() throws Exception {
929 setAsProfileOwner(admin1);
930
931 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
932
933 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
934 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
935
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800936 // First try when the user is locked, which should fail.
937 when(mContext.userManager.isUserUnlocked(anyInt()))
938 .thenReturn(false);
939 try {
940 dpm.clearProfileOwner(admin1);
941 fail("Didn't throw IllegalStateException");
942 } catch (IllegalStateException expected) {
943 MoreAsserts.assertContainsRegex(
944 "User must be running and unlocked", expected.getMessage());
945 }
946 // Clear, really.
947 when(mContext.userManager.isUserUnlocked(anyInt()))
948 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800949 dpm.clearProfileOwner(admin1);
950
951 // Check
952 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700953 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800954 }
955
Makoto Onukib643fb02015-09-22 15:03:44 -0700956 public void testSetProfileOwner_failures() throws Exception {
957 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
958 }
959
Makoto Onukia52562c2015-10-01 16:12:31 -0700960 public void testGetDeviceOwnerAdminLocked() throws Exception {
961 checkDeviceOwnerWithMultipleDeviceAdmins();
962 }
963
964 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
965 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
966 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
967 // make sure it gets the right component from the right user.
968
969 final int ANOTHER_USER_ID = 100;
970 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
971
972 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
973
974 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800975 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700976 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
977 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
978
979 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
980
Victor Change29cd472016-03-02 20:57:42 +0000981 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
982
Makoto Onukia52562c2015-10-01 16:12:31 -0700983 // Make sure the admin packge is installed to each user.
984 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
985 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
986
987 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
988 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
989
990 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
991
992
993 // Set active admins to the users.
994 dpm.setActiveAdmin(admin1, /* replace =*/ false);
995 dpm.setActiveAdmin(admin3, /* replace =*/ false);
996
997 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
998 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
999
1000 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1001
1002 // Set DO on the first non-system user.
1003 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1004 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1005
Makoto Onukic8a5a552015-11-19 14:29:12 -08001006 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001007
1008 // Then check getDeviceOwnerAdminLocked().
1009 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1010 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1011 }
1012
1013 /**
1014 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001015 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1016 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001017 *
1018 * We didn't use to persist the DO component class name, but now we do, and the above method
1019 * finds the right component from a package name upon migration.
1020 */
1021 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001022 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001023 checkDeviceOwnerWithMultipleDeviceAdmins();
1024
1025 // Overwrite the device owner setting and clears the clas name.
1026 dpms.mOwners.setDeviceOwner(
1027 new ComponentName(admin2.getPackageName(), ""),
1028 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1029 dpms.mOwners.writeDeviceOwner();
1030
1031 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001032 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001033
1034 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001035 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1036 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001037 initializeDpms();
1038
1039 // Now the DO component name is a full name.
1040 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1041 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001042 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001043 }
1044
Makoto Onukib643fb02015-09-22 15:03:44 -07001045 public void testSetGetApplicationRestriction() {
1046 setAsProfileOwner(admin1);
1047
1048 {
1049 Bundle rest = new Bundle();
1050 rest.putString("KEY_STRING", "Foo1");
1051 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1052 }
1053
1054 {
1055 Bundle rest = new Bundle();
1056 rest.putString("KEY_STRING", "Foo2");
1057 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1058 }
1059
1060 {
1061 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1062 assertNotNull(returned);
1063 assertEquals(returned.size(), 1);
1064 assertEquals(returned.get("KEY_STRING"), "Foo1");
1065 }
1066
1067 {
1068 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1069 assertNotNull(returned);
1070 assertEquals(returned.size(), 1);
1071 assertEquals(returned.get("KEY_STRING"), "Foo2");
1072 }
1073
1074 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1075 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1076 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001077
Esteban Talaverabf60f722015-12-10 16:26:44 +00001078 public void testApplicationRestrictionsManagingApp() throws Exception {
1079 setAsProfileOwner(admin1);
1080
Rubin Xued1928a2016-02-11 17:23:06 +00001081 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001082 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1083 final int appRestrictionsManagerAppId = 20987;
1084 final int appRestrictionsManagerUid = UserHandle.getUid(
1085 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001086 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001087 eq(appRestrictionsManagerPackage),
1088 eq(DpmMockContext.CALLER_USER_HANDLE));
1089 mContext.binder.callingUid = appRestrictionsManagerUid;
1090
Rubin Xued1928a2016-02-11 17:23:06 +00001091 final PackageInfo pi = new PackageInfo();
1092 pi.applicationInfo = new ApplicationInfo();
1093 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1094 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1095 eq(appRestrictionsManagerPackage),
1096 anyInt(),
1097 eq(DpmMockContext.CALLER_USER_HANDLE));
1098
Esteban Talaverabf60f722015-12-10 16:26:44 +00001099 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1100 // delegated that permission yet.
1101 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1102 Bundle rest = new Bundle();
1103 rest.putString("KEY_STRING", "Foo1");
1104 try {
1105 dpm.setApplicationRestrictions(null, "pkg1", rest);
1106 fail("Didn't throw expected SecurityException");
1107 } catch (SecurityException expected) {
1108 MoreAsserts.assertContainsRegex(
1109 "caller cannot manage application restrictions", expected.getMessage());
1110 }
1111 try {
1112 dpm.getApplicationRestrictions(null, "pkg1");
1113 fail("Didn't throw expected SecurityException");
1114 } catch (SecurityException expected) {
1115 MoreAsserts.assertContainsRegex(
1116 "caller cannot manage application restrictions", expected.getMessage());
1117 }
1118
1119 // Check via the profile owner that no restrictions were set.
1120 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1121 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1122
Rubin Xued1928a2016-02-11 17:23:06 +00001123 // Check the API does not allow setting a non-existent package
1124 try {
1125 dpm.setApplicationRestrictionsManagingPackage(admin1,
1126 nonExistAppRestrictionsManagerPackage);
1127 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001128 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001129 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001130 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001131 }
1132
Esteban Talaverabf60f722015-12-10 16:26:44 +00001133 // Let appRestrictionsManagerPackage manage app restrictions
1134 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1135 assertEquals(appRestrictionsManagerPackage,
1136 dpm.getApplicationRestrictionsManagingPackage(admin1));
1137
1138 // Now that package should be able to set and retrieve app restrictions.
1139 mContext.binder.callingUid = appRestrictionsManagerUid;
1140 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1141 dpm.setApplicationRestrictions(null, "pkg1", rest);
1142 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1143 assertEquals(1, returned.size(), 1);
1144 assertEquals("Foo1", returned.get("KEY_STRING"));
1145
1146 // The same app running on a separate user shouldn't be able to manage app restrictions.
1147 mContext.binder.callingUid = UserHandle.getUid(
1148 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1149 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1150 try {
1151 dpm.setApplicationRestrictions(null, "pkg1", rest);
1152 fail("Didn't throw expected SecurityException");
1153 } catch (SecurityException expected) {
1154 MoreAsserts.assertContainsRegex(
1155 "caller cannot manage application restrictions", expected.getMessage());
1156 }
1157
1158 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1159 // too.
1160 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1161 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1162 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1163 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1164
1165 // Removing the ability for the package to manage app restrictions.
1166 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1167 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1168 mContext.binder.callingUid = appRestrictionsManagerUid;
1169 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1170 try {
1171 dpm.setApplicationRestrictions(null, "pkg1", null);
1172 fail("Didn't throw expected SecurityException");
1173 } catch (SecurityException expected) {
1174 MoreAsserts.assertContainsRegex(
1175 "caller cannot manage application restrictions", expected.getMessage());
1176 }
1177 }
1178
Makoto Onukia4f11972015-10-01 13:19:58 -07001179 public void testSetUserRestriction_asDo() throws Exception {
1180 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001181 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001182 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1183 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1184
1185 // First, set DO.
1186
1187 // Call from a process on the system user.
1188 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1189
1190 // Make sure admin1 is installed on system user.
1191 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001192
1193 // Call.
1194 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001195 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001196 UserHandle.USER_SYSTEM));
1197
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001198 // Check that the user restrictions that are enabled by default are set. Then unset them.
1199 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001200 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001201 DpmTestUtils.assertRestrictions(
1202 DpmTestUtils.newRestrictions(defaultRestrictions),
1203 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1204 );
1205 DpmTestUtils.assertRestrictions(
1206 DpmTestUtils.newRestrictions(defaultRestrictions),
1207 dpm.getUserRestrictions(admin1)
1208 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001209 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1210 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001211 MockUtils.checkUserRestrictions(defaultRestrictions),
1212 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001213 );
1214 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001215
1216 for (String restriction : defaultRestrictions) {
1217 dpm.clearUserRestriction(admin1, restriction);
1218 }
1219
Esteban Talavera548a04b2016-12-20 15:22:30 +00001220 assertNoDeviceOwnerRestrictions();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001221
1222 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1223 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1224 eq(UserHandle.USER_SYSTEM),
1225 MockUtils.checkUserRestrictions(),
1226 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001227 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001228 reset(mContext.userManagerInternal);
1229
Makoto Onukia4f11972015-10-01 13:19:58 -07001230 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1232 eq(UserHandle.USER_SYSTEM),
1233 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1234 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1235 );
1236 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001237
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238 DpmTestUtils.assertRestrictions(
1239 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001240 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001241 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1242 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001243 DpmTestUtils.assertRestrictions(
1244 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001245 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001246 dpm.getUserRestrictions(admin1)
1247 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001248
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001249 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1250 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1251 eq(UserHandle.USER_SYSTEM),
1252 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1253 MockUtils.checkUserRestrictions()
1254 );
1255 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001256
Makoto Onuki068c54a2015-10-13 14:34:03 -07001257 DpmTestUtils.assertRestrictions(
1258 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1259 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1260 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001261 DpmTestUtils.assertRestrictions(
1262 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1263 dpm.getUserRestrictions(admin1)
1264 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001265
1266 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001267 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1268 eq(UserHandle.USER_SYSTEM),
1269 MockUtils.checkUserRestrictions(),
1270 MockUtils.checkUserRestrictions()
1271 );
1272 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001273
Esteban Talavera548a04b2016-12-20 15:22:30 +00001274 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001275
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001276 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1277 // DO sets them, the scope is global.
1278 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1279 reset(mContext.userManagerInternal);
1280 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1281 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1282 eq(UserHandle.USER_SYSTEM),
1283 MockUtils.checkUserRestrictions(),
1284 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1285 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1286 );
1287 reset(mContext.userManagerInternal);
1288
1289 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1290 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1291
1292
1293 // More tests.
1294 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1295 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1296 eq(UserHandle.USER_SYSTEM),
1297 MockUtils.checkUserRestrictions(),
1298 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1299 );
1300 reset(mContext.userManagerInternal);
1301
1302 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1303 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1304 eq(UserHandle.USER_SYSTEM),
1305 MockUtils.checkUserRestrictions(),
1306 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1307 UserManager.DISALLOW_ADD_USER)
1308 );
1309 reset(mContext.userManagerInternal);
1310
1311 dpm.setCameraDisabled(admin1, true);
1312 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1313 eq(UserHandle.USER_SYSTEM),
1314 // DISALLOW_CAMERA will be applied to both local and global.
1315 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1316 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1317 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1318 );
1319 reset(mContext.userManagerInternal);
1320
1321 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1322 // locally.
1323 dpm.setCameraDisabled(admin1, false);
1324 reset(mContext.userManagerInternal);
1325
1326 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1327 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1328 dpm.setCameraDisabled(admin2, true);
1329
1330 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1331 eq(UserHandle.USER_SYSTEM),
1332 // DISALLOW_CAMERA will be applied to both local and global.
1333 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1334 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1335 UserManager.DISALLOW_ADD_USER)
1336 );
1337 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001338 // TODO Make sure restrictions are written to the file.
1339 }
1340
1341 public void testSetUserRestriction_asPo() {
1342 setAsProfileOwner(admin1);
1343
Makoto Onuki068c54a2015-10-13 14:34:03 -07001344 DpmTestUtils.assertRestrictions(
1345 DpmTestUtils.newRestrictions(),
1346 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1347 .ensureUserRestrictions()
1348 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001349
1350 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001351 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1352 eq(DpmMockContext.CALLER_USER_HANDLE),
1353 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1354 isNull(Bundle.class)
1355 );
1356 reset(mContext.userManagerInternal);
1357
Makoto Onukia4f11972015-10-01 13:19:58 -07001358 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001359 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1360 eq(DpmMockContext.CALLER_USER_HANDLE),
1361 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1362 UserManager.DISALLOW_OUTGOING_CALLS),
1363 isNull(Bundle.class)
1364 );
1365 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001366
Makoto Onuki068c54a2015-10-13 14:34:03 -07001367 DpmTestUtils.assertRestrictions(
1368 DpmTestUtils.newRestrictions(
1369 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1370 UserManager.DISALLOW_OUTGOING_CALLS
1371 ),
1372 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1373 .ensureUserRestrictions()
1374 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001375 DpmTestUtils.assertRestrictions(
1376 DpmTestUtils.newRestrictions(
1377 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1378 UserManager.DISALLOW_OUTGOING_CALLS
1379 ),
1380 dpm.getUserRestrictions(admin1)
1381 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001382
1383 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001384 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1385 eq(DpmMockContext.CALLER_USER_HANDLE),
1386 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1387 isNull(Bundle.class)
1388 );
1389 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001390
1391 DpmTestUtils.assertRestrictions(
1392 DpmTestUtils.newRestrictions(
1393 UserManager.DISALLOW_OUTGOING_CALLS
1394 ),
1395 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1396 .ensureUserRestrictions()
1397 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001398 DpmTestUtils.assertRestrictions(
1399 DpmTestUtils.newRestrictions(
1400 UserManager.DISALLOW_OUTGOING_CALLS
1401 ),
1402 dpm.getUserRestrictions(admin1)
1403 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001404
1405 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1407 eq(DpmMockContext.CALLER_USER_HANDLE),
1408 MockUtils.checkUserRestrictions(),
1409 isNull(Bundle.class)
1410 );
1411 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001412
Makoto Onuki068c54a2015-10-13 14:34:03 -07001413 DpmTestUtils.assertRestrictions(
1414 DpmTestUtils.newRestrictions(),
1415 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1416 .ensureUserRestrictions()
1417 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001418 DpmTestUtils.assertRestrictions(
1419 DpmTestUtils.newRestrictions(),
1420 dpm.getUserRestrictions(admin1)
1421 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001422
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001423 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1424 // though when DO sets them they'll be applied globally.
1425 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1426 reset(mContext.userManagerInternal);
1427 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1428 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1429 eq(DpmMockContext.CALLER_USER_HANDLE),
1430 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1431 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1432 isNull(Bundle.class)
1433 );
1434 reset(mContext.userManagerInternal);
1435
1436 dpm.setCameraDisabled(admin1, true);
1437 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1438 eq(DpmMockContext.CALLER_USER_HANDLE),
1439 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1440 UserManager.DISALLOW_ADJUST_VOLUME,
1441 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1442 isNull(Bundle.class)
1443 );
1444 reset(mContext.userManagerInternal);
1445
Makoto Onukia4f11972015-10-01 13:19:58 -07001446 // TODO Make sure restrictions are written to the file.
1447 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001448
Esteban Talavera548a04b2016-12-20 15:22:30 +00001449
1450 public void testDefaultEnabledUserRestrictions() throws Exception {
1451 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1452 mContext.callerPermissions.add(permission.MANAGE_USERS);
1453 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1454 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1455
1456 // First, set DO.
1457
1458 // Call from a process on the system user.
1459 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1460
1461 // Make sure admin1 is installed on system user.
1462 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1463
1464 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1465 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1466 UserHandle.USER_SYSTEM));
1467
1468 // Check that the user restrictions that are enabled by default are set. Then unset them.
1469 String[] defaultRestrictions = UserRestrictionsUtils
1470 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1471 assertTrue(defaultRestrictions.length > 0);
1472 DpmTestUtils.assertRestrictions(
1473 DpmTestUtils.newRestrictions(defaultRestrictions),
1474 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1475 );
1476 DpmTestUtils.assertRestrictions(
1477 DpmTestUtils.newRestrictions(defaultRestrictions),
1478 dpm.getUserRestrictions(admin1)
1479 );
1480 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1481 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001482 MockUtils.checkUserRestrictions(defaultRestrictions),
1483 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001484 );
1485 reset(mContext.userManagerInternal);
1486
1487 for (String restriction : defaultRestrictions) {
1488 dpm.clearUserRestriction(admin1, restriction);
1489 }
1490
1491 assertNoDeviceOwnerRestrictions();
1492
1493 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1494 reset(mContext.userManagerInternal);
1495 initializeDpms();
1496 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1497 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1498
1499 assertNoDeviceOwnerRestrictions();
1500
1501 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1502 // is set as it wasn't enabled during setDeviceOwner.
1503 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1504 assertFalse(UserRestrictionsUtils
1505 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1506 UserRestrictionsUtils
1507 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1508 try {
1509 reset(mContext.userManagerInternal);
1510 initializeDpms();
1511 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1512 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1513
1514 DpmTestUtils.assertRestrictions(
1515 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1516 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1517 );
1518 DpmTestUtils.assertRestrictions(
1519 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1520 dpm.getUserRestrictions(admin1)
1521 );
1522 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1523 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001524 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
1525 MockUtils.checkUserRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00001526 );
1527 reset(mContext.userManagerInternal);
1528
1529 // Remove the restriction.
1530 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1531
1532 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1533 initializeDpms();
1534 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1535 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1536 assertNoDeviceOwnerRestrictions();
1537 } finally {
1538 UserRestrictionsUtils
1539 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1540 }
1541 }
1542
1543 private void assertNoDeviceOwnerRestrictions() {
1544 DpmTestUtils.assertRestrictions(
1545 DpmTestUtils.newRestrictions(),
1546 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1547 );
1548 DpmTestUtils.assertRestrictions(
1549 DpmTestUtils.newRestrictions(),
1550 dpm.getUserRestrictions(admin1)
1551 );
1552 }
1553
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001554 public void testGetMacAddress() throws Exception {
1555 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1556 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1557 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1558
1559 // In this test, change the caller user to "system".
1560 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1561
1562 // Make sure admin1 is installed on system user.
1563 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1564
1565 // Test 1. Caller doesn't have DO or DA.
1566 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001567 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001568 fail();
1569 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001570 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001571 }
1572
1573 // DO needs to be an DA.
1574 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1575 assertTrue(dpm.isAdminActive(admin1));
1576
1577 // Test 2. Caller has DA, but not DO.
1578 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001579 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001580 fail();
1581 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001582 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001583 }
1584
1585 // Test 3. Caller has PO, but not DO.
1586 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1587 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001588 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001589 fail();
1590 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001591 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001592 }
1593
1594 // Remove PO.
1595 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001596 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001597 // Test 4, Caller is DO now.
1598 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1599
1600 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001601 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001602
1603 // 4-2. Returns WifiInfo, but with the default MAC.
1604 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001605 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001606
1607 // 4-3. With a real MAC address.
1608 final WifiInfo wi = new WifiInfo();
1609 wi.setMacAddress("11:22:33:44:55:66");
1610 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001611 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001612 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001613
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001614 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001615 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1616 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1617
1618 // In this test, change the caller user to "system".
1619 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1620
1621 // Make sure admin1 is installed on system user.
1622 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1623
1624 // Set admin1 as DA.
1625 dpm.setActiveAdmin(admin1, false);
1626 assertTrue(dpm.isAdminActive(admin1));
1627 try {
1628 dpm.reboot(admin1);
1629 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1630 } catch (SecurityException expected) {
1631 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1632 }
1633
1634 // Set admin1 as PO.
1635 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1636 try {
1637 dpm.reboot(admin1);
1638 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1639 } catch (SecurityException expected) {
1640 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1641 }
1642
1643 // Remove PO and add DO.
1644 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001645 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001646 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1647
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001648 // admin1 is DO.
1649 // Set current call state of device to ringing.
1650 when(mContext.telephonyManager.getCallState())
1651 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1652 try {
1653 dpm.reboot(admin1);
1654 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1655 } catch (IllegalStateException expected) {
1656 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1657 }
1658
1659 // Set current call state of device to dialing/active.
1660 when(mContext.telephonyManager.getCallState())
1661 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1662 try {
1663 dpm.reboot(admin1);
1664 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1665 } catch (IllegalStateException expected) {
1666 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1667 }
1668
1669 // Set current call state of device to idle.
1670 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001671 dpm.reboot(admin1);
1672 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001673
1674 public void testSetGetSupportText() {
1675 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1676 dpm.setActiveAdmin(admin1, true);
1677 dpm.setActiveAdmin(admin2, true);
1678 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1679
1680 // Null default support messages.
1681 {
1682 assertNull(dpm.getLongSupportMessage(admin1));
1683 assertNull(dpm.getShortSupportMessage(admin1));
1684 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1685 assertNull(dpm.getShortSupportMessageForUser(admin1,
1686 DpmMockContext.CALLER_USER_HANDLE));
1687 assertNull(dpm.getLongSupportMessageForUser(admin1,
1688 DpmMockContext.CALLER_USER_HANDLE));
1689 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1690 }
1691
1692 // Only system can call the per user versions.
1693 {
1694 try {
1695 dpm.getShortSupportMessageForUser(admin1,
1696 DpmMockContext.CALLER_USER_HANDLE);
1697 fail("Only system should be able to call getXXXForUser versions");
1698 } catch (SecurityException expected) {
1699 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1700 }
1701 try {
1702 dpm.getLongSupportMessageForUser(admin1,
1703 DpmMockContext.CALLER_USER_HANDLE);
1704 fail("Only system should be able to call getXXXForUser versions");
1705 } catch (SecurityException expected) {
1706 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1707 }
1708 }
1709
1710 // Can't set message for admin in another uid.
1711 {
1712 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1713 try {
1714 dpm.setShortSupportMessage(admin1, "Some text");
1715 fail("Admins should only be able to change their own support text.");
1716 } catch (SecurityException expected) {
1717 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1718 }
1719 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1720 }
1721
1722 // Set/Get short returns what it sets and other admins text isn't changed.
1723 {
1724 final String supportText = "Some text to test with.";
1725 dpm.setShortSupportMessage(admin1, supportText);
1726 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1727 assertNull(dpm.getLongSupportMessage(admin1));
1728 assertNull(dpm.getShortSupportMessage(admin2));
1729
1730 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1731 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1732 DpmMockContext.CALLER_USER_HANDLE));
1733 assertNull(dpm.getShortSupportMessageForUser(admin2,
1734 DpmMockContext.CALLER_USER_HANDLE));
1735 assertNull(dpm.getLongSupportMessageForUser(admin1,
1736 DpmMockContext.CALLER_USER_HANDLE));
1737 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1738
1739 dpm.setShortSupportMessage(admin1, null);
1740 assertNull(dpm.getShortSupportMessage(admin1));
1741 }
1742
1743 // Set/Get long returns what it sets and other admins text isn't changed.
1744 {
1745 final String supportText = "Some text to test with.\nWith more text.";
1746 dpm.setLongSupportMessage(admin1, supportText);
1747 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1748 assertNull(dpm.getShortSupportMessage(admin1));
1749 assertNull(dpm.getLongSupportMessage(admin2));
1750
1751 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1752 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1753 DpmMockContext.CALLER_USER_HANDLE));
1754 assertNull(dpm.getLongSupportMessageForUser(admin2,
1755 DpmMockContext.CALLER_USER_HANDLE));
1756 assertNull(dpm.getShortSupportMessageForUser(admin1,
1757 DpmMockContext.CALLER_USER_HANDLE));
1758 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1759
1760 dpm.setLongSupportMessage(admin1, null);
1761 assertNull(dpm.getLongSupportMessage(admin1));
1762 }
1763 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001764
1765 /**
1766 * Test for:
1767 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001768 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001769 * {@link DevicePolicyManager#isAffiliatedUser}
1770 */
1771 public void testUserAffiliation() throws Exception {
1772 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1773 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1774 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1775
1776 // Check that the system user is unaffiliated.
1777 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1778 assertFalse(dpm.isAffiliatedUser());
1779
1780 // Set a device owner on the system user. Check that the system user becomes affiliated.
1781 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1782 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1783 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1784 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001785 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001786
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001787 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001788 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1789 setAsProfileOwner(admin2);
1790 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001791 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001792
1793 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1794 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001795 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001796 userAffiliationIds.add("red");
1797 userAffiliationIds.add("green");
1798 userAffiliationIds.add("blue");
1799 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001800 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001801 assertFalse(dpm.isAffiliatedUser());
1802
1803 // Have the device owner specify a set of affiliation ids that do not intersect with those
1804 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001805 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001806 deviceAffiliationIds.add("cyan");
1807 deviceAffiliationIds.add("yellow");
1808 deviceAffiliationIds.add("magenta");
1809 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1810 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001811 MoreAsserts.assertContentsInAnyOrder(
1812 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001813 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1814 assertFalse(dpm.isAffiliatedUser());
1815
1816 // Have the profile owner specify a set of affiliation ids that intersect with those
1817 // specified by the device owner. Check that the test user becomes affiliated.
1818 userAffiliationIds.add("yellow");
1819 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001820 MoreAsserts.assertContentsInAnyOrder(
1821 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001822 assertTrue(dpm.isAffiliatedUser());
1823
Esteban Talaverac9bb3782016-11-11 15:41:14 +00001824 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
1825 dpm.setAffiliationIds(admin2, Collections.emptyList());
1826 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001827 assertFalse(dpm.isAffiliatedUser());
1828
1829 // Check that the system user remains affiliated.
1830 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1831 assertTrue(dpm.isAffiliatedUser());
1832 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001833
1834 public void testGetUserProvisioningState_defaultResult() {
1835 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1836 }
1837
1838 public void testSetUserProvisioningState_permission() throws Exception {
1839 setupProfileOwner();
1840 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1841
1842 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1843 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1844 }
1845
1846 public void testSetUserProvisioningState_unprivileged() throws Exception {
1847 setupProfileOwner();
1848 try {
1849 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1850 DpmMockContext.CALLER_USER_HANDLE);
1851 fail("Expected SecurityException");
1852 } catch (SecurityException expected) {
1853 }
1854 }
1855
1856 public void testSetUserProvisioningState_noManagement() {
1857 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1858 try {
1859 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1860 DpmMockContext.CALLER_USER_HANDLE);
1861 fail("IllegalStateException expected");
1862 } catch (IllegalStateException e) {
1863 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1864 e.getMessage());
1865 }
1866 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1867 }
1868
1869 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1870 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1871 setupDeviceOwner();
1872 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1873
1874 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1875 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1876 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1877 }
1878
1879 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1880 throws Exception {
1881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1882 setupDeviceOwner();
1883 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1884
1885 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1886 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1887 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1888 }
1889
1890 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1892 setupDeviceOwner();
1893 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1894
1895 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1896 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1897 }
1898
1899 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1900 throws Exception {
1901 setupProfileOwner();
1902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1903
1904 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1905 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1906 DevicePolicyManager.STATE_USER_UNMANAGED);
1907 }
1908
1909 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1910 throws Exception {
1911 setupProfileOwner();
1912 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1913
1914 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1915 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1916 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1917 }
1918
1919 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1920 setupProfileOwner();
1921 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1922
1923 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1924 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1925 }
1926
1927 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1928 setupProfileOwner();
1929 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1930
1931 try {
1932 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1933 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1934 DevicePolicyManager.STATE_USER_UNMANAGED);
1935 fail("Expected IllegalStateException");
1936 } catch (IllegalStateException e) {
1937 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1938 e.getMessage());
1939 }
1940 }
1941
1942 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1943 throws Exception {
1944 setupProfileOwner();
1945 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1946
1947 try {
1948 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1949 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1950 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1951 fail("Expected IllegalStateException");
1952 } catch (IllegalStateException e) {
1953 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1954 e.getMessage());
1955 }
1956 }
1957
1958 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1959 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1960 for (int state : states) {
1961 dpm.setUserProvisioningState(state, userId);
1962 assertEquals(state, dpm.getUserProvisioningState());
1963 }
1964 }
1965
1966 private void setupProfileOwner() throws Exception {
1967 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1968
1969 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1970 dpm.setActiveAdmin(admin1, false);
1971 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1972
1973 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1974 }
1975
1976 private void setupDeviceOwner() throws Exception {
1977 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1978
1979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1980 dpm.setActiveAdmin(admin1, false);
1981 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1982
1983 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1984 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001985
1986 public void testSetMaximumTimeToLock() {
1987 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1988
1989 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1990 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1991
1992 reset(mMockContext.powerManagerInternal);
1993 reset(mMockContext.settings);
1994
1995 dpm.setMaximumTimeToLock(admin1, 0);
1996 verifyScreenTimeoutCall(null, false);
1997 reset(mMockContext.powerManagerInternal);
1998 reset(mMockContext.settings);
1999
2000 dpm.setMaximumTimeToLock(admin1, 1);
2001 verifyScreenTimeoutCall(1, true);
2002 reset(mMockContext.powerManagerInternal);
2003 reset(mMockContext.settings);
2004
2005 dpm.setMaximumTimeToLock(admin2, 10);
2006 verifyScreenTimeoutCall(null, false);
2007 reset(mMockContext.powerManagerInternal);
2008 reset(mMockContext.settings);
2009
2010 dpm.setMaximumTimeToLock(admin1, 5);
2011 verifyScreenTimeoutCall(5, true);
2012 reset(mMockContext.powerManagerInternal);
2013 reset(mMockContext.settings);
2014
2015 dpm.setMaximumTimeToLock(admin2, 4);
2016 verifyScreenTimeoutCall(4, true);
2017 reset(mMockContext.powerManagerInternal);
2018 reset(mMockContext.settings);
2019
2020 dpm.setMaximumTimeToLock(admin1, 0);
2021 reset(mMockContext.powerManagerInternal);
2022 reset(mMockContext.settings);
2023
2024 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2025 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2026 reset(mMockContext.powerManagerInternal);
2027 reset(mMockContext.settings);
2028
2029 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2030 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2031 reset(mMockContext.powerManagerInternal);
2032 reset(mMockContext.settings);
2033
2034 dpm.setMaximumTimeToLock(admin2, 10);
2035 verifyScreenTimeoutCall(10, true);
2036 reset(mMockContext.powerManagerInternal);
2037 reset(mMockContext.settings);
2038
2039 // There's no restriction; shold be set to MAX.
2040 dpm.setMaximumTimeToLock(admin2, 0);
2041 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2042 }
2043
Michal Karpinski943aabd2016-10-06 11:09:25 +01002044 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2045 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2046 setupDeviceOwner();
2047 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2048
2049 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
2050 final long ONE_MINUTE = 60 * 1000;
2051
2052 // aggregation should be the default if unset by any admin
2053 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2054 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2055
2056 // admin not participating by default
2057 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2058
2059 //clamping from the top
2060 dpm.setRequiredStrongAuthTimeout(admin1,
2061 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2062 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2063 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2064 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2065 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2066
2067 // 0 means default
2068 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2069 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2070 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2071 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2072
2073 // clamping from the bottom
2074 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2075 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2076 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2077
2078 // value within range
2079 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2080 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2081 + ONE_MINUTE);
2082 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
2083 + ONE_MINUTE);
2084
2085 // reset to default
2086 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2087 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2088 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2089 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2090
2091 // negative value
2092 try {
2093 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2094 fail("Didn't throw IllegalArgumentException");
2095 } catch (IllegalArgumentException iae) {
2096 }
2097 }
2098
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002099 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2100 boolean shouldStayOnWhilePluggedInBeCleared) {
2101 if (expectedTimeout == null) {
2102 verify(mMockContext.powerManagerInternal, times(0))
2103 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2104 } else {
2105 verify(mMockContext.powerManagerInternal, times(1))
2106 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2107 }
2108 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2109 // UnfinishedVerificationException.
2110 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002111
Esteban Talavera01576862016-12-15 11:16:44 +00002112 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002113 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2114 .thenReturn(false);
2115 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2116 .thenReturn(false);
2117 initializeDpms();
2118 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2119 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2120 .thenReturn(true);
2121 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2122
2123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002124 }
Victor Chang3e794af2016-03-04 13:48:17 +00002125
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002126 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2127 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002128 mContext.packageName = admin1.getPackageName();
2129 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002130 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2133 false);
2134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2135 }
2136
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002137 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2138 setup_DeviceAdminFeatureOff();
2139 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2140 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2141 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2142 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2143 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2144 assertCheckProvisioningPreCondition(
2145 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2146 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2147 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2148 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2149 }
2150
Esteban Talavera01576862016-12-15 11:16:44 +00002151 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002152 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2153 .thenReturn(false);
2154 initializeDpms();
2155 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2156 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2157 .thenReturn(true);
2158 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2159
2160 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002161 }
Victor Chang3e794af2016-03-04 13:48:17 +00002162
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002163 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2164 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002165 mContext.packageName = admin1.getPackageName();
2166 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002167 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2170 false);
2171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2172
2173 // Test again when split user is on
2174 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2175 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2177 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2178 true);
2179 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2180 }
2181
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002182 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2183 setup_ManagedProfileFeatureOff();
2184 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2185 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2186 DevicePolicyManager.CODE_OK);
2187 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2188 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2189 assertCheckProvisioningPreCondition(
2190 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2191 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2192 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2193 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2194
2195 // Test again when split user is on
2196 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2197 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2198 DevicePolicyManager.CODE_OK);
2199 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2200 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2201 assertCheckProvisioningPreCondition(
2202 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2203 DevicePolicyManager.CODE_OK);
2204 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2205 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2206 }
2207
Esteban Talavera01576862016-12-15 11:16:44 +00002208 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002209 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2210 .thenReturn(true);
2211 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2212 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2213 .thenReturn(true);
2214 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2215
2216 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002217 }
Victor Chang3e794af2016-03-04 13:48:17 +00002218
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002219 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2220 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002221 mContext.packageName = admin1.getPackageName();
2222 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002223 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2224 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2225 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2226 false /* because of non-split user */);
2227 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2228 false /* because of non-split user */);
2229 }
2230
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002231 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002232 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002233 setup_nonSplitUser_firstBoot_primaryUser();
2234 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2235 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2236 DevicePolicyManager.CODE_OK);
2237 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2238 DevicePolicyManager.CODE_OK);
2239 assertCheckProvisioningPreCondition(
2240 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2241 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2243 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2244 }
2245
Esteban Talavera01576862016-12-15 11:16:44 +00002246 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002247 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2248 .thenReturn(true);
2249 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2250 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2251 .thenReturn(true);
2252 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2253
2254 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002255 }
Victor Chang3e794af2016-03-04 13:48:17 +00002256
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002257 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2258 throws Exception {
2259 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002260 mContext.packageName = admin1.getPackageName();
2261 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002262 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2263 false/* because of completed device setup */);
2264 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2265 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2266 false/* because of non-split user */);
2267 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2268 false/* because of non-split user */);
2269 }
2270
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002271 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2272 throws Exception {
2273 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2274 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2275 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2276 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2277 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2278 DevicePolicyManager.CODE_OK);
2279 assertCheckProvisioningPreCondition(
2280 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2281 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2283 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2284 }
2285
Esteban Talavera01576862016-12-15 11:16:44 +00002286 public void testIsProvisioningAllowed_nonSplitUser_withDo_primaryUser() throws Exception {
2287 setDeviceOwner();
2288 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2289 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2290 mContext.packageName = admin1.getPackageName();
2291
2292 // COMP mode is allowed.
2293 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2294
2295 when(mContext.userManager.hasUserRestriction(
2296 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2297 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2298 .thenReturn(true);
2299
2300 // The DO should be allowed to initiate provisioning if it set the restriction itself.
2301 when(mContext.userManager.getUserRestrictionSource(
2302 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2303 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2304 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2305 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2306
2307 // The DO should not be allowed to initiate provisioning if the restriction is set by
2308 // another entity.
2309 when(mContext.userManager.getUserRestrictionSource(
2310 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2311 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2312 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2313 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2314 }
2315
2316 public void
2317 testCheckProvisioningPreCondition_nonSplitUser_withDo_primaryUser() throws Exception {
2318 setDeviceOwner();
2319 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2320 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2321
2322 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2323 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
2324
2325 // COMP mode is allowed.
2326 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2327 DevicePolicyManager.CODE_OK);
2328
2329 // And other DPCs can also provisioning a managed profile (DO + BYOD case).
2330 assertCheckProvisioningPreCondition(
2331 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2332 "some.other.dpc.package.name",
2333 DevicePolicyManager.CODE_OK);
2334
2335 when(mContext.userManager.hasUserRestriction(
2336 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2337 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2338 .thenReturn(true);
2339
2340 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2341 // other packages should be forbidden.
2342 when(mContext.userManager.getUserRestrictionSource(
2343 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2344 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2345 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2346 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2347 DevicePolicyManager.CODE_OK);
2348 assertCheckProvisioningPreCondition(
2349 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2350 "some.other.dpc.package.name",
2351 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2352
2353 // The DO should not be allowed to initiate provisioning if the restriction is set by
2354 // another entity.
2355 when(mContext.userManager.getUserRestrictionSource(
2356 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2357 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2358 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2359 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2360 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2361 assertCheckProvisioningPreCondition(
2362 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2363 "some.other.dpc.package.name",
2364 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
2365 }
2366
2367 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002368 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2369 .thenReturn(true);
2370 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2371 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2372 .thenReturn(false);
2373 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2374
2375 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002376 }
Victor Chang3e794af2016-03-04 13:48:17 +00002377
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002378 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2379 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002380 mContext.packageName = admin1.getPackageName();
2381 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002382 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2383 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2384 false /* because canAddMoreManagedProfiles returns false */);
2385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2386 true);
2387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2388 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002389 }
2390
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002391 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2392 throws Exception {
2393 setup_splitUser_firstBoot_systemUser();
2394 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2395 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2396 DevicePolicyManager.CODE_OK);
2397 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002398 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002399 assertCheckProvisioningPreCondition(
2400 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2401 DevicePolicyManager.CODE_OK);
2402 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2403 DevicePolicyManager.CODE_SYSTEM_USER);
2404 }
2405
Esteban Talavera01576862016-12-15 11:16:44 +00002406 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002407 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2408 .thenReturn(true);
2409 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2410 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2411 .thenReturn(false);
2412 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2413
2414 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002415 }
Victor Chang3e794af2016-03-04 13:48:17 +00002416
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002417 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2418 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002419 mContext.packageName = admin1.getPackageName();
2420 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002421 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2422 true/* it's undefined behavior. Can be changed into false in the future */);
2423 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2424 false /* because canAddMoreManagedProfiles returns false */);
2425 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2426 true/* it's undefined behavior. Can be changed into false in the future */);
2427 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2428 false/* because calling uid is system user */);
2429 }
2430
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002431 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2432 throws Exception {
2433 setup_splitUser_afterDeviceSetup_systemUser();
2434 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2435 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2436 DevicePolicyManager.CODE_OK);
2437 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002438 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002439 assertCheckProvisioningPreCondition(
2440 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2441 DevicePolicyManager.CODE_OK);
2442 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2443 DevicePolicyManager.CODE_SYSTEM_USER);
2444 }
2445
Esteban Talavera01576862016-12-15 11:16:44 +00002446 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002447 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2448 .thenReturn(true);
2449 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2450 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2451 true)).thenReturn(true);
2452 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2453
2454 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002455 }
Victor Chang3e794af2016-03-04 13:48:17 +00002456
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002457 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2458 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002459 mContext.packageName = admin1.getPackageName();
2460 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002461 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2462 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2463 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2464 true);
2465 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002466 }
2467
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002468 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002469 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002470 setup_splitUser_firstBoot_primaryUser();
2471 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2472 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2473 DevicePolicyManager.CODE_OK);
2474 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2475 DevicePolicyManager.CODE_OK);
2476 assertCheckProvisioningPreCondition(
2477 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2478 DevicePolicyManager.CODE_OK);
2479 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2480 DevicePolicyManager.CODE_OK);
2481 }
2482
Esteban Talavera01576862016-12-15 11:16:44 +00002483 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002484 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2485 .thenReturn(true);
2486 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2487 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2488 true)).thenReturn(true);
2489 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2490
2491 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002492 }
Victor Chang3e794af2016-03-04 13:48:17 +00002493
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002494 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2495 throws Exception {
2496 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002497 mContext.packageName = admin1.getPackageName();
2498 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002499 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2500 true/* it's undefined behavior. Can be changed into false in the future */);
2501 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2502 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2503 true/* it's undefined behavior. Can be changed into false in the future */);
2504 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2505 false/* because user setup completed */);
2506 }
2507
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002508 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002509 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002510 setup_splitUser_afterDeviceSetup_primaryUser();
2511 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2512 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2513 DevicePolicyManager.CODE_OK);
2514 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2515 DevicePolicyManager.CODE_OK);
2516 assertCheckProvisioningPreCondition(
2517 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2518 DevicePolicyManager.CODE_OK);
2519 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2520 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2521 }
2522
Esteban Talavera01576862016-12-15 11:16:44 +00002523 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002524 setDeviceOwner();
2525
2526 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2527 .thenReturn(true);
2528 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2529 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2530 .thenReturn(false);
2531 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2532
2533 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002534 }
Victor Chang3e794af2016-03-04 13:48:17 +00002535
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002536 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2537 throws Exception {
2538 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002539 mContext.packageName = admin1.getPackageName();
2540 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002541 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2542 false /* can't provision managed profile on system user */);
2543 }
2544
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002545 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002546 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002547 setup_provisionManagedProfileWithDeviceOwner_systemUser();
2548 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2549 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2550 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
2551 }
2552
2553 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002554 setDeviceOwner();
2555
2556 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2557 .thenReturn(true);
2558 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2559 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2560 true)).thenReturn(true);
2561 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2562
2563 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002564 }
Victor Chang3e794af2016-03-04 13:48:17 +00002565
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002566 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2567 throws Exception {
2568 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002569 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2570 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00002571 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2572 }
2573
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002574 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00002575 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002576 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
2577 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002578
2579 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002580 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2581 DevicePolicyManager.CODE_OK);
2582 }
2583
2584 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00002585 setDeviceOwner();
2586
2587 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2588 .thenReturn(true);
2589 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002590 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002591 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2592 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00002593 .thenReturn(true);
2594 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002595 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002596 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2597 true)).thenReturn(true);
2598 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2599
2600 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002601 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00002602
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002603 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2604 throws Exception {
2605 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002606 mContext.packageName = admin1.getPackageName();
2607 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00002608 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2609 }
2610
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002611 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
2612 throws Exception {
2613 setup_provisionManagedProfileCantRemoveUser_primaryUser();
2614 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2615 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2616 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2617 }
2618
2619 public void testCheckProvisioningPreCondition_permission() {
2620 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2621 try {
Esteban Talavera01576862016-12-15 11:16:44 +00002622 dpm.checkProvisioningPreCondition(
2623 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002624 fail("Didn't throw SecurityException");
2625 } catch (SecurityException expected) {
2626 }
2627 }
2628
Victor Chang3577ed22016-08-25 18:49:26 +01002629 public void testForceUpdateUserSetupComplete_permission() {
2630 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2631 try {
2632 dpm.forceUpdateUserSetupComplete();
2633 fail("Didn't throw SecurityException");
2634 } catch (SecurityException expected) {
2635 }
2636 }
2637
2638 public void testForceUpdateUserSetupComplete_systemUser() {
2639 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2640 // GIVEN calling from user 20
2641 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2642 try {
2643 dpm.forceUpdateUserSetupComplete();
2644 fail("Didn't throw SecurityException");
2645 } catch (SecurityException expected) {
2646 }
2647 }
2648
2649 public void testForceUpdateUserSetupComplete_userbuild() {
2650 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2652
2653 final int userId = UserHandle.USER_SYSTEM;
2654 // GIVEN userComplete is false in SettingsProvider
2655 setUserSetupCompleteForUser(false, userId);
2656
2657 // GIVEN userComplete is true in DPM
2658 DevicePolicyManagerService.DevicePolicyData userData =
2659 new DevicePolicyManagerService.DevicePolicyData(userId);
2660 userData.mUserSetupComplete = true;
2661 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2662
2663 // GIVEN it's user build
2664 mContext.buildMock.isDebuggable = false;
2665
2666 assertTrue(dpms.hasUserSetupCompleted());
2667
2668 dpm.forceUpdateUserSetupComplete();
2669
2670 // THEN the state in dpms is not changed
2671 assertTrue(dpms.hasUserSetupCompleted());
2672 }
2673
2674 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2675 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2676 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2677
2678 final int userId = UserHandle.USER_SYSTEM;
2679 // GIVEN userComplete is false in SettingsProvider
2680 setUserSetupCompleteForUser(false, userId);
2681
2682 // GIVEN userComplete is true in DPM
2683 DevicePolicyManagerService.DevicePolicyData userData =
2684 new DevicePolicyManagerService.DevicePolicyData(userId);
2685 userData.mUserSetupComplete = true;
2686 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2687
2688 // GIVEN it's userdebug build
2689 mContext.buildMock.isDebuggable = true;
2690
2691 assertTrue(dpms.hasUserSetupCompleted());
2692
2693 dpm.forceUpdateUserSetupComplete();
2694
2695 // THEN the state in dpms is not changed
2696 assertFalse(dpms.hasUserSetupCompleted());
2697 }
2698
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002699 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002700 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002701 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2702 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
2703 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
2704 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002705 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002706 }
2707
2708 public void testGetLastSecurityLogRetrievalTime() throws Exception {
2709 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2710 setupDeviceOwner();
2711 when(mContext.userManager.getUserCount()).thenReturn(1);
2712 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
2713 .thenReturn(true);
2714
2715 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002716 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002717
2718 // Enabling logging should not change the timestamp.
2719 dpm.setSecurityLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002720 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002721
2722 // Retrieving the logs should update the timestamp.
2723 final long beforeRetrieval = System.currentTimeMillis();
2724 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002725 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002726 final long afterRetrieval = System.currentTimeMillis();
2727 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
2728 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
2729
2730 // Retrieving the pre-boot logs should update the timestamp.
2731 Thread.sleep(2);
2732 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002733 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002734 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
2735
2736 // Checking the timestamp again should not change it.
2737 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002738 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002739
2740 // Retrieving the logs again should update the timestamp.
2741 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002742 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002743 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
2744
2745 // Disabling logging should not change the timestamp.
2746 Thread.sleep(2);
2747 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002748 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002749
2750 // Restarting the DPMS should not lose the timestamp.
2751 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002752 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002753
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002754 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2755 mContext.binder.callingUid = 1234567;
2756 mContext.callerPermissions.add(permission.MANAGE_USERS);
2757 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2758 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2759
2760 // System can retrieve the timestamp.
2761 mContext.binder.clearCallingIdentity();
2762 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
2763
2764 // Removing the device owner should clear the timestamp.
2765 clearDeviceOwner();
2766 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002767 }
2768
2769 public void testGetLastBugReportRequestTime() throws Exception {
2770 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2771 setupDeviceOwner();
2772 when(mContext.userManager.getUserCount()).thenReturn(1);
2773 mContext.packageName = admin1.getPackageName();
2774 mContext.applicationInfo = new ApplicationInfo();
2775 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
2776 .thenReturn(Color.WHITE);
2777 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
2778 anyObject())).thenReturn(Color.WHITE);
2779
2780 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002781 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002782
2783 // Requesting a bug report should update the timestamp.
2784 final long beforeRequest = System.currentTimeMillis();
2785 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002786 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002787 final long afterRequest = System.currentTimeMillis();
2788 assertTrue(bugReportRequestTime >= beforeRequest);
2789 assertTrue(bugReportRequestTime <= afterRequest);
2790
2791 // Checking the timestamp again should not change it.
2792 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002793 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002794
2795 // Restarting the DPMS should not lose the timestamp.
2796 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002797 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002798
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002799 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2800 mContext.binder.callingUid = 1234567;
2801 mContext.callerPermissions.add(permission.MANAGE_USERS);
2802 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2803 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2804
2805 // System can retrieve the timestamp.
2806 mContext.binder.clearCallingIdentity();
2807 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
2808
2809 // Removing the device owner should clear the timestamp.
2810 clearDeviceOwner();
2811 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002812 }
2813
2814 public void testGetLastNetworkLogRetrievalTime() throws Exception {
2815 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2816 setupDeviceOwner();
2817 when(mContext.userManager.getUserCount()).thenReturn(1);
2818 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
2819 .thenReturn(true);
2820
2821 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002822 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002823
2824 // Attempting to retrieve logs without enabling logging should not change the timestamp.
2825 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002826 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002827
2828 // Enabling logging should not change the timestamp.
2829 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002830 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002831
2832 // Retrieving the logs should update the timestamp.
2833 final long beforeRetrieval = System.currentTimeMillis();
2834 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002835 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002836 final long afterRetrieval = System.currentTimeMillis();
2837 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
2838 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
2839
2840 // Checking the timestamp again should not change it.
2841 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002842 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002843
2844 // Retrieving the logs again should update the timestamp.
2845 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002846 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002847 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
2848
2849 // Disabling logging should not change the timestamp.
2850 Thread.sleep(2);
2851 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002852 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002853
2854 // Restarting the DPMS should not lose the timestamp.
2855 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01002856 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2857
2858 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
2859 mContext.binder.callingUid = 1234567;
2860 mContext.callerPermissions.add(permission.MANAGE_USERS);
2861 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2862 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2863
2864 // System can retrieve the timestamp.
2865 mContext.binder.clearCallingIdentity();
2866 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
2867
2868 // Removing the device owner should clear the timestamp.
2869 clearDeviceOwner();
2870 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01002871 }
2872
Tony Mak2f26b792016-11-28 17:54:51 +00002873 public void testGetBindDeviceAdminTargetUsers() throws Exception {
2874 // Setup device owner.
2875 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2876 setupDeviceOwner();
2877
2878 // Only device owner is setup, the result list should be empty.
2879 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2880 MoreAsserts.assertEmpty(targetUsers);
2881
2882 // Setup a managed profile managed by the same admin.
2883 final int MANAGED_PROFILE_USER_ID = 15;
2884 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2885 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2886
2887 // Add a secondary user, it should never talk with.
2888 final int ANOTHER_USER_ID = 36;
2889 mContext.addUser(ANOTHER_USER_ID, 0);
2890
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002891 // Since the managed profile is not affiliated, they should not be allowed to talk to each
2892 // other.
2893 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2894 MoreAsserts.assertEmpty(targetUsers);
2895
2896 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2897 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2898 MoreAsserts.assertEmpty(targetUsers);
2899
2900 // Setting affiliation ids
2901 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
2902 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2903 dpm.setAffiliationIds(admin1, userAffiliationIds);
2904
2905 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2906 dpm.setAffiliationIds(admin1, userAffiliationIds);
2907
Tony Mak2f26b792016-11-28 17:54:51 +00002908 // Calling from device owner admin, the result list should just contain the managed
2909 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002910 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002911 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2912 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
2913
2914 // Calling from managed profile admin, the result list should just contain the system
2915 // user id.
2916 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2917 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2918 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002919
2920 // Changing affiliation ids in one
2921 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
2922
2923 // Since the managed profile is not affiliated any more, they should not be allowed to talk
2924 // to each other.
2925 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2926 MoreAsserts.assertEmpty(targetUsers);
2927
2928 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2929 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2930 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00002931 }
2932
2933 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
2934 // Setup a device owner.
2935 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2936 setupDeviceOwner();
2937
2938 // Set up a managed profile managed by different package.
2939 final int MANAGED_PROFILE_USER_ID = 15;
2940 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
2941 final ComponentName adminDifferentPackage =
2942 new ComponentName("another.package", "whatever.class");
2943 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
2944
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002945 // Setting affiliation ids
2946 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
2947 dpm.setAffiliationIds(admin1, userAffiliationIds);
2948
2949 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2950 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
2951
Tony Mak2f26b792016-11-28 17:54:51 +00002952 // Calling from device owner admin, we should get zero bind device admin target users as
2953 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00002954 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00002955 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
2956 MoreAsserts.assertEmpty(targetUsers);
2957
2958 // Calling from managed profile admin, we should still get zero target users for the same
2959 // reason.
2960 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2961 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
2962 MoreAsserts.assertEmpty(targetUsers);
2963 }
2964
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01002965 public void testIsDeviceManaged() throws Exception {
2966 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2967 setupDeviceOwner();
2968
2969 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
2970 // find out that the device has a device owner.
2971 assertTrue(dpm.isDeviceManaged());
2972 mContext.binder.callingUid = 1234567;
2973 mContext.callerPermissions.add(permission.MANAGE_USERS);
2974 assertTrue(dpm.isDeviceManaged());
2975 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2976 mContext.binder.clearCallingIdentity();
2977 assertTrue(dpm.isDeviceManaged());
2978
2979 clearDeviceOwner();
2980
2981 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
2982 // not have a device owner.
2983 mContext.binder.callingUid = 1234567;
2984 mContext.callerPermissions.add(permission.MANAGE_USERS);
2985 assertFalse(dpm.isDeviceManaged());
2986 mContext.callerPermissions.remove(permission.MANAGE_USERS);
2987 mContext.binder.clearCallingIdentity();
2988 assertFalse(dpm.isDeviceManaged());
2989 }
2990
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01002991 public void testDeviceOwnerOrganizationName() throws Exception {
2992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2993 setupDeviceOwner();
2994
2995 dpm.setOrganizationName(admin1, "organization");
2996
2997 // Device owner can retrieve organization managing the device.
2998 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
2999
3000 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3001 mContext.binder.callingUid = 1234567;
3002 mContext.callerPermissions.add(permission.MANAGE_USERS);
3003 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3004 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3005
3006 // System can retrieve organization managing the device.
3007 mContext.binder.clearCallingIdentity();
3008 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3009
3010 // Removing the device owner clears the organization managing the device.
3011 clearDeviceOwner();
3012 assertNull(dpm.getDeviceOwnerOrganizationName());
3013 }
3014
Victor Chang3e794af2016-03-04 13:48:17 +00003015 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
3016 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
3017 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
3018 dpms.notifyChangeToContentObserver(
3019 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
3020 }
3021
3022 private void assertProvisioningAllowed(String action, boolean expected) {
3023 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
3024 dpm.isProvisioningAllowed(action));
3025 }
Tony Mak2f26b792016-11-28 17:54:51 +00003026
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003027 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00003028 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
3029 }
3030
3031 private void assertCheckProvisioningPreCondition(
3032 String action, String packageName, int provisioningCondition) {
3033 assertEquals("checkProvisioningPreCondition("
3034 + action + ", " + packageName + ") returning unexpected result",
3035 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003036 }
3037
Tony Mak2f26b792016-11-28 17:54:51 +00003038 /**
3039 * Setup a managed profile with the specified admin and its uid.
3040 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
3041 * @param adminUid uid of the admin package.
3042 * @param copyFromAdmin package information for {@code admin} will be built based on this
3043 * component's information.
3044 */
3045 private void addManagedProfile(
3046 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
3047 final int userId = UserHandle.getUserId(adminUid);
3048 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
3049 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3050 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
3051 dpm.setActiveAdmin(admin, false, userId);
3052 assertTrue(dpm.setProfileOwner(admin, null, userId));
3053 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3054 }
Victor Chang3e794af2016-03-04 13:48:17 +00003055}