blob: 71379b8258e26792bd7c5c3b60caf098bc5efa51 [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;
Rubin Xued1928a2016-02-11 17:23:06 +000025import android.content.pm.ApplicationInfo;
26import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070027import android.content.pm.PackageManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080028import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080029import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070030import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080031import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070032import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070033import android.os.UserManager;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080034import android.provider.Settings;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000035import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080036import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000037import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010038import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070039import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070040
Alan Treadwayafad8782016-01-19 15:15:08 +000041import com.android.server.LocalServices;
42import com.android.server.SystemService;
43
Makoto Onukib643fb02015-09-22 15:03:44 -070044import org.mockito.invocation.InvocationOnMock;
45import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070046
Makoto Onukic8a5a552015-11-19 14:29:12 -080047import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000048import java.util.Arrays;
Makoto Onukib643fb02015-09-22 15:03:44 -070049import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070050import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070051import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010052import java.util.Set;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070053
54import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070055import static org.mockito.Matchers.anyInt;
Makoto Onukif76b06a2015-09-22 15:03:44 -070056import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070057import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import static org.mockito.Matchers.isNull;
Makoto Onukib643fb02015-09-22 15:03:44 -070059import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import static org.mockito.Mockito.doReturn;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080061import static org.mockito.Mockito.reset;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062import static org.mockito.Mockito.times;
63import static org.mockito.Mockito.verify;
64import static org.mockito.Mockito.when;
65
66/**
Makoto Onukif76b06a2015-09-22 15:03:44 -070067 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068 *
69 m FrameworksServicesTests &&
70 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +000071 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -080073 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070074
75 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
76 */
Benjamin Franz6d009032016-01-25 18:56:38 +000077@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070078public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +000079 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
80 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
81 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
82
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083 private DpmMockContext mContext;
84 public DevicePolicyManager dpm;
85 public DevicePolicyManagerServiceTestable dpms;
86
87 @Override
88 protected void setUp() throws Exception {
89 super.setUp();
90
91 mContext = getContext();
92
93 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
94 .thenReturn(true);
95
Makoto Onuki1a5ee772016-02-12 15:34:57 -080096 // By default, pretend all users are running and unlocked.
97 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
98
Makoto Onukia52562c2015-10-01 16:12:31 -070099 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700100
Makoto Onukid932f762015-09-29 16:53:38 -0700101 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
102 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
103 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800104 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700105
Makoto Onukib643fb02015-09-22 15:03:44 -0700106 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700107 }
108
Makoto Onukia52562c2015-10-01 16:12:31 -0700109 private void initializeDpms() {
110 // Need clearCallingIdentity() to pass permission checks.
111 final long ident = mContext.binder.clearCallingIdentity();
112 try {
113 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
114
115 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
116
117 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
118 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
119
120 dpm = new DevicePolicyManagerTestable(mContext, dpms);
121 } finally {
122 mContext.binder.restoreCallingIdentity(ident);
123 }
124 }
125
Makoto Onukib643fb02015-09-22 15:03:44 -0700126 private void setUpUserManager() {
127 // Emulate UserManager.set/getApplicationRestriction().
128 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
129
130 // UM.setApplicationRestrictions() will save to appRestrictions.
131 doAnswer(new Answer<Void>() {
132 @Override
133 public Void answer(InvocationOnMock invocation) throws Throwable {
134 String pkg = (String) invocation.getArguments()[0];
135 Bundle bundle = (Bundle) invocation.getArguments()[1];
136 UserHandle user = (UserHandle) invocation.getArguments()[2];
137
138 appRestrictions.put(Pair.create(pkg, user), bundle);
139
140 return null;
141 }
142 }).when(mContext.userManager).setApplicationRestrictions(
143 anyString(), any(Bundle.class), any(UserHandle.class));
144
145 // UM.getApplicationRestrictions() will read from appRestrictions.
146 doAnswer(new Answer<Bundle>() {
147 @Override
148 public Bundle answer(InvocationOnMock invocation) throws Throwable {
149 String pkg = (String) invocation.getArguments()[0];
150 UserHandle user = (UserHandle) invocation.getArguments()[1];
151
152 return appRestrictions.get(Pair.create(pkg, user));
153 }
154 }).when(mContext.userManager).getApplicationRestrictions(
155 anyString(), any(UserHandle.class));
156
Makoto Onukid932f762015-09-29 16:53:38 -0700157 // Add the first secondary user.
158 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700159 }
160
161 private void setAsProfileOwner(ComponentName admin) {
162 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
163 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
164
Makoto Onukia4f11972015-10-01 13:19:58 -0700165 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700166 dpm.setActiveAdmin(admin, /* replace =*/ false);
167
168 // Fire!
169 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
170
171 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700172 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700173 }
174
175 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700176 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
177 .thenReturn(false);
178
179 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
180 new DevicePolicyManagerServiceTestable(mContext, dataDir);
181
182 // If the device has no DPMS feature, it shouldn't register the local service.
183 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
184 }
185
186 /**
187 * Caller doesn't have proper permissions.
188 */
189 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700190 // 1. Failure cases.
191
192 // Caller doesn't have MANAGE_DEVICE_ADMINS.
193 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700194 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700195 fail("Didn't throw SecurityException");
196 } catch (SecurityException expected) {
197 }
198
199 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
200 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
201 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700202 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700203 fail("Didn't throw SecurityException");
204 } catch (SecurityException expected) {
205 }
206 }
207
Makoto Onukif76b06a2015-09-22 15:03:44 -0700208 /**
209 * Test for:
210 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800211 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700212 * {@link DevicePolicyManager#isAdminActive}
213 * {@link DevicePolicyManager#isAdminActiveAsUser}
214 * {@link DevicePolicyManager#getActiveAdmins}
215 * {@link DevicePolicyManager#getActiveAdminsAsUser}
216 */
217 public void testSetActiveAdmin() throws Exception {
218 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700219 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
220
Makoto Onukif76b06a2015-09-22 15:03:44 -0700221 // 2. Call the API.
222 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700223
224 // 3. Verify internal calls.
225
226 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700227 verify(mContext.spiedContext).sendBroadcastAsUser(
228 MockUtils.checkIntentAction(
229 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
230 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
231 verify(mContext.spiedContext).sendBroadcastAsUser(
232 MockUtils.checkIntentAction(
233 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700234 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
235
Makoto Onukif76b06a2015-09-22 15:03:44 -0700236 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
237 eq(admin1.getPackageName()),
238 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
239 eq(PackageManager.DONT_KILL_APP),
240 eq(DpmMockContext.CALLER_USER_HANDLE),
241 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700242
243 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700244
245 // Make sure it's active admin1.
246 assertTrue(dpm.isAdminActive(admin1));
247 assertFalse(dpm.isAdminActive(admin2));
248 assertFalse(dpm.isAdminActive(admin3));
249
250 // But not admin1 for a different user.
251
252 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
253 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
254 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
255
256 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
257 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
258
259 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
260
261 // Next, add one more admin.
262 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700263 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
264 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700265
266 dpm.setActiveAdmin(admin2, /* replace =*/ false);
267
268 // Now we have two admins.
269 assertTrue(dpm.isAdminActive(admin1));
270 assertTrue(dpm.isAdminActive(admin2));
271 assertFalse(dpm.isAdminActive(admin3));
272
273 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
274 // again. (times(1) because it was previously called for admin1)
275 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
276 eq(admin1.getPackageName()),
277 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
278 eq(PackageManager.DONT_KILL_APP),
279 eq(DpmMockContext.CALLER_USER_HANDLE),
280 anyString());
281
282 // 4. Add the same admin1 again without replace, which should throw.
283 try {
284 dpm.setActiveAdmin(admin1, /* replace =*/ false);
285 fail("Didn't throw");
286 } catch (IllegalArgumentException expected) {
287 }
288
289 // 5. Add the same admin1 again with replace, which should succeed.
290 dpm.setActiveAdmin(admin1, /* replace =*/ true);
291
292 // TODO make sure it's replaced.
293
294 // 6. Test getActiveAdmins()
295 List<ComponentName> admins = dpm.getActiveAdmins();
296 assertEquals(2, admins.size());
297 assertEquals(admin1, admins.get(0));
298 assertEquals(admin2, admins.get(1));
299
300 // Another user has no admins.
301 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
302
303 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
304 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
305
306 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
307 }
308
Makoto Onukid932f762015-09-29 16:53:38 -0700309 public void testSetActiveAdmin_multiUsers() throws Exception {
310
311 final int ANOTHER_USER_ID = 100;
312 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
313
314 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
315
316 // Set up pacakge manager for the other user.
317 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700318
319 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
320
321 dpm.setActiveAdmin(admin1, /* replace =*/ false);
322
323 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
324 dpm.setActiveAdmin(admin2, /* replace =*/ false);
325
326
327 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
328 assertTrue(dpm.isAdminActive(admin1));
329 assertFalse(dpm.isAdminActive(admin2));
330
331 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
332 assertFalse(dpm.isAdminActive(admin1));
333 assertTrue(dpm.isAdminActive(admin2));
334 }
335
Makoto Onukif76b06a2015-09-22 15:03:44 -0700336 /**
337 * Test for:
338 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800339 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700340 */
341 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
342 // 1. Make sure the caller has proper permissions.
343 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
344
345 dpm.setActiveAdmin(admin1, /* replace =*/ false);
346 assertTrue(dpm.isAdminActive(admin1));
347
348 // Add the same admin1 again without replace, which should throw.
349 try {
350 dpm.setActiveAdmin(admin1, /* replace =*/ false);
351 fail("Didn't throw");
352 } catch (IllegalArgumentException expected) {
353 }
354 }
355
356 /**
357 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800358 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
359 * BIND_DEVICE_ADMIN.
360 */
361 public void testSetActiveAdmin_permissionCheck() throws Exception {
362 // 1. Make sure the caller has proper permissions.
363 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
364
365 try {
366 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
367 fail();
368 } catch (IllegalArgumentException expected) {
369 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
370 }
371 assertFalse(dpm.isAdminActive(adminNoPerm));
372
373 // Change the target API level to MNC. Now it can be set as DA.
374 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
375 VERSION_CODES.M);
376 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
377 assertTrue(dpm.isAdminActive(adminNoPerm));
378
379 // TODO Test the "load from the file" case where DA will still be loaded even without
380 // BIND_DEVICE_ADMIN and target API is N.
381 }
382
383 /**
384 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700385 * {@link DevicePolicyManager#removeActiveAdmin}
386 */
387 public void testRemoveActiveAdmin_SecurityException() {
388 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
389
390 // Add admin.
391
392 dpm.setActiveAdmin(admin1, /* replace =*/ false);
393
394 assertTrue(dpm.isAdminActive(admin1));
395
396 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
397
398 // Directly call the DPMS method with a different userid, which should fail.
399 try {
400 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
401 fail("Didn't throw SecurityException");
402 } catch (SecurityException expected) {
403 }
404
405 // Try to remove active admin with a different caller userid should fail too, without
406 // having MANAGE_DEVICE_ADMINS.
407 mContext.callerPermissions.clear();
408
Makoto Onukid932f762015-09-29 16:53:38 -0700409 // Change the caller, and call into DPMS directly with a different user-id.
410
Makoto Onukif76b06a2015-09-22 15:03:44 -0700411 mContext.binder.callingUid = 1234567;
412 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700413 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700414 fail("Didn't throw SecurityException");
415 } catch (SecurityException expected) {
416 }
417 }
418
419 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800420 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
421 * (because we can't send the remove broadcast).
422 */
423 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
424 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
425
426 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
427
428 // Add admin.
429
430 dpm.setActiveAdmin(admin1, /* replace =*/ false);
431
432 assertTrue(dpm.isAdminActive(admin1));
433
434 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
435
436 // 1. User not unlocked.
437 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
438 .thenReturn(false);
439 try {
440 dpm.removeActiveAdmin(admin1);
441 fail("Didn't throw IllegalStateException");
442 } catch (IllegalStateException expected) {
443 MoreAsserts.assertContainsRegex(
444 "User must be running and unlocked", expected.getMessage());
445 }
446
447 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
448
449 // 2. User unlocked.
450 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
451 .thenReturn(true);
452
453 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700454 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800455 }
456
457 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700458 * Test for:
459 * {@link DevicePolicyManager#removeActiveAdmin}
460 */
Makoto Onukid932f762015-09-29 16:53:38 -0700461 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700462 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
463
464 // Add admin1.
465
466 dpm.setActiveAdmin(admin1, /* replace =*/ false);
467
468 assertTrue(dpm.isAdminActive(admin1));
469 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
470
471 // Different user, but should work, because caller has proper permissions.
472 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700473
474 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700475 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700478 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700479
480 // TODO DO Still can't be removed in this case.
481 }
482
483 /**
484 * Test for:
485 * {@link DevicePolicyManager#removeActiveAdmin}
486 */
487 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
488 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
489 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
490
491 // Add admin1.
492
493 dpm.setActiveAdmin(admin1, /* replace =*/ false);
494
495 assertTrue(dpm.isAdminActive(admin1));
496 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
497
498 // Broadcast from saveSettingsLocked().
499 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
500 MockUtils.checkIntentAction(
501 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
502 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
503
504 // Remove. No permissions, but same user, so it'll work.
505 mContext.callerPermissions.clear();
506 dpm.removeActiveAdmin(admin1);
507
Makoto Onukif76b06a2015-09-22 15:03:44 -0700508 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
509 MockUtils.checkIntentAction(
510 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
511 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
512 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700513 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700514 eq(dpms.mHandler),
515 eq(Activity.RESULT_OK),
516 isNull(String.class),
517 isNull(Bundle.class));
518
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700519 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700520
521 // Again broadcast from saveSettingsLocked().
522 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
523 MockUtils.checkIntentAction(
524 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
525 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
526
527 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700528 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700529
530 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000531 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700532 */
533 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000534 setDeviceOwner();
535
536 // Try to set a profile owner on the same user, which should fail.
537 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
538 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
539 try {
540 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
541 fail("IllegalStateException not thrown");
542 } catch (IllegalStateException expected) {
543 assertTrue("Message was: " + expected.getMessage(),
544 expected.getMessage().contains("already has a device owner"));
545 }
546
547 // DO admin can't be deactivated.
548 dpm.removeActiveAdmin(admin1);
549 assertTrue(dpm.isAdminActive(admin1));
550
551 // TODO Test getDeviceOwnerName() too. To do so, we need to change
552 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
553 }
554
555 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700556 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800557 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700558 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
559 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
560
Makoto Onukid932f762015-09-29 16:53:38 -0700561 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700562 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
563
Makoto Onukid932f762015-09-29 16:53:38 -0700564 // Make sure admin1 is installed on system user.
565 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700566
Makoto Onukic8a5a552015-11-19 14:29:12 -0800567 // Check various get APIs.
568 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
569
Makoto Onukib643fb02015-09-22 15:03:44 -0700570 // DO needs to be an DA.
571 dpm.setActiveAdmin(admin1, /* replace =*/ false);
572
573 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700574 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700575
Makoto Onukic8a5a552015-11-19 14:29:12 -0800576 // getDeviceOwnerComponent should return the admin1 component.
577 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
578 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
579
580 // Check various get APIs.
581 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
582
583 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
584 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
585 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
586 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
587
588 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
589
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000590 // Verify internal calls.
591 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
592 eq(admin1.getPackageName()));
593
Makoto Onukib643fb02015-09-22 15:03:44 -0700594 // TODO We should check if the caller has called clearCallerIdentity().
595 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
596 eq(UserHandle.USER_SYSTEM), eq(false));
597
598 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
599 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
600 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
601
Makoto Onukic8a5a552015-11-19 14:29:12 -0800602 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700603 }
604
Makoto Onukic8a5a552015-11-19 14:29:12 -0800605 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
606 final int origCallingUser = mContext.binder.callingUid;
607 final List origPermissions = new ArrayList(mContext.callerPermissions);
608 mContext.callerPermissions.clear();
609
610 mContext.callerPermissions.add(permission.MANAGE_USERS);
611
612 mContext.binder.callingUid = Process.SYSTEM_UID;
613
614 // TODO Test getDeviceOwnerName() too. To do so, we need to change
615 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
616 if (hasDeviceOwner) {
617 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
618 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
619 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
620
621 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
622 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
623 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
624 } else {
625 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
626 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
627 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
628
629 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
630 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
631 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
632 }
633
634 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
635 if (hasDeviceOwner) {
636 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
637 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
638 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
639
640 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
641 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
642 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
643 } else {
644 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
645 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
646 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
647
648 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
649 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
650 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
651 }
652
653 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
654 // Still with MANAGE_USERS.
655 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
656 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
657 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
658
659 if (hasDeviceOwner) {
660 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
661 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
662 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
663 } else {
664 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
665 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
666 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
667 }
668
669 mContext.binder.callingUid = Process.SYSTEM_UID;
670 mContext.callerPermissions.remove(permission.MANAGE_USERS);
671 // System can still call "OnAnyUser" without MANAGE_USERS.
672 if (hasDeviceOwner) {
673 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
674 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
675 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
676
677 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
678 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
679 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
680 } else {
681 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
682 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
683 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
684
685 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
686 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
687 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
688 }
689
690 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
691 // Still no MANAGE_USERS.
692 if (hasDeviceOwner) {
693 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
694 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
695 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
696 } else {
697 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
698 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
699 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
700 }
701
702 try {
703 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
704 fail();
705 } catch (SecurityException expected) {
706 }
707 try {
708 dpm.getDeviceOwnerComponentOnAnyUser();
709 fail();
710 } catch (SecurityException expected) {
711 }
712 try {
713 dpm.getDeviceOwnerUserId();
714 fail();
715 } catch (SecurityException expected) {
716 }
717 try {
718 dpm.getDeviceOwnerNameOnAnyUser();
719 fail();
720 } catch (SecurityException expected) {
721 }
722
723 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
724 // Still no MANAGE_USERS.
725 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
726 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
727 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
728
729 try {
730 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
731 fail();
732 } catch (SecurityException expected) {
733 }
734 try {
735 dpm.getDeviceOwnerComponentOnAnyUser();
736 fail();
737 } catch (SecurityException expected) {
738 }
739 try {
740 dpm.getDeviceOwnerUserId();
741 fail();
742 } catch (SecurityException expected) {
743 }
744 try {
745 dpm.getDeviceOwnerNameOnAnyUser();
746 fail();
747 } catch (SecurityException expected) {
748 }
749
750 // Restore.
751 mContext.binder.callingUid = origCallingUser;
752 mContext.callerPermissions.addAll(origPermissions);
753 }
754
755
Makoto Onukib643fb02015-09-22 15:03:44 -0700756 /**
757 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
758 */
759 public void testSetDeviceOwner_noSuchPackage() {
760 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800761 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700762 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
763 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
764
765 // Call from a process on the system user.
766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
767
Makoto Onukib643fb02015-09-22 15:03:44 -0700768 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700769 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700770 fail("Didn't throw IllegalArgumentException");
771 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700772 assertTrue("Message was: " + expected.getMessage(),
773 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700774 }
775 }
776
777 public void testSetDeviceOwner_failures() throws Exception {
778 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
779 }
780
Makoto Onukia52562c2015-10-01 16:12:31 -0700781 public void testClearDeviceOwner() throws Exception {
782 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800783 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700784 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
785 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
786
787 // Set admin1 as a DA to the secondary user.
788 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
789
790 dpm.setActiveAdmin(admin1, /* replace =*/ false);
791
792 // Set admin 1 as the DO to the system user.
793
794 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
795 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
796 dpm.setActiveAdmin(admin1, /* replace =*/ false);
797 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
798
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000799 // Verify internal calls.
800 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
801 eq(admin1.getPackageName()));
802
Makoto Onukic8a5a552015-11-19 14:29:12 -0800803 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700804
Makoto Onuki90b89652016-01-28 14:44:18 -0800805 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
806
807 assertTrue(dpm.isAdminActive(admin1));
808 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
809
Makoto Onukia52562c2015-10-01 16:12:31 -0700810 // Set up other mocks.
811 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
812
813 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700814 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700815 eq(admin1.getPackageName()),
816 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800817
818 // But first pretend the user is locked. Then it should fail.
819 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
820 try {
821 dpm.clearDeviceOwnerApp(admin1.getPackageName());
822 fail("Didn't throw IllegalStateException");
823 } catch (IllegalStateException expected) {
824 MoreAsserts.assertContainsRegex(
825 "User must be running and unlocked", expected.getMessage());
826 }
827
828 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800829 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700830 dpm.clearDeviceOwnerApp(admin1.getPackageName());
831
832 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800833 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700834
Makoto Onuki90b89652016-01-28 14:44:18 -0800835 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
836 eq(UserHandle.USER_SYSTEM),
837 MockUtils.checkUserRestrictions(),
838 MockUtils.checkUserRestrictions()
839 );
840
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700841 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100842
843 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
844 // and once for clearing it.
845 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
846 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
847 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -0700848 // TODO Check other calls.
849 }
850
851 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
852 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800853 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700854 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
855 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
856
857 // Set admin1 as a DA to the secondary user.
858 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
859
860 dpm.setActiveAdmin(admin1, /* replace =*/ false);
861
862 // Set admin 1 as the DO to the system user.
863
864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
865 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
866 dpm.setActiveAdmin(admin1, /* replace =*/ false);
867 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
868
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000869 // Verify internal calls.
870 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
871 eq(admin1.getPackageName()));
872
Makoto Onukic8a5a552015-11-19 14:29:12 -0800873 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700874
875 // Now call clear from the secondary user, which should throw.
876 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
877
878 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700879 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700880 eq(admin1.getPackageName()),
881 anyInt());
882 try {
883 dpm.clearDeviceOwnerApp(admin1.getPackageName());
884 fail("Didn't throw");
885 } catch (SecurityException e) {
886 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
887 }
888
Makoto Onukic8a5a552015-11-19 14:29:12 -0800889 // DO shouldn't be removed.
890 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -0700891 }
892
Makoto Onukib643fb02015-09-22 15:03:44 -0700893 public void testSetProfileOwner() throws Exception {
894 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -0700895
Makoto Onuki90b89652016-01-28 14:44:18 -0800896 // PO admin can't be deactivated.
897 dpm.removeActiveAdmin(admin1);
898 assertTrue(dpm.isAdminActive(admin1));
899
Makoto Onuki803d6752015-10-30 12:58:39 -0700900 // Try setting DO on the same user, which should fail.
901 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
902 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
903 try {
904 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
905 fail("IllegalStateException not thrown");
906 } catch (IllegalStateException expected) {
907 assertTrue("Message was: " + expected.getMessage(),
908 expected.getMessage().contains("already has a profile owner"));
909 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700910 }
911
Makoto Onuki90b89652016-01-28 14:44:18 -0800912 public void testClearProfileOwner() throws Exception {
913 setAsProfileOwner(admin1);
914
915 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
916
917 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
918 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
919
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800920 // First try when the user is locked, which should fail.
921 when(mContext.userManager.isUserUnlocked(anyInt()))
922 .thenReturn(false);
923 try {
924 dpm.clearProfileOwner(admin1);
925 fail("Didn't throw IllegalStateException");
926 } catch (IllegalStateException expected) {
927 MoreAsserts.assertContainsRegex(
928 "User must be running and unlocked", expected.getMessage());
929 }
930 // Clear, really.
931 when(mContext.userManager.isUserUnlocked(anyInt()))
932 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800933 dpm.clearProfileOwner(admin1);
934
935 // Check
936 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700937 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -0800938 }
939
Makoto Onukib643fb02015-09-22 15:03:44 -0700940 public void testSetProfileOwner_failures() throws Exception {
941 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
942 }
943
Makoto Onukia52562c2015-10-01 16:12:31 -0700944 public void testGetDeviceOwnerAdminLocked() throws Exception {
945 checkDeviceOwnerWithMultipleDeviceAdmins();
946 }
947
948 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
949 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
950 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
951 // make sure it gets the right component from the right user.
952
953 final int ANOTHER_USER_ID = 100;
954 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
955
956 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
957
958 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800959 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
962
963 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
964
Victor Change29cd472016-03-02 20:57:42 +0000965 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
966
Makoto Onukia52562c2015-10-01 16:12:31 -0700967 // Make sure the admin packge is installed to each user.
968 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
969 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
970
971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
972 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
973
974 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
975
976
977 // Set active admins to the users.
978 dpm.setActiveAdmin(admin1, /* replace =*/ false);
979 dpm.setActiveAdmin(admin3, /* replace =*/ false);
980
981 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
982 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
983
984 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
985
986 // Set DO on the first non-system user.
987 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
988 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
989
Makoto Onukic8a5a552015-11-19 14:29:12 -0800990 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -0700991
992 // Then check getDeviceOwnerAdminLocked().
993 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
994 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
995 }
996
997 /**
998 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800999 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1000 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001001 *
1002 * We didn't use to persist the DO component class name, but now we do, and the above method
1003 * finds the right component from a package name upon migration.
1004 */
1005 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001006 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001007 checkDeviceOwnerWithMultipleDeviceAdmins();
1008
1009 // Overwrite the device owner setting and clears the clas name.
1010 dpms.mOwners.setDeviceOwner(
1011 new ComponentName(admin2.getPackageName(), ""),
1012 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1013 dpms.mOwners.writeDeviceOwner();
1014
1015 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001016 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001017
1018 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001019 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1020 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001021 initializeDpms();
1022
1023 // Now the DO component name is a full name.
1024 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1025 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001026 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001027 }
1028
Makoto Onukib643fb02015-09-22 15:03:44 -07001029 public void testSetGetApplicationRestriction() {
1030 setAsProfileOwner(admin1);
1031
1032 {
1033 Bundle rest = new Bundle();
1034 rest.putString("KEY_STRING", "Foo1");
1035 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1036 }
1037
1038 {
1039 Bundle rest = new Bundle();
1040 rest.putString("KEY_STRING", "Foo2");
1041 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1042 }
1043
1044 {
1045 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1046 assertNotNull(returned);
1047 assertEquals(returned.size(), 1);
1048 assertEquals(returned.get("KEY_STRING"), "Foo1");
1049 }
1050
1051 {
1052 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1053 assertNotNull(returned);
1054 assertEquals(returned.size(), 1);
1055 assertEquals(returned.get("KEY_STRING"), "Foo2");
1056 }
1057
1058 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1059 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1060 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001061
Esteban Talaverabf60f722015-12-10 16:26:44 +00001062 public void testApplicationRestrictionsManagingApp() throws Exception {
1063 setAsProfileOwner(admin1);
1064
Rubin Xued1928a2016-02-11 17:23:06 +00001065 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001066 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1067 final int appRestrictionsManagerAppId = 20987;
1068 final int appRestrictionsManagerUid = UserHandle.getUid(
1069 DpmMockContext.CALLER_USER_HANDLE, appRestrictionsManagerAppId);
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001070 doReturn(appRestrictionsManagerUid).when(mContext.packageManager).getPackageUidAsUser(
Esteban Talaverabf60f722015-12-10 16:26:44 +00001071 eq(appRestrictionsManagerPackage),
1072 eq(DpmMockContext.CALLER_USER_HANDLE));
1073 mContext.binder.callingUid = appRestrictionsManagerUid;
1074
Rubin Xued1928a2016-02-11 17:23:06 +00001075 final PackageInfo pi = new PackageInfo();
1076 pi.applicationInfo = new ApplicationInfo();
1077 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1078 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1079 eq(appRestrictionsManagerPackage),
1080 anyInt(),
1081 eq(DpmMockContext.CALLER_USER_HANDLE));
1082
Esteban Talaverabf60f722015-12-10 16:26:44 +00001083 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1084 // delegated that permission yet.
1085 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1086 Bundle rest = new Bundle();
1087 rest.putString("KEY_STRING", "Foo1");
1088 try {
1089 dpm.setApplicationRestrictions(null, "pkg1", rest);
1090 fail("Didn't throw expected SecurityException");
1091 } catch (SecurityException expected) {
1092 MoreAsserts.assertContainsRegex(
1093 "caller cannot manage application restrictions", expected.getMessage());
1094 }
1095 try {
1096 dpm.getApplicationRestrictions(null, "pkg1");
1097 fail("Didn't throw expected SecurityException");
1098 } catch (SecurityException expected) {
1099 MoreAsserts.assertContainsRegex(
1100 "caller cannot manage application restrictions", expected.getMessage());
1101 }
1102
1103 // Check via the profile owner that no restrictions were set.
1104 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1105 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1106
Rubin Xued1928a2016-02-11 17:23:06 +00001107 // Check the API does not allow setting a non-existent package
1108 try {
1109 dpm.setApplicationRestrictionsManagingPackage(admin1,
1110 nonExistAppRestrictionsManagerPackage);
1111 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001112 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001113 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001114 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001115 }
1116
Esteban Talaverabf60f722015-12-10 16:26:44 +00001117 // Let appRestrictionsManagerPackage manage app restrictions
1118 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1119 assertEquals(appRestrictionsManagerPackage,
1120 dpm.getApplicationRestrictionsManagingPackage(admin1));
1121
1122 // Now that package should be able to set and retrieve app restrictions.
1123 mContext.binder.callingUid = appRestrictionsManagerUid;
1124 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1125 dpm.setApplicationRestrictions(null, "pkg1", rest);
1126 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1127 assertEquals(1, returned.size(), 1);
1128 assertEquals("Foo1", returned.get("KEY_STRING"));
1129
1130 // The same app running on a separate user shouldn't be able to manage app restrictions.
1131 mContext.binder.callingUid = UserHandle.getUid(
1132 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1133 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1134 try {
1135 dpm.setApplicationRestrictions(null, "pkg1", rest);
1136 fail("Didn't throw expected SecurityException");
1137 } catch (SecurityException expected) {
1138 MoreAsserts.assertContainsRegex(
1139 "caller cannot manage application restrictions", expected.getMessage());
1140 }
1141
1142 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1143 // too.
1144 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1145 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1146 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1147 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1148
1149 // Removing the ability for the package to manage app restrictions.
1150 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1151 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1152 mContext.binder.callingUid = appRestrictionsManagerUid;
1153 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1154 try {
1155 dpm.setApplicationRestrictions(null, "pkg1", null);
1156 fail("Didn't throw expected SecurityException");
1157 } catch (SecurityException expected) {
1158 MoreAsserts.assertContainsRegex(
1159 "caller cannot manage application restrictions", expected.getMessage());
1160 }
1161 }
1162
Makoto Onukia4f11972015-10-01 13:19:58 -07001163 public void testSetUserRestriction_asDo() throws Exception {
1164 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001165 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001166 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1167 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1168
1169 // First, set DO.
1170
1171 // Call from a process on the system user.
1172 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1173
1174 // Make sure admin1 is installed on system user.
1175 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001176
1177 // Call.
1178 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001179 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001180 UserHandle.USER_SYSTEM));
1181
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 DpmTestUtils.assertRestrictions(
1183 DpmTestUtils.newRestrictions(),
1184 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1185 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001186 DpmTestUtils.assertRestrictions(
1187 DpmTestUtils.newRestrictions(),
1188 dpm.getUserRestrictions(admin1)
1189 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001190
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001191 reset(mContext.userManagerInternal);
1192
1193 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1194 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1195 eq(UserHandle.USER_SYSTEM),
1196 MockUtils.checkUserRestrictions(),
1197 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001198 );
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001199 reset(mContext.userManagerInternal);
1200
Makoto Onukia4f11972015-10-01 13:19:58 -07001201 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001202 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1203 eq(UserHandle.USER_SYSTEM),
1204 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1205 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1206 );
1207 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001208
Makoto Onuki068c54a2015-10-13 14:34:03 -07001209 DpmTestUtils.assertRestrictions(
1210 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001211 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001212 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1213 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001214 DpmTestUtils.assertRestrictions(
1215 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001216 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001217 dpm.getUserRestrictions(admin1)
1218 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001219
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001220 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1221 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1222 eq(UserHandle.USER_SYSTEM),
1223 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1224 MockUtils.checkUserRestrictions()
1225 );
1226 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001227
Makoto Onuki068c54a2015-10-13 14:34:03 -07001228 DpmTestUtils.assertRestrictions(
1229 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1230 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1231 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001232 DpmTestUtils.assertRestrictions(
1233 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1234 dpm.getUserRestrictions(admin1)
1235 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001236
1237 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001238 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1239 eq(UserHandle.USER_SYSTEM),
1240 MockUtils.checkUserRestrictions(),
1241 MockUtils.checkUserRestrictions()
1242 );
1243 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001244
Makoto Onuki068c54a2015-10-13 14:34:03 -07001245 DpmTestUtils.assertRestrictions(
1246 DpmTestUtils.newRestrictions(),
1247 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1248 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001249 DpmTestUtils.assertRestrictions(
1250 DpmTestUtils.newRestrictions(),
1251 dpm.getUserRestrictions(admin1)
1252 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001253
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001254 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1255 // DO sets them, the scope is global.
1256 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1257 reset(mContext.userManagerInternal);
1258 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1259 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1260 eq(UserHandle.USER_SYSTEM),
1261 MockUtils.checkUserRestrictions(),
1262 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1263 UserManager.DISALLOW_UNMUTE_MICROPHONE)
1264 );
1265 reset(mContext.userManagerInternal);
1266
1267 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1268 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1269
1270
1271 // More tests.
1272 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1273 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1274 eq(UserHandle.USER_SYSTEM),
1275 MockUtils.checkUserRestrictions(),
1276 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER)
1277 );
1278 reset(mContext.userManagerInternal);
1279
1280 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1281 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1282 eq(UserHandle.USER_SYSTEM),
1283 MockUtils.checkUserRestrictions(),
1284 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1285 UserManager.DISALLOW_ADD_USER)
1286 );
1287 reset(mContext.userManagerInternal);
1288
1289 dpm.setCameraDisabled(admin1, true);
1290 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1291 eq(UserHandle.USER_SYSTEM),
1292 // DISALLOW_CAMERA will be applied to both local and global.
1293 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1294 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1295 UserManager.DISALLOW_CAMERA, UserManager.DISALLOW_ADD_USER)
1296 );
1297 reset(mContext.userManagerInternal);
1298
1299 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1300 // locally.
1301 dpm.setCameraDisabled(admin1, false);
1302 reset(mContext.userManagerInternal);
1303
1304 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1305 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1306 dpm.setCameraDisabled(admin2, true);
1307
1308 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1309 eq(UserHandle.USER_SYSTEM),
1310 // DISALLOW_CAMERA will be applied to both local and global.
1311 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
1312 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
1313 UserManager.DISALLOW_ADD_USER)
1314 );
1315 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001316 // TODO Make sure restrictions are written to the file.
1317 }
1318
1319 public void testSetUserRestriction_asPo() {
1320 setAsProfileOwner(admin1);
1321
Makoto Onuki068c54a2015-10-13 14:34:03 -07001322 DpmTestUtils.assertRestrictions(
1323 DpmTestUtils.newRestrictions(),
1324 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1325 .ensureUserRestrictions()
1326 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001327
1328 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001329 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1330 eq(DpmMockContext.CALLER_USER_HANDLE),
1331 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1332 isNull(Bundle.class)
1333 );
1334 reset(mContext.userManagerInternal);
1335
Makoto Onukia4f11972015-10-01 13:19:58 -07001336 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1338 eq(DpmMockContext.CALLER_USER_HANDLE),
1339 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1340 UserManager.DISALLOW_OUTGOING_CALLS),
1341 isNull(Bundle.class)
1342 );
1343 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001344
Makoto Onuki068c54a2015-10-13 14:34:03 -07001345 DpmTestUtils.assertRestrictions(
1346 DpmTestUtils.newRestrictions(
1347 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1348 UserManager.DISALLOW_OUTGOING_CALLS
1349 ),
1350 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1351 .ensureUserRestrictions()
1352 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001353 DpmTestUtils.assertRestrictions(
1354 DpmTestUtils.newRestrictions(
1355 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1356 UserManager.DISALLOW_OUTGOING_CALLS
1357 ),
1358 dpm.getUserRestrictions(admin1)
1359 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001360
1361 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001362 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1363 eq(DpmMockContext.CALLER_USER_HANDLE),
1364 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1365 isNull(Bundle.class)
1366 );
1367 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001368
1369 DpmTestUtils.assertRestrictions(
1370 DpmTestUtils.newRestrictions(
1371 UserManager.DISALLOW_OUTGOING_CALLS
1372 ),
1373 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1374 .ensureUserRestrictions()
1375 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001376 DpmTestUtils.assertRestrictions(
1377 DpmTestUtils.newRestrictions(
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_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001384 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1385 eq(DpmMockContext.CALLER_USER_HANDLE),
1386 MockUtils.checkUserRestrictions(),
1387 isNull(Bundle.class)
1388 );
1389 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001390
Makoto Onuki068c54a2015-10-13 14:34:03 -07001391 DpmTestUtils.assertRestrictions(
1392 DpmTestUtils.newRestrictions(),
1393 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1394 .ensureUserRestrictions()
1395 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001396 DpmTestUtils.assertRestrictions(
1397 DpmTestUtils.newRestrictions(),
1398 dpm.getUserRestrictions(admin1)
1399 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001400
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001401 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1402 // though when DO sets them they'll be applied globally.
1403 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1404 reset(mContext.userManagerInternal);
1405 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1406 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1407 eq(DpmMockContext.CALLER_USER_HANDLE),
1408 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1409 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1410 isNull(Bundle.class)
1411 );
1412 reset(mContext.userManagerInternal);
1413
1414 dpm.setCameraDisabled(admin1, true);
1415 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1416 eq(DpmMockContext.CALLER_USER_HANDLE),
1417 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA,
1418 UserManager.DISALLOW_ADJUST_VOLUME,
1419 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1420 isNull(Bundle.class)
1421 );
1422 reset(mContext.userManagerInternal);
1423
Makoto Onukia4f11972015-10-01 13:19:58 -07001424 // TODO Make sure restrictions are written to the file.
1425 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001426
1427 public void testGetMacAddress() throws Exception {
1428 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1429 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1430 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1431
1432 // In this test, change the caller user to "system".
1433 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1434
1435 // Make sure admin1 is installed on system user.
1436 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1437
1438 // Test 1. Caller doesn't have DO or DA.
1439 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001440 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001441 fail();
1442 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001443 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001444 }
1445
1446 // DO needs to be an DA.
1447 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1448 assertTrue(dpm.isAdminActive(admin1));
1449
1450 // Test 2. Caller has DA, but not DO.
1451 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001452 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001453 fail();
1454 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001455 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001456 }
1457
1458 // Test 3. Caller has PO, but not DO.
1459 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1460 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001461 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001462 fail();
1463 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001464 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001465 }
1466
1467 // Remove PO.
1468 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001469 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001470 // Test 4, Caller is DO now.
1471 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1472
1473 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001474 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001475
1476 // 4-2. Returns WifiInfo, but with the default MAC.
1477 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001478 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001479
1480 // 4-3. With a real MAC address.
1481 final WifiInfo wi = new WifiInfo();
1482 wi.setMacAddress("11:22:33:44:55:66");
1483 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001484 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001485 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001486
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001487 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001488 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1489 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1490
1491 // In this test, change the caller user to "system".
1492 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1493
1494 // Make sure admin1 is installed on system user.
1495 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1496
1497 // Set admin1 as DA.
1498 dpm.setActiveAdmin(admin1, false);
1499 assertTrue(dpm.isAdminActive(admin1));
1500 try {
1501 dpm.reboot(admin1);
1502 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1503 } catch (SecurityException expected) {
1504 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1505 }
1506
1507 // Set admin1 as PO.
1508 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1509 try {
1510 dpm.reboot(admin1);
1511 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1512 } catch (SecurityException expected) {
1513 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1514 }
1515
1516 // Remove PO and add DO.
1517 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001518 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001519 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1520
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001521 // admin1 is DO.
1522 // Set current call state of device to ringing.
1523 when(mContext.telephonyManager.getCallState())
1524 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1525 try {
1526 dpm.reboot(admin1);
1527 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1528 } catch (IllegalStateException expected) {
1529 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1530 }
1531
1532 // Set current call state of device to dialing/active.
1533 when(mContext.telephonyManager.getCallState())
1534 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1535 try {
1536 dpm.reboot(admin1);
1537 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1538 } catch (IllegalStateException expected) {
1539 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1540 }
1541
1542 // Set current call state of device to idle.
1543 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001544 dpm.reboot(admin1);
1545 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001546
1547 public void testSetGetSupportText() {
1548 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1549 dpm.setActiveAdmin(admin1, true);
1550 dpm.setActiveAdmin(admin2, true);
1551 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1552
1553 // Null default support messages.
1554 {
1555 assertNull(dpm.getLongSupportMessage(admin1));
1556 assertNull(dpm.getShortSupportMessage(admin1));
1557 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1558 assertNull(dpm.getShortSupportMessageForUser(admin1,
1559 DpmMockContext.CALLER_USER_HANDLE));
1560 assertNull(dpm.getLongSupportMessageForUser(admin1,
1561 DpmMockContext.CALLER_USER_HANDLE));
1562 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1563 }
1564
1565 // Only system can call the per user versions.
1566 {
1567 try {
1568 dpm.getShortSupportMessageForUser(admin1,
1569 DpmMockContext.CALLER_USER_HANDLE);
1570 fail("Only system should be able to call getXXXForUser versions");
1571 } catch (SecurityException expected) {
1572 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1573 }
1574 try {
1575 dpm.getLongSupportMessageForUser(admin1,
1576 DpmMockContext.CALLER_USER_HANDLE);
1577 fail("Only system should be able to call getXXXForUser versions");
1578 } catch (SecurityException expected) {
1579 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1580 }
1581 }
1582
1583 // Can't set message for admin in another uid.
1584 {
1585 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
1586 try {
1587 dpm.setShortSupportMessage(admin1, "Some text");
1588 fail("Admins should only be able to change their own support text.");
1589 } catch (SecurityException expected) {
1590 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
1591 }
1592 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1593 }
1594
1595 // Set/Get short returns what it sets and other admins text isn't changed.
1596 {
1597 final String supportText = "Some text to test with.";
1598 dpm.setShortSupportMessage(admin1, supportText);
1599 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
1600 assertNull(dpm.getLongSupportMessage(admin1));
1601 assertNull(dpm.getShortSupportMessage(admin2));
1602
1603 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1604 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
1605 DpmMockContext.CALLER_USER_HANDLE));
1606 assertNull(dpm.getShortSupportMessageForUser(admin2,
1607 DpmMockContext.CALLER_USER_HANDLE));
1608 assertNull(dpm.getLongSupportMessageForUser(admin1,
1609 DpmMockContext.CALLER_USER_HANDLE));
1610 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1611
1612 dpm.setShortSupportMessage(admin1, null);
1613 assertNull(dpm.getShortSupportMessage(admin1));
1614 }
1615
1616 // Set/Get long returns what it sets and other admins text isn't changed.
1617 {
1618 final String supportText = "Some text to test with.\nWith more text.";
1619 dpm.setLongSupportMessage(admin1, supportText);
1620 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
1621 assertNull(dpm.getShortSupportMessage(admin1));
1622 assertNull(dpm.getLongSupportMessage(admin2));
1623
1624 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1625 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
1626 DpmMockContext.CALLER_USER_HANDLE));
1627 assertNull(dpm.getLongSupportMessageForUser(admin2,
1628 DpmMockContext.CALLER_USER_HANDLE));
1629 assertNull(dpm.getShortSupportMessageForUser(admin1,
1630 DpmMockContext.CALLER_USER_HANDLE));
1631 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1632
1633 dpm.setLongSupportMessage(admin1, null);
1634 assertNull(dpm.getLongSupportMessage(admin1));
1635 }
1636 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001637
1638 /**
1639 * Test for:
1640 * {@link DevicePolicyManager#setAffiliationIds}
1641 * {@link DevicePolicyManager#isAffiliatedUser}
1642 */
1643 public void testUserAffiliation() throws Exception {
1644 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1645 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1646 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1647
1648 // Check that the system user is unaffiliated.
1649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1650 assertFalse(dpm.isAffiliatedUser());
1651
1652 // Set a device owner on the system user. Check that the system user becomes affiliated.
1653 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1654 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1655 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1656 assertTrue(dpm.isAffiliatedUser());
1657
1658 // Install a profile owner whose package name matches the device owner on a test user. Check
1659 // that the test user is unaffiliated.
1660 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1661 setAsProfileOwner(admin2);
1662 assertFalse(dpm.isAffiliatedUser());
1663
1664 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
1665 // unaffiliated.
1666 final Set<String> userAffiliationIds = new ArraySet<>();
1667 userAffiliationIds.add("red");
1668 userAffiliationIds.add("green");
1669 userAffiliationIds.add("blue");
1670 dpm.setAffiliationIds(admin2, userAffiliationIds);
1671 assertFalse(dpm.isAffiliatedUser());
1672
1673 // Have the device owner specify a set of affiliation ids that do not intersect with those
1674 // specified by the profile owner. Check that the test user remains unaffiliated.
1675 final Set<String> deviceAffiliationIds = new ArraySet<>();
1676 deviceAffiliationIds.add("cyan");
1677 deviceAffiliationIds.add("yellow");
1678 deviceAffiliationIds.add("magenta");
1679 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1680 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
1681 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1682 assertFalse(dpm.isAffiliatedUser());
1683
1684 // Have the profile owner specify a set of affiliation ids that intersect with those
1685 // specified by the device owner. Check that the test user becomes affiliated.
1686 userAffiliationIds.add("yellow");
1687 dpm.setAffiliationIds(admin2, userAffiliationIds);
1688 assertTrue(dpm.isAffiliatedUser());
1689
1690 // Change the profile owner to one whose package name does not match the device owner. Check
1691 // that the test user is not affiliated anymore.
1692 dpm.clearProfileOwner(admin2);
1693 final ComponentName admin = new ComponentName("test", "test");
Makoto Onuki184db602016-02-17 15:35:01 -08001694
1695 setUpPackageManagerForFakeAdmin(admin, DpmMockContext.CALLER_UID,
1696 /* enabledSetting =*/ PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
1697 /* appTargetSdk = */ null, admin2);
1698
1699 dpm.setActiveAdmin(admin, /* refreshing =*/ true, DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01001700 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1701 assertFalse(dpm.isAffiliatedUser());
1702
1703 // Check that the system user remains affiliated.
1704 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1705 assertTrue(dpm.isAffiliatedUser());
1706 }
Alan Treadwayafad8782016-01-19 15:15:08 +00001707
1708 public void testGetUserProvisioningState_defaultResult() {
1709 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1710 }
1711
1712 public void testSetUserProvisioningState_permission() throws Exception {
1713 setupProfileOwner();
1714 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1715
1716 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1717 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1718 }
1719
1720 public void testSetUserProvisioningState_unprivileged() throws Exception {
1721 setupProfileOwner();
1722 try {
1723 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1724 DpmMockContext.CALLER_USER_HANDLE);
1725 fail("Expected SecurityException");
1726 } catch (SecurityException expected) {
1727 }
1728 }
1729
1730 public void testSetUserProvisioningState_noManagement() {
1731 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1732 try {
1733 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1734 DpmMockContext.CALLER_USER_HANDLE);
1735 fail("IllegalStateException expected");
1736 } catch (IllegalStateException e) {
1737 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
1738 e.getMessage());
1739 }
1740 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1741 }
1742
1743 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
1744 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1745 setupDeviceOwner();
1746 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1747
1748 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1749 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1750 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1751 }
1752
1753 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
1754 throws Exception {
1755 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1756 setupDeviceOwner();
1757 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1758
1759 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1760 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1761 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1762 }
1763
1764 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
1765 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1766 setupDeviceOwner();
1767 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1768
1769 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
1770 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1771 }
1772
1773 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
1774 throws Exception {
1775 setupProfileOwner();
1776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1777
1778 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1779 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
1780 DevicePolicyManager.STATE_USER_UNMANAGED);
1781 }
1782
1783 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
1784 throws Exception {
1785 setupProfileOwner();
1786 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1787
1788 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1789 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
1790 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1791 }
1792
1793 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
1794 setupProfileOwner();
1795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1796
1797 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1798 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
1799 }
1800
1801 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
1802 setupProfileOwner();
1803 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1804
1805 try {
1806 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1807 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
1808 DevicePolicyManager.STATE_USER_UNMANAGED);
1809 fail("Expected IllegalStateException");
1810 } catch (IllegalStateException e) {
1811 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1812 e.getMessage());
1813 }
1814 }
1815
1816 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
1817 throws Exception {
1818 setupProfileOwner();
1819 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1820
1821 try {
1822 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
1823 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
1824 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
1825 fail("Expected IllegalStateException");
1826 } catch (IllegalStateException e) {
1827 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
1828 e.getMessage());
1829 }
1830 }
1831
1832 private void exerciseUserProvisioningTransitions(int userId, int... states) {
1833 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
1834 for (int state : states) {
1835 dpm.setUserProvisioningState(state, userId);
1836 assertEquals(state, dpm.getUserProvisioningState());
1837 }
1838 }
1839
1840 private void setupProfileOwner() throws Exception {
1841 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1842
1843 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1844 dpm.setActiveAdmin(admin1, false);
1845 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
1846
1847 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1848 }
1849
1850 private void setupDeviceOwner() throws Exception {
1851 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
1852
1853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1854 dpm.setActiveAdmin(admin1, false);
1855 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1856
1857 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
1858 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001859
1860 public void testSetMaximumTimeToLock() {
1861 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1862
1863 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1864 dpm.setActiveAdmin(admin2, /* replace =*/ false);
1865
1866 reset(mMockContext.powerManagerInternal);
1867 reset(mMockContext.settings);
1868
1869 dpm.setMaximumTimeToLock(admin1, 0);
1870 verifyScreenTimeoutCall(null, false);
1871 reset(mMockContext.powerManagerInternal);
1872 reset(mMockContext.settings);
1873
1874 dpm.setMaximumTimeToLock(admin1, 1);
1875 verifyScreenTimeoutCall(1, true);
1876 reset(mMockContext.powerManagerInternal);
1877 reset(mMockContext.settings);
1878
1879 dpm.setMaximumTimeToLock(admin2, 10);
1880 verifyScreenTimeoutCall(null, false);
1881 reset(mMockContext.powerManagerInternal);
1882 reset(mMockContext.settings);
1883
1884 dpm.setMaximumTimeToLock(admin1, 5);
1885 verifyScreenTimeoutCall(5, true);
1886 reset(mMockContext.powerManagerInternal);
1887 reset(mMockContext.settings);
1888
1889 dpm.setMaximumTimeToLock(admin2, 4);
1890 verifyScreenTimeoutCall(4, true);
1891 reset(mMockContext.powerManagerInternal);
1892 reset(mMockContext.settings);
1893
1894 dpm.setMaximumTimeToLock(admin1, 0);
1895 reset(mMockContext.powerManagerInternal);
1896 reset(mMockContext.settings);
1897
1898 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
1899 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1900 reset(mMockContext.powerManagerInternal);
1901 reset(mMockContext.settings);
1902
1903 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
1904 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
1905 reset(mMockContext.powerManagerInternal);
1906 reset(mMockContext.settings);
1907
1908 dpm.setMaximumTimeToLock(admin2, 10);
1909 verifyScreenTimeoutCall(10, true);
1910 reset(mMockContext.powerManagerInternal);
1911 reset(mMockContext.settings);
1912
1913 // There's no restriction; shold be set to MAX.
1914 dpm.setMaximumTimeToLock(admin2, 0);
1915 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
1916 }
1917
Michal Karpinski943aabd2016-10-06 11:09:25 +01001918 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
1919 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1920 setupDeviceOwner();
1921 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1922
1923 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
1924 final long ONE_MINUTE = 60 * 1000;
1925
1926 // aggregation should be the default if unset by any admin
1927 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1928 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1929
1930 // admin not participating by default
1931 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1932
1933 //clamping from the top
1934 dpm.setRequiredStrongAuthTimeout(admin1,
1935 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1936 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
1937 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1938 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1939 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1940
1941 // 0 means default
1942 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1943 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1944 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1945 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1946
1947 // clamping from the bottom
1948 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
1949 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1950 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
1951
1952 // value within range
1953 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
1954 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1955 + ONE_MINUTE);
1956 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS
1957 + ONE_MINUTE);
1958
1959 // reset to default
1960 dpm.setRequiredStrongAuthTimeout(admin1, 0);
1961 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
1962 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
1963 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
1964
1965 // negative value
1966 try {
1967 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
1968 fail("Didn't throw IllegalArgumentException");
1969 } catch (IllegalArgumentException iae) {
1970 }
1971 }
1972
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001973 private void verifyScreenTimeoutCall(Integer expectedTimeout,
1974 boolean shouldStayOnWhilePluggedInBeCleared) {
1975 if (expectedTimeout == null) {
1976 verify(mMockContext.powerManagerInternal, times(0))
1977 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
1978 } else {
1979 verify(mMockContext.powerManagerInternal, times(1))
1980 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
1981 }
1982 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
1983 // UnfinishedVerificationException.
1984 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001985
Victor Chang3e794af2016-03-04 13:48:17 +00001986 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
1987 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
1988 .thenReturn(false);
1989 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
1990 .thenReturn(false);
1991 initializeDpms();
1992 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
1993 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
1994 .thenReturn(true);
1995 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
1996
1997 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1998
1999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2002 false);
2003 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2004 }
2005
2006 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2007 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2008 .thenReturn(false);
2009 initializeDpms();
2010 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2011 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2012 .thenReturn(true);
2013 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2014
2015 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2016
2017 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2018 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2019 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2020 false);
2021 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2022
2023 // Test again when split user is on
2024 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2025 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2027 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2028 true);
2029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2030 }
2031
2032 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2033 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2034 .thenReturn(true);
2035 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2036 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2037 .thenReturn(true);
2038 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2039
2040 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2041
2042 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2043 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2044 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2045 false /* because of non-split user */);
2046 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2047 false /* because of non-split user */);
2048 }
2049
2050 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2051 throws Exception {
2052 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2053 .thenReturn(true);
2054 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2055 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2056 .thenReturn(true);
2057 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2058
2059 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2060
2061 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2062 false/* because of completed device setup */);
2063 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2064 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2065 false/* because of non-split user */);
2066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2067 false/* because of non-split user */);
2068 }
2069
2070 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2071 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2072 .thenReturn(true);
2073 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2074 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2075 .thenReturn(false);
2076 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2077
2078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2079
2080 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2081 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2082 false /* because canAddMoreManagedProfiles returns false */);
2083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2084 true);
2085 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2086 false/* because calling uid is system user */);
2087
2088 }
2089
2090 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2091 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2092 .thenReturn(true);
2093 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2094 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2095 .thenReturn(false);
2096 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2097
2098 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2099
2100 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2101 true/* it's undefined behavior. Can be changed into false in the future */);
2102 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2103 false /* because canAddMoreManagedProfiles returns false */);
2104 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2105 true/* it's undefined behavior. Can be changed into false in the future */);
2106 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2107 false/* because calling uid is system user */);
2108 }
2109
2110 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2111 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2112 .thenReturn(true);
2113 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2114 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2115 true)).thenReturn(true);
2116 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2117
2118 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2119
2120 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2121 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2122 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2123 true);
2124 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
2125
2126 }
2127
2128 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2129 throws Exception {
2130 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2131 .thenReturn(true);
2132 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2133 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2134 true)).thenReturn(true);
2135 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2136
2137 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2138
2139 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2140 true/* it's undefined behavior. Can be changed into false in the future */);
2141 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2142 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2143 true/* it's undefined behavior. Can be changed into false in the future */);
2144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2145 false/* because user setup completed */);
2146 }
2147
2148 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2149 throws Exception {
2150 setDeviceOwner();
2151
2152 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2153 .thenReturn(true);
2154 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2155 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2156 .thenReturn(false);
2157 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2158
2159 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2160
2161 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2162 false /* can't provision managed profile on system user */);
2163 }
2164
2165 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
2166 throws Exception {
2167 setDeviceOwner();
2168
2169 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2170 .thenReturn(true);
2171 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2172 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2173 true)).thenReturn(true);
2174 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2175
2176 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2177
2178 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2179 }
2180
Nicolas Prevot56400a42016-11-10 12:57:54 +00002181 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
2182 throws Exception {
2183 setDeviceOwner();
2184
2185 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2186 .thenReturn(true);
2187 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2188 when(mContext.userManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER))
2189 .thenReturn(true);
2190 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2191 false /* we can't remove a managed profile*/)).thenReturn(false);
2192 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2193 true)).thenReturn(true);
2194 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2195
2196 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2197
2198 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2199 }
2200
Victor Chang3577ed22016-08-25 18:49:26 +01002201 public void testForceUpdateUserSetupComplete_permission() {
2202 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
2203 try {
2204 dpm.forceUpdateUserSetupComplete();
2205 fail("Didn't throw SecurityException");
2206 } catch (SecurityException expected) {
2207 }
2208 }
2209
2210 public void testForceUpdateUserSetupComplete_systemUser() {
2211 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2212 // GIVEN calling from user 20
2213 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2214 try {
2215 dpm.forceUpdateUserSetupComplete();
2216 fail("Didn't throw SecurityException");
2217 } catch (SecurityException expected) {
2218 }
2219 }
2220
2221 public void testForceUpdateUserSetupComplete_userbuild() {
2222 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2223 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2224
2225 final int userId = UserHandle.USER_SYSTEM;
2226 // GIVEN userComplete is false in SettingsProvider
2227 setUserSetupCompleteForUser(false, userId);
2228
2229 // GIVEN userComplete is true in DPM
2230 DevicePolicyManagerService.DevicePolicyData userData =
2231 new DevicePolicyManagerService.DevicePolicyData(userId);
2232 userData.mUserSetupComplete = true;
2233 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2234
2235 // GIVEN it's user build
2236 mContext.buildMock.isDebuggable = false;
2237
2238 assertTrue(dpms.hasUserSetupCompleted());
2239
2240 dpm.forceUpdateUserSetupComplete();
2241
2242 // THEN the state in dpms is not changed
2243 assertTrue(dpms.hasUserSetupCompleted());
2244 }
2245
2246 public void testForceUpdateUserSetupComplete_userDebugbuild() {
2247 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2249
2250 final int userId = UserHandle.USER_SYSTEM;
2251 // GIVEN userComplete is false in SettingsProvider
2252 setUserSetupCompleteForUser(false, userId);
2253
2254 // GIVEN userComplete is true in DPM
2255 DevicePolicyManagerService.DevicePolicyData userData =
2256 new DevicePolicyManagerService.DevicePolicyData(userId);
2257 userData.mUserSetupComplete = true;
2258 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
2259
2260 // GIVEN it's userdebug build
2261 mContext.buildMock.isDebuggable = true;
2262
2263 assertTrue(dpms.hasUserSetupCompleted());
2264
2265 dpm.forceUpdateUserSetupComplete();
2266
2267 // THEN the state in dpms is not changed
2268 assertFalse(dpms.hasUserSetupCompleted());
2269 }
2270
Victor Chang3e794af2016-03-04 13:48:17 +00002271 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
2272 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
2273 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
2274 dpms.notifyChangeToContentObserver(
2275 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
2276 }
2277
2278 private void assertProvisioningAllowed(String action, boolean expected) {
2279 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
2280 dpm.isProvisioningAllowed(action));
2281 }
2282}